Merge "AAudio should not use legacy path if not allowed"
diff --git a/media/libmedia/include/media/MediaProfiles.h b/media/libmedia/include/media/MediaProfiles.h
index 6975581..0feb4f3 100644
--- a/media/libmedia/include/media/MediaProfiles.h
+++ b/media/libmedia/include/media/MediaProfiles.h
@@ -83,6 +83,7 @@
      * successful only when validation is successful.
      */
     static constexpr char const * const xmlFiles[] = {
+            "odm/etc/media_profiles_V1_0.xml",
             "vendor/etc/media_profiles_V1_0.xml",
             "system/etc/media_profiles.xml"
             };
diff --git a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
index 2dd7d69..f173e0f 100644
--- a/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
+++ b/media/libstagefright/codecs/xaacdec/SoftXAAC.cpp
@@ -23,42 +23,53 @@
 #include <OMX_AudioExt.h>
 #include <OMX_IndexExt.h>
 #include <cutils/properties.h>
+#include <math.h>
+#include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/hexdump.h>
-#include <media/stagefright/MediaErrors.h>
 #include <utils/misc.h>
-#include <math.h>
 
-#define DRC_DEFAULT_MOBILE_REF_LEVEL 64  /* 64*-0.25dB = -16 dB below full scale for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_CUT   127 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_BOOST 127 /* maximum compression of dynamic range for mobile conf */
-#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1   /* switch for heavy compression for mobile conf */
-#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) */
-#define DRC_KEY_AAC_DRC_EFFECT_TYPE   (3)  /* Default Effect type is "Limited playback" */
+/* 64*-0.25dB = -16 dB below full scale for mobile conf */
+#define DRC_DEFAULT_MOBILE_REF_LEVEL 64
+/* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_CUT 127
+/* maximum compression of dynamic range for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_BOOST 127
+/* switch for heavy compression for mobile conf */
+#define DRC_DEFAULT_MOBILE_DRC_HEAVY 1
+/* encoder target level; -1 => the value is unknown,
+ * otherwise dB step value (e.g. 64 for -16 dB) */
+#define DRC_DEFAULT_MOBILE_ENC_LEVEL (-1)
+
+/* Default Effect type is "Limited playback" */
+#define DRC_KEY_AAC_DRC_EFFECT_TYPE (3)
+
 /* REF_LEVEL of 64 pairs well with EFFECT_TYPE of 3. */
-#define DRC_DEFAULT_MOBILE_LOUDNESS_LEVEL (64)  /* Default loudness value for MPEG-D DRC */
+/* Default loudness value for MPEG-D DRC */
+#define DRC_DEFAULT_MOBILE_LOUDNESS_LEVEL (64)
 
-#define PROP_DRC_OVERRIDE_REF_LEVEL  "aac_drc_reference_level"
-#define PROP_DRC_OVERRIDE_CUT        "aac_drc_cut"
-#define PROP_DRC_OVERRIDE_BOOST      "aac_drc_boost"
-#define PROP_DRC_OVERRIDE_HEAVY      "aac_drc_heavy"
+#define PROP_DRC_OVERRIDE_REF_LEVEL "aac_drc_reference_level"
+#define PROP_DRC_OVERRIDE_CUT "aac_drc_cut"
+#define PROP_DRC_OVERRIDE_BOOST "aac_drc_boost"
+#define PROP_DRC_OVERRIDE_HEAVY "aac_drc_heavy"
 #define PROP_DRC_OVERRIDE_ENC_LEVEL "aac_drc_enc_target_level"
 #define PROP_DRC_OVERRIDE_EFFECT_TYPE "ro.aac_drc_effect_type"
 
-#define MAX_CHANNEL_COUNT            8  /* maximum number of audio channels that can be decoded */
+/* maximum number of audio channels that can be decoded */
+#define MAX_CHANNEL_COUNT 8
 
-
-#define RETURN_IF_NE(returned, expected, retval, str) \
-        if ( returned != expected ) { \
-            ALOGE("Error in %s: Returned: %d Expected: %d", str, returned, expected); \
-            return retval; \
-        }
-
+#define RETURN_IF_FATAL(retval, str)                       \
+    if (retval & IA_FATAL_ERROR) {                         \
+        ALOGE("Error in %s: Returned: %d", str, retval);   \
+        return retval;                                     \
+    } else if (retval != IA_NO_ERROR) {                    \
+        ALOGW("Warning in %s: Returned: %d", str, retval); \
+    }
 
 namespace android {
 
-template<class T>
-static void InitOMXParams(T *params) {
+template <class T>
+static void InitOMXParams(T* params) {
     params->nSize = sizeof(T);
     params->nVersion.s.nVersionMajor = 1;
     params->nVersion.s.nVersionMinor = 0;
@@ -67,41 +78,35 @@
 }
 
 static const OMX_U32 kSupportedProfiles[] = {
-    OMX_AUDIO_AACObjectLC,
-    OMX_AUDIO_AACObjectHE,
-    OMX_AUDIO_AACObjectHE_PS,
-    OMX_AUDIO_AACObjectLD,
-    OMX_AUDIO_AACObjectELD,
+    OMX_AUDIO_AACObjectLC, OMX_AUDIO_AACObjectHE,  OMX_AUDIO_AACObjectHE_PS,
+    OMX_AUDIO_AACObjectLD, OMX_AUDIO_AACObjectELD,
 };
 
-SoftXAAC::SoftXAAC(
-        const char *name,
-        const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData,
-        OMX_COMPONENTTYPE **component)
+SoftXAAC::SoftXAAC(const char* name, const OMX_CALLBACKTYPE* callbacks, OMX_PTR appData,
+                   OMX_COMPONENTTYPE** component)
     : SimpleSoftOMXComponent(name, callbacks, appData, component),
-    mIsADTS(false),
-    mInputBufferCount(0),
-    mOutputBufferCount(0),
-    mSignalledError(false),
-    mLastInHeader(NULL),
-    mPrevTimestamp(0),
-    mCurrentTimestamp(0),
-    mOutputPortSettingsChange(NONE),
-    mXheaacCodecHandle(NULL),
-    mMpegDDrcHandle(NULL),
-    mInputBufferSize(0),
-    mOutputFrameLength(1024),
-    mInputBuffer(NULL),
-    mOutputBuffer(NULL),
-    mSampFreq(0),
-    mNumChannels(0),
-    mPcmWdSz(0),
-    mChannelMask(0),
-    mIsCodecInitialized(false),
-    mIsCodecConfigFlushRequired(false),
-    mpegd_drc_present(0),
-    drc_flag(0)
+      mIsADTS(false),
+      mInputBufferCount(0),
+      mOutputBufferCount(0),
+      mSignalledError(false),
+      mLastInHeader(NULL),
+      mPrevTimestamp(0),
+      mCurrentTimestamp(0),
+      mOutputPortSettingsChange(NONE),
+      mXheaacCodecHandle(NULL),
+      mMpegDDrcHandle(NULL),
+      mInputBufferSize(0),
+      mOutputFrameLength(1024),
+      mInputBuffer(NULL),
+      mOutputBuffer(NULL),
+      mSampFreq(0),
+      mNumChannels(0),
+      mPcmWdSz(0),
+      mChannelMask(0),
+      mIsCodecInitialized(false),
+      mIsCodecConfigFlushRequired(false),
+      mMpegDDRCPresent(0),
+      mDRCFlag(0)
 
 {
     initPorts();
@@ -111,7 +116,7 @@
 SoftXAAC::~SoftXAAC() {
     int errCode = deInitXAACDecoder();
     if (0 != errCode) {
-        ALOGE("deInitXAACDecoder() failed %d",errCode);
+        ALOGE("deInitXAACDecoder() failed %d", errCode);
     }
 
     mIsCodecInitialized = false;
@@ -133,7 +138,7 @@
     def.bBuffersContiguous = OMX_FALSE;
     def.nBufferAlignment = 1;
 
-    def.format.audio.cMIMEType = const_cast<char *>("audio/aac");
+    def.format.audio.cMIMEType = const_cast<char*>("audio/aac");
     def.format.audio.pNativeRender = NULL;
     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
     def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
@@ -151,7 +156,7 @@
     def.bBuffersContiguous = OMX_FALSE;
     def.nBufferAlignment = 2;
 
-    def.format.audio.cMIMEType = const_cast<char *>("audio/raw");
+    def.format.audio.cMIMEType = const_cast<char*>("audio/raw");
     def.format.audio.pNativeRender = NULL;
     def.format.audio.bFlagErrorConcealment = OMX_FALSE;
     def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
@@ -167,24 +172,23 @@
     int loop = 0;
 
     err_code = initXAACDecoder();
-    if(err_code != IA_NO_ERROR) {
+    if (err_code != IA_NO_ERROR) {
         if (NULL == mXheaacCodecHandle) {
             ALOGE("AAC decoder handle is null");
         }
         if (NULL == mMpegDDrcHandle) {
             ALOGE("MPEG-D DRC decoder handle is null");
         }
-        for(loop= 1; loop < mMallocCount; loop++) {
+        for (loop = 1; loop < mMallocCount; loop++) {
             if (mMemoryArray[loop] == NULL) {
-                ALOGE(" memory allocation error %d\n",loop);
+                ALOGE(" memory allocation error %d\n", loop);
                 break;
             }
         }
         ALOGE("initXAACDecoder Failed");
 
-        for(loop = 0; loop < mMallocCount; loop++) {
-           if(mMemoryArray[loop])
-           free(mMemoryArray[loop]);
+        for (loop = 0; loop < mMallocCount; loop++) {
+            if (mMemoryArray[loop]) free(mMemoryArray[loop]);
         }
         mMallocCount = 0;
         return status;
@@ -196,121 +200,87 @@
     mEndOfOutput = false;
 
     char value[PROPERTY_VALUE_MAX];
-    if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_REF_LEVEL, value, NULL)) {
         ui_drc_val = atoi(value);
-        ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d",ui_drc_val,
-                DRC_DEFAULT_MOBILE_REF_LEVEL);
-    }
-    else
-    {
-        ui_drc_val= DRC_DEFAULT_MOBILE_REF_LEVEL;
+        ALOGV("AAC decoder using desired DRC target reference level of %d instead of %d",
+              ui_drc_val, DRC_DEFAULT_MOBILE_REF_LEVEL);
+    } else {
+        ui_drc_val = DRC_DEFAULT_MOBILE_REF_LEVEL;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL,
-                                &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL, &ui_drc_val);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
-#ifdef     ENABLE_MPEG_D_DRC
-
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
+#ifdef ENABLE_MPEG_D_DRC
     /* Use ui_drc_val from PROP_DRC_OVERRIDE_REF_LEVEL or DRC_DEFAULT_MOBILE_REF_LEVEL
      * for IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS too */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS,
-                                &ui_drc_val);
 
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS, &ui_drc_val);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
 #endif
 
-
-    if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_CUT, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC attenuation factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_CUT);
-    }
-    else
-    {
-        ui_drc_val=DRC_DEFAULT_MOBILE_DRC_CUT;
+              DRC_DEFAULT_MOBILE_DRC_CUT);
+    } else {
+        ui_drc_val = DRC_DEFAULT_MOBILE_DRC_CUT;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT,
-                                &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT, &ui_drc_val);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
 
-    if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_BOOST, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC boost factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_BOOST);
-    }
-    else
-    {
+              DRC_DEFAULT_MOBILE_DRC_BOOST);
+    } else {
         ui_drc_val = DRC_DEFAULT_MOBILE_DRC_BOOST;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST,
-                                &ui_drc_val);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST, &ui_drc_val);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
 
-    if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_HEAVY, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired Heavy compression factor of %d instead of %d", ui_drc_val,
-                DRC_DEFAULT_MOBILE_DRC_HEAVY);
-    }
-    else
-    {
+              DRC_DEFAULT_MOBILE_DRC_HEAVY);
+    } else {
         ui_drc_val = DRC_DEFAULT_MOBILE_DRC_HEAVY;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP,
-                                &ui_drc_val);
-   RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP, &ui_drc_val);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
 
 #ifdef ENABLE_MPEG_D_DRC
-    if (property_get(PROP_DRC_OVERRIDE_EFFECT_TYPE, value, NULL))
-    {
+    if (property_get(PROP_DRC_OVERRIDE_EFFECT_TYPE, value, NULL)) {
         ui_drc_val = atoi(value);
         ALOGV("AAC decoder using desired DRC effect type of %d instead of %d", ui_drc_val,
-                DRC_KEY_AAC_DRC_EFFECT_TYPE);
-    }
-    else
-    {
+              DRC_KEY_AAC_DRC_EFFECT_TYPE);
+    } else {
         ui_drc_val = DRC_KEY_AAC_DRC_EFFECT_TYPE;
     }
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                              IA_API_CMD_SET_CONFIG_PARAM,
-                              IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE,
-                              &ui_drc_val);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE, &ui_drc_val);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
 
 #endif
     return status;
 }
 
-OMX_ERRORTYPE SoftXAAC::internalGetParameter(
-        OMX_INDEXTYPE index, OMX_PTR params) {
-
-    switch ((OMX_U32) index) {
-
-        case OMX_IndexParamAudioPortFormat:
-        {
-            OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
+OMX_ERRORTYPE SoftXAAC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) {
+    switch ((OMX_U32)index) {
+        case OMX_IndexParamAudioPortFormat: {
+            OMX_AUDIO_PARAM_PORTFORMATTYPE* formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE*)params;
 
             if (!isValidOMXParam(formatParams)) {
                 return OMX_ErrorBadParameter;
@@ -325,16 +295,13 @@
             }
 
             formatParams->eEncoding =
-                (formatParams->nPortIndex == 0)
-                    ? OMX_AUDIO_CodingAAC : OMX_AUDIO_CodingPCM;
+                (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingAAC : OMX_AUDIO_CodingPCM;
 
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAac:
-        {
-            OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
+        case OMX_IndexParamAudioAac: {
+            OMX_AUDIO_PARAM_AACPROFILETYPE* aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE*)params;
 
             if (!isValidOMXParam(aacParams)) {
                 return OMX_ErrorBadParameter;
@@ -351,9 +318,7 @@
             aacParams->eAACProfile = OMX_AUDIO_AACObjectMain;
 
             aacParams->eAACStreamFormat =
-                mIsADTS
-                    ? OMX_AUDIO_AACStreamFormatMP4ADTS
-                    : OMX_AUDIO_AACStreamFormatMP4FF;
+                mIsADTS ? OMX_AUDIO_AACStreamFormatMP4ADTS : OMX_AUDIO_AACStreamFormatMP4FF;
 
             aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo;
 
@@ -370,10 +335,8 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPcm:
-        {
-            OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+        case OMX_IndexParamAudioPcm: {
+            OMX_AUDIO_PARAM_PCMMODETYPE* pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE*)params;
 
             if (!isValidOMXParam(pcmParams)) {
                 return OMX_ErrorBadParameter;
@@ -406,10 +369,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioProfileQuerySupported:
-        {
-            OMX_AUDIO_PARAM_ANDROID_PROFILETYPE *profileParams =
-                (OMX_AUDIO_PARAM_ANDROID_PROFILETYPE *)params;
+        case OMX_IndexParamAudioProfileQuerySupported: {
+            OMX_AUDIO_PARAM_ANDROID_PROFILETYPE* profileParams =
+                (OMX_AUDIO_PARAM_ANDROID_PROFILETYPE*)params;
 
             if (!isValidOMXParam(profileParams)) {
                 return OMX_ErrorBadParameter;
@@ -423,8 +385,7 @@
                 return OMX_ErrorNoMore;
             }
 
-            profileParams->eProfile =
-                kSupportedProfiles[profileParams->nProfileIndex];
+            profileParams->eProfile = kSupportedProfiles[profileParams->nProfileIndex];
 
             return OMX_ErrorNone;
         }
@@ -434,21 +395,17 @@
     }
 }
 
-OMX_ERRORTYPE SoftXAAC::internalSetParameter(
-        OMX_INDEXTYPE index, const OMX_PTR params) {
-
+OMX_ERRORTYPE SoftXAAC::internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params) {
     switch ((int)index) {
-        case OMX_IndexParamStandardComponentRole:
-        {
-            const OMX_PARAM_COMPONENTROLETYPE *roleParams =
-                (const OMX_PARAM_COMPONENTROLETYPE *)params;
+        case OMX_IndexParamStandardComponentRole: {
+            const OMX_PARAM_COMPONENTROLETYPE* roleParams =
+                (const OMX_PARAM_COMPONENTROLETYPE*)params;
 
             if (!isValidOMXParam(roleParams)) {
                 return OMX_ErrorBadParameter;
             }
 
-            if (strncmp((const char *)roleParams->cRole,
-                        "audio_decoder.aac",
+            if (strncmp((const char*)roleParams->cRole, "audio_decoder.aac",
                         OMX_MAX_STRINGNAME_SIZE - 1)) {
                 return OMX_ErrorUndefined;
             }
@@ -456,10 +413,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPortFormat:
-        {
-            const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams =
-                (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params;
+        case OMX_IndexParamAudioPortFormat: {
+            const OMX_AUDIO_PARAM_PORTFORMATTYPE* formatParams =
+                (const OMX_AUDIO_PARAM_PORTFORMATTYPE*)params;
 
             if (!isValidOMXParam(formatParams)) {
                 return OMX_ErrorBadParameter;
@@ -469,20 +425,17 @@
                 return OMX_ErrorUndefined;
             }
 
-            if ((formatParams->nPortIndex == 0
-                        && formatParams->eEncoding != OMX_AUDIO_CodingAAC)
-                || (formatParams->nPortIndex == 1
-                        && formatParams->eEncoding != OMX_AUDIO_CodingPCM)) {
+            if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingAAC) ||
+                (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingPCM)) {
                 return OMX_ErrorUndefined;
             }
 
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAac:
-        {
-            const OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams =
-                (const OMX_AUDIO_PARAM_AACPROFILETYPE *)params;
+        case OMX_IndexParamAudioAac: {
+            const OMX_AUDIO_PARAM_AACPROFILETYPE* aacParams =
+                (const OMX_AUDIO_PARAM_AACPROFILETYPE*)params;
 
             if (!isValidOMXParam(aacParams)) {
                 return OMX_ErrorBadParameter;
@@ -494,8 +447,7 @@
 
             if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4FF) {
                 mIsADTS = false;
-            } else if (aacParams->eAACStreamFormat
-                        == OMX_AUDIO_AACStreamFormatMP4ADTS) {
+            } else if (aacParams->eAACStreamFormat == OMX_AUDIO_AACStreamFormatMP4ADTS) {
                 mIsADTS = true;
             } else {
                 return OMX_ErrorUndefined;
@@ -504,10 +456,9 @@
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioAndroidAacDrcPresentation:
-        {
-            const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE *aacPresParams =
-                    (const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE *)params;
+        case OMX_IndexParamAudioAndroidAacDrcPresentation: {
+            const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE* aacPresParams =
+                (const OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE*)params;
 
             if (!isValidOMXParam(aacPresParams)) {
                 ALOGE("set OMX_ErrorBadParameter");
@@ -524,31 +475,36 @@
             //   nEncodedTargetLevel      idem
             if (aacPresParams->nMaxOutputChannels >= 0) {
                 int max;
-                if (aacPresParams->nMaxOutputChannels >= 8) { max = 8; }
-                else if (aacPresParams->nMaxOutputChannels >= 6) { max = 6; }
-                else if (aacPresParams->nMaxOutputChannels >= 2) { max = 2; }
-                else {
+                if (aacPresParams->nMaxOutputChannels >= 8) {
+                    max = 8;
+                } else if (aacPresParams->nMaxOutputChannels >= 6) {
+                    max = 6;
+                } else if (aacPresParams->nMaxOutputChannels >= 2) {
+                    max = 2;
+                } else {
                     // -1 or 0: disable downmix,  1: mono
                     max = aacPresParams->nMaxOutputChannels;
                 }
             }
             /* Apply DRC Changes */
-            setXAACDRCInfo(aacPresParams->nDrcCut,
-                           aacPresParams->nDrcBoost,
-                           aacPresParams->nTargetReferenceLevel,
-                           aacPresParams->nHeavyCompression
-                          #ifdef ENABLE_MPEG_D_DRC
-                           ,aacPresParams->nDrcEffectType
-                          #endif
-                           );    // TOD0 : Revert this change
+            IA_ERRORCODE err_code = setXAACDRCInfo(aacPresParams->nDrcCut, aacPresParams->nDrcBoost,
+                                                   aacPresParams->nTargetReferenceLevel,
+                                                   aacPresParams->nHeavyCompression
+#ifdef ENABLE_MPEG_D_DRC
+                                                   ,
+                                                   aacPresParams->nDrcEffectType
+#endif
+            );  // TOD0 : Revert this change
+            if (err_code != IA_NO_ERROR) {
+                ALOGE("Error in OMX_IndexParamAudioAndroidAacDrcPresentation");
+                return OMX_ErrorBadParameter;
+            }
 
             return OMX_ErrorNone;
         }
 
-        case OMX_IndexParamAudioPcm:
-        {
-            const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
-                (OMX_AUDIO_PARAM_PCMMODETYPE *)params;
+        case OMX_IndexParamAudioPcm: {
+            const OMX_AUDIO_PARAM_PCMMODETYPE* pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE*)params;
 
             if (!isValidOMXParam(pcmParams)) {
                 return OMX_ErrorBadParameter;
@@ -572,15 +528,15 @@
 
 void SoftXAAC::onQueueFilled(OMX_U32 /* portIndex */) {
     if (mSignalledError || mOutputPortSettingsChange != NONE) {
-        ALOGE("onQueueFilled do not process %d %d",mSignalledError,mOutputPortSettingsChange);
+        ALOGE("onQueueFilled do not process %d %d", mSignalledError, mOutputPortSettingsChange);
         return;
     }
 
-    uint8_t*  inBuffer        = NULL;
-    uint32_t  inBufferLength  = 0;
+    uint8_t* inBuffer = NULL;
+    uint32_t inBufferLength = 0;
 
-    List<BufferInfo *> &inQueue = getPortQueue(0);
-    List<BufferInfo *> &outQueue = getPortQueue(1);
+    List<BufferInfo*>& inQueue = getPortQueue(0);
+    List<BufferInfo*>& outQueue = getPortQueue(1);
 
     signed int numOutBytes = 0;
 
@@ -590,32 +546,30 @@
     /* Note: entire buffer logic to save and retrieve assumes 2 bytes per*/
     /* sample currently                                                  */
     if (mIsCodecInitialized) {
-        numOutBytes = mOutputFrameLength * (mPcmWdSz/8) * mNumChannels;
-        if ((mPcmWdSz/8) != 2) {
-            ALOGE("XAAC assumes 2 bytes per sample! mPcmWdSz %d",mPcmWdSz);
+        numOutBytes = mOutputFrameLength * (mPcmWdSz / 8) * mNumChannels;
+        if ((mPcmWdSz / 8) != 2) {
+            ALOGE("XAAC assumes 2 bytes per sample! mPcmWdSz %d", mPcmWdSz);
         }
     }
 
     while ((!inQueue.empty() || mEndOfInput) && !outQueue.empty()) {
         if (!inQueue.empty()) {
-            BufferInfo *inInfo = *inQueue.begin();
-            OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
+            BufferInfo* inInfo = *inQueue.begin();
+            OMX_BUFFERHEADERTYPE* inHeader = inInfo->mHeader;
 
+            /* No need to check inHeader != NULL, as inQueue is not empty */
             mEndOfInput = (inHeader->nFlags & OMX_BUFFERFLAG_EOS) != 0;
 
             if (mInputBufferCount == 0 && !(inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG)) {
-                ALOGE("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set");
+                ALOGW("first buffer should have OMX_BUFFERFLAG_CODECCONFIG set");
                 inHeader->nFlags |= OMX_BUFFERFLAG_CODECCONFIG;
             }
             if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) != 0) {
-                BufferInfo *inInfo = *inQueue.begin();
-                OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
-
                 inBuffer = inHeader->pBuffer + inHeader->nOffset;
                 inBufferLength = inHeader->nFilledLen;
 
                 /* GA header configuration sent to Decoder! */
-                int err_code = configXAACDecoder(inBuffer,inBufferLength);
+                int err_code = configXAACDecoder(inBuffer, inBufferLength);
                 if (0 != err_code) {
                     ALOGW("configXAACDecoder err_code = %d", err_code);
                     mSignalledError = true;
@@ -623,7 +577,8 @@
                     return;
                 }
                 mInputBufferCount++;
-                mOutputBufferCount++; // fake increase of outputBufferCount to keep the counters aligned
+                mOutputBufferCount++;  // fake increase of outputBufferCount to keep the counters
+                                       // aligned
 
                 inInfo->mOwnedByUs = false;
                 inQueue.erase(inQueue.begin());
@@ -654,34 +609,35 @@
             }
 
             // Restore Offset and Length for Port reconfig case
-            size_t tempOffset =  inHeader->nOffset;
+            size_t tempOffset = inHeader->nOffset;
             size_t tempFilledLen = inHeader->nFilledLen;
             if (mIsADTS) {
-                 size_t adtsHeaderSize = 0;
+                size_t adtsHeaderSize = 0;
                 // skip 30 bits, aac_frame_length follows.
                 // ssssssss ssssiiip ppffffPc ccohCCll llllllll lll?????
 
-                const uint8_t *adtsHeader = inHeader->pBuffer + inHeader->nOffset;
+                const uint8_t* adtsHeader = inHeader->pBuffer + inHeader->nOffset;
 
                 bool signalError = false;
                 if (inHeader->nFilledLen < 7) {
-                    ALOGE("Audio data too short to contain even the ADTS header. "
-                            "Got %d bytes.", inHeader->nFilledLen);
+                    ALOGE(
+                        "Audio data too short to contain even the ADTS header. "
+                        "Got %d bytes.",
+                        inHeader->nFilledLen);
                     hexdump(adtsHeader, inHeader->nFilledLen);
                     signalError = true;
                 } else {
                     bool protectionAbsent = (adtsHeader[1] & 1);
 
                     unsigned aac_frame_length =
-                        ((adtsHeader[3] & 3) << 11)
-                        | (adtsHeader[4] << 3)
-                        | (adtsHeader[5] >> 5);
+                        ((adtsHeader[3] & 3) << 11) | (adtsHeader[4] << 3) | (adtsHeader[5] >> 5);
 
                     if (inHeader->nFilledLen < aac_frame_length) {
-                        ALOGE("Not enough audio data for the complete frame. "
-                                "Got %d bytes, frame size according to the ADTS "
-                                "header is %u bytes.",
-                                inHeader->nFilledLen, aac_frame_length);
+                        ALOGE(
+                            "Not enough audio data for the complete frame. "
+                            "Got %d bytes, frame size according to the ADTS "
+                            "header is %u bytes.",
+                            inHeader->nFilledLen, aac_frame_length);
                         hexdump(adtsHeader, inHeader->nFilledLen);
                         signalError = true;
                     } else {
@@ -689,7 +645,7 @@
                         if (aac_frame_length < adtsHeaderSize) {
                             signalError = true;
                         } else {
-                            inBuffer = (uint8_t *)adtsHeader + adtsHeaderSize;
+                            inBuffer = (uint8_t*)adtsHeader + adtsHeaderSize;
                             inBufferLength = aac_frame_length - adtsHeaderSize;
 
                             inHeader->nOffset += adtsHeaderSize;
@@ -709,8 +665,7 @@
                     mCurrentTimestamp = inHeader->nTimeStamp;
                     mLastInHeader = inHeader;
                 } else {
-                    mCurrentTimestamp = mPrevTimestamp +
-                        mOutputFrameLength  * 1000000ll / mSampFreq;
+                    mCurrentTimestamp = mPrevTimestamp + mOutputFrameLength * 1000000ll / mSampFreq;
                 }
             } else {
                 inBuffer = inHeader->pBuffer + inHeader->nOffset;
@@ -727,7 +682,7 @@
             /* which should initialize the codec. Once this state is reached, call the  */
             /* decodeXAACStream API with same frame to decode!                        */
             if (!mIsCodecInitialized) {
-                int err_code = configXAACDecoder(inBuffer,inBufferLength);
+                int err_code = configXAACDecoder(inBuffer, inBufferLength);
                 if (0 != err_code) {
                     ALOGW("configXAACDecoder Failed 2 err_code = %d", err_code);
                     mSignalledError = true;
@@ -740,15 +695,14 @@
             if (!mSampFreq || !mNumChannels) {
                 if ((mInputBufferCount > 2) && (mOutputBufferCount <= 1)) {
                     ALOGW("Invalid AAC stream");
-                    ALOGW("mSampFreq %d mNumChannels %d ",mSampFreq,mNumChannels);
+                    ALOGW("mSampFreq %d mNumChannels %d ", mSampFreq, mNumChannels);
                     mSignalledError = true;
                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
                     return;
                 }
-            } else if ((mSampFreq != prevSampleRate) ||
-                       (mNumChannels != prevNumChannels)) {
-                ALOGV("Reconfiguring decoder: %d->%d Hz, %d->%d channels",
-                      prevSampleRate, mSampFreq, prevNumChannels, mNumChannels);
+            } else if ((mSampFreq != prevSampleRate) || (mNumChannels != prevNumChannels)) {
+                ALOGV("Reconfiguring decoder: %d->%d Hz, %d->%d channels", prevSampleRate,
+                      mSampFreq, prevNumChannels, mNumChannels);
                 inHeader->nOffset = tempOffset;
                 inHeader->nFilledLen = tempFilledLen;
                 notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
@@ -759,7 +713,8 @@
             signed int bytesConsumed = 0;
             int errorCode = 0;
             if (mIsCodecInitialized) {
-                errorCode = decodeXAACStream(inBuffer,inBufferLength, &bytesConsumed, &numOutBytes);
+                errorCode =
+                    decodeXAACStream(inBuffer, inBufferLength, &bytesConsumed, &numOutBytes);
             } else {
                 ALOGW("Assumption that first frame after header initializes decoder failed!");
             }
@@ -772,31 +727,24 @@
 
             /* In case of error, decoder would have given out empty buffer */
             if ((0 != errorCode) && (0 == numOutBytes) && mIsCodecInitialized) {
-                numOutBytes = mOutputFrameLength * (mPcmWdSz/8) * mNumChannels;
+                numOutBytes = mOutputFrameLength * (mPcmWdSz / 8) * mNumChannels;
             }
             numLoops++;
 
             if (0 == bytesConsumed) {
-                ALOGE("bytesConsumed = 0 should never happen");
-                mSignalledError = true;
-                notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
-                return;
+                ALOGW("bytesConsumed is zero");
             }
 
             if (errorCode) {
                 /* Clear buffer for output buffer is done inside XAAC codec */
                 /* TODO - Check if below memset is on top of reset inside codec */
-                memset(mOutputBuffer, 0, numOutBytes); // TODO: check for overflow, ASAN
-
+                memset(mOutputBuffer, 0, numOutBytes);  // TODO: check for overflow, ASAN
                 // Discard input buffer.
-                if (inHeader) {
-                    inHeader->nFilledLen = 0;
-                }
-
+                inHeader->nFilledLen = 0;
                 // fall through
             }
 
-            if (inHeader && inHeader->nFilledLen == 0) {
+            if (inHeader->nFilledLen == 0) {
                 inInfo->mOwnedByUs = false;
                 mInputBufferCount++;
                 inQueue.erase(inQueue.begin());
@@ -805,12 +753,12 @@
                 notifyEmptyBufferDone(inHeader);
                 inHeader = NULL;
             } else {
-                ALOGV("inHeader->nFilledLen = %d", inHeader ? inHeader->nFilledLen : 0);
+                ALOGV("inHeader->nFilledLen = %d", inHeader->nFilledLen);
             }
 
             if (!outQueue.empty() && numOutBytes) {
-                BufferInfo *outInfo = *outQueue.begin();
-                OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+                BufferInfo* outInfo = *outQueue.begin();
+                OMX_BUFFERHEADERTYPE* outHeader = outInfo->mHeader;
 
                 if (outHeader->nOffset != 0) {
                     ALOGE("outHeader->nOffset != 0 is not handled");
@@ -819,12 +767,10 @@
                     return;
                 }
 
-                signed short *outBuffer =
-                        reinterpret_cast<signed short *>(outHeader->pBuffer + outHeader->nOffset);
+                signed short* outBuffer =
+                    reinterpret_cast<signed short*>(outHeader->pBuffer + outHeader->nOffset);
                 int samplesize = mNumChannels * sizeof(int16_t);
-                if (outHeader->nOffset
-                        + mOutputFrameLength * samplesize
-                        > outHeader->nAllocLen) {
+                if (outHeader->nOffset + mOutputFrameLength * samplesize > outHeader->nAllocLen) {
                     ALOGE("buffer overflow");
                     mSignalledError = true;
                     notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
@@ -857,12 +803,12 @@
                     ALOGV(" empty block signaling EOS");
                     // send partial or empty block signaling EOS
                     mEndOfOutput = true;
-                    BufferInfo *outInfo = *outQueue.begin();
-                    OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
+                    BufferInfo* outInfo = *outQueue.begin();
+                    OMX_BUFFERHEADERTYPE* outHeader = outInfo->mHeader;
 
                     outHeader->nFilledLen = 0;
                     outHeader->nFlags = OMX_BUFFERFLAG_EOS;
-                    outHeader->nTimeStamp = mPrevTimestamp ;
+                    outHeader->nTimeStamp = mPrevTimestamp;
 
                     mOutputBufferCount++;
                     outInfo->mOwnedByUs = false;
@@ -871,7 +817,7 @@
                     notifyFillBufferDone(outHeader);
                     outHeader = NULL;
                 }
-                break; // if outQueue not empty but no more output
+                break;  // if outQueue not empty but no more output
             }
         }
     }
@@ -883,7 +829,10 @@
         // depend on fragments from the last one decoded.
         // drain all existing data
         if (mIsCodecInitialized) {
-            configflushDecode();
+            IA_ERRORCODE err_code = configflushDecode();
+            if (err_code != IA_NO_ERROR) {
+                ALOGE("Error in configflushDecode: Error %d", err_code);
+            }
         }
         drainDecoder();
         mLastInHeader = NULL;
@@ -893,44 +842,39 @@
     }
 }
 
-void SoftXAAC::configflushDecode() {
+int SoftXAAC::configflushDecode() {
     IA_ERRORCODE err_code;
     UWORD32 ui_init_done;
-    uint32_t inBufferLength=8203;
+    uint32_t inBufferLength = 8203;
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_FLUSH_MEM,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_FLUSH_MEM, NULL);
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_FLUSH_MEM");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_INPUT_BYTES,
-                                0,
-                                &inBufferLength);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_FLUSH_MEM,
-                                NULL);
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_FLUSH_MEM, NULL);
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_FLUSH_MEM");
 
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_DONE_QUERY,
                                 &ui_init_done);
-
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_DONE_QUERY");
 
     if (ui_init_done) {
         err_code = getXAACStreamInfo();
-        ALOGV("Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz %d\nchannelMask %d\noutputFrameLength %d",
-                                    mSampFreq,mNumChannels,mPcmWdSz,mChannelMask,mOutputFrameLength);
-        if(mNumChannels > MAX_CHANNEL_COUNT) {
+        RETURN_IF_FATAL(err_code, "getXAACStreamInfo");
+
+        ALOGV(
+            "Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz "
+            "%d\nchannelMask %d\noutputFrameLength %d",
+            mSampFreq, mNumChannels, mPcmWdSz, mChannelMask, mOutputFrameLength);
+        if (mNumChannels > MAX_CHANNEL_COUNT) {
             ALOGE(" No of channels are more than max channels\n");
             mIsCodecInitialized = false;
-        }
-        else
+        } else
             mIsCodecInitialized = true;
     }
-
+    return err_code;
 }
 int SoftXAAC::drainDecoder() {
     return 0;
@@ -959,15 +903,13 @@
         case NONE:
             break;
 
-        case AWAITING_DISABLED:
-        {
+        case AWAITING_DISABLED: {
             CHECK(!enabled);
             mOutputPortSettingsChange = AWAITING_ENABLED;
             break;
         }
 
-        default:
-        {
+        default: {
             CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
             CHECK(enabled);
             mOutputPortSettingsChange = NONE;
@@ -1006,171 +948,157 @@
     /* ******************************************************************/
 
     /* Get the API size */
-    err_code = ixheaacd_dec_api(NULL,
-                                IA_API_CMD_GET_API_SIZE,
-                                0,
-                                &pui_api_size);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_API_SIZE");
+    err_code = ixheaacd_dec_api(NULL, IA_API_CMD_GET_API_SIZE, 0, &pui_api_size);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_API_SIZE");
+
+    if (mMallocCount == MAX_MEM_ALLOCS) {
+        ALOGE("mMemoryArray is full");
+        return IA_FATAL_ERROR;
+    }
 
     /* Allocate memory for API */
     mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
     if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE("malloc for pui_api_size + 4 >> %d Failed",pui_api_size + 4);
+        ALOGE("malloc for pui_api_size + 4 >> %d Failed", pui_api_size + 4);
         return IA_FATAL_ERROR;
     }
     /* Set API object with the memory allocated */
-    mXheaacCodecHandle =
-        (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+    mXheaacCodecHandle = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
     mMallocCount++;
 
     /* Set the config params to default values */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS,
-                                NULL);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT,
+                                IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS, NULL);
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
 #ifdef ENABLE_MPEG_D_DRC
     /* Get the API size */
     err_code = ia_drc_dec_api(NULL, IA_API_CMD_GET_API_SIZE, 0, &pui_api_size);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_API_SIZE");
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_API_SIZE");
 
-   /* Allocate memory for API */
-   mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
+    if (mMallocCount == MAX_MEM_ALLOCS) {
+        ALOGE("mMemoryArray is full");
+        return IA_FATAL_ERROR;
+    }
 
-   if(mMemoryArray[mMallocCount] == NULL)
-   {
-       ALOGE("malloc for drc api structure Failed");
-       return IA_FATAL_ERROR;
-   }
-   memset(mMemoryArray[mMallocCount],0,pui_api_size);
+    /* Allocate memory for API */
+    mMemoryArray[mMallocCount] = memalign(4, pui_api_size);
 
-   /* Set API object with the memory allocated */
-   mMpegDDrcHandle =
-       (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+    if (mMemoryArray[mMallocCount] == NULL) {
+        ALOGE("malloc for drc api structure Failed");
+        return IA_FATAL_ERROR;
+    }
+    memset(mMemoryArray[mMallocCount], 0, pui_api_size);
+
+    /* Set API object with the memory allocated */
+    mMpegDDrcHandle = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
     mMallocCount++;
 
-
     /* Set the config params to default values */
-    err_code = ia_drc_dec_api(
-       mMpegDDrcHandle,
-       IA_API_CMD_INIT,
-       IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS,
-       NULL);
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                              IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS, NULL);
 
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_PRE_CONFIG_PARAMS");
 #endif
 
     /* ******************************************************************/
     /* Set config parameters                                            */
     /* ******************************************************************/
     UWORD32 ui_mp4_flag = 1;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4,
-                                &ui_mp4_flag);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4, &ui_mp4_flag);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_ISMP4");
 
     /* ******************************************************************/
     /* Initialize Memory info tables                                    */
     /* ******************************************************************/
 
     /* Get memory info tables size */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_MEMTABS_SIZE,
-                                0,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEMTABS_SIZE, 0,
                                 &ui_proc_mem_tabs_size);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEMTABS_SIZE");
-    mMemoryArray[mMallocCount] = memalign(4, ui_proc_mem_tabs_size);
-    if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE("Malloc for size (ui_proc_mem_tabs_size + 4) = %d failed!",ui_proc_mem_tabs_size + 4);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEMTABS_SIZE");
+
+    if (mMallocCount == MAX_MEM_ALLOCS) {
+        ALOGE("mMemoryArray is full");
         return IA_FATAL_ERROR;
     }
 
-    /* Set pointer for process memory tables    */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_MEMTABS_PTR,
-                                0,
-                                (pVOID)((WORD8*)mMemoryArray[mMallocCount]));
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_MEMTABS_PTR");
+    mMemoryArray[mMallocCount] = memalign(4, ui_proc_mem_tabs_size);
+    if (mMemoryArray[mMallocCount] == NULL) {
+        ALOGE("Malloc for size (ui_proc_mem_tabs_size + 4) = %d failed!",
+              ui_proc_mem_tabs_size + 4);
+        return IA_FATAL_ERROR;
+    }
     mMallocCount++;
+    /* Set pointer for process memory tables    */
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_MEMTABS_PTR, 0,
+                                (pVOID)((WORD8*)mMemoryArray[mMallocCount - 1]));
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEMTABS_PTR");
+
 
     /* initialize the API, post config, fill memory tables  */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS,
-                                NULL);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT,
+                                IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
 
     /* ******************************************************************/
     /* Allocate Memory with info from library                           */
     /* ******************************************************************/
     /* There are four different types of memories, that needs to be allocated */
     /* persistent,scratch,input and output */
-    for(i = 0; i < 4; i++) {
+    for (i = 0; i < 4; i++) {
         int ui_size = 0, ui_alignment = 0, ui_type = 0;
         pVOID pv_alloc_ptr;
 
         /* Get memory size */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_SIZE,
-                                    i,
-                                    &ui_size);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
 
         /* Get memory alignment */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_ALIGNMENT,
-                                    i,
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i,
                                     &ui_alignment);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
 
         /* Get memory type */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_GET_MEM_INFO_TYPE,
-                                    i,
-                                    &ui_type);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
 
-        mMemoryArray[mMallocCount] =
-            memalign(ui_alignment , ui_size);
-        if (mMemoryArray[mMallocCount] == NULL) {
-            ALOGE("Malloc for size (ui_size + ui_alignment) = %d failed!",ui_size + ui_alignment);
+        if (mMallocCount == MAX_MEM_ALLOCS) {
+            ALOGE("mMemoryArray is full");
             return IA_FATAL_ERROR;
         }
-        pv_alloc_ptr =
-            (pVOID )((WORD8*)mMemoryArray[mMallocCount]);
+        mMemoryArray[mMallocCount] = memalign(ui_alignment, ui_size);
+        if (mMemoryArray[mMallocCount] == NULL) {
+            ALOGE("Malloc for size (ui_size + ui_alignment) = %d failed!", ui_size + ui_alignment);
+            return IA_FATAL_ERROR;
+        }
+        pv_alloc_ptr = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
         mMallocCount++;
 
         /* Set the buffer pointer */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_MEM_PTR,
-                                    i,
-                                    pv_alloc_ptr);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_MEM_PTR");
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
         if (ui_type == IA_MEMTYPE_INPUT) {
             mInputBuffer = (pWORD8)pv_alloc_ptr;
             mInputBufferSize = ui_size;
-
         }
 
         if (ui_type == IA_MEMTYPE_OUTPUT) {
             mOutputBuffer = (pWORD8)pv_alloc_ptr;
         }
-
     }
     /* End first part */
 
-  return IA_NO_ERROR;
+    return IA_NO_ERROR;
 }
 
 int SoftXAAC::configXAACDecoder(uint8_t* inBuffer, uint32_t inBufferLength) {
-
     UWORD32 ui_init_done;
     int32_t i_bytes_consumed;
 
     if (mInputBufferSize < inBufferLength) {
-        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d",mInputBufferSize,inBufferLength);
+        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d", mInputBufferSize,
+              inBufferLength);
         return false;
     }
 
@@ -1178,479 +1106,411 @@
     memcpy(mInputBuffer, inBuffer, inBufferLength);
 
     /* Set number of bytes to be processed */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_SET_INPUT_BYTES,
-                                             0,
-                                             &inBufferLength);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_INPUT_BYTES");
+    IA_ERRORCODE err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
     if (mIsCodecConfigFlushRequired) {
         /* If codec is already initialized, then GA header is passed again */
         /* Need to call the Flush API instead of INIT_PROCESS */
         mIsCodecInitialized = false; /* Codec needs to be Reinitialized after flush */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_GA_HDR,
-                                    NULL);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_GA_HDR");
-    }
-    else {
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_GA_HDR, NULL);
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_GA_HDR");
+    } else {
         /* Initialize the process */
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_PROCESS,
-                                    NULL);
-        ALOGV("IA_CMD_TYPE_INIT_PROCESS returned error_code = %d",err_code);
+        err_code =
+            ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_PROCESS, NULL);
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_PROCESS");
     }
 
     /* Checking for end of initialization */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_DONE_QUERY,
                                 &ui_init_done);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_INIT_DONE_QUERY");
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_DONE_QUERY");
 
     /* How much buffer is used in input buffers */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CURIDX_INPUT_BUF,
-                                0,
-                                &i_bytes_consumed);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CURIDX_INPUT_BUF, 0, &i_bytes_consumed);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
 
-    if(ui_init_done){
+    if (ui_init_done) {
         err_code = getXAACStreamInfo();
-        ALOGI("Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz %d\nchannelMask %d\noutputFrameLength %d",
-                                    mSampFreq,mNumChannels,mPcmWdSz,mChannelMask,mOutputFrameLength);
+        RETURN_IF_FATAL(err_code, "getXAACStreamInfo");
+
+        ALOGI(
+            "Found Codec with below config---\nsampFreq %d\nnumChannels %d\npcmWdSz "
+            "%d\nchannelMask %d\noutputFrameLength %d",
+            mSampFreq, mNumChannels, mPcmWdSz, mChannelMask, mOutputFrameLength);
         mIsCodecInitialized = true;
 
 #ifdef ENABLE_MPEG_D_DRC
-        configMPEGDDrc();
+        err_code = configMPEGDDrc();
+        RETURN_IF_FATAL(err_code, "configMPEGDDrc");
 #endif
     }
 
+    return IA_NO_ERROR;
+}
+int SoftXAAC::configMPEGDDrc() {
+    IA_ERRORCODE err_code = IA_NO_ERROR;
+    int i_effect_type;
+    int i_loud_norm;
+    int i_target_loudness;
+    unsigned int i_sbr_mode;
+    int n_mems;
+    int i;
+
+#ifdef ENABLE_MPEG_D_DRC
+    {
+        /* Sampling Frequency */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ");
+        /* Total Number of Channels */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
+
+        /* PCM word size  */
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ");
+
+        /*Set Effect Type*/
+
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
+
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
+
+        /*Set target loudness */
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS,
+                                    &i_target_loudness);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
+
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
+
+        /*Set loud_norm_flag*/
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
+
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                  IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
+        RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
+
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &i_sbr_mode);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
+
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                  IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
+
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
+
+        for (i = 0; i < (WORD32)2; i++) {
+            WORD32 ui_size, ui_alignment, ui_type;
+            pVOID pv_alloc_ptr;
+
+            /* Get memory size */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
+
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
+
+            /* Get memory alignment */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i,
+                                      &ui_alignment);
+
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
+
+            /* Get memory type */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
+
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
+            pv_alloc_ptr = (pVOID)((WORD8*)mMemoryArray[mMallocCount]);
+            mMallocCount++;
+
+            /* Set the buffer pointer */
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
+
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
+        }
+        {
+            WORD32 ui_size;
+            ui_size = 8192 * 2;
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
+
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
+
+            mDrcInBuf = (int8_t*)mMemoryArray[mMallocCount];
+            mMallocCount++;
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, 2,
+                                      /*mOutputBuffer*/ mDrcInBuf);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
+
+            if (mMallocCount == MAX_MEM_ALLOCS) {
+                ALOGE("mMemoryArray is full");
+                return IA_FATAL_ERROR;
+            }
+            mMemoryArray[mMallocCount] = memalign(4, ui_size);
+            if (mMemoryArray[mMallocCount] == NULL) {
+                ALOGE(" Cannot create requested memory  %d", ui_size);
+                return IA_FATAL_ERROR;
+            }
+
+            mDrcOutBuf = (int8_t*)mMemoryArray[mMallocCount];
+            mMallocCount++;
+            err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR, 3,
+                                      /*mOutputBuffer*/ mDrcOutBuf);
+            RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_MEM_PTR");
+        }
+        /* DRC buffers
+            buf[0] - contains extension element pay load loudness related
+            buf[1] - contains extension element pay load*/
+        {
+            VOID* p_array[2][16];
+            WORD32 ii;
+            WORD32 buf_sizes[2][16];
+            WORD32 num_elements;
+            WORD32 num_config_ext;
+            WORD32 bit_str_fmt = 1;
+
+            WORD32 uo_num_chan;
+
+            memset(buf_sizes, 0, 32 * sizeof(WORD32));
+
+            err_code =
+                ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                 IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES, &buf_sizes[0][0]);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR, &p_array);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR");
+
+            err_code =
+                ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT, IA_CMD_TYPE_INIT_SET_BUFF_PTR, 0);
+            RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_SET_BUFF_PTR");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE, &num_elements);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE");
+
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT, &num_config_ext);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT");
+
+            for (ii = 0; ii < num_config_ext; ii++) {
+                /*copy loudness bitstream*/
+                if (buf_sizes[0][ii] > 0) {
+                    memcpy(mDrcInBuf, p_array[0][ii], buf_sizes[0][ii]);
+
+                    /*Set bitstream_split_format */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+
+                    /* Set number of bytes to be processed */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_IL_BS, 0,
+                                              &buf_sizes[0][ii]);
+                    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IL_BS");
+
+                    /* Execute process */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                              IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF, NULL);
+                    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF");
+
+                    mDRCFlag = 1;
+                }
+            }
+
+            for (ii = 0; ii < num_elements; ii++) {
+                /*copy config bitstream*/
+                if (buf_sizes[1][ii] > 0) {
+                    memcpy(mDrcInBuf, p_array[1][ii], buf_sizes[1][ii]);
+                    /* Set number of bytes to be processed */
+
+                    /*Set bitstream_split_format */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
+
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_IC_BS, 0,
+                                              &buf_sizes[1][ii]);
+                    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES_IC_BS");
+
+                    /* Execute process */
+                    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                              IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF, NULL);
+
+                    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF");
+
+                    mDRCFlag = 1;
+                }
+            }
+
+            if (mDRCFlag == 1) {
+                mMpegDDRCPresent = 1;
+            } else {
+                mMpegDDRCPresent = 0;
+            }
+
+            /*Read interface buffer config file bitstream*/
+            if (mMpegDDRCPresent == 1) {
+                WORD32 interface_is_present = 1;
+                WORD32 frame_length;
+
+                if (i_sbr_mode != 0) {
+                    if (i_sbr_mode == 1) {
+                        frame_length = 2048;
+                    } else if (i_sbr_mode == 3) {
+                        frame_length = 4096;
+                    } else {
+                        frame_length = 1024;
+                    }
+                } else {
+                    frame_length = 4096;
+                }
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE, &frame_length);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE");
+
+                err_code =
+                    ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                   IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT, &interface_is_present);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT");
+
+                /* Execute process */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF, NULL);
+                RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF");
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_PROCESS, NULL);
+                RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_INIT_PROCESS");
+
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &uo_num_chan);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
+            }
+        }
+    }
+#endif
+
     return err_code;
 }
-int SoftXAAC::configMPEGDDrc()
-{
-   IA_ERRORCODE err_code = IA_NO_ERROR;
-   int i_effect_type;
-   int i_loud_norm;
-   int i_target_loudness;
-   unsigned int i_sbr_mode;
-   int n_mems;
-   int i;
-
-#ifdef     ENABLE_MPEG_D_DRC
-    {
-
-    /* Sampling Frequency */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
-      RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_PARAM_SAMP_FREQ");
-    }
-    /* Total Number of Channels */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
-      RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS");
-    }
-
-    /* PCM word size  */
-    {
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                         IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
-      RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_PARAM_PCM_WDSZ");
-    }
-
-    /*Set Effect Type*/
-
-    {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
-
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
-
-    }
-
-/*Set target loudness */
-
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
-
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
-
-    }
-
-    /*Set loud_norm_flag*/
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_NE(err_code, IA_NO_ERROR , err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
-
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_NE(err_code, IA_NO_ERROR , err_code,"IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
-
-    }
-
-
-
-    err_code = ixheaacd_dec_api(
-        mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-        IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &i_sbr_mode);
-        RETURN_IF_NE(err_code, IA_NO_ERROR , err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
-
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                              IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS, NULL);
-
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_INIT_API_POST_CONFIG_PARAMS");
-
-
-
-    for (i = 0; i < (WORD32)2; i++) {
-      WORD32 ui_size, ui_alignment, ui_type;
-      pVOID pv_alloc_ptr;
-
-      /* Get memory size */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_GET_MEM_INFO_SIZE, i, &ui_size);
-
-     RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_SIZE");
-
-      /* Get memory alignment */
-      err_code =
-          ia_drc_dec_api(mMpegDDrcHandle,
-                         IA_API_CMD_GET_MEM_INFO_ALIGNMENT, i, &ui_alignment);
-
-      RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_ALIGNMENT");
-
-      /* Get memory type */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_GET_MEM_INFO_TYPE, i, &ui_type);
-
-     RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_MEM_INFO_TYPE");
-
-
-      mMemoryArray[mMallocCount] = memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-        pv_alloc_ptr =
-            (pVOID )((WORD8*)mMemoryArray[mMallocCount]);
-        mMallocCount++;
-
-           /* Set the buffer pointer */
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_SET_MEM_PTR, i, pv_alloc_ptr);
-
-      RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_MEM_PTR");
-    }
-    {
-    WORD32 ui_size;
-    ui_size=8192*2;
-    mMemoryArray[mMallocCount]=memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-
-    drc_ip_buf=(int8_t *)mMemoryArray[mMallocCount];
-    mMallocCount++;
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR,
-                              2, /*mOutputBuffer*/ drc_ip_buf);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_MEM_PTR");
-
-    mMemoryArray[mMallocCount]=memalign(4, ui_size);
-      if (mMemoryArray[mMallocCount] == NULL) {
-        ALOGE(" Cannot create requested memory  %d",ui_size);
-        return IA_FATAL_ERROR;
-      }
-
-    drc_op_buf=(int8_t *)mMemoryArray[mMallocCount];
-    mMallocCount++;
-    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_MEM_PTR,
-                              3, /*mOutputBuffer*/ drc_op_buf);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_MEM_PTR");
-    }
-    /*ITTIAM: DRC buffers
-            buf[0] - contains extension element pay load loudness related
-            buf[1] - contains extension element pay load*/
-    {
-      VOID *p_array[2][16];
-      WORD32 ii;
-      WORD32 buf_sizes[2][16];
-      WORD32 num_elements;
-      WORD32 num_config_ext;
-      WORD32 bit_str_fmt = 1;
-
-
-
-      WORD32 uo_num_chan;
-
-      memset(buf_sizes, 0, 32 * sizeof(WORD32));
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_BUF_SIZES, &buf_sizes[0][0]);
-
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_EXT_ELE_PTR, &p_array);
-
-
-      err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                IA_CMD_TYPE_INIT_SET_BUFF_PTR, 0);
-
-
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_NUM_ELE, &num_elements);
-
-      err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-          IA_ENHAACPLUS_DEC_CONFIG_NUM_CONFIG_EXT, &num_config_ext);
-
-      for (ii = 0; ii < num_config_ext; ii++) {
-        /*copy loudness bitstream*/
-        if (buf_sizes[0][ii] > 0) {
-          memcpy(drc_ip_buf, p_array[0][ii], buf_sizes[0][ii]);
-
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
-
-          /* Set number of bytes to be processed */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                    IA_API_CMD_SET_INPUT_BYTES_IL_BS, 0,
-                                    &buf_sizes[0][ii]);
-
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_IL_BSF_BUFF, NULL);
-
-
-
-          drc_flag = 1;
-        }
-      }
-
-      for (ii = 0; ii < num_elements; ii++) {
-        /*copy config bitstream*/
-        if (buf_sizes[1][ii] > 0) {
-          memcpy(drc_ip_buf, p_array[1][ii], buf_sizes[1][ii]);
-          /* Set number of bytes to be processed */
-
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
-
-          err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                    IA_API_CMD_SET_INPUT_BYTES_IC_BS, 0,
-                                    &buf_sizes[1][ii]);
-
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_IC_BSF_BUFF, NULL);
-
-
-
-          drc_flag = 1;
-        }
-      }
-
-      if (drc_flag == 1) {
-        mpegd_drc_present = 1;
-      } else {
-        mpegd_drc_present = 0;
-      }
-
-
-      /*Read interface buffer config file bitstream*/
-      if(mpegd_drc_present==1){
-
-        WORD32 interface_is_present = 1;
-        WORD32 frame_length;
-
-        if(i_sbr_mode != 0)
-        {
-            if (i_sbr_mode == 1)
-            {
-                frame_length = 2048;
-            }
-            else if(i_sbr_mode == 3)
-            {
-                frame_length = 4096;
-            }
-            else
-            {
-                frame_length = 1024;
-            }
-        }
-        else
-        {
-            frame_length = 4096;
-        }
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE, &frame_length);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_PARAM_FRAME_SIZE");
-
-
-
-        err_code = ia_drc_dec_api(
-            mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-            IA_DRC_DEC_CONFIG_PARAM_INT_PRESENT, &interface_is_present);
-
-
-
-        /* Execute process */
-        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                  IA_CMD_TYPE_INIT_CPY_IN_BSF_BUFF, NULL);
-
-
-        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                  IA_CMD_TYPE_INIT_PROCESS, NULL);
-
-
-        err_code = ia_drc_dec_api(
-            mMpegDDrcHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_DRC_DEC_CONFIG_PARAM_NUM_CHANNELS, &uo_num_chan);
-
-      }
-    }
-  }
-#endif
-
-return err_code;
-
-}
-int SoftXAAC::decodeXAACStream(uint8_t* inBuffer,
-                               uint32_t inBufferLength,
-                               int32_t *bytesConsumed,
-                               int32_t *outBytes) {
+int SoftXAAC::decodeXAACStream(uint8_t* inBuffer, uint32_t inBufferLength, int32_t* bytesConsumed,
+                               int32_t* outBytes) {
     if (mInputBufferSize < inBufferLength) {
-        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d",mInputBufferSize,inBufferLength);
+        ALOGE("Cannot config AAC, input buffer size %d < inBufferLength %d", mInputBufferSize,
+              inBufferLength);
         return -1;
     }
 
     /* Copy the buffer passed by Android plugin to codec input buffer */
-    memcpy(mInputBuffer,inBuffer,inBufferLength);
+    memcpy(mInputBuffer, inBuffer, inBufferLength);
 
     /* Set number of bytes to be processed */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_SET_INPUT_BYTES,
-                                             0,
-                                             &inBufferLength);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_SET_INPUT_BYTES");
+    IA_ERRORCODE err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_INPUT_BYTES, 0, &inBufferLength);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
     /* Execute process */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DO_EXECUTE,
-                                NULL);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_DO_EXECUTE");
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DO_EXECUTE, NULL);
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DO_EXECUTE");
 
     UWORD32 ui_exec_done;
     /* Checking for end of processing */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DONE_QUERY,
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DONE_QUERY,
                                 &ui_exec_done);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_CMD_TYPE_DONE_QUERY");
+    RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DONE_QUERY");
 
 #ifdef ENABLE_MPEG_D_DRC
-     {
-      if (ui_exec_done != 1) {
-        VOID *p_array;        // ITTIAM:buffer to handle gain payload
-        WORD32 buf_size = 0;  // ITTIAM:gain payload length
-        WORD32 bit_str_fmt = 1;
-        WORD32 gain_stream_flag = 1;
+    {
+        if (ui_exec_done != 1) {
+            VOID* p_array;        // ITTIAM:buffer to handle gain payload
+            WORD32 buf_size = 0;  // ITTIAM:gain payload length
+            WORD32 bit_str_fmt = 1;
+            WORD32 gain_stream_flag = 1;
 
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN, &buf_size);
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN, &buf_size);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_LEN");
 
+            err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                        IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF, &p_array);
+            RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF");
 
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_GAIN_PAYLOAD_BUF, &p_array);
+            if (buf_size > 0) {
+                /*Set bitstream_split_format */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
+                memcpy(mDrcInBuf, p_array, buf_size);
+                /* Set number of bytes to be processed */
+                err_code =
+                    ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES_BS, 0, &buf_size);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-        if (buf_size > 0) {
-          /*Set bitstream_split_format */
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT, &bit_str_fmt);
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                          IA_DRC_DEC_CONFIG_GAIN_STREAM_FLAG, &gain_stream_flag);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-          memcpy(drc_ip_buf, p_array, buf_size);
-          /* Set number of bytes to be processed */
-          err_code =
-              ia_drc_dec_api(mMpegDDrcHandle,
-                             IA_API_CMD_SET_INPUT_BYTES_BS, 0, &buf_size);
+                /* Execute process */
+                err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
+                                          IA_CMD_TYPE_INIT_CPY_BSF_BUFF, NULL);
+                RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_PARAM_BITS_FORMAT");
 
-          err_code = ia_drc_dec_api(
-              mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-              IA_DRC_DEC_CONFIG_GAIN_STREAM_FLAG, &gain_stream_flag);
-
-
-          /* Execute process */
-          err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_INIT,
-                                    IA_CMD_TYPE_INIT_CPY_BSF_BUFF, NULL);
-
-
-          mpegd_drc_present = 1;
+                mMpegDDRCPresent = 1;
+            }
         }
-      }
     }
 #endif
     /* How much buffer is used in input buffers */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CURIDX_INPUT_BUF,
-                                0,
-                                bytesConsumed);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CURIDX_INPUT_BUF, 0, bytesConsumed);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_CURIDX_INPUT_BUF");
 
     /* Get the output bytes */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_OUTPUT_BYTES,
-                                0,
-                                outBytes);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_GET_OUTPUT_BYTES");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_OUTPUT_BYTES, 0, outBytes);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_GET_OUTPUT_BYTES");
 #ifdef ENABLE_MPEG_D_DRC
 
-    if (mpegd_drc_present == 1) {
-      memcpy(drc_ip_buf, mOutputBuffer, *outBytes);
-      err_code = ia_drc_dec_api(mMpegDDrcHandle,
-                                IA_API_CMD_SET_INPUT_BYTES, 0, outBytes);
+    if (mMpegDDRCPresent == 1) {
+        memcpy(mDrcInBuf, mOutputBuffer, *outBytes);
+        err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_INPUT_BYTES, 0, outBytes);
+        RETURN_IF_FATAL(err_code, "IA_API_CMD_SET_INPUT_BYTES");
 
+        err_code =
+            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_EXECUTE, IA_CMD_TYPE_DO_EXECUTE, NULL);
+        RETURN_IF_FATAL(err_code, "IA_CMD_TYPE_DO_EXECUTE");
 
-      err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_EXECUTE,
-                                IA_CMD_TYPE_DO_EXECUTE, NULL);
-
-      memcpy(mOutputBuffer, drc_op_buf, *outBytes);
+        memcpy(mOutputBuffer, mDrcOutBuf, *outBytes);
     }
 #endif
     return err_code;
@@ -1660,16 +1520,11 @@
     ALOGI("deInitXAACDecoder");
 
     /* Tell that the input is over in this buffer */
-    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                             IA_API_CMD_INPUT_OVER,
-                                             0,
-                                             NULL);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_API_CMD_INPUT_OVER");
+    IA_ERRORCODE err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_INPUT_OVER, 0, NULL);
+    RETURN_IF_FATAL(err_code, "IA_API_CMD_INPUT_OVER");
 
-    for(int i = 0; i < mMallocCount; i++)
-    {
-        if(mMemoryArray[i])
-            free(mMemoryArray[i]);
+    for (int i = 0; i < mMallocCount; i++) {
+        if (mMemoryArray[i]) free(mMemoryArray[i]);
     }
     mMallocCount = 0;
 
@@ -1680,59 +1535,47 @@
     IA_ERRORCODE err_code = IA_NO_ERROR;
 
     /* Sampling frequency */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ,
-                                &mSampFreq);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ, &mSampFreq);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SAMP_FREQ");
 
     /* Total Number of Channels */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS,
-                                &mNumChannels);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS, &mNumChannels);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_NUM_CHANNELS");
 
     /* PCM word size */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ,
-                                &mPcmWdSz);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ, &mPcmWdSz);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_PCM_WDSZ");
 
     /* channel mask to tell the arrangement of channels in bit stream */
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK,
-                                &mChannelMask);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK, &mChannelMask);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MASK");
 
     /* Channel mode to tell MONO/STEREO/DUAL-MONO/NONE_OF_THESE */
     UWORD32 ui_channel_mode;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE,
-                                &ui_channel_mode);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE");
-    if(ui_channel_mode == 0)
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE, &ui_channel_mode);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_CHANNEL_MODE");
+    if (ui_channel_mode == 0)
         ALOGV("Channel Mode: MONO_OR_PS\n");
-    else if(ui_channel_mode == 1)
+    else if (ui_channel_mode == 1)
         ALOGV("Channel Mode: STEREO\n");
-    else if(ui_channel_mode == 2)
+    else if (ui_channel_mode == 2)
         ALOGV("Channel Mode: DUAL-MONO\n");
     else
         ALOGV("Channel Mode: NONE_OF_THESE or MULTICHANNEL\n");
 
     /* Channel mode to tell SBR PRESENT/NOT_PRESENT */
     UWORD32 ui_sbr_mode;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_GET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE,
-                                &ui_sbr_mode);
-    RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
-    if(ui_sbr_mode == 0)
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE, &ui_sbr_mode);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_SBR_MODE");
+    if (ui_sbr_mode == 0)
         ALOGV("SBR Mode: NOT_PRESENT\n");
-    else if(ui_sbr_mode == 1)
+    else if (ui_sbr_mode == 1)
         ALOGV("SBR Mode: PRESENT\n");
     else
         ALOGV("SBR Mode: ILLEGAL\n");
@@ -1742,132 +1585,103 @@
     /* not yet added in codec                            */
     mOutputFrameLength = 1024 * (1 + ui_sbr_mode);
 
-    ALOGI("mOutputFrameLength %d ui_sbr_mode %d",mOutputFrameLength,ui_sbr_mode);
+    ALOGI("mOutputFrameLength %d ui_sbr_mode %d", mOutputFrameLength, ui_sbr_mode);
 
     return IA_NO_ERROR;
 }
 
-IA_ERRORCODE SoftXAAC::setXAACDRCInfo(int32_t drcCut,
-                                      int32_t drcBoost,
-                                      int32_t drcRefLevel,
+IA_ERRORCODE SoftXAAC::setXAACDRCInfo(int32_t drcCut, int32_t drcBoost, int32_t drcRefLevel,
                                       int32_t drcHeavyCompression
-                                #ifdef ENABLE_MPEG_D_DRC
-                                      ,int32_t drEffectType
-                                #endif
-                                      ) {
+#ifdef ENABLE_MPEG_D_DRC
+                                      ,
+                                      int32_t drEffectType
+#endif
+) {
     IA_ERRORCODE err_code = IA_NO_ERROR;
 
     int32_t ui_drc_enable = 1;
     int32_t i_effect_type, i_target_loudness, i_loud_norm;
-    err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                IA_API_CMD_SET_CONFIG_PARAM,
-                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE,
-                                &ui_drc_enable);
-     RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE");
-    if (drcCut !=-1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT,
-                                    &drcCut);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE, &ui_drc_enable);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_ENABLE");
+    if (drcCut != -1) {
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT, &drcCut);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_CUT");
     }
 
-    if (drcBoost !=-1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST,
-                                    &drcBoost);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
+    if (drcBoost != -1) {
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST, &drcBoost);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_BOOST");
     }
 
     if (drcRefLevel != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL,
-                                    &drcRefLevel);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL, &drcRefLevel);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LEVEL");
     }
 #ifdef ENABLE_MPEG_D_DRC
     if (drcRefLevel != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS,
-                                    &drcRefLevel);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
+        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                    IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS, &drcRefLevel);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_TARGET_LOUDNESS");
     }
 #endif
     if (drcHeavyCompression != -1) {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP,
-                                    &drcHeavyCompression);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
+        err_code =
+            ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                             IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP, &drcHeavyCompression);
+        RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_HEAVY_COMP");
     }
 
 #ifdef ENABLE_MPEG_D_DRC
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle,
-                                    IA_API_CMD_SET_CONFIG_PARAM,
-                                    IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE,
-                                    &drEffectType);
-
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE, &drEffectType);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_DRC_EFFECT_TYPE");
 #endif
 
 #ifdef ENABLE_MPEG_D_DRC
     /*Set Effect Type*/
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
 
-    {
-        err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE, &i_effect_type);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_EFFECT_TYPE");
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
 
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE, &i_effect_type);
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
 
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_DRC_EFFECT_TYPE");
+    /*Set target loudness */
+    err_code =
+        ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                         IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
 
-    }
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
 
-/*Set target loudness */
-
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_TARGET_LOUDNESS");
-
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS, &i_target_loudness);
-        RETURN_IF_NE(err_code, IA_NO_ERROR, err_code, "IA_DRC_DEC_CONFIG_DRC_TARGET_LOUDNESS");
-
-    }
     /*Set loud_norm_flag*/
-    {
-        err_code = ixheaacd_dec_api(
-            mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
-            IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
-        RETURN_IF_NE(err_code, IA_NO_ERROR , err_code,"IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
+    err_code = ixheaacd_dec_api(mXheaacCodecHandle, IA_API_CMD_GET_CONFIG_PARAM,
+                                IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM, &i_loud_norm);
+    RETURN_IF_FATAL(err_code, "IA_ENHAACPLUS_DEC_CONFIG_PARAM_DRC_LOUD_NORM");
 
-        err_code =
-            ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
-                IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
+    err_code = ia_drc_dec_api(mMpegDDrcHandle, IA_API_CMD_SET_CONFIG_PARAM,
+                              IA_DRC_DEC_CONFIG_DRC_LOUD_NORM, &i_loud_norm);
 
-        RETURN_IF_NE(err_code, IA_NO_ERROR , err_code,"IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
-
-    }
+    RETURN_IF_FATAL(err_code, "IA_DRC_DEC_CONFIG_DRC_LOUD_NORM");
 
 #endif
 
-
     return IA_NO_ERROR;
 }
 
 }  // namespace android
 
-android::SoftOMXComponent *createSoftOMXComponent(
-        const char *name, const OMX_CALLBACKTYPE *callbacks,
-        OMX_PTR appData, OMX_COMPONENTTYPE **component) {
+android::SoftOMXComponent* createSoftOMXComponent(const char* name,
+                                                  const OMX_CALLBACKTYPE* callbacks,
+                                                  OMX_PTR appData, OMX_COMPONENTTYPE** component) {
     ALOGI("createSoftOMXComponent for SoftXAACDEC");
     return new android::SoftXAAC(name, callbacks, appData, component);
 }
diff --git a/media/libstagefright/codecs/xaacdec/SoftXAAC.h b/media/libstagefright/codecs/xaacdec/SoftXAAC.h
index 11a9c77..6176082 100644
--- a/media/libstagefright/codecs/xaacdec/SoftXAAC.h
+++ b/media/libstagefright/codecs/xaacdec/SoftXAAC.h
@@ -35,59 +35,49 @@
 
 #define MAX_MEM_ALLOCS 100
 
-extern "C" IA_ERRORCODE ixheaacd_dec_api(pVOID p_ia_module_obj,
-                        WORD32 i_cmd, WORD32 i_idx, pVOID pv_value);
-extern "C" IA_ERRORCODE ia_drc_dec_api(pVOID p_ia_module_obj,
-                        WORD32 i_cmd, WORD32 i_idx, pVOID pv_value);
-extern "C"  IA_ERRORCODE ixheaacd_get_config_param(pVOID p_ia_process_api_obj,
-                                       pWORD32 pi_samp_freq,
-                                       pWORD32 pi_num_chan,
-                                       pWORD32 pi_pcm_wd_sz,
-                                       pWORD32 pi_channel_mask);
+extern "C" IA_ERRORCODE ixheaacd_dec_api(pVOID p_ia_module_obj, WORD32 i_cmd, WORD32 i_idx,
+                                         pVOID pv_value);
+extern "C" IA_ERRORCODE ia_drc_dec_api(pVOID p_ia_module_obj, WORD32 i_cmd, WORD32 i_idx,
+                                       pVOID pv_value);
+extern "C" IA_ERRORCODE ixheaacd_get_config_param(pVOID p_ia_process_api_obj, pWORD32 pi_samp_freq,
+                                                  pWORD32 pi_num_chan, pWORD32 pi_pcm_wd_sz,
+                                                  pWORD32 pi_channel_mask);
 
 namespace android {
 
 struct SoftXAAC : public SimpleSoftOMXComponent {
-    SoftXAAC(const char *name,
-            const OMX_CALLBACKTYPE *callbacks,
-            OMX_PTR appData,
-            OMX_COMPONENTTYPE **component);
+    SoftXAAC(const char* name, const OMX_CALLBACKTYPE* callbacks, OMX_PTR appData,
+             OMX_COMPONENTTYPE** component);
 
-protected:
+   protected:
     virtual ~SoftXAAC();
 
-    virtual OMX_ERRORTYPE internalGetParameter(
-            OMX_INDEXTYPE index, OMX_PTR params);
+    virtual OMX_ERRORTYPE internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params);
 
-    virtual OMX_ERRORTYPE internalSetParameter(
-            OMX_INDEXTYPE index, const OMX_PTR params);
+    virtual OMX_ERRORTYPE internalSetParameter(OMX_INDEXTYPE index, const OMX_PTR params);
 
     virtual void onQueueFilled(OMX_U32 portIndex);
     virtual void onPortFlushCompleted(OMX_U32 portIndex);
     virtual void onPortEnableCompleted(OMX_U32 portIndex, bool enabled);
     virtual void onReset();
 
-private:
+   private:
     enum {
-        kNumInputBuffers        = 4,
-        kNumOutputBuffers       = 4,
-        kNumDelayBlocksMax      = 8,
+        kNumInputBuffers = 4,
+        kNumOutputBuffers = 4,
+        kNumDelayBlocksMax = 8,
     };
 
     bool mIsADTS;
     size_t mInputBufferCount;
     size_t mOutputBufferCount;
     bool mSignalledError;
-    OMX_BUFFERHEADERTYPE *mLastInHeader;
+    OMX_BUFFERHEADERTYPE* mLastInHeader;
     int64_t mPrevTimestamp;
     int64_t mCurrentTimestamp;
     uint32_t mBufSize;
 
-    enum {
-        NONE,
-        AWAITING_DISABLED,
-        AWAITING_ENABLED
-    } mOutputPortSettingsChange;
+    enum { NONE, AWAITING_DISABLED, AWAITING_ENABLED } mOutputPortSettingsChange;
 
     void initPorts();
     status_t initDecoder();
@@ -98,48 +88,43 @@
 
     int configXAACDecoder(uint8_t* inBuffer, uint32_t inBufferLength);
     int configMPEGDDrc();
-    int decodeXAACStream(uint8_t* inBuffer,
-                         uint32_t inBufferLength,
-                         int32_t *bytesConsumed,
-                         int32_t *outBytes);
+    int decodeXAACStream(uint8_t* inBuffer, uint32_t inBufferLength, int32_t* bytesConsumed,
+                         int32_t* outBytes);
 
-    void configflushDecode();
+    int configflushDecode();
     IA_ERRORCODE getXAACStreamInfo();
-    IA_ERRORCODE setXAACDRCInfo(int32_t drcCut,
-                                int32_t drcBoost,
-                                int32_t drcRefLevel,
+    IA_ERRORCODE setXAACDRCInfo(int32_t drcCut, int32_t drcBoost, int32_t drcRefLevel,
                                 int32_t drcHeavyCompression
 #ifdef ENABLE_MPEG_D_DRC
-                                ,int32_t drEffectType
+                                ,
+                                int32_t drEffectType
 #endif
-                               );
+    );
 
     bool mEndOfInput;
     bool mEndOfOutput;
 
-    void*       mXheaacCodecHandle;
-    void*       mMpegDDrcHandle;
-    uint32_t    mInputBufferSize;
-    uint32_t    mOutputFrameLength;
-    int8_t*     mInputBuffer;
-    int8_t*     mOutputBuffer;
-    int32_t     mSampFreq;
-    int32_t     mNumChannels;
-    int32_t     mPcmWdSz;
-    int32_t     mChannelMask;
-    bool        mIsCodecInitialized;
-    bool        mIsCodecConfigFlushRequired;
-    int8_t *drc_ip_buf;
-    int8_t *drc_op_buf;
-    int32_t mpegd_drc_present;
-    int32_t drc_flag;
-//    int32_t is_drc_enabled;
+    void* mXheaacCodecHandle;
+    void* mMpegDDrcHandle;
+    uint32_t mInputBufferSize;
+    uint32_t mOutputFrameLength;
+    int8_t* mInputBuffer;
+    int8_t* mOutputBuffer;
+    int32_t mSampFreq;
+    int32_t mNumChannels;
+    int32_t mPcmWdSz;
+    int32_t mChannelMask;
+    bool mIsCodecInitialized;
+    bool mIsCodecConfigFlushRequired;
+    int8_t* mDrcInBuf;
+    int8_t* mDrcOutBuf;
+    int32_t mMpegDDRCPresent;
+    int32_t mDRCFlag;
 
-    void*       mMemoryArray[MAX_MEM_ALLOCS];
-    int32_t     mMallocCount;
+    void* mMemoryArray[MAX_MEM_ALLOCS];
+    int32_t mMallocCount;
 
     DISALLOW_EVIL_CONSTRUCTORS(SoftXAAC);
-
 };
 
 }  // namespace android
diff --git a/media/utils/ServiceUtilities.cpp b/media/utils/ServiceUtilities.cpp
index 6a90bea..0d50be0 100644
--- a/media/utils/ServiceUtilities.cpp
+++ b/media/utils/ServiceUtilities.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#define LOG_TAG "ServiceUtilities"
+
 #include <binder/AppOpsManager.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
@@ -172,4 +174,29 @@
     return ok;
 }
 
+status_t checkIMemory(const sp<IMemory>& iMemory)
+{
+    if (iMemory == 0) {
+        ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
+        return BAD_VALUE;
+    }
+
+    sp<IMemoryHeap> heap = iMemory->getMemory();
+    if (heap == 0) {
+        ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
+        return BAD_VALUE;
+    }
+
+    off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
+    lseek(heap->getHeapID(), 0, SEEK_SET);
+
+    if (iMemory->pointer() == NULL || size < (off_t)iMemory->size()) {
+        ALOGE("%s check failed: pointer %p size %zu fd size %u",
+              __FUNCTION__, iMemory->pointer(), iMemory->size(), (uint32_t)size);
+        return BAD_VALUE;
+    }
+
+    return NO_ERROR;
+}
+
 } // namespace android
diff --git a/media/utils/include/mediautils/ServiceUtilities.h b/media/utils/include/mediautils/ServiceUtilities.h
index 2bdba5e..0911744 100644
--- a/media/utils/include/mediautils/ServiceUtilities.h
+++ b/media/utils/include/mediautils/ServiceUtilities.h
@@ -16,6 +16,7 @@
 
 #include <unistd.h>
 
+#include <binder/IMemory.h>
 #include <binder/PermissionController.h>
 #include <cutils/multiuser.h>
 #include <private/android_filesystem_config.h>
@@ -69,4 +70,5 @@
 bool modifyAudioRoutingAllowed();
 bool dumpAllowed();
 bool modifyPhoneStateAllowed(pid_t pid, uid_t uid);
+status_t checkIMemory(const sp<IMemory>& iMemory);
 }
diff --git a/services/audioflinger/PlaybackTracks.h b/services/audioflinger/PlaybackTracks.h
index 3381e77..a93899b 100644
--- a/services/audioflinger/PlaybackTracks.h
+++ b/services/audioflinger/PlaybackTracks.h
@@ -244,7 +244,7 @@
                                     AudioSystem::SYNC_EVENT_NONE,
                              audio_session_t triggerSession = AUDIO_SESSION_NONE);
     virtual void        stop();
-            bool        write(void* data, uint32_t frames);
+            ssize_t     write(void* data, uint32_t frames);
             bool        bufferQueueEmpty() const { return mBufferQueue.size() == 0; }
             bool        isActive() const { return mActive; }
     const wp<ThreadBase>& thread() const { return mThread; }
@@ -252,6 +252,18 @@
             void        copyMetadataTo(MetadataInserter& backInserter) const override;
     /** Set the metadatas of the upstream tracks. Thread safe. */
             void        setMetadatas(const SourceMetadatas& metadatas);
+    /** returns client timestamp to the upstream duplicating thread. */
+    ExtendedTimestamp   getClientProxyTimestamp() const {
+                            // server - kernel difference is not true latency when drained
+                            // i.e. mServerProxy->isDrained().
+                            ExtendedTimestamp timestamp;
+                            (void) mClientProxy->getTimestamp(&timestamp);
+                            // On success, the timestamp LOCATION_SERVER and LOCATION_KERNEL
+                            // entries will be properly filled. If getTimestamp()
+                            // is unsuccessful, then a default initialized timestamp
+                            // (with mTimeNs[] filled with -1's) is returned.
+                            return timestamp;
+                        }
 
 private:
     status_t            obtainBuffer(AudioBufferProvider::Buffer* buffer,
@@ -268,6 +280,7 @@
     bool                        mActive;
     DuplicatingThread* const    mSourceThread; // for waitTimeMs() in write()
     sp<AudioTrackClientProxy>   mClientProxy;
+
     /** Attributes of the source tracks.
      *
      * This member must be accessed with mTrackMetadatasMutex taken.
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 1a24365..6220bbf 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -1891,11 +1891,17 @@
     status_t lStatus;
     audio_output_flags_t outputFlags = mOutput->flags;
     audio_output_flags_t requestedFlags = *flags;
+    uint32_t sampleRate;
+
+    if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
+        lStatus = BAD_VALUE;
+        goto Exit;
+    }
 
     if (*pSampleRate == 0) {
         *pSampleRate = mSampleRate;
     }
-    uint32_t sampleRate = *pSampleRate;
+    sampleRate = *pSampleRate;
 
     // special case for FAST flag considered OK if fast mixer is present
     if (hasFastMixer()) {
@@ -3203,12 +3209,10 @@
             // and associate with the sink frames written out.  We need
             // this to convert the sink timestamp to the track timestamp.
             bool kernelLocationUpdate = false;
-            if (mNormalSink != 0) {
-                // Note: The DuplicatingThread may not have a mNormalSink.
+            ExtendedTimestamp timestamp; // use private copy to fetch
+            if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
                 // We always fetch the timestamp here because often the downstream
                 // sink will block while writing.
-                ExtendedTimestamp timestamp; // use private copy to fetch
-                (void) mNormalSink->getTimestamp(timestamp);
 
                 // We keep track of the last valid kernel position in case we are in underrun
                 // and the normal mixer period is the same as the fast mixer period, or there
@@ -6096,7 +6100,22 @@
 ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
 {
     for (size_t i = 0; i < outputTracks.size(); i++) {
-        outputTracks[i]->write(mSinkBuffer, writeFrames);
+        const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
+
+        // Consider the first OutputTrack for timestamp and frame counting.
+
+        // The threadLoop() generally assumes writing a full sink buffer size at a time.
+        // Here, we correct for writeFrames of 0 (a stop) or underruns because
+        // we always claim success.
+        if (i == 0) {
+            const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
+            ALOGD_IF(correction != 0 && writeFrames != 0,
+                    "%s: writeFrames:%u  actualWritten:%zd  correction:%zd  mFramesWritten:%lld",
+                    __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
+            mFramesWritten -= correction;
+        }
+
+        // TODO: Report correction for the other output tracks and show in the dump.
     }
     mStandby = false;
     return (ssize_t)mSinkBufferSize;
diff --git a/services/audioflinger/Threads.h b/services/audioflinger/Threads.h
index 680e021..b691ca9 100644
--- a/services/audioflinger/Threads.h
+++ b/services/audioflinger/Threads.h
@@ -434,6 +434,12 @@
     virtual     void        setMasterMono_l(bool mono __unused) { }
     virtual     bool        requireMonoBlend() { return false; }
 
+                            // called within the threadLoop to obtain timestamp from the HAL.
+    virtual     status_t    threadloop_getHalTimestamp_l(
+                                    ExtendedTimestamp *timestamp __unused) const {
+                                return INVALID_OPERATION;
+                            }
+
     friend class AudioFlinger;      // for mEffectChains
 
                 const type_t            mType;
@@ -1150,6 +1156,14 @@
                               return mFastMixerDumpState.mTracks[fastIndex].mUnderruns;
                             }
 
+                status_t    threadloop_getHalTimestamp_l(
+                                    ExtendedTimestamp *timestamp) const override {
+                                if (mNormalSink.get() != nullptr) {
+                                    return mNormalSink->getTimestamp(*timestamp);
+                                }
+                                return INVALID_OPERATION;
+                            }
+
 protected:
     virtual     void       setMasterMono_l(bool mono) {
                                mMasterMono.store(mono);
@@ -1314,6 +1328,22 @@
     SortedVector < sp<OutputTrack> >  mOutputTracks;
 public:
     virtual     bool        hasFastMixer() const { return false; }
+                status_t    threadloop_getHalTimestamp_l(
+                                    ExtendedTimestamp *timestamp) const override {
+        if (mOutputTracks.size() > 0) {
+            // forward the first OutputTrack's kernel information for timestamp.
+            const ExtendedTimestamp trackTimestamp =
+                    mOutputTracks[0]->getClientProxyTimestamp();
+            if (trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
+                timestamp->mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
+                        trackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
+                timestamp->mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
+                        trackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
+                return OK;  // discard server timestamp - that's ignored.
+            }
+        }
+        return INVALID_OPERATION;
+    }
 };
 
 // record thread
diff --git a/services/audioflinger/Tracks.cpp b/services/audioflinger/Tracks.cpp
index 8b5cc32..f6c33e2 100644
--- a/services/audioflinger/Tracks.cpp
+++ b/services/audioflinger/Tracks.cpp
@@ -435,7 +435,8 @@
     }
     mName = TRACK_NAME_PENDING;
 
-    mServerLatencySupported = thread->type() == ThreadBase::MIXER;
+    mServerLatencySupported = thread->type() == ThreadBase::MIXER
+            || thread->type() == ThreadBase::DUPLICATING;
 #ifdef TEE_SINK
     mTee.setId(std::string("_") + std::to_string(mThreadIoHandle)
             + "_" + std::to_string(mId) +
@@ -1360,7 +1361,7 @@
     mActive = false;
 }
 
-bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
+ssize_t AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
 {
     Buffer *pInBuffer;
     Buffer inBuffer;
@@ -1449,9 +1450,12 @@
                 mBufferQueue.add(pInBuffer);
                 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %zu", this,
                         mThread.unsafe_get(), mBufferQueue.size());
+                // audio data is consumed (stored locally); set frameCount to 0.
+                inBuffer.frameCount = 0;
             } else {
                 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
                         mThread.unsafe_get(), this);
+                // TODO: return error for this.
             }
         }
     }
@@ -1462,7 +1466,7 @@
         stop();
     }
 
-    return outputBufferFull;
+    return frames - inBuffer.frameCount;  // number of frames consumed.
 }
 
 void AudioFlinger::PlaybackThread::OutputTrack::copyMetadataTo(MetadataInserter& backInserter) const
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
index f747c36..f861b95 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioPolicyConfig.h
@@ -38,12 +38,12 @@
     AudioPolicyConfig(HwModuleCollection &hwModules,
                       DeviceVector &availableOutputDevices,
                       DeviceVector &availableInputDevices,
-                      sp<DeviceDescriptor> &defaultOutputDevices,
+                      sp<DeviceDescriptor> &defaultOutputDevice,
                       VolumeCurvesCollection *volumes = nullptr)
         : mHwModules(hwModules),
           mAvailableOutputDevices(availableOutputDevices),
           mAvailableInputDevices(availableInputDevices),
-          mDefaultOutputDevices(defaultOutputDevices),
+          mDefaultOutputDevice(defaultOutputDevice),
           mVolumeCurves(volumes),
           mIsSpeakerDrcEnabled(false)
     {}
@@ -108,40 +108,44 @@
 
     void setDefaultOutputDevice(const sp<DeviceDescriptor> &defaultDevice)
     {
-        mDefaultOutputDevices = defaultDevice;
+        mDefaultOutputDevice = defaultDevice;
     }
 
-    const sp<DeviceDescriptor> &getDefaultOutputDevice() const { return mDefaultOutputDevices; }
+    const sp<DeviceDescriptor> &getDefaultOutputDevice() const { return mDefaultOutputDevice; }
 
     void setDefault(void)
     {
         mSource = "AudioPolicyConfig::setDefault";
-        mDefaultOutputDevices = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
-        sp<HwModule> module;
+        mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
+        mDefaultOutputDevice->addAudioProfile(AudioProfile::createFullDynamic());
         sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
-        mAvailableOutputDevices.add(mDefaultOutputDevices);
+        defaultInputDevice->addAudioProfile(AudioProfile::createFullDynamic());
+        sp<AudioProfile> micProfile = new AudioProfile(
+                AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_MONO, 8000);
+        defaultInputDevice->addAudioProfile(micProfile);
+        mAvailableOutputDevices.add(mDefaultOutputDevice);
         mAvailableInputDevices.add(defaultInputDevice);
 
-        module = new HwModule(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
+        sp<HwModule> module = new HwModule(AUDIO_HARDWARE_MODULE_ID_PRIMARY, 2 /*halVersionMajor*/);
+        mHwModules.add(module);
+        mDefaultOutputDevice->attach(module);
+        defaultInputDevice->attach(module);
 
         sp<OutputProfile> outProfile;
         outProfile = new OutputProfile(String8("primary"));
         outProfile->attach(module);
         outProfile->addAudioProfile(
                 new AudioProfile(AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_OUT_STEREO, 44100));
-        outProfile->addSupportedDevice(mDefaultOutputDevices);
+        outProfile->addSupportedDevice(mDefaultOutputDevice);
         outProfile->setFlags(AUDIO_OUTPUT_FLAG_PRIMARY);
         module->addOutputProfile(outProfile);
 
         sp<InputProfile> inProfile;
         inProfile = new InputProfile(String8("primary"));
         inProfile->attach(module);
-        inProfile->addAudioProfile(
-                new AudioProfile(AUDIO_FORMAT_PCM_16_BIT, AUDIO_CHANNEL_IN_MONO, 8000));
+        inProfile->addAudioProfile(micProfile);
         inProfile->addSupportedDevice(defaultInputDevice);
         module->addInputProfile(inProfile);
-
-        mHwModules.add(module);
     }
 
 private:
@@ -149,7 +153,7 @@
     HwModuleCollection &mHwModules; /**< Collection of Module, with Profiles, i.e. Mix Ports. */
     DeviceVector &mAvailableOutputDevices;
     DeviceVector &mAvailableInputDevices;
-    sp<DeviceDescriptor> &mDefaultOutputDevices;
+    sp<DeviceDescriptor> &mDefaultOutputDevice;
     VolumeCurvesCollection *mVolumeCurves;
     // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
     // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioProfile.h b/services/audiopolicy/common/managerdefinitions/include/AudioProfile.h
index 8741c66..4226ff2 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioProfile.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioProfile.h
@@ -36,6 +36,8 @@
 class AudioProfile : public virtual RefBase
 {
 public:
+    static sp<AudioProfile> createFullDynamic();
+
     AudioProfile(audio_format_t format,
                  audio_channel_mask_t channelMasks,
                  uint32_t samplingRate) :
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioProfile.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioProfile.cpp
index fd6fc1c..26af9b4 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioProfile.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioProfile.cpp
@@ -28,6 +28,23 @@
 
 namespace android {
 
+static AudioProfile* createFullDynamicImpl()
+{
+    AudioProfile* dynamicProfile = new AudioProfile(gDynamicFormat,
+            ChannelsVector(), SampleRateVector());
+    dynamicProfile->setDynamicFormat(true);
+    dynamicProfile->setDynamicChannels(true);
+    dynamicProfile->setDynamicRate(true);
+    return dynamicProfile;
+}
+
+// static
+sp<AudioProfile> AudioProfile::createFullDynamic()
+{
+    static sp<AudioProfile> dynamicProfile = createFullDynamicImpl();
+    return dynamicProfile;
+}
+
 status_t AudioProfile::checkExact(uint32_t samplingRate, audio_channel_mask_t channelMask,
                                   audio_format_t format) const
 {
diff --git a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
index a253113..8008a7c 100644
--- a/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/Serializer.cpp
@@ -242,12 +242,7 @@
     AudioProfileTraits::Collection profiles;
     deserializeCollection<AudioProfileTraits>(doc, child, profiles, NULL);
     if (profiles.isEmpty()) {
-        sp <AudioProfile> dynamicProfile = new AudioProfile(gDynamicFormat,
-                                                            ChannelsVector(), SampleRateVector());
-        dynamicProfile->setDynamicFormat(true);
-        dynamicProfile->setDynamicChannels(true);
-        dynamicProfile->setDynamicRate(true);
-        profiles.add(dynamicProfile);
+        profiles.add(AudioProfile::createFullDynamic());
     }
     mixPort->setAudioProfiles(profiles);
 
@@ -328,12 +323,7 @@
     AudioProfileTraits::Collection profiles;
     deserializeCollection<AudioProfileTraits>(doc, root, profiles, NULL);
     if (profiles.isEmpty()) {
-        sp <AudioProfile> dynamicProfile = new AudioProfile(gDynamicFormat,
-                                                            ChannelsVector(), SampleRateVector());
-        dynamicProfile->setDynamicFormat(true);
-        dynamicProfile->setDynamicChannels(true);
-        dynamicProfile->setDynamicRate(true);
-        profiles.add(dynamicProfile);
+        profiles.add(AudioProfile::createFullDynamic());
     }
     deviceDesc->setAudioProfiles(profiles);
 
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index 0a8bed1..7154cb2 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -4832,11 +4832,15 @@
     //      use device for strategy DTMF
     // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
     //      use device for strategy t-t-s
+
+    // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
+    // with a refined rule considering mutually exclusive devices (using same backend)
+    // as opposed to all streams on the same audio HAL module.
     if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
         mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
     } else if (isInCall() ||
-                    isStrategyActive(outputDesc, STRATEGY_PHONE)) {
+               isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
     } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
@@ -5778,6 +5782,20 @@
     return false;
 }
 
+bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
+                                          routing_strategy strategy, uint32_t inPastMs,
+                                          nsecs_t sysTime) const
+{
+    for (size_t i = 0; i < mOutputs.size(); i++) {
+        sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
+        if (outputDesc->sharesHwModuleWith(desc)
+            && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
+            return true;
+        }
+    }
+    return false;
+}
+
 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
 {
     return mEngine->getForceUse(usage);
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.h b/services/audiopolicy/managerdefault/AudioPolicyManager.h
index 008e1ca..893b963 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.h
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.h
@@ -321,6 +321,10 @@
         bool isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc, routing_strategy strategy,
                               uint32_t inPastMs = 0, nsecs_t sysTime = 0) const;
 
+        bool isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
+                                                  routing_strategy strategy, uint32_t inPastMs = 0,
+                                                  nsecs_t sysTime = 0) const;
+
         // change the route of the specified output. Returns the number of ms we have slept to
         // allow new routing to take effect in certain cases.
         virtual uint32_t setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
diff --git a/services/audiopolicy/tests/audiopolicymanager_tests.cpp b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
index 2d9260e..56af152 100644
--- a/services/audiopolicy/tests/audiopolicymanager_tests.cpp
+++ b/services/audiopolicy/tests/audiopolicymanager_tests.cpp
@@ -16,9 +16,13 @@
 
 #include <memory>
 #include <set>
+#include <sys/wait.h>
+#include <unistd.h>
 
 #include <gtest/gtest.h>
 
+#define LOG_TAG "APM_Test"
+#include <log/log.h>
 #include <media/PatchBuilder.h>
 
 #include "AudioPolicyTestClient.h"
@@ -134,6 +138,36 @@
     // SetUp must finish with no assertions.
 }
 
+TEST_F(AudioPolicyManagerTest, Dump) {
+    int pipefd[2];
+    ASSERT_NE(-1, pipe(pipefd));
+    pid_t cpid = fork();
+    ASSERT_NE(-1, cpid);
+    if (cpid == 0) {
+        // Child process reads from the pipe and logs.
+        close(pipefd[1]);
+        std::string line;
+        char buf;
+        while (read(pipefd[0], &buf, sizeof(buf)) > 0) {
+            if (buf != '\n') {
+                line += buf;
+            } else {
+                ALOGI("%s", line.c_str());
+                line = "";
+            }
+        }
+        if (!line.empty()) ALOGI("%s", line.c_str());
+        close(pipefd[0]);
+        _exit(EXIT_SUCCESS);
+    } else {
+        // Parent does the dump and checks the status code.
+        close(pipefd[0]);
+        ASSERT_EQ(NO_ERROR, mManager->dump(pipefd[1]));
+        close(pipefd[1]);
+        wait(NULL);  // Wait for the child to exit.
+    }
+}
+
 TEST_F(AudioPolicyManagerTest, CreateAudioPatchFailure) {
     audio_patch patch{};
     audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 282871b..c41de82 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -55,6 +55,7 @@
 #include <utils/Errors.h>
 #include <utils/Log.h>
 #include <utils/String16.h>
+#include <utils/SystemClock.h>
 #include <utils/Trace.h>
 #include <private/android_filesystem_config.h>
 #include <system/camera_vendor_tags.h>
@@ -2433,6 +2434,8 @@
     return isUidActiveLocked(uid, callingPackage);
 }
 
+static const int kPollUidActiveTimeoutMillis = 50;
+
 bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, String16 callingPackage) {
     // Non-app UIDs are considered always active
     // If activity manager is unreachable, assume everything is active
@@ -2452,7 +2455,28 @@
         ActivityManager am;
         // Okay to access with a lock held as UID changes are dispatched without
         // a lock and we are a higher level component.
-        active = am.isUidActive(uid, callingPackage);
+        int64_t startTimeMillis = 0;
+        do {
+            // TODO: Fix this b/109950150!
+            // Okay this is a hack. There is a race between the UID turning active and
+            // activity being resumed. The proper fix is very risky, so we temporary add
+            // some polling which should happen pretty rarely anyway as the race is hard
+            // to hit.
+            active = am.isUidActive(uid, callingPackage);
+            if (active) {
+                break;
+            }
+            if (startTimeMillis <= 0) {
+                startTimeMillis = uptimeMillis();
+            }
+            int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
+            int64_t remainingTimeMillis = kPollUidActiveTimeoutMillis - ellapsedTimeMillis;
+            if (remainingTimeMillis <= 0) {
+                break;
+            }
+            usleep(remainingTimeMillis * 1000);
+        } while (true);
+
         if (active) {
             // Now that we found out the UID is actually active, cache that
             mActiveUids.insert(uid);
diff --git a/services/camera/libcameraservice/device3/DistortionMapper.cpp b/services/camera/libcameraservice/device3/DistortionMapper.cpp
index 9229079..eef6658 100644
--- a/services/camera/libcameraservice/device3/DistortionMapper.cpp
+++ b/services/camera/libcameraservice/device3/DistortionMapper.cpp
@@ -18,6 +18,7 @@
 #define ATRACE_TAG ATRACE_TAG_CAMERA
 //#define LOG_NDEBUG 0
 
+#include <algorithm>
 #include <cmath>
 
 #include "device3/DistortionMapper.h"
@@ -43,13 +44,13 @@
 };
 
 // Only for capture result
-constexpr std::array<uint32_t, 2> DistortionMapper::kResultRectsToCorrect = {
+constexpr std::array<uint32_t, 1> DistortionMapper::kResultRectsToCorrect = {
     ANDROID_SCALER_CROP_REGION,
-    ANDROID_STATISTICS_FACE_RECTANGLES
 };
 
 // Only for capture result
-constexpr std::array<uint32_t, 1> DistortionMapper::kResultPointsToCorrect = {
+constexpr std::array<uint32_t, 2> DistortionMapper::kResultPointsToCorrect = {
+    ANDROID_STATISTICS_FACE_RECTANGLES, // Says rectangles, is really points
     ANDROID_STATISTICS_FACE_LANDMARKS,
 };
 
@@ -81,6 +82,10 @@
     mArrayWidth = array.data.i32[2];
     mArrayHeight = array.data.i32[3];
 
+    array = deviceInfo.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
+    mActiveWidth = array.data.i32[2];
+    mActiveHeight = array.data.i32[3];
+
     return updateCalibration(deviceInfo);
 }
 
@@ -102,8 +107,21 @@
         for (auto region : kMeteringRegionsToCorrect) {
             e = request->find(region);
             for (size_t j = 0; j < e.count; j += 5) {
+                int32_t weight = e.data.i32[j + 4];
+                if (weight == 0) {
+                    continue;
+                }
                 res = mapCorrectedToRaw(e.data.i32 + j, 2);
                 if (res != OK) return res;
+                for (size_t k = 0; k < 4; k+=2) {
+                    int32_t& x = e.data.i32[j + k];
+                    int32_t& y = e.data.i32[j + k + 1];
+                    // Clamp to within active array
+                    x = std::max(0, x);
+                    x = std::min(mActiveWidth - 1, x);
+                    y = std::max(0, y);
+                    y = std::min(mActiveHeight - 1, y);
+                }
             }
         }
         for (auto rect : kRequestRectsToCorrect) {
@@ -134,8 +152,21 @@
         for (auto region : kMeteringRegionsToCorrect) {
             e = result->find(region);
             for (size_t j = 0; j < e.count; j += 5) {
+                int32_t weight = e.data.i32[j + 4];
+                if (weight == 0) {
+                    continue;
+                }
                 res = mapRawToCorrected(e.data.i32 + j, 2);
                 if (res != OK) return res;
+                for (size_t k = 0; k < 4; k+=2) {
+                    int32_t& x = e.data.i32[j + k];
+                    int32_t& y = e.data.i32[j + k + 1];
+                    // Clamp to within active array
+                    x = std::max(0, x);
+                    x = std::min(mActiveWidth - 1, x);
+                    y = std::max(0, y);
+                    y = std::min(mActiveHeight - 1, y);
+                }
             }
         }
         for (auto rect : kResultRectsToCorrect) {
@@ -212,7 +243,8 @@
     for (int i = 0; i < coordCount * 2; i += 2) {
         const GridQuad *quad = findEnclosingQuad(coordPairs + i, mDistortedGrid);
         if (quad == nullptr) {
-            ALOGE("Raw to corrected mapping failure: No quad found");
+            ALOGE("Raw to corrected mapping failure: No quad found for (%d, %d)",
+                    *(coordPairs + i), *(coordPairs + i + 1));
             return INVALID_OPERATION;
         }
         ALOGV("src xy: %d, %d, enclosing quad: (%f, %f), (%f, %f), (%f, %f), (%f, %f)",
diff --git a/services/camera/libcameraservice/device3/DistortionMapper.h b/services/camera/libcameraservice/device3/DistortionMapper.h
index c6d715b..00cbd32 100644
--- a/services/camera/libcameraservice/device3/DistortionMapper.h
+++ b/services/camera/libcameraservice/device3/DistortionMapper.h
@@ -148,10 +148,10 @@
     static const std::array<uint32_t, 1> kRequestRectsToCorrect;
 
     // Only capture result
-    static const std::array<uint32_t, 2> kResultRectsToCorrect;
+    static const std::array<uint32_t, 1> kResultRectsToCorrect;
 
     // Only for capture results
-    static const std::array<uint32_t, 1> kResultPointsToCorrect;
+    static const std::array<uint32_t, 2> kResultPointsToCorrect;
 
     // Utility to create reverse mapping grids
     status_t buildGrids();
@@ -169,6 +169,8 @@
 
     // pre-correction active array dimensions
     int mArrayWidth, mArrayHeight;
+    // active array dimensions
+    int mActiveWidth, mActiveHeight;
 
     std::vector<GridQuad> mCorrectedGrid;
     std::vector<GridQuad> mDistortedGrid;
diff --git a/services/mediaextractor/Android.mk b/services/mediaextractor/Android.mk
index 37d6cc9..73c9535 100644
--- a/services/mediaextractor/Android.mk
+++ b/services/mediaextractor/Android.mk
@@ -18,6 +18,7 @@
 LOCAL_REQUIRED_MODULES_arm := crash_dump.policy mediaextractor.policy
 LOCAL_REQUIRED_MODULES_arm64 := crash_dump.policy mediaextractor.policy
 LOCAL_REQUIRED_MODULES_x86 := crash_dump.policy mediaextractor.policy
+LOCAL_REQUIRED_MODULES_x86_64 := crash_dump.policy mediaextractor.policy
 
 # extractor libraries
 LOCAL_REQUIRED_MODULES += \
diff --git a/services/mediaextractor/seccomp_policy/mediaextractor-x86_64.policy b/services/mediaextractor/seccomp_policy/mediaextractor-x86_64.policy
old mode 100755
new mode 100644
index 63c7780..6d9ed6f
--- a/services/mediaextractor/seccomp_policy/mediaextractor-x86_64.policy
+++ b/services/mediaextractor/seccomp_policy/mediaextractor-x86_64.policy
@@ -21,6 +21,7 @@
 getuid: 1
 setpriority: 1
 sigaltstack: 1
+fstatfs: 1
 newfstatat: 1
 restart_syscall: 1
 exit: 1
@@ -30,28 +31,21 @@
 sched_setscheduler: 1
 getrlimit: 1
 nanosleep: 1
+getrandom: 1
+
+# for dynamically loading extractors
+getdents64: 1
+readlinkat: 1
+pread64: 1
+mremap: 1
 
 # for FileSource
 readlinkat: 1
 
-# for attaching to debuggerd on process crash
-tgkill: 1
-socket: arg0 == 1
-connect: 1
-fcntl: 1
-rt_sigprocmask: 1
-rt_sigaction: 1
-rt_tgsigqueueinfo: 1
-geteuid: 1
-getgid: 1
-getegid: 1
-getgroups: 1
-getdents64: 1
-pipe2: 1
-ppoll: 1
-
 # Required by AddressSanitizer
 gettid: 1
 sched_yield: 1
 getpid: 1
 gettid: 1
+
+@include /system/etc/seccomp_policy/crash_dump.x86_64.policy
diff --git a/services/soundtrigger/SoundTriggerHwService.cpp b/services/soundtrigger/SoundTriggerHwService.cpp
index 6bf6e94..eb9cd1d 100644
--- a/services/soundtrigger/SoundTriggerHwService.cpp
+++ b/services/soundtrigger/SoundTriggerHwService.cpp
@@ -562,10 +562,7 @@
     if (mHalInterface == 0) {
         return NO_INIT;
     }
-    if (modelMemory == 0 || modelMemory->pointer() == NULL) {
-        ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()");
-        return BAD_VALUE;
-    }
+
     struct sound_trigger_sound_model *sound_model =
             (struct sound_trigger_sound_model *)modelMemory->pointer();
 
@@ -659,11 +656,6 @@
     if (mHalInterface == 0) {
         return NO_INIT;
     }
-    if (dataMemory == 0 || dataMemory->pointer() == NULL) {
-        ALOGE("startRecognition() dataMemory is 0 or has NULL pointer()");
-        return BAD_VALUE;
-
-    }
 
     struct sound_trigger_recognition_config *config =
             (struct sound_trigger_recognition_config *)dataMemory->pointer();
@@ -966,6 +958,9 @@
                                IPCThreadState::self()->getCallingUid())) {
         return PERMISSION_DENIED;
     }
+    if (checkIMemory(modelMemory) != NO_ERROR) {
+        return BAD_VALUE;
+    }
 
     sp<Module> module = mModule.promote();
     if (module == 0) {
@@ -997,6 +992,9 @@
                                IPCThreadState::self()->getCallingUid())) {
         return PERMISSION_DENIED;
     }
+    if (checkIMemory(dataMemory) != NO_ERROR) {
+        return BAD_VALUE;
+    }
 
     sp<Module> module = mModule.promote();
     if (module == 0) {