am 08945576: Merge change I9ac0777e into eclair-mr2

Merge commit '089455760c05289c1315268a6cb896577ceebc64' into eclair-mr2-plus-aosp

* commit '089455760c05289c1315268a6cb896577ceebc64':
  Initial checkin of software AMR NB encoder based on PV source code.
diff --git a/include/media/stagefright/MetaData.h b/include/media/stagefright/MetaData.h
index 583128f..c6ac6c2 100644
--- a/include/media/stagefright/MetaData.h
+++ b/include/media/stagefright/MetaData.h
@@ -34,7 +34,7 @@
     kKeyHeight            = 'heig',
     kKeyChannelCount      = '#chn',
     kKeySampleRate        = 'srte',
-    kKeyBitRate           = 'brte',
+    kKeyBitRate           = 'brte',  // int32_t (bps)
     kKeyESDS              = 'esds',  // raw data
     kKeyAVCC              = 'avcc',  // raw data
     kKeyWantsNALFragments = 'NALf',
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index d4c6708..d145542 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -56,6 +56,7 @@
 LOCAL_STATIC_LIBRARIES := \
         libstagefright_aacdec \
         libstagefright_amrnbdec \
+        libstagefright_amrnbenc \
         libstagefright_amrwbdec \
         libstagefright_avcdec \
         libstagefright_mp3dec
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 9dbefe4..39d4c0b 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -366,7 +366,7 @@
 
         mMeta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
         mMeta->setInt32(kKeySampleRate, sample_rate);
-        mMeta->setInt32(kKeyBitRate, bitrate);
+        mMeta->setInt32(kKeyBitRate, bitrate * 1000);
         mMeta->setInt32(kKeyChannelCount, num_channels);
 
         off_t fileSize;
@@ -462,14 +462,14 @@
     if (options != NULL && options->getSeekTo(&seekTimeUs)) {
         int32_t bitrate;
         if (!mMeta->findInt32(kKeyBitRate, &bitrate)) {
-            // bitrate is in kbits/sec.
+            // bitrate is in bits/sec.
             LOGI("no bitrate");
 
             return ERROR_UNSUPPORTED;
         }
 
         mCurrentTimeUs = seekTimeUs;
-        mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 1000000 * 125;
+        mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000;
     }
 
     MediaBuffer *buffer;
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 9c9787f..5a89b73 100644
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -21,6 +21,7 @@
 #if BUILD_WITH_FULL_STAGEFRIGHT
 #include "include/AACDecoder.h"
 #include "include/AMRNBDecoder.h"
+#include "include/AMRNBEncoder.h"
 #include "include/AMRWBDecoder.h"
 #include "include/AVCDecoder.h"
 #include "include/MP3Decoder.h"
@@ -306,6 +307,10 @@
                     && (flags & kPreferSoftwareCodecs)) {
             return new AVCDecoder(source);
         }
+    } else {
+        if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_NB)) {
+            return new AMRNBEncoder(source);
+        }
     }
 #endif
 
diff --git a/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp b/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp
new file mode 100644
index 0000000..b6d7ea3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/AMRNBEncoder.cpp
@@ -0,0 +1,234 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "AMRNBEncoder.h"
+
+#include "gsmamr_enc.h"
+
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+static const int32_t kNumSamplesPerFrame = 160;
+static const int32_t kSampleRate = 8000;
+
+AMRNBEncoder::AMRNBEncoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mBufferGroup(NULL),
+      mEncState(NULL),
+      mSidState(NULL),
+      mAnchorTimeUs(0),
+      mNumFramesOutput(0),
+      mInputBuffer(NULL),
+      mMode(MR475),
+      mNumInputSamples(0) {
+}
+
+AMRNBEncoder::~AMRNBEncoder() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+static Mode PickModeFromBitrate(int32_t bps) {
+    if (bps <= 4750) {
+        return MR475;
+    } else if (bps <= 5150) {
+        return MR515;
+    } else if (bps <= 5900) {
+        return MR59;
+    } else if (bps <= 6700) {
+        return MR67;
+    } else if (bps <= 7400) {
+        return MR74;
+    } else if (bps <= 7950) {
+        return MR795;
+    } else if (bps <= 10200) {
+        return MR102;
+    } else {
+        return MR122;
+    }
+}
+
+status_t AMRNBEncoder::start(MetaData *params) {
+    CHECK(!mStarted);
+
+    mBufferGroup = new MediaBufferGroup;
+    mBufferGroup->add_buffer(new MediaBuffer(32));
+
+    CHECK_EQ(AMREncodeInit(
+                &mEncState, &mSidState, false /* dtx_enable */),
+             0);
+
+    mSource->start();
+
+    mAnchorTimeUs = 0;
+    mNumFramesOutput = 0;
+    mStarted = true;
+    mNumInputSamples = 0;
+
+    int32_t bitrate;
+    if (params && params->findInt32(kKeyBitRate, &bitrate)) {
+        mMode = PickModeFromBitrate(bitrate);
+    } else {
+        mMode = MR475;
+    }
+
+    return OK;
+}
+
+status_t AMRNBEncoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    delete mBufferGroup;
+    mBufferGroup = NULL;
+
+    mSource->stop();
+
+    AMREncodeExit(&mEncState, &mSidState);
+    mEncState = mSidState = NULL;
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> AMRNBEncoder::getFormat() {
+    sp<MetaData> srcFormat = mSource->getFormat();
+
+    int32_t numChannels;
+    int32_t sampleRate;
+
+    CHECK(srcFormat->findInt32(kKeyChannelCount, &numChannels));
+    CHECK_EQ(numChannels, 1);
+
+    CHECK(srcFormat->findInt32(kKeySampleRate, &sampleRate));
+    CHECK_EQ(sampleRate, kSampleRate);
+
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
+    meta->setInt32(kKeyChannelCount, numChannels);
+    meta->setInt32(kKeySampleRate, sampleRate);
+
+    int64_t durationUs;
+    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
+        meta->setInt64(kKeyDuration, durationUs);
+    }
+
+    return meta;
+}
+
+status_t AMRNBEncoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    status_t err;
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    CHECK(options == NULL || !options->getSeekTo(&seekTimeUs));
+
+    while (mNumInputSamples < kNumSamplesPerFrame) {
+        if (mInputBuffer == NULL) {
+            err = mSource->read(&mInputBuffer, options);
+
+            if (err != OK) {
+                if (mNumInputSamples == 0) {
+                    return ERROR_END_OF_STREAM;
+                }
+                memset(&mInputFrame[mNumInputSamples],
+                       0,
+                       sizeof(int16_t)
+                            * (kNumSamplesPerFrame - mNumInputSamples));
+                mNumInputSamples = kNumSamplesPerFrame;
+                break;
+            }
+
+            size_t align = mInputBuffer->range_length() % sizeof(int16_t);
+            CHECK_EQ(align, 0);
+
+            int64_t timeUs;
+            if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
+                mAnchorTimeUs = timeUs;
+                mNumFramesOutput = 0;
+            }
+        }
+
+        size_t copy =
+            (kNumSamplesPerFrame - mNumInputSamples) * sizeof(int16_t);
+
+        if (copy > mInputBuffer->range_length()) {
+            copy = mInputBuffer->range_length();
+        }
+
+        memcpy(&mInputFrame[mNumInputSamples],
+               (const uint8_t *)mInputBuffer->data()
+                    + mInputBuffer->range_offset(),
+               copy);
+
+        mNumInputSamples += copy / sizeof(int16_t);
+
+        mInputBuffer->set_range(
+                mInputBuffer->range_offset() + copy,
+                mInputBuffer->range_length() - copy);
+
+        if (mInputBuffer->range_length() == 0) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+    }
+
+    MediaBuffer *buffer;
+    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
+
+    uint8_t *outPtr = (uint8_t *)buffer->data();
+
+    Frame_Type_3GPP frameType;
+    int res = AMREncode(
+            mEncState, mSidState, (Mode)mMode,
+            mInputFrame, outPtr, &frameType, AMR_TX_WMF);
+
+    CHECK(res >= 0);
+    CHECK((size_t)res < buffer->size());
+
+    // Convert header byte from WMF to IETF format.
+    outPtr[0] = ((outPtr[0] << 3) | 4) & 0x7c;
+
+    buffer->set_range(0, res);
+
+    // Each frame of 160 samples is 20ms long.
+    buffer->meta_data()->setInt64(
+            kKeyTime, mAnchorTimeUs + mNumFramesOutput * 20000);
+
+    ++mNumFramesOutput;
+
+    *out = buffer;
+
+    mNumInputSamples = 0;
+
+    return OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/amrnb/enc/Android.mk b/media/libstagefright/codecs/amrnb/enc/Android.mk
new file mode 100644
index 0000000..b6aed81
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/Android.mk
@@ -0,0 +1,76 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        AMRNBEncoder.cpp \
+	src/amrencode.cpp \
+ 	src/autocorr.cpp \
+ 	src/c1035pf.cpp \
+ 	src/c2_11pf.cpp \
+ 	src/c2_9pf.cpp \
+ 	src/c3_14pf.cpp \
+ 	src/c4_17pf.cpp \
+ 	src/c8_31pf.cpp \
+ 	src/calc_cor.cpp \
+ 	src/calc_en.cpp \
+ 	src/cbsearch.cpp \
+ 	src/cl_ltp.cpp \
+ 	src/cod_amr.cpp \
+ 	src/convolve.cpp \
+ 	src/cor_h.cpp \
+ 	src/cor_h_x.cpp \
+ 	src/cor_h_x2.cpp \
+ 	src/corrwght_tab.cpp \
+ 	src/dtx_enc.cpp \
+ 	src/enc_lag3.cpp \
+ 	src/enc_lag6.cpp \
+ 	src/enc_output_format_tab.cpp \
+ 	src/ets_to_if2.cpp \
+ 	src/ets_to_wmf.cpp \
+ 	src/g_adapt.cpp \
+ 	src/g_code.cpp \
+ 	src/g_pitch.cpp \
+ 	src/gain_q.cpp \
+ 	src/hp_max.cpp \
+ 	src/inter_36.cpp \
+ 	src/inter_36_tab.cpp \
+ 	src/l_comp.cpp \
+ 	src/l_extract.cpp \
+ 	src/l_negate.cpp \
+ 	src/lag_wind.cpp \
+ 	src/lag_wind_tab.cpp \
+ 	src/levinson.cpp \
+ 	src/lpc.cpp \
+ 	src/ol_ltp.cpp \
+ 	src/p_ol_wgh.cpp \
+ 	src/pitch_fr.cpp \
+ 	src/pitch_ol.cpp \
+ 	src/pre_big.cpp \
+ 	src/pre_proc.cpp \
+ 	src/prm2bits.cpp \
+ 	src/q_gain_c.cpp \
+ 	src/q_gain_p.cpp \
+ 	src/qgain475.cpp \
+ 	src/qgain795.cpp \
+ 	src/qua_gain.cpp \
+ 	src/s10_8pf.cpp \
+ 	src/set_sign.cpp \
+ 	src/sid_sync.cpp \
+ 	src/sp_enc.cpp \
+ 	src/spreproc.cpp \
+ 	src/spstproc.cpp \
+ 	src/ton_stab.cpp
+
+LOCAL_C_INCLUDES := \
+        frameworks/base/media/libstagefright/include \
+        $(LOCAL_PATH)/src \
+        $(LOCAL_PATH)/include \
+        $(LOCAL_PATH)/../common/include \
+        $(LOCAL_PATH)/../common
+
+LOCAL_CFLAGS := \
+        -DOSCL_UNUSED_ARG=
+
+LOCAL_MODULE := libstagefright_amrnbenc
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/amrnb/enc/src/amrencode.cpp b/media/libstagefright/codecs/amrnb/enc/src/amrencode.cpp
new file mode 100644
index 0000000..d07c846
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/amrencode.cpp
@@ -0,0 +1,897 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename:  /audio/gsm-amr/c/src/amrencode.c
+ Functions: AMREncode
+            AMREncodeInit
+            AMREncodeReset
+            AMREncodeExit
+
+     Date: 01/26/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added input_type in the parameter list and updated code to
+              check the type of output formatting to use.
+
+ Description: Corrected typo in Include section.
+
+ Description: Added code to support ETS format.
+
+ Description: Modified file by adding the return of the number of encoder
+              frame bytes.
+
+ Description: Added call to sid_sync function to support TX_NO_DATA case.
+              Added SID type and mode info to ets_output_bfr for ETS SID
+              frames. Created AMREncodeInit, AMREncodeReset, and AMREncodeExit
+              functions.
+
+ Description: Modified design of handling of ETS outputs such that the ETS
+              testvectors could be compared directly to the output of this
+              function.
+
+ Description: Added conditional compile around calls to AMR Encoder interface
+              functions to allow amrencode.c to be used in the ETS reference
+              console.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions required to initialize, reset, exit, and
+ invoke the ETS 3GPP GSM AMR encoder.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "cnst.h"
+#include "mode.h"
+#include "frame_type_3gpp.h"
+#include "typedef.h"
+
+#include "amrencode.h"
+#include "ets_to_if2.h"
+#include "ets_to_wmf.h"
+#include "sid_sync.h"
+#include "sp_enc.h"
+
+/*----------------------------------------------------------------------------
+; MACROS [optional]
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES [optional]
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: AMREncodeInit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pEncStructure = pointer containing the pointer to a structure used by
+                    the encoder (void)
+    pSidSyncStructure = pointer containing the pointer to a structure used for
+                        SID synchronization (void)
+    dtx_enable = flag to turn off or turn on DTX (Flag)
+
+ Outputs:
+    None
+
+ Returns:
+    init_status = 0, if initialization was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    speech_encoder_state = pointer to encoder frame structure
+                           (Speech_Encode_FrameState)
+    sid_state = pointer to SID sync structure (sid_syncState)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the GSM AMR Encoder library by calling
+ GSMInitEncode and sid_sync_init. If initialization was successful,
+ init_status is set to zero, otherwise, it is set to -1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ // Initialize GSM AMR Encoder
+ CALL GSMInitEncode(state_data = &pEncStructure,
+                    dtx = dtx_enable,
+                    id = char_id            )
+   MODIFYING(nothing)
+   RETURNING(return_value = enc_init_status)
+
+ // Initialize SID synchronization
+ CALL sid_sync_init(state = &pSidSyncStructure)
+   MODIFYING(nothing)
+   RETURNING(return_value = sid_sync_init_status)
+
+ IF ((enc_init_status != 0) || (sid_sync_init != 0))
+ THEN
+     init_status = -1
+
+ ENDIF
+
+ MODIFY(nothing)
+ RETURN(init_status)
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 AMREncodeInit(
+    void **pEncStructure,
+    void **pSidSyncStructure,
+    Flag dtx_enable)
+{
+    Word16 enc_init_status = 0;
+    Word16 sid_sync_init_status = 0;
+    Word16 init_status = 0;
+
+    /* Initialize GSM AMR Encoder */
+#ifdef CONSOLE_ENCODER_REF
+    /* Change to original ETS input types */
+    Speech_Encode_FrameState **speech_encode_frame =
+        (Speech_Encode_FrameState **)(pEncStructure);
+
+    sid_syncState **sid_sync_state = (sid_syncState **)(pSidSyncStructure);
+
+    /* Use ETS version of sp_enc.c */
+    enc_init_status = Speech_Encode_Frame_init(speech_encode_frame,
+                      dtx_enable,
+                      (Word8*)"encoder");
+
+    /* Initialize SID synchronization */
+    sid_sync_init_status = sid_sync_init(sid_sync_state);
+
+#else
+    /* Use PV version of sp_enc.c */
+    enc_init_status = GSMInitEncode(pEncStructure,
+                                    dtx_enable,
+                                    (Word8*)"encoder");
+
+    /* Initialize SID synchronization */
+    sid_sync_init_status = sid_sync_init(pSidSyncStructure);
+
+
+#endif
+
+    if ((enc_init_status != 0) || (sid_sync_init_status != 0))
+    {
+        init_status = -1;
+    }
+
+    return(init_status);
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: AMREncodeReset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pEncStructure = pointer to a structure used by the encoder (void)
+    pSidSyncStructure = pointer to a structure used for SID synchronization
+                        (void)
+
+ Outputs:
+    None
+
+ Returns:
+    reset_status = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    speech_encoder_state = pointer to encoder frame structure
+                           (Speech_Encode_FrameState)
+    sid_state = pointer to SID sync structure (sid_syncState)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets the state memory used by the Encoder and SID sync
+ function. If reset was successful, reset_status is set to zero, otherwise,
+ it is set to -1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ // Reset GSM AMR Encoder
+ CALL Speech_Encode_Frame_reset(state_data = pEncStructure)
+   MODIFYING(nothing)
+   RETURNING(return_value = enc_reset_status)
+
+ // Reset SID synchronization
+ CALL sid_sync_reset(state = pSidSyncStructure)
+   MODIFYING(nothing)
+   RETURNING(return_value = sid_sync_reset_status)
+
+ IF ((enc_reset_status != 0) || (sid_sync_reset_status != 0))
+ THEN
+     reset_status = -1
+
+ ENDIF
+
+ MODIFY(nothing)
+ RETURN(reset_status)
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 AMREncodeReset(
+    void *pEncStructure,
+    void *pSidSyncStructure)
+{
+    Word16 enc_reset_status = 0;
+    Word16 sid_sync_reset_status = 0;
+    Word16 reset_status = 0;
+
+    /* Reset GSM AMR Encoder */
+    enc_reset_status = Speech_Encode_Frame_reset(pEncStructure);
+
+
+    /* Reset SID synchronization */
+    sid_sync_reset_status = sid_sync_reset(pSidSyncStructure);
+
+    if ((enc_reset_status != 0) || (sid_sync_reset_status != 0))
+    {
+        reset_status = -1;
+    }
+
+    return(reset_status);
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: AMREncodeExit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pEncStructure = pointer containing the pointer to a structure used by
+                    the encoder (void)
+    pSidSyncStructure = pointer containing the pointer to a structure used for
+                        SID synchronization (void)
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    speech_encoder_state = pointer to encoder frame structure
+                           (Speech_Encode_FrameState)
+    sid_state = pointer to SID sync structure (sid_syncState)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees up the state memory used by the Encoder and SID
+ synchronization function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ // Exit GSM AMR Encoder
+ CALL GSMEncodeFrameExit(state_data = &pEncStructure)
+   MODIFYING(nothing)
+   RETURNING(nothing)
+
+ // Exit SID synchronization
+ CALL sid_sync_exit(state = &pSidSyncStructure)
+   MODIFYING(nothing)
+   RETURNING(nothing)
+
+ MODIFY(nothing)
+ RETURN(nothing)
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void AMREncodeExit(
+    void **pEncStructure,
+    void **pSidSyncStructure)
+{
+    /* Exit GSM AMR Encoder */
+
+#ifdef CONSOLE_ENCODER_REF
+    /* Change to original ETS input types */
+    Speech_Encode_FrameState ** speech_encode_frame =
+        (Speech_Encode_FrameState **)(pEncStructure);
+
+    sid_syncState ** sid_sync_state = (sid_syncState **)(pSidSyncStructure);
+
+    /* Use ETS version of sp_enc.c */
+    Speech_Encode_Frame_exit(speech_encode_frame);
+
+
+    /* Exit SID synchronization */
+    sid_sync_exit(sid_sync_state);
+
+#else
+
+    /* Use PV version of sp_enc.c */
+    GSMEncodeFrameExit(pEncStructure);
+
+    /* Exit SID synchronization */
+    sid_sync_exit(pSidSyncStructure);
+
+#endif
+
+    return;
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: AMREncode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pEncState = pointer to encoder state structure (void)
+    pSidSyncState = pointer to SID sync state structure (void)
+    mode = codec mode (enum Mode)
+    pEncInput = pointer to the input speech samples (Word16)
+    pEncOutput = pointer to the encoded bit stream (unsigned char)
+    p3gpp_frame_type = pointer to the 3GPP frame type (enum Frame_Type_3GPP)
+    output_format = output format type (Word16); valid values are AMR_WMF,
+                    AMR_IF2, and AMR_ETS
+
+ Outputs:
+    pEncOutput buffer contains to the newly encoded bit stream
+    p3gpp_frame_type store contains the new 3GPP frame type
+
+ Returns:
+    num_enc_bytes = number of encoded bytes for a particular
+                    mode or -1, if an error occurred (int)
+
+ Global Variables Used:
+    WmfEncBytesPerFrame = table containing the number of encoder frame
+                          data bytes per codec mode for WMF output
+                          format (const int)
+    If2EncBytesPerFrame = table containing the number of encoder frame
+                          data bytes per codec mode for IF2 output
+                          format (const int)
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is the top-level entry point to the GSM AMR Encoder library.
+
+ The following describes the encoding process for WMF or IF2 formatted output
+ data. This functions calls GSMEncodeFrame to encode one frame's worth of
+ input speech samples, and returns the newly encoded bit stream in the buffer
+ pointed to by pEncOutput.Then the function sid_sync is called to determine
+ the transmit frame type. If the transmit frame type is TX_SPEECH_GOOD or
+ TX_SID_FIRST or TX_SID_UPDATE, p3gpp_frame_type will be set to the encoder
+ used mode. For SID frames, the SID type information and mode information are
+ added to the encoded parameter bitstream according to the SID frame format
+ described in [1]. If the transmit frame type is TX_NO_DATA, the store
+ pointed to by p3gpp_frame_type will be set to NO_DATA. Then the output
+ format type (output_format) will be checked to determine the format of the
+ encoded data.
+
+ If output_format is AMR_TX_WMF, the function ets_to_wmf will be called to
+ convert from ETS format (1 bit/word, where 1 word = 16 bits, information in
+ least significant bit) to WMF (aka, non-IF2). The WMF format stores the data
+ in octets. The least significant 4 bits of the first octet contains the 3GPP
+ frame type information and the most significant 4 bits are zeroed out. The
+ succeeding octets contain the packed encoded speech bits. The total number of
+ WMF bytes encoded is obtained from WmfEncBytesPerFrame table and returned via
+ num_enc_bytes.
+
+ If output_format is AMR_TX_IF2, the function if2_to_ets will be called to
+ convert from ETS format to IF2 [1]. The IF2 format stores the data in octets.
+ The least significant nibble of the first octet contains the 3GPP frame type
+ and the most significant nibble contains the first 4 encoded speech bits. The
+ suceeding octets contain the packed encoded speech bits. The total number of
+ IF2 bytes encoded is obtained from If2EncBytesPerFrame table and returned via
+ num_enc_bytes.
+
+ If output_format is AMR_TX_ETS, GSMFrameEncode is called to generate the
+ encoded speech parameters, then, sid_sync is called to determine the transmit
+ frame type. If the transmit frame type is not TX_NO_DATA, then the transmit
+ frame type information is saved in the first location of the ets_output_bfr,
+ followed by the encoded speech parameters. The codec mode information is
+ stored immediately after the MAX_SERIAL_SIZE encoded speech parameters. If
+ the transmit frame type is TX_NO_DATA, the transmit frame type, encoded
+ speech parameters, and codec mode are stored in the same order as before
+ in ets_output_bfr. However, for the no data case, the codec mode is set to
+ -1.
+
+ After all the required information is generated, the 16-bit data generated
+ by the Encoder (in ets_output_bfr) is copied to the buffer pointed to by
+ pEncOutput in the little endian configuration, i.e., least significant byte,
+ followed by most significant byte. The num_enc_bytes is set to
+ 2*(MAX_SERIAL_SIZE+2).
+
+ If output_format is invalid, this function flags the error and sets
+ num_enc_bytes to -1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] "AMR Speech Codec Frame Structure", 3GPP TS 26.101 version 4.1.0
+     Release 4, June 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ IF ((output_format == AMR_TX_WMF) | (output_format == AMR_TX_IF2))
+ THEN
+     // Encode one speech frame (20 ms)
+     CALL GSMEncodeFrame( state_data = pEncState,
+                          mode = mode,
+                          new_speech = pEncInput,
+                          serial = &ets_output_bfr[0],
+                          usedMode = &usedMode )
+       MODIFYING(nothing)
+       RETURNING(return_value = 0)
+
+     // Determine transmit frame type
+     CALL sid_sync(st = pSidSyncState,
+                   mode = usedMode
+                   tx_frame_type = &tx_frame_type)
+       MODIFYING(nothing)
+       RETURNING(nothing)
+
+     IF (tx_frame_type != TX_NO_DATA)
+     THEN
+         // There is data to transmit
+         *p3gpp_frame_type = (enum Frame_Type_3GPP) usedMode
+
+         // Add SID type and mode info for SID frames
+         IF (*p3gpp_frame_type == AMR_SID)
+         THEN
+             // Add SID type to encoder output buffer
+             IF (tx_frame_type == TX_SID_FIRST)
+             THEN
+                 ets_output_bfr[AMRSID_TXTYPE_BIT_OFFSET] &= 0x7f
+
+             ELSEIF (tx_frame_type == TX_SID_UPDATE )
+             THEN
+                 ets_output_bfr[AMRSID_TXTYPE_BIT_OFFSET] |= 0x80
+
+             ENDIF
+
+             // Add mode information bits
+             FOR i = 0 TO NUM_AMRSID_TXMODE_BITS-1
+
+                 ets_output_bfr[AMRSID_TXMODE_BIT_OFFSET+i] = (mode>>i)&&0x0001
+
+             ENDFOR
+
+         ENDIF
+
+     ELSE
+         // There is no data to transmit
+         *p3gpp_frame_type = NO_DATA
+
+     ENDIF
+
+     // Determine the output format to use
+     IF (output_format == AMR_TX_WMF)
+     THEN
+         // Change output data format to WMF
+         CALL ets_to_wmf( frame_type_3gpp = *p3gpp_frame_type,
+                          ets_input_ptr = &ets_output_bfr[0],
+                          wmf_output_ptr = pEncOutput         )
+           MODIFYING(nothing)
+           RETURNING(nothing)
+
+         // Set up the number of encoded WMF bytes
+         num_enc_bytes = WmfEncBytesPerFrame[(int) *p3gpp_frame_type]
+
+     ELSEIF (output_format == AMR_TX_IF2)
+     THEN
+         // Change output data format to IF2
+         CALL ets_to_if2( frame_type_3gpp = *p3gpp_frame_type,
+                          ets_input_ptr = &ets_output_bfr[0],
+                          if2_output_ptr = pEncOutput         )
+           MODIFYING(nothing)
+           RETURNING(nothing)
+
+         // Set up the number of encoded IF2 bytes
+         num_enc_bytes = If2EncBytesPerFrame[(int) *p3gpp_frame_type]
+
+     ENDIF
+
+ ELSEIF (output_format = AMR_TX_ETS)
+ THEN
+     // Encode one speech frame (20 ms)
+     CALL GSMEncodeFrame( state_data = pEncState,
+                          mode = mode,
+                          new_speech = pEncInput,
+                          serial = &ets_output_bfr[1],
+                          usedMode = &usedMode )
+       MODIFYING(nothing)
+       RETURNING(return_value = 0)
+
+     // Save used mode
+     *p3gpp_frame_type = (enum Frame_Type_3GPP) usedMode
+
+     // Determine transmit frame type
+     CALL sid_sync(st = pSidSyncState,
+                   mode = usedMode
+                   tx_frame_type = &tx_frame_type)
+       MODIFYING(nothing)
+       RETURNING(nothing)
+
+     // Put TX frame type in output buffer
+     ets_output_bfr[0] = tx_frame_type
+
+     // Put mode information after the encoded speech parameters
+     IF (tx_frame_type != TX_NO_DATA)
+     THEN
+         ets_output_bfr[MAX_SERIAL_SIZE+1] = mode
+
+     ELSE
+         ets_output_bfr[MAX_SERIAL_SIZE+1] = -1
+
+     ENDIF
+
+     // Copy output of encoder to pEncOutput buffer
+     ets_output_ptr = (unsigned char *) &ets_output_bfr[0]
+
+     // Copy 16-bit data in 8-bit chunks using Little Endian configuration
+     FOR i = 0 TO (2*(MAX_SERIAL_SIZE+6))-1
+
+         *(pEncOutput+i) = *ets_output_ptr
+         ets_output_ptr = ets_output_ptr + 1
+
+     ENDFOR
+
+     // Set up number of encoded bytes
+     num_enc_bytes = 2*(MAX_SERIAL_SIZE+6)
+
+ ELSE
+     // Invalid output_format, set up error code
+     num_enc_bytes = -1
+
+ ENDIF
+
+ MODIFY (nothing)
+ RETURN (num_enc_bytes)
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 AMREncode(
+    void *pEncState,
+    void *pSidSyncState,
+    enum Mode mode,
+    Word16 *pEncInput,
+    UWord8 *pEncOutput,
+    enum Frame_Type_3GPP *p3gpp_frame_type,
+    Word16 output_format
+)
+{
+    Word16 ets_output_bfr[MAX_SERIAL_SIZE+2];
+    UWord8 *ets_output_ptr;
+    Word16 num_enc_bytes = -1;
+    Word16 i;
+    enum TXFrameType tx_frame_type;
+    enum Mode usedMode = MR475;
+
+    /* Encode WMF or IF2 frames */
+    if ((output_format == AMR_TX_WMF) | (output_format == AMR_TX_IF2))
+    {
+        /* Encode one speech frame (20 ms) */
+
+#ifndef CONSOLE_ENCODER_REF
+
+        /* Use PV version of sp_enc.c */
+        GSMEncodeFrame(pEncState, mode, pEncInput, ets_output_bfr, &usedMode);
+
+#else
+        /* Use ETS version of sp_enc.c */
+        Speech_Encode_Frame(pEncState, mode, pEncInput, ets_output_bfr, &usedMode);
+
+#endif
+
+        /* Determine transmit frame type */
+        sid_sync(pSidSyncState, usedMode, &tx_frame_type);
+
+        if (tx_frame_type != TX_NO_DATA)
+        {
+            /* There is data to transmit */
+            *p3gpp_frame_type = (enum Frame_Type_3GPP) usedMode;
+
+            /* Add SID type and mode info for SID frames */
+            if (*p3gpp_frame_type == AMR_SID)
+            {
+                /* Add SID type to encoder output buffer */
+                if (tx_frame_type == TX_SID_FIRST)
+                {
+                    ets_output_bfr[AMRSID_TXTYPE_BIT_OFFSET] &= 0x0000;
+                }
+                else if (tx_frame_type == TX_SID_UPDATE)
+                {
+                    ets_output_bfr[AMRSID_TXTYPE_BIT_OFFSET] |= 0x0001;
+                }
+
+                /* Add mode information bits */
+                for (i = 0; i < NUM_AMRSID_TXMODE_BITS; i++)
+                {
+                    ets_output_bfr[AMRSID_TXMODE_BIT_OFFSET+i] =
+                        (mode >> i) & 0x0001;
+                }
+            }
+        }
+        else
+        {
+            /* This is no data to transmit */
+            *p3gpp_frame_type = (enum Frame_Type_3GPP)AMR_NO_DATA;
+        }
+
+        /* At this point, output format is ETS */
+        /* Determine the output format to use */
+        if (output_format == AMR_TX_WMF)
+        {
+            /* Change output data format to WMF */
+            ets_to_wmf(*p3gpp_frame_type, ets_output_bfr, pEncOutput);
+
+            /* Set up the number of encoded WMF bytes */
+            num_enc_bytes = WmfEncBytesPerFrame[(Word16) *p3gpp_frame_type];
+
+        }
+        else if (output_format == AMR_TX_IF2)
+        {
+            /* Change output data format to IF2 */
+            ets_to_if2(*p3gpp_frame_type, ets_output_bfr, pEncOutput);
+
+            /* Set up the number of encoded IF2 bytes */
+            num_enc_bytes = If2EncBytesPerFrame[(Word16) *p3gpp_frame_type];
+
+        }
+    }
+
+    /* Encode ETS frames */
+    else if (output_format == AMR_TX_ETS)
+    {
+        /* Encode one speech frame (20 ms) */
+
+#ifndef CONSOLE_ENCODER_REF
+
+        /* Use PV version of sp_enc.c */
+        GSMEncodeFrame(pEncState, mode, pEncInput, &ets_output_bfr[1], &usedMode);
+
+#else
+        /* Use ETS version of sp_enc.c */
+        Speech_Encode_Frame(pEncState, mode, pEncInput, &ets_output_bfr[1], &usedMode);
+
+#endif
+
+        /* Save used mode */
+        *p3gpp_frame_type = (enum Frame_Type_3GPP) usedMode;
+
+        /* Determine transmit frame type */
+        sid_sync(pSidSyncState, usedMode, &tx_frame_type);
+
+        /* Put TX frame type in output buffer */
+        ets_output_bfr[0] = tx_frame_type;
+
+        /* Put mode information after the encoded speech parameters */
+        if (tx_frame_type != TX_NO_DATA)
+        {
+            ets_output_bfr[1+MAX_SERIAL_SIZE] = (Word16) mode;
+        }
+        else
+        {
+            ets_output_bfr[1+MAX_SERIAL_SIZE] = -1;
+        }
+
+        /* Copy output of encoder to pEncOutput buffer */
+        ets_output_ptr = (UWord8 *) & ets_output_bfr[0];
+
+        /* Copy 16-bit data in 8-bit chunks  */
+        /* using Little Endian configuration */
+        for (i = 0; i < 2*(MAX_SERIAL_SIZE + 2); i++)
+        {
+            *(pEncOutput + i) = *ets_output_ptr;
+            ets_output_ptr += 1;
+        }
+
+        /* Set up the number of encoded bytes */
+        num_enc_bytes = 2 * (MAX_SERIAL_SIZE + 2);
+
+    }
+
+    /* Invalid frame format */
+    else
+    {
+        /* Invalid output format, set up error code */
+        num_enc_bytes = -1;
+    }
+
+    return(num_enc_bytes);
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/amrencode.h b/media/libstagefright/codecs/amrnb/enc/src/amrencode.h
new file mode 100644
index 0000000..1e85db1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/amrencode.h
@@ -0,0 +1,156 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm-amr/c/include/amrencode.h
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed hard tabs from file.
+
+ Description: Added #define for WMF and IF2, and updated function prototype.
+
+ Description: Renamed WMF to AMR_WMF, IF2 to AMR_IF2, and added AMR_ETS.
+
+ Description: Changed output_type to output_format.
+
+ Description: Added external reference to WmfEncBytesPerFrame and
+              If2EncBytesPerFrame tables.
+
+ Description: Updated function prototype for AMREncode(). Added function
+              prototype for AMREncodeInit, AMREncodeReset, and AMREncodeExit.
+              Added #defines for TX SID frame formatting.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the function prototype of AMREncode.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _AMRENCODE_H_
+#define _AMRENCODE_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "frame_type_3gpp.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+#define NUM_AMRSID_TXMODE_BITS     3
+#define AMRSID_TXMODE_BIT_OFFSET   36
+#define AMRSID_TXTYPE_BIT_OFFSET   35
+
+    /* Output format types */
+#define AMR_TX_WMF 0
+#define AMR_TX_IF2 1
+#define AMR_TX_ETS 2
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+    extern const Word16 WmfEncBytesPerFrame[];
+    extern const Word16 If2EncBytesPerFrame[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 AMREncodeInit(
+        void **pEncStructure,
+        void **pSidSyncStructure,
+        Flag dtx_enable);
+
+    Word16 AMREncodeReset(
+        void *pEncStructure,
+        void *pSidSyncStructure);
+
+    void AMREncodeExit(
+        void **pEncStructure,
+        void **pSidSyncStructure);
+
+    Word16 AMREncode(
+        void *pEncState,
+        void *pSidSyncState,
+        enum Mode mode,
+        Word16 *pEncInput,
+        UWord8 *pEncOutput,
+        enum Frame_Type_3GPP *p3gpp_frame_type,
+        Word16 output_format
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _AMRENCODE_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/autocorr.cpp b/media/libstagefright/codecs/amrnb/enc/src/autocorr.cpp
new file mode 100644
index 0000000..0d3acac4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/autocorr.cpp
@@ -0,0 +1,459 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/autocorr.c
+
+     Date: 05/15/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put into template...starting optimization.
+
+ Description: Removed call to mult_r routine.
+
+ Description: Modified Input/Output Definitions section to comply with the
+          current template. Fixed tabs.
+
+ Description: Updated Input/Output definitions by making them more
+          descriptive.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Added full pathname of file.
+              2. Fixed typecasting issue with TI compiler.
+              3. Modified FOR loops to count down.
+              4. Added comment to the code.
+
+ Description: Removed extern to global paramter (Flag Overflow) and replaced
+ by passing in a pointer to Overflow.  Also, made several small changes to
+ bring code more in line with PV Standards.
+
+ Description:
+            1. Added pointer to avoid adding offsets in every pass
+            2. Break last loop in two nested loop to speed up processing
+            3. Removed extra check for overflow by doing scaling right
+               after overflow is detected.
+            4. Eliminated calls to basic operations (like extract) not
+               needed because of the nature of the number (all bounded)
+
+ Description:
+              1. Fixed for:
+                overflow check was looking for positive number before a left
+                shift. When numbers were big enough, positive numbers after
+                shifted became negative, causing a 1/0 division).
+                Fixed so now it checks for numbers lesser than 0x40000000
+                before the left shift
+
+ Description:
+              1.Modified check for saturation to match bit exact test.
+                Also, when saturation is reached, a faster loop is used
+                (with no energy accumulation) to speed up processing
+
+
+ Description:
+              1.Added pointer initialization to for loop when saturation
+                is found. This because some compiler ( like Vcpp in release
+                mode) when optimizing code, may remove pointer information
+                once the loop is broken.
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Using inlines from fxp_arithmetic.h.
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "autocorr.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Autocorr
+----------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x = buffer of input signals of type Word16
+    m = LPC order of type Word16
+    wind = buffer of window signals of type Word16
+    r_h = buffer containing the high word of the autocorrelation values
+          of type Word16
+    r_l = buffer containing the low word of the autocorrelation values
+          of type Word16
+
+    pOverflow = pointer to variable of type Flag *, which indicates if
+                overflow occurs.
+
+ Outputs:
+    r_h buffer contains the high word of the new autocorrelation values
+    r_l buffer contains the low word of the new autocorrelation values
+    pOverflow -> 1 if overflow occurs.
+
+ Returns:
+    norm = normalized autocorrelation at lag zero of type Word16
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function windows the input signal with the provided window
+ then calculates the autocorrelation values for lags of 0,1,...m,
+ where m is the passed in LPC order.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ autocorr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Autocorr (
+    Word16 x[],            // (i)    : Input signal (L_WINDOW)
+    Word16 m,              // (i)    : LPC order
+    Word16 r_h[],          // (o)    : Autocorrelations  (msb)
+    Word16 r_l[],          // (o)    : Autocorrelations  (lsb)
+    const Word16 wind[]    // (i)    : window for LPC analysis (L_WINDOW)
+)
+{
+    Word16 i, j, norm;
+    Word16 y[L_WINDOW];
+    Word32 sum;
+    Word16 overfl, overfl_shft;
+
+    // Windowing of signal
+
+    for (i = 0; i < L_WINDOW; i++)
+    {
+        y[i] = mult_r (x[i], wind[i]);
+    }
+
+    // Compute r[0] and test for overflow
+
+    overfl_shft = 0;
+
+    do
+    {
+        overfl = 0;
+        sum = 0L;
+
+        for (i = 0; i < L_WINDOW; i++)
+        {
+            sum = L_mac (sum, y[i], y[i]);
+        }
+
+        // If overflow divide y[] by 4
+
+        if (L_sub (sum, MAX_32) == 0L)
+        {
+            overfl_shft = add (overfl_shft, 4);
+            overfl = 1; // Set the overflow flag
+
+            for (i = 0; i < L_WINDOW; i++)
+            {
+                y[i] = shr (y[i], 2);
+            }
+        }
+    }
+    while (overfl != 0);
+
+    sum = L_add (sum, 1L);             // Avoid the case of all zeros
+
+    // Normalization of r[0]
+
+    norm = norm_l (sum);
+    sum = L_shl (sum, norm);
+    L_Extract (sum, &r_h[0], &r_l[0]); // Put in DPF format (see oper_32b)
+
+    // r[1] to r[m]
+
+    for (i = 1; i <= m; i++)
+    {
+        sum = 0;
+
+        for (j = 0; j < L_WINDOW - i; j++)
+        {
+            sum = L_mac (sum, y[j], y[j + i]);
+        }
+
+        sum = L_shl (sum, norm);
+        L_Extract (sum, &r_h[i], &r_l[i]);
+    }
+
+    norm = sub (norm, overfl_shft);
+
+    return norm;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Autocorr(
+    Word16 x[],            /* (i)    : Input signal (L_WINDOW)            */
+    Word16 m,              /* (i)    : LPC order                          */
+    Word16 r_h[],          /* (o)    : Autocorrelations  (msb)            */
+    Word16 r_l[],          /* (o)    : Autocorrelations  (lsb)            */
+    const Word16 wind[],   /* (i)    : window for LPC analysis (L_WINDOW) */
+    Flag  *pOverflow       /* (o)    : indicates overflow                 */
+)
+{
+    register Word16 i;
+    register Word16 j;
+    register Word16 norm;
+
+    Word16 y[L_WINDOW];
+    Word32 sum;
+    Word16 overfl_shft;
+
+
+    /* Added for optimization  */
+
+
+    Word16 temp;
+    Word16 *p_x;
+    Word16 *p_y;
+    Word16 *p_y_1;
+    Word16 *p_y_ref;
+    Word16 *p_rh;
+    Word16 *p_rl;
+    const Word16 *p_wind;
+    p_y = y;
+    p_x = x;
+    p_wind = wind;
+    /*
+     *  Windowing of the signal
+     */
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    sum = 0L;
+    j = 0;
+
+    for (i = L_WINDOW; i != 0; i--)
+    {
+        temp = (amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_wind++), 0x04000)) >> 15;
+        *(p_y++) = temp;
+
+        sum += ((Word32)temp * temp) << 1;
+        if (sum < 0)
+        {
+            /*
+             * if oveflow exist, then stop accumulation
+             */
+            j = 1;
+            break;
+        }
+
+    }
+    /*
+     * if oveflow existed, complete  windowing operation
+     * without computing energy
+     */
+
+    if (j)
+    {
+        p_y = &y[L_WINDOW-i];
+        p_x = &x[L_WINDOW-i];
+        p_wind = &wind[L_WINDOW-i];
+
+        for (; i != 0; i--)
+        {
+            temp = (amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_wind++), 0x04000)) >> 15;
+            *(p_y++) = temp;
+        }
+    }
+
+
+    /*
+     *  Compute r[0] and test for overflow
+     */
+
+    overfl_shft = 0;
+
+    /*
+     * scale down by 1/4 only when needed
+     */
+    while (j == 1)
+    {
+        /* If overflow divide y[] by 4          */
+        /* FYI: For better resolution, we could */
+        /*      divide y[] by 2                 */
+        overfl_shft += 4;
+        p_y   = &y[0];
+        sum = 0L;
+
+        for (i = (L_WINDOW >> 1); i != 0 ; i--)
+        {
+            temp = *p_y >> 2;
+            *(p_y++) = temp;
+            sum += ((Word32)temp * temp) << 1;
+            temp = *p_y >> 2;
+            *(p_y++) = temp;
+            sum += ((Word32)temp * temp) << 1;
+        }
+        if (sum > 0)
+        {
+            j = 0;
+        }
+
+    }
+
+    sum += 1L;              /* Avoid the case of all zeros */
+
+    /* Normalization of r[0] */
+
+    norm = norm_l(sum);
+
+    sum <<= norm;
+
+    /* Put in DPF format (see oper_32b) */
+    r_h[0] = (Word16)(sum >> 16);
+    r_l[0] = (Word16)((sum >> 1) - ((Word32)(r_h[0]) << 15));
+
+    /* r[1] to r[m] */
+
+    p_y_ref = &y[L_WINDOW - 1 ];
+    p_rh = &r_h[m];
+    p_rl = &r_l[m];
+
+    for (i = m; i > 0; i--)
+    {
+        sum  = 0;
+
+        p_y   = &y[L_WINDOW - i - 1];
+        p_y_1 = p_y_ref;
+
+        for (j = (L_WINDOW - i - 1) >> 1; j != 0; j--)
+        {
+            sum = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y--), (Word32) * (p_y_1--), sum);
+            sum = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y--), (Word32) * (p_y_1--), sum);
+        }
+
+        sum = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y--), (Word32) * (p_y_1--), sum);
+
+        if (((L_WINDOW - i - 1) & 1))
+        {
+            sum = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y--), (Word32) * (p_y_1--), sum);
+        }
+
+        sum  <<= (norm + 1);
+
+        *(p_rh)   = (Word16)(sum >> 16);
+        *(p_rl--) = (Word16)((sum >> 1) - ((Word32) * (p_rh--) << 15));
+
+    }
+
+    norm -= overfl_shft;
+
+    return (norm);
+
+} /* Autocorr */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/autocorr.h b/media/libstagefright/codecs/amrnb/enc/src/autocorr.h
new file mode 100644
index 0000000..6045d6e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/autocorr.h
@@ -0,0 +1,118 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/autocorr.h
+
+     Date: 01/23/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the autocorr function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef autocorr_h
+#define autocorr_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 Autocorr(
+        Word16 x[],            /* (i)    : Input signal (L_WINDOW)            */
+        Word16 m,              /* (i)    : LPC order                          */
+        Word16 r_h[],          /* (o)    : Autocorrelations  (msb)            */
+        Word16 r_l[],          /* (o)    : Autocorrelations  (lsb)            */
+        const Word16 wind[],   /* (i)    : window for LPC analysis (L_WINDOW) */
+        Flag  *pOverflow       /* (o)    : indicates overflow                 */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _AUTO_CORR_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c1035pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c1035pf.cpp
new file mode 100644
index 0000000..d95995c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c1035pf.cpp
@@ -0,0 +1,676 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c1035pf.c
+ Functions: q_p
+            build_code
+            code_10i40_35bits
+
+
+     Date: 09/28/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Cleaned up code. Passing in a pointer to
+              overflow flag for build_code() and code_10i40_35bits() functions.
+              Removed unnecessary header files.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation
+              4. Replaced for-loops with memset()
+
+ Description: Changed function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the function that searches a 35 bit algebraic codebook
+ containing 10 pulses in a frame of 40 samples.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "c1035pf.h"
+#include "cnst.h"
+#include "basic_op.h"
+#include "inv_sqrt.h"
+#include "set_sign.h"
+#include "cor_h.h"
+#include "cor_h_x.h"
+#include "s10_8pf.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+#define NB_PULSE  10
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: q_p
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pShift_reg = pointer to Old CN generator shift register state (Word32)
+    no_bits = Number of bits (Word16)
+
+ Outputs:
+    pShift_reg -> Updated CN generator shift register state
+
+ Returns:
+    noise_bits = Generated random integer value (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This is a local function that determnes the index of the pulses by looking up
+ the gray encoder table
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c1035pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void q_p (
+    Word16 *ind,        // Pulse position
+    Word16 n            // Pulse number
+)
+{
+    Word16 tmp;
+
+    tmp = *ind;
+
+    if (sub (n, 5) < 0)
+    {
+        *ind = (tmp & 0x8) | gray[tmp & 0x7];
+    }
+    else
+    {
+        *ind = gray[tmp & 0x7];
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void q_p(
+    Word16 *pInd,       /* Pulse position */
+    Word16 n            /* Pulse number   */
+)
+{
+    Word16 tmp;
+
+    tmp = *pInd;
+
+    if (n < 5)
+    {
+        *pInd = (tmp & 0x8) | gray[tmp & 0x7];
+    }
+    else
+    {
+        *pInd = gray[tmp & 0x7];
+    }
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: build_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pSeed = pointer to the Old CN generator shift register state (Word32)
+    n_param = Number of parameters to randomize (Word16)
+    param_size_table = table holding paameter sizes (Word16)
+    param[] = array to hold CN generated paramters (Word16)
+    pOverflow = pointer to overflow flag (Flag)
+
+ Outputs:
+    param[] = CN generated parameters (Word16)
+    pSeed = Updated CN generator shift register state (Word16)
+    pOverflow -> 1 if overflow occured
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function builds the codeword, the filtered codeword and index of the
+ codevector, based on the signs and positions of 10 pulses.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c1035pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+static void build_code (
+    Word16 codvec[],    // (i)  : position of pulses
+    Word16 sign[],      // (i)  : sign of d[n]
+    Word16 cod[],       // (o)  : innovative code vector
+    Word16 h[],         // (i)  : impulse response of weighted synthesis filter
+    Word16 y[],         // (o)  : filtered innovative code
+    Word16 indx[]       // (o)  : index of 10 pulses (sign+position)
+)
+{
+    Word16 i, j, k, track, index, _sign[NB_PULSE];
+    Word16 *p0, *p1, *p2, *p3, *p4, *p5, *p6, *p7, *p8, *p9;
+    Word32 s;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        cod[i] = 0;
+    }
+    for (i = 0; i < NB_TRACK; i++)
+    {
+        indx[i] = -1;
+    }
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        // read pulse position
+        i = codvec[k];
+        // read sign
+        j = sign[i];
+
+        index = mult (i, 6554);                  // index = pos/5
+        // track = pos%5
+        track = sub (i, extract_l (L_shr (L_mult (index, 5), 1)));
+
+        if (j > 0)
+        {
+            cod[i] = add (cod[i], 4096);
+            _sign[k] = 8192;
+
+        }
+        else
+        {
+            cod[i] = sub (cod[i], 4096);
+            _sign[k] = -8192;
+            index = add (index, 8);
+        }
+
+        if (indx[track] < 0)
+        {
+            indx[track] = index;
+        }
+        else
+        {
+            if (((index ^ indx[track]) & 8) == 0)
+            {
+                // sign of 1st pulse == sign of 2nd pulse
+
+                if (sub (indx[track], index) <= 0)
+                {
+                    indx[track + 5] = index;
+                }
+                else
+                {
+                    indx[track + 5] = indx[track];
+                    indx[track] = index;
+                }
+            }
+            else
+            {
+                // sign of 1st pulse != sign of 2nd pulse
+
+                if (sub ((Word16)(indx[track] & 7), (Word16)(index & 7)) <= 0)
+                {
+                    indx[track + 5] = indx[track];
+                    indx[track] = index;
+                }
+                else
+                {
+                    indx[track + 5] = index;
+                }
+            }
+        }
+    }
+
+    p0 = h - codvec[0];
+    p1 = h - codvec[1];
+    p2 = h - codvec[2];
+    p3 = h - codvec[3];
+    p4 = h - codvec[4];
+    p5 = h - codvec[5];
+    p6 = h - codvec[6];
+    p7 = h - codvec[7];
+    p8 = h - codvec[8];
+    p9 = h - codvec[9];
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = 0;
+        s = L_mac (s, *p0++, _sign[0]);
+        s = L_mac (s, *p1++, _sign[1]);
+        s = L_mac (s, *p2++, _sign[2]);
+        s = L_mac (s, *p3++, _sign[3]);
+        s = L_mac (s, *p4++, _sign[4]);
+        s = L_mac (s, *p5++, _sign[5]);
+        s = L_mac (s, *p6++, _sign[6]);
+        s = L_mac (s, *p7++, _sign[7]);
+        s = L_mac (s, *p8++, _sign[8]);
+        s = L_mac (s, *p9++, _sign[9]);
+        y[i] = pv_round (s);
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+static void build_code(
+    Word16 codvec[],    /* (i)  : position of pulses                        */
+    Word16 sign[],      /* (i)  : sign of d[n]                              */
+    Word16 cod[],       /* (o)  : innovative code vector                    */
+    Word16 h[],         /* (i)  : impulse response of weighted synthesis filter*/
+    Word16 y[],         /* (o)  : filtered innovative code                  */
+    Word16 indx[],      /* (o)  : index of 10 pulses (sign+position)        */
+    Flag   *pOverflow   /* i/o  : overflow Flag                             */
+)
+{
+    Word16 i, k, track, index, _sign[NB_PULSE];
+    Word16 *p0, *p1, *p2, *p3, *p4, *p5, *p6, *p7, *p8, *p9;
+    Word32 s;
+    Word16 temp;
+    Word16 *p__sign;
+    Word16 *p_y;
+    Word16 *p_codvec;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    memset(cod, 0, L_CODE*sizeof(*cod));
+    memset(indx, 0xFF, NB_TRACK*sizeof(*indx));
+
+    p__sign = _sign;
+
+    p0 = &codvec[0];
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        /* read pulse position */
+        i = *(p0++);
+        /* read sign           */
+
+        index = ((Word32)i * 6554) >> 15;       /* index = pos/5    */
+
+        /* track = pos%5 */
+        /* track = sub (i, extract_l (L_shr (L_mult (index, 5), 1))); */
+        track = i - (index * 5);
+
+        if (sign[i] > 0)
+        {
+            cod[i] +=  4096;
+            *(p__sign++) = 8192;
+
+        }
+        else
+        {
+            cod[i] -=  4096;
+            *(p__sign++) = -8192;
+            /* index = add (index, 8); */
+            index += 8;
+        }
+
+        p1 = &indx[track];
+
+        temp = *p1;
+
+        if (temp < 0)
+        {
+            *p1 = index;
+        }
+        else
+        {
+            if (((index ^ temp) & 8) == 0)
+            {
+                /* sign of 1st pulse == sign of 2nd pulse */
+
+                /* if (sub (indx[track], index) <= 0) */
+                if (temp <= index)
+                {
+                    *(p1 + 5) = index;
+                }
+                else
+                {
+                    *(p1 + 5) = temp;
+                    *p1 = index;
+                }
+            }
+            else
+            {
+                /* sign of 1st pulse != sign of 2nd pulse */
+
+                /* if (sub ((Word16)(indx[track] & 7), (Word16)(index & 7)) <= 0) */
+                if ((temp & 7) <= (index & 7))
+                {
+                    *(p1 + 5) = temp;
+                    *p1 = index;
+                }
+                else
+                {
+                    *(p1 + 5) = index;
+                }
+            }
+        }
+    }
+
+    p_codvec = &codvec[0];
+
+    p0 = h - *(p_codvec++);
+    p1 = h - *(p_codvec++);
+    p2 = h - *(p_codvec++);
+    p3 = h - *(p_codvec++);
+    p4 = h - *(p_codvec++);
+    p5 = h - *(p_codvec++);
+    p6 = h - *(p_codvec++);
+    p7 = h - *(p_codvec++);
+    p8 = h - *(p_codvec++);
+    p9 = h - *(p_codvec++);
+
+    p_y = y;
+
+    for (i = L_CODE; i != 0; i--)
+    {
+        p__sign = _sign;
+
+        s  = (*p0++ * *(p__sign++)) >> 7;
+        s += (*p1++ * *(p__sign++)) >> 7;
+        s += (*p2++ * *(p__sign++)) >> 7;
+        s += (*p3++ * *(p__sign++)) >> 7;
+        s += (*p4++ * *(p__sign++)) >> 7;
+        s += (*p5++ * *(p__sign++)) >> 7;
+        s += (*p6++ * *(p__sign++)) >> 7;
+        s += (*p7++ * *(p__sign++)) >> 7;
+        s += (*p8++ * *(p__sign++)) >> 7;
+        s += (*p9++ * *(p__sign++)) >> 7;
+
+        *(p_y++) = (s + 0x080) >> 8;
+    }
+
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: code_10i40_35bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pSeed = pointer to the Old CN generator shift register state (Word32)
+    n_param = Number of parameters to randomize (Word16)
+    param_size_table = table holding paameter sizes (Word16)
+    param[] = array to hold CN generated paramters (Word16)
+    pOverflow = pointer to overflow flag (Flag)
+
+ Outputs:
+    param[] = CN generated parameters (Word16)
+    pSeed = Updated CN generator shift register state (Word16)
+    pOverflow -> 1 if overflow occured
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function searches a 35 bit algebraic codebook containing 10 pulses in a
+ frame of 40 samples.
+
+ The code contains 10 nonzero pulses: i0...i9.
+ All pulses can have two possible amplitudes: +1 or -1.
+ The 40 positions in a subframe are divided into 5 tracks of
+ interleaved positions. Each track contains two pulses.
+ The pulses can have the following possible positions:
+
+    i0, i5 :  0, 5, 10, 15, 20, 25, 30, 35.
+    i1, i6 :  1, 6, 11, 16, 21, 26, 31, 36.
+    i2, i7 :  2, 7, 12, 17, 22, 27, 32, 37.
+    i3, i8 :  3, 8, 13, 18, 23, 28, 33, 38.
+    i4, i9 :  4, 9, 14, 19, 24, 29, 34, 39.
+
+ Each pair of pulses require 1 bit for their signs and 6 bits for their
+ positions (3 bits + 3 bits). This results in a 35 bit codebook.
+ The function determines the optimal pulse signs and positions, builds
+ the codevector, and computes the filtered codevector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c1035pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+void code_10i40_35bits (
+    Word16 x[],   // (i)   : target vector
+    Word16 cn[],  // (i)   : residual after long term prediction
+    Word16 h[],   // (i)   : impulse response of weighted synthesis filter
+                           // h[-L_subfr..-1] must be set to zero
+    Word16 cod[], // (o)   : algebraic (fixed) codebook excitation
+    Word16 y[],   // (o)   : filtered fixed codebook excitation
+    Word16 indx[] // (o)   : index of 10 pulses (sign + position)
+)
+{
+    Word16 ipos[NB_PULSE], pos_max[NB_TRACK], codvec[NB_PULSE];
+    Word16 dn[L_CODE], sign[L_CODE];
+    Word16 rr[L_CODE][L_CODE], i;
+
+    cor_h_x (h, x, dn, 2);
+    set_sign12k2 (dn, cn, sign, pos_max, NB_TRACK, ipos, STEP);
+    cor_h (h, sign, rr);
+
+    search_10and8i40 (NB_PULSE, STEP, NB_TRACK,
+                      dn, rr, ipos, pos_max, codvec);
+
+    build_code (codvec, sign, cod, h, y, indx);
+    for (i = 0; i < 10; i++)
+    {
+        q_p (&indx[i], i);
+    }
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void code_10i40_35bits(
+    Word16 x[],     /* (i)   : target vector                                */
+    Word16 cn[],    /* (i)   : residual after long term prediction          */
+    Word16 h[],     /* (i)   : impulse response of weighted synthesis filter
+                             h[-L_subfr..-1] must be set to zero            */
+    Word16 cod[],   /* (o)   : algebraic (fixed) codebook excitation        */
+    Word16 y[],     /* (o)   : filtered fixed codebook excitation           */
+    Word16 indx[],  /* (o)   : index of 10 pulses (sign + position)         */
+    Flag *pOverflow /* (i/o) : overflow Flag                                */
+)
+{
+    Word16 ipos[NB_PULSE], pos_max[NB_TRACK], codvec[NB_PULSE];
+    Word16 dn[L_CODE], sign[L_CODE];
+    Word16 rr[L_CODE][L_CODE], i;
+
+    cor_h_x(h, x, dn, 2, pOverflow);
+    set_sign12k2(dn, cn, sign, pos_max, NB_TRACK, ipos, STEP, pOverflow);
+    cor_h(h, sign, rr, pOverflow);
+
+    search_10and8i40(NB_PULSE, STEP, NB_TRACK,
+                     dn, rr, ipos, pos_max, codvec, pOverflow);
+
+    build_code(codvec, sign, cod, h, y, indx, pOverflow);
+    for (i = 0; i < 10; i++)
+    {
+        q_p(&indx[i], i);
+    }
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c1035pf.h b/media/libstagefright/codecs/amrnb/enc/src/c1035pf.h
new file mode 100644
index 0000000..be45cbb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c1035pf.h
@@ -0,0 +1,124 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c1035pf.h
+
+     Date: 09/28/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Updated function prototype for
+              code_10i40_35bits(). Added extern declaration for gray[] defined
+              in gray_tbl.c
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the prototype declaration for code_10i40_35bits function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef C1035PF_H
+#define C1035PF_H "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern Word16 gray[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void code_10i40_35bits(
+        Word16 x[],     /* (i)   : target vector                                */
+        Word16 cn[],    /* (i)   : residual after long term prediction          */
+        Word16 h[],     /* (i)   : impulse response of weighted synthesis filter
+                             h[-L_subfr..-1] must be set to zero            */
+        Word16 cod[],   /* (o)   : algebraic (fixed) codebook excitation        */
+        Word16 y[],     /* (o)   : filtered fixed codebook excitation           */
+        Word16 indx[],  /* (o)   : index of 10 pulses (sign + position)         */
+        Flag *pOverflow /* (i/o) : overflow Flag                                */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _C1035PF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.cpp
new file mode 100644
index 0000000..87fa9b8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.cpp
@@ -0,0 +1,841 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c2_11pf.c
+ Functions:
+            code_2i40_11bits
+            search_2i40
+            build_code
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to pass overflow flag through to basic math function.
+ The flag is passed back to the calling function by pointer reference.
+
+ Description: Fixed tabs prior to optimization to make diff'ing easier.
+              Optimized search_2i40() to reduce clock cycle usage.
+
+ Description: Optimized build_code() to reduce clock cycle usage.
+
+ Description: Changed function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ *************************************************************************
+ *
+ *  FUNCTION:  code_2i40_11bits()
+ *
+ *  PURPOSE:  Searches a 11 bit algebraic codebook containing 2 pulses
+ *            in a frame of 40 samples.
+ *
+ *  DESCRIPTION:
+ *    The code length is 40, containing 2 nonzero pulses: i0...i1.
+ *    All pulses can have two possible amplitudes: +1 or -1.
+ *    Pulse i0 can have 2x8=16 possible positions, pulse i1 can have
+ *    4x8=32 positions.
+ *
+ *       i0 :  1, 6, 11, 16, 21, 26, 31, 36.
+ *             3, 8, 13, 18, 23, 28, 33, 38.
+ *       i1 :  0, 5, 10, 15, 20, 25, 30, 35.
+ *             1, 6, 11, 16, 21, 26, 31, 36.
+ *             2, 7, 12, 17, 22, 27, 32, 37.
+ *             4, 9, 14, 19, 24, 29, 34, 39.
+ *
+ *************************************************************************
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "c2_11pf.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "inv_sqrt.h"
+#include "cnst.h"
+#include "cor_h.h"
+#include "set_sign.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NB_PULSE  2
+
+#define _1_2    (Word16)(32768L/2)
+#define _1_4    (Word16)(32768L/4)
+#define _1_8    (Word16)(32768L/8)
+#define _1_16   (Word16)(32768L/16)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+static void search_2i40(
+    Word16 dn[],        /* i : correlation between target and h[]            */
+    Word16 rr[][L_CODE],/* i : matrix of autocorrelation                     */
+    Word16 codvec[],    /* o : algebraic codebook vector                     */
+    Flag   * pOverflow
+);
+
+static Word16 build_code(
+    Word16 codvec[],    /* i : algebraic codebook vector                     */
+    Word16 dn_sign[],   /* i : sign of dn[]                                  */
+    Word16 cod[],       /* o : algebraic (fixed) codebook excitation         */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter */
+    Word16 y[],         /* o : filtered fixed codebook excitation            */
+    Word16 sign[],      /* o : sign of 2 pulses                              */
+    Flag   * pOverflow
+);
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+const Word16 startPos1[2] = {1, 3};
+const Word16 startPos2[4] = {0, 1, 2, 4};
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: code_2i40_11bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x,  target vector, array of type Word16
+    h,  impulse response of weighted synthesis filter, array of type Word16
+    T0, Pitch lag, variable of type Word16
+    pitch_sharp, Last quantized pitch gain, variable of type Word16
+
+ Outputs:
+    code[], Innovative codebook, array of type Word16
+    y[],    filtered fixed codebook excitation, array of type Word16
+    sign,   Signs of 2 pulses, pointer of type Word16 *
+    pOverflow  Flag set when overflow occurs, pointer of type Flag *
+
+ Returns:
+    index
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+     Searches a 11 bit algebraic codebook containing 2 pulses
+     in a frame of 40 samples.
+
+     The code length is 40, containing 2 nonzero pulses: i0...i1.
+     All pulses can have two possible amplitudes: +1 or -1.
+     Pulse i0 can have 2x8=16 possible positions, pulse i1 can have
+     4x8=32 positions.
+
+        i0 :  1, 6, 11, 16, 21, 26, 31, 36.
+              3, 8, 13, 18, 23, 28, 33, 38.
+        i1 :  0, 5, 10, 15, 20, 25, 30, 35.
+              1, 6, 11, 16, 21, 26, 31, 36.
+              2, 7, 12, 17, 22, 27, 32, 37.
+              4, 9, 14, 19, 24, 29, 34, 39.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c2_11pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 code_2i40_11bits(
+    Word16 x[],         /* i : target vector                                 */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter */
+    /*     h[-L_subfr..-1] must be set to zero.          */
+    Word16 T0,          /* i : Pitch lag                                     */
+    Word16 pitch_sharp, /* i : Last quantized pitch gain                     */
+    Word16 code[],      /* o : Innovative codebook                           */
+    Word16 y[],         /* o : filtered fixed codebook excitation            */
+    Word16 * sign,      /* o : Signs of 2 pulses                             */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+)
+{
+    Word16 codvec[NB_PULSE];
+    Word16 dn[L_CODE];
+    Word16 dn2[L_CODE];
+    Word16 dn_sign[L_CODE];
+
+    Word16 rr[L_CODE][L_CODE];
+
+    Word16 i;
+    Word16 index;
+    Word16 sharp;
+    Word16 tempWord;
+
+    sharp = pitch_sharp << 1;
+
+    if (T0 < L_CODE)
+    {
+        for (i = T0; i < L_CODE; i++)
+        {
+            tempWord =
+                mult(
+                    h[i - T0],
+                    sharp,
+                    pOverflow);
+
+            h[i] =
+                add(
+                    h[i],
+                    tempWord,
+                    pOverflow);
+        }
+
+    }
+
+    cor_h_x(
+        h,
+        x,
+        dn,
+        1,
+        pOverflow);
+
+    set_sign(
+        dn,
+        dn_sign,
+        dn2,
+        8); /* dn2[] not used in this codebook search */
+
+    cor_h(
+        h,
+        dn_sign,
+        rr,
+        pOverflow);
+
+    search_2i40(
+        dn,
+        rr,
+        codvec,
+        pOverflow);
+
+    /* function result */
+
+    index =
+        build_code(
+            codvec,
+            dn_sign,
+            code,
+            h,
+            y,
+            sign,
+            pOverflow);
+
+    /*
+    * Compute innovation vector gain.
+    * Include fixed-gain pitch contribution into code[].
+    */
+
+    if (T0 < L_CODE)
+    {
+        for (i = T0; i < L_CODE; i++)
+        {
+            tempWord =
+                mult(
+                    code[i - T0],
+                    sharp,
+                    pOverflow);
+
+            code[i] =
+                add(
+                    code[i],
+                    tempWord,
+                    pOverflow);
+        }
+    }
+
+    return index;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: search_2i40
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    dn, correlation between target and h[], array of type Word16
+    rr, matrix of autocorrelation, double-array of type Word16
+
+ Outputs:
+    codvec[],  algebraic codebook vector, array of type Word16
+    pOverflow, Flag set when overflow occurs, pointer of type Flag *
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Search the best codevector; determine positions of the 2 pulses
+ in the 40-sample frame.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c2_11pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void search_2i40(
+    Word16 dn[],         /* i : correlation between target and h[] */
+    Word16 rr[][L_CODE], /* i : matrix of autocorrelation          */
+    Word16 codvec[],     /* o : algebraic codebook vector          */
+    Flag   * pOverflow   /* o : Flag set when overflow occurs      */
+)
+{
+    Word16 i0;
+    Word16 i1;
+    Word16 ix = 0; /* initialization only needed to keep gcc silent */
+    Word16 track1;
+    Word16 track2;
+    Word16 ipos[NB_PULSE];
+
+    Word16 psk;
+    Word16 ps0;
+    Word16 ps1;
+    Word16 sq;
+    Word16 sq1;
+
+    Word16 alpk;
+    Word16 alp;
+    Word16 alp_16;
+
+    Word32 s;
+    Word32 alp0;
+    Word32 alp1;
+
+    Word16 i;
+    Word16 *p_codvec = &codvec[0];
+
+    psk = -1;
+    alpk = 1;
+
+    for (i = 0; i < NB_PULSE; i++)
+    {
+        *(p_codvec++) = i;
+    }
+
+    /*------------------------------------------------------------------*
+    * main loop: try 2x4  tracks.                                      *
+    *------------------------------------------------------------------*/
+
+    for (track1 = 0; track1 < 2; track1++)
+    {
+        for (track2 = 0; track2 < 4; track2++)
+        {
+            /* fix starting position */
+            ipos[0] = startPos1[track1];
+            ipos[1] = startPos2[track2];
+
+            /*----------------------------------------------------------------*
+            * i0 loop: try 8 positions.                                      *
+            *----------------------------------------------------------------*/
+            for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP)
+            {
+                ps0 = dn[i0];
+
+                /* alp0 = L_mult(rr[i0][i0], _1_4, pOverflow); */
+                alp0 = (Word32) rr[i0][i0] << 14;
+
+                /*-------------------------------------------------------------*
+                * i1 loop: 8 positions.                                       *
+                *-------------------------------------------------------------*/
+
+                sq = -1;
+                alp = 1;
+                ix = ipos[1];
+
+                /*---------------------------------------------------------------*
+                * These index have low complexity address computation because   *
+                * they are, in fact, pointers with fixed increment. For example,*
+                * "rr[i0][i2]" is a pointer initialized to "&rr[i0][ipos[2]]"   *
+                * and incremented by "STEP".                                    *
+                *---------------------------------------------------------------*/
+
+                for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP)
+                {
+                    /* idx increment = STEP */
+                    ps1 = add(ps0, dn[i1], pOverflow);
+
+                    /* alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1]; */
+
+                    /* idx incr = STEP */
+                    /* alp1 = L_mac(alp0, rr[i1][i1], _1_4, pOverflow); */
+                    alp1 = alp0 + ((Word32) rr[i1][i1] << 14);
+
+                    /* idx incr = STEP */
+                    /* alp1 = L_mac(alp1, rr[i0][i1], _1_2, pOverflow); */
+                    alp1 += (Word32) rr[i0][i1] << 15;
+
+                    /* sq1 = mult(ps1, ps1, pOverflow); */
+                    sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                    /* alp_16 = pv_round(alp1, pOverflow); */
+                    alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                    /* s = L_mult(alp, sq1, pOverflow); */
+                    s = ((Word32) alp * sq1) << 1;
+
+                    /* s =L_msu(s, sq, alp_16, pOverflow); */
+                    s -= (((Word32) sq * alp_16) << 1);
+
+                    if (s > 0)
+                    {
+                        sq = sq1;
+                        alp = alp_16;
+                        ix = i1;
+                    }
+
+                } /* for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP) */
+
+                /* memorize codevector if this one is better than the last one. */
+
+                /* s = L_mult(alpk, sq, pOverflow); */
+                s = ((Word32) alpk * sq) << 1;
+
+                /* s = L_msu(s, psk, alp, pOverflow); */
+                s -= (((Word32) psk * alp) << 1);
+
+                if (s > 0)
+                {
+                    psk = sq;
+                    alpk = alp;
+                    p_codvec = &codvec[0];
+
+                    *(p_codvec++) = i0;
+                    *(p_codvec) = ix;
+                }
+
+            } /* for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP) */
+
+        } /* for (track2 = 0; track2 < 4; track2++) */
+
+    } /* for (track1 = 0; track1 < 2; track1++) */
+
+    return;
+
+} /* search_2i40 */
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: build_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    codvec,  position of pulses, array of type Word16
+    dn_sign, sign of pulses, array of type Word16
+    h,       impulse response of weighted synthesis filter, Word16 array
+
+ Outputs:
+
+    cod,       innovative code vector, array of type Word16
+    y[],       filtered innovative code, array of type Word16
+    sign[],    sign of 2 pulses, array of type Word16
+    pOverflow, Flag set when overflow occurs, pointer of type Flag *
+
+ Returns:
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Builds the codeword, the filtered codeword and index of the
+ codevector, based on the signs and positions of 2 pulses.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c2_11pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+static Word16 build_code(
+    Word16 codvec[],    /* i : position of pulses                            */
+    Word16 dn_sign[],   /* i : sign of pulses                                */
+    Word16 cod[],       /* o : innovative code vector                        */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter */
+    Word16 y[],         /* o : filtered innovative code                      */
+    Word16 sign[],      /* o : sign of 2 pulses                              */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 k;
+    Word16 track;
+    Word16 index;
+    Word16 _sign[NB_PULSE];
+    Word16 indx;
+    Word16 rsign;
+    Word16 tempWord;
+
+    Word16 *p0;
+    Word16 *p1;
+
+    Word32 s;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        cod[i] = 0;
+    }
+
+    indx = 0;
+    rsign = 0;
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        i = codvec[k];      /* read pulse position */
+        j = dn_sign[i];     /* read sign           */
+
+        /* index = pos/5 */
+        /* index = mult(i, 6554, pOverflow); */
+        index = (Word16)(((Word32) i * 6554) >> 15);
+
+        /* track = pos%5 */
+        /* tempWord =
+            L_mult(
+            index,
+            5,
+            pOverflow); */
+        tempWord = ((Word32) index * 5) << 1;
+
+        /* tempWord =
+            L_shr(
+            tempWord,
+            1,
+            pOverflow); */
+        tempWord >>= 1;
+
+
+        /* track =
+            sub(
+            i,
+            tempWord,
+            pOverflow); */
+        track = i - tempWord;
+
+        tempWord = track;
+
+        if (tempWord == 0)
+        {
+            track = 1;
+
+            /* index =
+                shl(
+                index,
+                6,
+                pOverflow); */
+            index <<= 6;
+        }
+        else if (track == 1)
+        {
+            tempWord = k;
+
+            if (tempWord == 0)
+            {
+                track = 0;
+                /* index =
+                    shl(
+                    index,
+                    1,
+                    pOverflow); */
+                index <<= 1;
+            }
+            else
+            {
+                track = 1;
+
+                /* tempWord =
+                    shl(
+                    index,
+                    6,
+                    pOverflow); */
+                tempWord = index << 6;
+
+                /* index =
+                    add(
+                    tempWord,
+                    16,
+                    pOverflow); */
+                index = tempWord + 16;
+            }
+        }
+        else if (track == 2)
+        {
+            track = 1;
+
+            /* tempWord =
+                shl(
+                index,
+                6,
+                pOverflow); */
+            tempWord = index << 6;
+
+            /* index =
+                add(
+                tempWord,
+                32,
+                pOverflow); */
+            index = tempWord + 32;
+        }
+        else if (track == 3)
+        {
+            track = 0;
+
+            /* tempWord =
+                shl(
+                index,
+                1,
+                pOverflow); */
+            tempWord = index << 1;
+
+            /* index =
+                add(
+                tempWord,
+                1,
+                pOverflow); */
+            index = tempWord + 1;
+        }
+        else if (track == 4)
+        {
+            track = 1;
+
+            /* tempWord =
+                shl(
+                index,
+                6,
+                pOverflow); */
+            tempWord = index << 6;
+
+            /* index =
+                add(
+                tempWord,
+                48,
+                pOverflow); */
+            index = tempWord + 48;
+        }
+
+        if (j > 0)
+        {
+            cod[i] = 8191;
+            _sign[k] = 32767;
+
+            tempWord =
+                shl(
+                    1,
+                    track,
+                    pOverflow);
+
+            rsign =
+                add(
+                    rsign,
+                    tempWord,
+                    pOverflow);
+        }
+        else
+        {
+            cod[i] = -8192;
+            _sign[k] = (Word16) - 32768L;
+        }
+
+        indx =
+            add(
+                indx,
+                index,
+                pOverflow);
+    }
+    *sign = rsign;
+
+    p0 = h - codvec[0];
+    p1 = h - codvec[1];
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = 0;
+
+        s =
+            L_mac(
+                s,
+                *p0++,
+                _sign[0],
+                pOverflow);
+
+        s =
+            L_mac(
+                s,
+                *p1++,
+                _sign[1],
+                pOverflow);
+
+        y[i] =
+            pv_round(
+                s,
+                pOverflow);
+    }
+
+    return indx;
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.h b/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.h
new file mode 100644
index 0000000..f963ae1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c2_11pf.h
@@ -0,0 +1,121 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c2_11pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the c2_11pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef c2_11pf_h
+#define c2_11pf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 code_2i40_11bits(
+        Word16 x[], /* i : target vector                                 */
+        Word16 h[], /* i : impulse response of weighted synthesis filter */
+        /*     h[-L_subfr..-1] must be set to zero.          */
+        Word16 T0,  /* i : Pitch lag                                     */
+        Word16 pitch_sharp, /* i : Last quantized pitch gain             */
+        Word16 code[],      /* o : Innovative codebook                   */
+        Word16 y[],         /* o : filtered fixed codebook excitation    */
+        Word16 * sign,      /* o : Signs of 2 pulses                     */
+        Flag   * pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _c2_11PF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.cpp
new file mode 100644
index 0000000..a33cdf7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.cpp
@@ -0,0 +1,1219 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c2_9pf.c
+ Funtions: code_2i40_9bits
+           search_2i40
+           Test_search_2i40
+           build_code
+           Test_build_code
+
+     Date: 05/26/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Updated file per comments gathered from Phase 2/3 review.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template.
+
+ Description: Replaced basic_op.h with the header files of the math functions
+              used by the file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Defined one local variable per line.
+
+ Description: Passed in pOverflow flag for EPOC compatibility.
+
+ Description: Optimized search_2i40() to reduce clock cycle usage.
+
+ Description: Removed unnecessary include files and #defines.
+
+ Description: Changed function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that search a 9 bit algebraic codebook
+ containing 2 pulses in a frame of 40 samples.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "c2_9pf.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "inv_sqrt.h"
+#include "cnst.h"
+#include "cor_h.h"
+#include "cor_h_x.h"
+#include "set_sign.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define NB_PULSE  2
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    static void search_2i40(
+        Word16 subNr,       /* i : subframe number                               */
+        Word16 dn[],        /* i : correlation between target and h[]            */
+        Word16 rr[][L_CODE],/* i : matrix of autocorrelation                     */
+        Word16 codvec[],    /* o : algebraic codebook vector                     */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    );
+
+    static Word16 build_code(
+        Word16 subNr,       /* i : subframe number                               */
+        Word16 codvec[],    /* i : algebraic codebook vector                     */
+        Word16 dn_sign[],   /* i : sign of dn[]                                  */
+        Word16 cod[],       /* o : algebraic (fixed) codebook excitation         */
+        Word16 h[],         /* i : impulse response of weighted synthesis filter */
+        Word16 y[],         /* o : filtered fixed codebook excitation            */
+        Word16 sign[],      /* o : sign of 2 pulses                              */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    const Word16 trackTable[4*5] =
+    {
+        0, 1, 0, 1, -1, /* subframe 1; track to code;
+                         * -1 do not code this position
+                         */
+        0, -1, 1, 0, 1, /* subframe 2 */
+        0, 1, 0, -1, 1, /* subframe 3 */
+        0, 1, -1, 0, 1
+    };/* subframe 4 */
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 startPos[];
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: code_2i40_9bits
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        subNr = subframe number (Word16)
+        x  = target buffer (Word16)
+        h  = buffer containing the impulse response of the
+             weighted synthesis filter; h[-L_subfr .. -1] must be
+             set to zero (Word16)
+        T0 = pitch lag (Word16)
+        pitch_sharp = last quantized pitch gain (Word16)
+        code = buffer containing the innovative codebook (Word16)
+        y = buffer containing the filtered fixed codebook excitation (Word16)
+        sign = pointer to the signs of 2 pulses (Word16)
+
+     Outputs:
+        code buffer contains the new innovation vector gains
+
+     Returns:
+        index = code index (Word16)
+
+     Global Variables Used:
+        Overflow = overflow flag (Flag)
+
+     Local Variables Needed:
+        None
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     This function searches a 9 bit algebraic codebook containing 2 pulses in a
+     frame of 40 samples.
+
+     The code length is 40, containing 2 nonzero pulses: i0...i1. All pulses can
+     have two possible amplitudes: +1 or -1. Pulse i0 can have 8 possible positions,
+     pulse i1 can have 8 positions. Also coded is which track pair should be used,
+     i.e. first or second pair. Where each pair contains 2 tracks.
+
+        First subframe:
+        first   i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+            i1 :  2, 7, 12, 17, 22, 27, 32, 37.
+        second  i0 :  1, 6, 11, 16, 21, 26, 31, 36.
+                    i1 :  3, 8, 13, 18, 23, 28, 33, 38.
+
+        Second subframe:
+        first   i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+                    i1 :  3, 8, 13, 18, 23, 28, 33, 38.
+        second  i0 :  2, 7, 12, 17, 22, 27, 32, 37.
+                    i1 :  4, 9, 14, 19, 24, 29, 34, 39.
+
+        Third subframe:
+        first   i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+                    i1 :  2, 7, 12, 17, 22, 27, 32, 37.
+        second  i0 :  1, 6, 11, 16, 21, 26, 31, 36.
+                    i1 :  4, 9, 14, 19, 24, 29, 34, 39.
+
+        Fourth subframe:
+        first   i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+                    i1 :  3, 8, 13, 18, 23, 28, 33, 38.
+        second  i0 :  1, 6, 11, 16, 21, 26, 31, 36.
+                    i1 :  4, 9, 14, 19, 24, 29, 34, 39.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c2_9pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    Word16 code_2i40_9bits(
+        Word16 subNr,       // i : subframe number
+        Word16 x[],         // i : target vector
+        Word16 h[],         // i : impulse response of weighted synthesis filter
+                            //     h[-L_subfr..-1] must be set to zero.
+        Word16 T0,          // i : Pitch lag
+        Word16 pitch_sharp, // i : Last quantized pitch gain
+        Word16 code[],      // o : Innovative codebook
+        Word16 y[],         // o : filtered fixed codebook excitation
+        Word16 * sign       // o : Signs of 2 pulses
+    )
+    {
+        Word16 codvec[NB_PULSE];
+        Word16 dn[L_CODE], dn2[L_CODE], dn_sign[L_CODE];
+        Word16 rr[L_CODE][L_CODE];
+        Word16 i, index, sharp;
+
+        sharp = shl(pitch_sharp, 1);
+        if (sub(T0, L_CODE) < 0)
+           for (i = T0; i < L_CODE; i++) {
+              h[i] = add(h[i], mult(h[i - T0], sharp));
+           }
+        cor_h_x(h, x, dn, 1);
+        set_sign(dn, dn_sign, dn2, 8); // dn2[] not used in this codebook search
+        cor_h(h, dn_sign, rr);
+        search_2i40(subNr, dn, rr, codvec);
+        index = build_code(subNr, codvec, dn_sign, code, h, y, sign);
+
+       *-----------------------------------------------------------------*
+       * Compute innovation vector gain.                                 *
+       * Include fixed-gain pitch contribution into code[].              *
+       *-----------------------------------------------------------------*
+
+        if (sub(T0, L_CODE) < 0)
+           for (i = T0; i < L_CODE; i++) {
+              code[i] = add(code[i], mult(code[i - T0], sharp));
+           }
+        return index;
+    }
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    Word16 code_2i40_9bits(
+        Word16 subNr,       /* i : subframe number                          */
+        Word16 x[],         /* i : target vector                            */
+        Word16 h[],         /* i : impulse response of weighted synthesis   */
+        /*     filter h[-L_subfr..-1] must be set to 0. */
+        Word16 T0,          /* i : Pitch lag                                */
+        Word16 pitch_sharp, /* i : Last quantized pitch gain                */
+        Word16 code[],      /* o : Innovative codebook                      */
+        Word16 y[],         /* o : filtered fixed codebook excitation       */
+        Word16 * sign,      /* o : Signs of 2 pulses                        */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs            */
+    )
+    {
+        Word16 codvec[NB_PULSE];
+        Word16 dn[L_CODE];
+        Word16 dn2[L_CODE];
+        Word16 dn_sign[L_CODE];
+        Word16 rr[L_CODE][L_CODE];
+
+        register Word16 i;
+
+        Word16 index;
+        Word16 sharp;
+        Word16 temp;
+        Word32 L_temp;
+
+        L_temp = ((Word32) pitch_sharp) << 1;
+
+        /* Check for overflow condition */
+        if (L_temp != (Word32)((Word16) L_temp))
+        {
+            *(pOverflow) = 1;
+            sharp = (pitch_sharp > 0) ? MAX_16 : MIN_16;
+        }
+        else
+        {
+            sharp = (Word16) L_temp;
+        }
+
+        if (T0 < L_CODE)
+        {
+            for (i = T0; i < L_CODE; i++)
+            {
+                temp =
+                    mult(
+                        *(h + i - T0),
+                        sharp,
+                        pOverflow);
+
+                *(h + i) =
+                    add(
+                        *(h + i),
+                        temp,
+                        pOverflow);
+            }
+        }
+
+        cor_h_x(
+            h,
+            x,
+            dn,
+            1,
+            pOverflow);
+
+        /* dn2[] not used in this codebook search */
+
+        set_sign(
+            dn,
+            dn_sign,
+            dn2,
+            8);
+
+        cor_h(
+            h,
+            dn_sign,
+            rr,
+            pOverflow);
+
+        search_2i40(
+            subNr,
+            dn,
+            rr,
+            codvec,
+            pOverflow);
+
+        index =
+            build_code(
+                subNr,
+                codvec,
+                dn_sign,
+                code,
+                h,
+                y,
+                sign,
+                pOverflow);
+
+        /*-----------------------------------------------------------------*
+         * Compute innovation vector gain.                                 *
+         * Include fixed-gain pitch contribution into code[].              *
+         *-----------------------------------------------------------------*/
+
+        if (T0 < L_CODE)
+        {
+            for (i = T0; i < L_CODE; i++)
+            {
+                temp =
+                    mult(
+                        *(code + i - T0),
+                        sharp,
+                        pOverflow);
+
+                *(code + i) =
+                    add(
+                        *(code + i),
+                        temp,
+                        pOverflow);
+            }
+        }
+
+        return(index);
+    }
+
+    /****************************************************************************/
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: search_2i40
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        subNr = subframe number (Word16)
+        dn = vector containing the correlation between target and the impulse
+             response of the weighted synthesis filter (Word16)
+        rr = autocorrelation matrix (Word16)
+        codvec = algebraic codebook vector (Word16)
+
+     Outputs:
+        codvec contains the newly calculated codevectors
+
+     Returns:
+        None
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+        startPos = table containing the start positions used by fixed codebook
+                   routines (const Word16)
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     This function searches the best codevector and determines the positions of
+     the 2 pulses in the 40-sample frame.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c2_9pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    static void search_2i40(
+        Word16 subNr,        // i : subframe number
+        Word16 dn[],         // i : correlation between target and h[]
+        Word16 rr[][L_CODE], // i : matrix of autocorrelation
+        Word16 codvec[]      // o : algebraic codebook vector
+    )
+    {
+        Word16 i0, i1;
+        Word16 ix = 0; // initialization only needed to keep gcc silent
+        Word16  track1, ipos[NB_PULSE];
+        Word16 psk, ps0, ps1, sq, sq1;
+        Word16 alpk, alp, alp_16;
+        Word32 s, alp0, alp1;
+        Word16 i;
+
+        psk = -1;
+        alpk = 1;
+        for (i = 0; i < NB_PULSE; i++)
+        {
+           codvec[i] = i;
+        }
+
+        for (track1 = 0; track1 < 2; track1++) {
+           // fix starting position
+
+           ipos[0] = startPos[subNr*2+8*track1];
+           ipos[1] = startPos[subNr*2+1+8*track1];
+
+
+               *----------------------------------------------------------------*
+               * i0 loop: try 8 positions.                                      *
+               *----------------------------------------------------------------*
+
+              for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP) {
+
+                 ps0 = dn[i0];
+                 alp0 = L_mult(rr[i0][i0], _1_4);
+
+               *----------------------------------------------------------------*
+               * i1 loop: 8 positions.                                          *
+               *----------------------------------------------------------------*
+
+                 sq = -1;
+                 alp = 1;
+                 ix = ipos[1];
+
+            *-------------------------------------------------------------------*
+            *  These index have low complexity address computation because      *
+            *  they are, in fact, pointers with fixed increment.  For example,  *
+            *  "rr[i0][i2]" is a pointer initialized to "&rr[i0][ipos[2]]"      *
+            *  and incremented by "STEP".                                       *
+            *-------------------------------------------------------------------*
+
+                 for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP) {
+                    ps1 = add(ps0, dn[i1]);   // idx increment = STEP
+
+                    // alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1];
+
+                    alp1 = L_mac(alp0, rr[i1][i1], _1_4); // idx incr = STEP
+                    alp1 = L_mac(alp1, rr[i0][i1], _1_2); // idx incr = STEP
+
+                    sq1 = mult(ps1, ps1);
+
+                    alp_16 = pv_round(alp1);
+
+                    s = L_msu(L_mult(alp, sq1), sq, alp_16);
+
+                    if (s > 0) {
+                       sq = sq1;
+                       alp = alp_16;
+                       ix = i1;
+                    }
+                 }
+
+               *----------------------------------------------------------------*
+               * memorise codevector if this one is better than the last one.   *
+               *----------------------------------------------------------------*
+
+                 s = L_msu(L_mult(alpk, sq), psk, alp);
+
+                 if (s > 0) {
+                    psk = sq;
+                    alpk = alp;
+                    codvec[0] = i0;
+                    codvec[1] = ix;
+                 }
+              }
+        }
+
+        return;
+    }
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    static void search_2i40(
+        Word16 subNr,        /* i : subframe number                    */
+        Word16 dn[],         /* i : correlation between target and h[] */
+        Word16 rr[][L_CODE], /* i : matrix of autocorrelation          */
+        Word16 codvec[],     /* o : algebraic codebook vector          */
+        Flag   * pOverflow   /* o : Flag set when overflow occurs      */
+    )
+    {
+        register Word16 i0;
+        register Word16 i1;
+        Word16 ix = 0; /* initialization only needed to keep gcc silent */
+        register Word16  track1;
+        Word16 ipos[NB_PULSE];
+        Word16 psk;
+        Word16 ps0;
+        Word16 ps1;
+        Word16 sq;
+        Word16 sq1;
+        Word16 alpk;
+        Word16 alp;
+        Word16 alp_16;
+        Word32 s;
+        Word32 alp0;
+        Word32 alp1;
+        register Word16 i;
+        Word32 L_temp;
+        Word16 *p_codvec = &codvec[0];
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        psk = -1;
+        alpk = 1;
+
+        /* Unrolled the following FOR loop to save MIPS */
+        /* for (i = 0; i < NB_PULSE; i++)           */
+        /* {                            */
+        /*  *(codvec + i) = i;          */
+        /* }                        */
+
+        *(p_codvec++) = 0;
+        *(p_codvec) = 1;
+
+        for (track1 = 0; track1 < 2; track1++)
+        {
+            /* fix starting position */
+
+            i = (subNr << 1) + (track1 << 3);
+            *ipos = *(startPos + i);
+            *(ipos + 1) = *(startPos + i + 1);
+
+
+            /*----------------------------------------------------------*
+             * i0 loop: try 8 positions.                                *
+             *----------------------------------------------------------*/
+
+            for (i0 = *ipos; i0 < L_CODE; i0 += STEP)
+            {
+                ps0 = *(dn + i0);
+
+                /* Left shift by 1 converts integer product to */
+                /* fractional product.                 */
+                alp0 = (Word32) rr[i0][i0] << 14;
+
+                /*--------------------------------------------------*
+                 * i1 loop: 8 positions.                            *
+                 *--------------------------------------------------*/
+
+                sq = -1;
+                alp = 1;
+                ix = *(ipos + 1);
+
+                /*--------------------------------------------------*
+                 * These index have low complexity address          *
+                 * computation because they are, in fact, pointers  *
+                 * with fixed increment. For example, "rr[i0][i2]"  *
+                 * is a pointer initialized to "&rr[i0][ipos[2]]"   *
+                *  and incremented by "STEP".                       *
+                *---------------------------------------------------*/
+
+                for (i1 = *(ipos + 1); i1 < L_CODE; i1 += STEP)
+                {
+                    /* idx increment = STEP */
+                    /* ps1 = add(ps0, *(dn + i1), pOverflow); */
+                    ps1 = ps0 + dn[i1];
+
+                    /* alp1 = alp0+rr[i0][i1]+1/2*rr[i1][i1]; */
+
+                    /* idx incr = STEP */
+                    /* Extra left shift by 1 converts integer  */
+                    /* product to fractional product     */
+                    /* alp1 = L_add(alp0, s, pOverflow); */
+                    alp1 = alp0 + ((Word32) rr[i1][i1] << 14);
+
+                    /* idx incr = STEP */
+                    /* Extra left shift by 1 converts integer  */
+                    /* product to fractional product     */
+                    /* alp1 = L_add(alp1, s, pOverflow); */
+                    alp1 += (Word32) rr[i0][i1] << 15;
+
+                    /* sq1 = mult(ps1, ps1, pOverflow); */
+                    sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                    /* alp_16 = pv_round(alp1, pOverflow); */
+                    alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                    /* L_temp = L_mult(alp, sq1, pOverflow); */
+                    L_temp = ((Word32) alp * sq1) << 1;
+
+                    /* s = L_msu(L_temp, sq, alp_16, pOverflow); */
+                    s = L_temp - (((Word32) sq * alp_16) << 1);
+
+                    if (s > 0)
+                    {
+                        sq = sq1;
+                        alp = alp_16;
+                        ix = i1;
+                    }
+                }
+
+                /* memorize codevector if this one is better than the last one. */
+
+                /* L_temp = L_mult(alpk, sq, pOverflow); */
+                L_temp = ((Word32) alpk * sq) << 1;
+
+                /* s = L_msu(L_temp, psk, alp, pOverflow); */
+                s = L_temp - (((Word32) psk * alp) << 1);
+
+                if (s > 0)
+                {
+                    psk = sq;
+                    alpk = alp;
+                    p_codvec = &codvec[0];
+                    *(p_codvec++) = i0;
+                    *(p_codvec) = ix;
+                }
+            }
+        }
+
+        return;
+    }
+
+    /****************************************************************************/
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Test_search_2i40
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        subNr = subframe number (Word16)
+        dn = vector containing the correlation between target and the impulse
+             response of the weighted synthesis filter (Word16)
+        rr = autocorrelation matrix (Word16)
+        codvec = algebraic codebook vector (Word16)
+
+     Outputs:
+        codvec contains the newly calculated codevectors
+
+     Returns:
+        None
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+        startPos = table containing the start positions used by fixed codebook
+                   routines (const Word16)
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     This function provides external access to the local function search_2i40.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c2_9pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+     CALL search_2i40 ( subNr = subNr
+                dn = dn
+                rr = rr
+                codvec = codvec )
+       MODIFYING(nothing)
+       RETURNING(nothing)
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    void Test_search_2i40(
+        Word16 subNr,        /* i : subframe number                    */
+        Word16 dn[],         /* i : correlation between target and h[] */
+        Word16 rr[][L_CODE], /* i : matrix of autocorrelation          */
+        Word16 codvec[],     /* o : algebraic codebook vector          */
+        Flag   * pOverflow   /* o : Flag set when overflow occurs      */
+    )
+    {
+        /*----------------------------------------------------------------------------
+         CALL search_2i40 ( subNr = subNr
+                    dn = dn
+                    rr = rr
+                    codvec = codvec )
+           MODIFYING(nothing)
+           RETURNING(nothing)
+        ----------------------------------------------------------------------------*/
+        search_2i40(
+            subNr,
+            dn,
+            rr,
+            codvec,
+            pOverflow);
+
+        return;
+    }
+
+    /****************************************************************************/
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: build_code
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        subNr = subframe number (Word16)
+        codvec = vector containing the position of pulses (Word16)
+        dn_sign = vector containing the sign of pulses (Word16)
+        cod = innovative code vector (Word16)
+        h = vector containing the impulse response of the weighted
+            synthesis filter (Word16)
+        y = vector containing the filtered innovative code (Word16)
+        sign = vector containing the sign of 2 pulses (Word16)
+
+     Outputs:
+        cod vector contains the new innovative code
+        y vector contains the new filtered innovative code
+        sign vector contains the sign of 2 pulses
+
+     Returns:
+        indx = codebook index (Word16)
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+        trackTable = table used for tracking codewords (Word16)
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     This function builds the codeword, the filtered codeword and index of the
+     codevector, based on the signs and positions of 2 pulses.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c2_9pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    static Word16 build_code(
+        Word16 subNr,     // i : subframe number
+        Word16 codvec[],  // i : position of pulses
+        Word16 dn_sign[], // i : sign of pulses
+        Word16 cod[],     // o : innovative code vector
+        Word16 h[],       // i : impulse response of weighted synthesis filter
+        Word16 y[],       // o : filtered innovative code
+        Word16 sign[]     // o : sign of 2 pulses
+    )
+    {
+        Word16 i, j, k, track, first, index, _sign[NB_PULSE], indx, rsign;
+        Word16 *p0, *p1, *pt;
+        Word32 s;
+        static Word16 trackTable[4*5] = {
+           0, 1, 0, 1, -1, // subframe 1; track to code; -1 do not code this position
+           0, -1, 1, 0, 1, // subframe 2
+           0, 1, 0, -1, 1, // subframe 3
+           0, 1, -1, 0, 1};// subframe 4
+
+        pt = &trackTable[add(subNr, shl(subNr, 2))];
+
+        for (i = 0; i < L_CODE; i++) {
+            cod[i] = 0;
+        }
+
+        indx = 0;
+        rsign = 0;
+        for (k = 0; k < NB_PULSE; k++) {
+           i = codvec[k];    // read pulse position
+           j = dn_sign[i];   // read sign
+
+           index = mult(i, 6554);    // index = pos/5
+                                     // track = pos%5
+           track = sub(i, extract_l(L_shr(L_mult(index, 5), 1)));
+
+           first = pt[track];
+
+           if (first == 0) {
+              if (k == 0) {
+                 track = 0;
+              } else {
+                 track = 1;
+                 index = shl(index, 3);
+              }
+           } else {
+              if (k == 0) {
+                 track = 0;
+                 index = add(index, 64);  // table bit is MSB
+              } else {
+                 track = 1;
+                 index = shl(index, 3);
+              }
+           }
+
+           if (j > 0) {
+              cod[i] = 8191;
+              _sign[k] = 32767;
+              rsign = add(rsign, shl(1, track));
+           } else {
+              cod[i] = -8192;
+              _sign[k] = (Word16) - 32768L;
+            }
+
+           indx = add(indx, index);
+        }
+        *sign = rsign;
+
+        p0 = h - codvec[0];
+        p1 = h - codvec[1];
+
+        for (i = 0; i < L_CODE; i++) {
+           s = 0;
+           s = L_mac(s, *p0++, _sign[0]);
+           s = L_mac(s, *p1++, _sign[1]);
+           y[i] = pv_round(s);
+        }
+
+        return indx;
+    }
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    static Word16 build_code(
+        Word16 subNr,     /* i : subframe number                            */
+        Word16 codvec[],  /* i : position of pulses                         */
+        Word16 dn_sign[], /* i : sign of pulses                             */
+        Word16 cod[],     /* o : innovative code vector                     */
+        Word16 h[],       /* i : impulse response of weighted synthesis     */
+        /*     filter                                     */
+        Word16 y[],       /* o : filtered innovative code                   */
+        Word16 sign[],    /* o : sign of 2 pulses                           */
+        Flag  *pOverflow  /* o : Flag set when overflow occurs              */
+    )
+    {
+        register Word16 i;
+        register Word16 j;
+        register Word16 k;
+        register Word16 track;
+        register Word16 first;
+        register Word16 index;
+        register Word16 rsign;
+        Word16 indx;
+        Word16 _sign[NB_PULSE];
+        Word16 *p0;
+        Word16 *p1;
+
+        const Word16 *pt;
+
+        Word32 s;
+
+        pt = trackTable + subNr + (subNr << 2);
+
+        for (i = 0; i < L_CODE; i++)
+        {
+            *(cod + i) = 0;
+        }
+
+        indx = 0;
+        rsign = 0;
+
+        for (k = 0; k < NB_PULSE; k++)
+        {
+            i = *(codvec + k);  /* read pulse position */
+            j = *(dn_sign + i); /* read sign           */
+
+            s = ((Word32)(i * 6554)) >> 15;
+            index = (Word16) s; /* index = pos/5 */
+
+            track = i - (5 * index);    /* track = pos%5 */
+
+            first = *(pt + track);
+
+
+            if (k == 0)
+            {
+                track = 0;
+
+                if (first != 0)
+                {
+                    index += 64;  /* table bit is MSB */
+                }
+            }
+            else
+            {
+                track = 1;
+                index <<= 3;
+            }
+
+            if (j > 0)
+            {
+                *(cod + i) = 8191;
+                *(_sign + k) = 32767;
+                rsign += (1 << track);
+            }
+            else
+            {
+                *(cod + i) = ~(8192) + 1;
+                *(_sign + k) = (Word16)(~(32768) + 1);
+            }
+
+            indx += index;
+        }
+
+        *sign = rsign;
+
+        p0 = h - *codvec;
+        p1 = h - *(codvec + 1);
+
+        for (i = 0; i < L_CODE; i++)
+        {
+            s = 0;
+            s =
+                L_mult(
+                    *p0++,
+                    *_sign,
+                    pOverflow);
+
+            s =
+                L_mac(
+                    s,
+                    *p1++,
+                    *(_sign + 1),
+                    pOverflow);
+
+            *(y + i) =
+                pv_round(
+                    s,
+                    pOverflow);
+        }
+
+        return(indx);
+    }
+
+    /****************************************************************************/
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Test_build_code
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        subNr = subframe number (Word16)
+        codvec = vector containing the position of pulses (Word16)
+        dn_sign = vector containing the sign of pulses (Word16)
+        cod = innovative code vector (Word16)
+        h = vector containing the impulse response of the weighted
+            synthesis filter (Word16)
+        y = vector containing the filtered innovative code (Word16)
+        sign = vector containing the sign of 2 pulses (Word16)
+
+     Outputs:
+        cod vector contains the new innovative code
+        y vector contains the new filtered innovative code
+        sign vector contains the sign of 2 pulses
+
+     Returns:
+        indx = codebook index (Word16)
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+        trackTable = table used for tracking codewords (Word16)
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     This function provides external access to the local function build_code.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c2_9pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+     CALL build_code ( subNr = subNr
+               codvec = codvec
+               dn_sign = dn_sign
+               cod = cod
+               h = h
+               y = y
+               sign = sign )
+       MODIFYING(nothing)
+       RETURNING(indx)
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    Word16 Test_build_code(
+        Word16 subNr,      /* i : subframe number                            */
+        Word16 codvec[],   /* i : position of pulses                         */
+        Word16 dn_sign[],  /* i : sign of pulses                             */
+        Word16 cod[],      /* o : innovative code vector                     */
+        Word16 h[],        /* i : impulse response of weighted synthesis     */
+        /*     filter                                     */
+        Word16 y[],        /* o : filtered innovative code                   */
+        Word16 sign[],     /* o : sign of 2 pulses                           */
+        Flag   * pOverflow /* o : Flag set when overflow occurs              */
+    )
+    {
+        Word16  test_index;
+
+        /*----------------------------------------------------------------------------
+         CALL build_code ( subNr = subNr
+                   codvec = codvec
+                   dn_sign = dn_sign
+                   cod = cod
+                   h = h
+                   y = y
+                   sign = sign )
+           MODIFYING(nothing)
+           RETURNING(indx)
+        ----------------------------------------------------------------------------*/
+        test_index =
+            build_code(
+                subNr,
+                codvec,
+                dn_sign,
+                cod,
+                h,
+                y,
+                sign,
+                pOverflow);
+
+        return(test_index);
+    }
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.h b/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.h
new file mode 100644
index 0000000..203e1d9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c2_9pf.h
@@ -0,0 +1,125 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c2_9pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the c2_9pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef c2_9pf_h
+#define c2_9pf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 code_2i40_9bits(
+        Word16 subNr,       /* i : subframe number                               */
+        Word16 x[],         /* i : target vector                                 */
+        Word16 h[],         /* i : impulse response of weighted synthesis filter */
+        /*     h[-L_subfr..-1] must be set to zero.          */
+        Word16 T0,          /* i : Pitch lag                                     */
+        Word16 pitch_sharp, /* i : Last quantized pitch gain                     */
+        Word16 code[],      /* o : Innovative codebook                           */
+        Word16 y[],         /* o : filtered fixed codebook excitation            */
+        Word16 * sign,      /* o : Signs of 2 pulses                             */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _c2_9PF_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.cpp
new file mode 100644
index 0000000..58ab2fa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.cpp
@@ -0,0 +1,817 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c3_14pf.c
+ Functions:
+
+     Date: 05/26/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to pass overflow flag through to basic math function.
+ The flag is passed back to the calling function by pointer reference.
+
+ Description: Optimized file to reduce clock cycle usage. Updated copyright
+              year. Removed unneccesary include files and added only the
+              include files for the math functions used. Removed unused
+              #defines.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "c3_14pf.h"
+#include "typedef.h"
+#include "inv_sqrt.h"
+#include "cnst.h"
+#include "cor_h.h"
+#include "set_sign.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define NB_PULSE  3
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+static void search_3i40(
+    Word16 dn[],        /* i : correlation between target and h[]            */
+    Word16 dn2[],       /* i : maximum of corr. in each track.               */
+    Word16 rr[][L_CODE],/* i : matrix of autocorrelation                     */
+    Word16 codvec[],    /* o : algebraic codebook vector                     */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+);
+
+static Word16 build_code(
+    Word16 codvec[],    /* i : algebraic codebook vector                     */
+    Word16 dn_sign[],   /* i : sign of dn[]                                  */
+    Word16 cod[],       /* o : algebraic (fixed) codebook excitation         */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter */
+    Word16 y[],         /* o : filtered fixed codebook excitation            */
+    Word16 sign[],      /* o : sign of 3 pulses                              */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+);
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: code_3i40_14bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x[]   Array of type Word16 -- target vector
+    h[]   Array of type Word16 -- impulse response of weighted synthesis filter
+                                  h[-L_subfr..-1] must be set to zero.
+
+    T0           Array of type Word16 -- Pitch lag
+    pitch_sharp, Array of type Word16 --  Last quantized pitch gain
+
+ Outputs:
+    code[]  Array of type Word16 -- Innovative codebook
+    y[]     Array of type Word16 -- filtered fixed codebook excitation
+    * sign  Pointer of type Word16 -- Pointer to the signs of 3 pulses
+    pOverflow    Pointer to Flag      -- set when overflow occurs
+
+ Returns:
+    index
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Searches a 14 bit algebraic codebook containing 3 pulses
+           in a frame of 40 samples.
+
+ DESCRIPTION:
+    The code length is 40, containing 3 nonzero pulses: i0...i2.
+    All pulses can have two possible amplitudes: +1 or -1.
+    Pulse i0 can have 8 possible positions, pulses i1 and i2 can have
+    2x8=16 positions.
+
+        i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+        i1 :  1, 6, 11, 16, 21, 26, 31, 36.
+              3, 8, 13, 18, 23, 28, 33, 38.
+        i2 :  2, 7, 12, 17, 22, 27, 32, 37.
+              4, 9, 14, 19, 24, 29, 34, 39.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 code_3i40_14bits(
+    Word16 x[],         /* i : target vector                                 */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter */
+    /*     h[-L_subfr..-1] must be set to zero.          */
+    Word16 T0,          /* i : Pitch lag                                     */
+    Word16 pitch_sharp, /* i : Last quantized pitch gain                     */
+    Word16 code[],      /* o : Innovative codebook                           */
+    Word16 y[],         /* o : filtered fixed codebook excitation            */
+    Word16 * sign,      /* o : Signs of 3 pulses                             */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+)
+{
+    Word16 codvec[NB_PULSE];
+    Word16 dn[L_CODE];
+    Word16 dn2[L_CODE];
+    Word16 dn_sign[L_CODE];
+    Word16 rr[L_CODE][L_CODE];
+    Word16 i;
+    Word16 index;
+    Word16 sharp;
+    Word16 tempWord;
+
+    /* sharp = shl(pitch_sharp, 1, pOverflow); */
+    sharp = pitch_sharp << 1;
+
+    if (T0 < L_CODE)
+    {
+        for (i = T0; i < L_CODE; i++)
+        {
+            tempWord =
+                mult(
+                    h[i - T0],
+                    sharp,
+                    pOverflow);
+
+            h[i] =
+                add(
+                    h[i],
+                    tempWord,
+                    pOverflow);
+        }
+    }
+
+    cor_h_x(
+        h,
+        x,
+        dn,
+        1,
+        pOverflow);
+
+    set_sign(
+        dn,
+        dn_sign,
+        dn2,
+        6);
+
+    cor_h(
+        h,
+        dn_sign,
+        rr,
+        pOverflow);
+
+    search_3i40(
+        dn,
+        dn2,
+        rr,
+        codvec,
+        pOverflow);
+
+    /* function result */
+    index =
+        build_code(
+            codvec,
+            dn_sign,
+            code,
+            h,
+            y,
+            sign,
+            pOverflow);
+
+    /*-----------------------------------------------------------------*
+    * Compute innovation vector gain.                                 *
+    * Include fixed-gain pitch contribution into code[].              *
+    *-----------------------------------------------------------------*/
+
+    if (T0 < L_CODE)
+    {
+        for (i = T0; i < L_CODE; i++)
+        {
+            tempWord =
+                mult(
+                    code[i - T0],
+                    sharp,
+                    pOverflow);
+
+            code[i] =
+                add(
+                    code[i],
+                    tempWord,
+                    pOverflow);
+        }
+    }
+    return index;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: search_3i40
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    dn[]         Array of type Word16 -- correlation between target and h[]
+    dn2[]        Array of type Word16 -- maximum of corr. in each track.
+    rr[][L_CODE] Double Array of type Word16 -- autocorrelation matrix
+
+ Outputs:
+    codvec[]     Array of type Word16 -- algebraic codebook vector
+    pOverflow    Pointer to Flag      -- set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: Search the best codevector; determine positions of the 3 pulses
+          in the 40-sample frame.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+static void search_3i40(
+    Word16 dn[],         /* i : correlation between target and h[] */
+    Word16 dn2[],        /* i : maximum of corr. in each track.    */
+    Word16 rr[][L_CODE], /* i : matrix of autocorrelation          */
+    Word16 codvec[],     /* o : algebraic codebook vector          */
+    Flag   * pOverflow   /* o : Flag set when overflow occurs      */
+)
+{
+    Word16 i0;
+    Word16 i1;
+    Word16 i2;
+
+    Word16 ix = 0; /* initialization only needed to keep gcc silent */
+    Word16 ps = 0; /* initialization only needed to keep gcc silent */
+
+    Word16 i;
+    Word16 pos;
+    Word16 track1;
+    Word16 track2;
+    Word16 ipos[NB_PULSE];
+
+    Word16 psk;
+    Word16 ps0;
+    Word16 ps1;
+    Word16 sq;
+    Word16 sq1;
+    Word16 alpk;
+    Word16 alp;
+    Word16 alp_16;
+
+    Word16 *p_codvec = &codvec[0];
+
+    Word32 s;
+    Word32 alp0;
+    Word32 alp1;
+
+    psk = -1;
+    alpk = 1;
+
+    for (i = 0; i < NB_PULSE; i++)
+    {
+        *(p_codvec++) = i;
+    }
+
+    for (track1 = 1; track1 < 4; track1 += 2)
+    {
+        for (track2 = 2; track2 < 5; track2 += 2)
+        {
+            /* fix starting position */
+
+            ipos[0] = 0;
+            ipos[1] = track1;
+            ipos[2] = track2;
+
+            /*------------------------------------------------------------------*
+             * main loop: try 3 tracks.                                         *
+             *------------------------------------------------------------------*/
+
+            for (i = 0; i < NB_PULSE; i++)
+            {
+                /*----------------------------------------------------------------*
+                 * i0 loop: try 8 positions.                                      *
+                 *----------------------------------------------------------------*/
+
+                /* account for ptr. init. (rr[io]) */
+                for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP)
+                {
+                    if (dn2[i0] >= 0)
+                    {
+                        ps0 = dn[i0];
+
+                        /* alp0 = L_mult(rr[i0][i0],_1_4, pOverflow); */
+                        alp0 = (Word32) rr[i0][i0] << 14;
+
+                        /*----------------------------------------------------------------*
+                         * i1 loop: 8 positions.                                          *
+                         *----------------------------------------------------------------*/
+
+                        sq = -1;
+                        alp = 1;
+                        ps = 0;
+                        ix = ipos[1];
+
+                        /* initialize 4 index for next loop. */
+                        /*-------------------------------------------------------------------*
+                         *  These index have low complexity address computation because      *
+                         *  they are, in fact, pointers with fixed increment.  For example,  *
+                         *  "rr[i0][i2]" is a pointer initialized to "&rr[i0][ipos[2]]"      *
+                         *  and incremented by "STEP".                                       *
+                         *-------------------------------------------------------------------*/
+
+                        for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP)
+                        {
+                            /* idx increment = STEP */
+                            /* ps1 = add(ps0, dn[i1], pOverflow); */
+                            ps1 = ps0 + dn[i1];
+
+                            /* alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1]; */
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp0, rr[i1][i1], _1_4, pOverflow); */
+                            alp1 = alp0 + ((Word32) rr[i1][i1] << 14);
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp1, rr[i0][i1], _1_2, pOverflow); */
+                            alp1 += (Word32) rr[i0][i1] << 15;
+
+                            /* sq1 = mult(ps1, ps1, pOverflow); */
+                            sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                            /* alp_16 = pv_round(alp1, pOverflow); */
+                            alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                            /* s = L_mult(alp, sq1, pOverflow); */
+                            s = ((Word32) alp * sq1) << 1;
+
+                            /* s = L_msu(s, sq, alp_16, pOverflow); */
+                            s -= (((Word32) sq * alp_16) << 1);
+
+                            if (s > 0)
+                            {
+                                sq = sq1;
+                                ps = ps1;
+                                alp = alp_16;
+                                ix = i1;
+                            }
+                        }
+                        i1 = ix;
+
+                        /*----------------------------------------------------------------*
+                         * i2 loop: 8 positions.                                          *
+                         *----------------------------------------------------------------*/
+
+                        ps0 = ps;
+
+                        /* alp0 = L_mult(alp, _1_4, pOverflow); */
+                        alp0 = (Word32) alp << 14;
+
+                        sq = -1;
+                        alp = 1;
+                        ps = 0;
+                        ix = ipos[2];
+
+                        /* initialize 4 index for next loop (see i1 loop) */
+
+                        for (i2 = ipos[2]; i2 < L_CODE; i2 += STEP)
+                        {
+                            /* index increment = STEP */
+                            /* ps1 = add(ps0, dn[i2], pOverflow); */
+                            ps1 = ps0 + dn[i2];
+
+                            /* alp1 = alp0 + rr[i0][i2] + rr[i1][i2] + 1/2*rr[i2][i2]; */
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp0, rr[i2][i2], _1_16, pOverflow); */
+                            alp1 = alp0 + ((Word32) rr[i2][i2] << 12);
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp1, rr[i1][i2], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i1][i2] << 13;
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp1,rr[i0][i2], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i0][i2] << 13;
+
+                            /* sq1 = mult(ps1, ps1, pOverflow); */
+                            sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                            /* alp_16 = pv_round(alp1, pOverflow); */
+                            alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                            /* s = L_mult(alp, sq1, pOverflow); */
+                            s = ((Word32) alp * sq1) << 1;
+
+                            /* s = L_msu(s, sq, alp_16, pOverflow); */
+                            s -= (((Word32) sq * alp_16) << 1);
+
+                            if (s > 0)
+                            {
+                                sq = sq1;
+                                ps = ps1;
+                                alp = alp_16;
+                                ix = i2;
+                            }
+                        }
+                        i2 = ix;
+
+                        /* memorize codevector if this one
+                         * is better than the last one.
+                         */
+
+                        s = L_mult(alpk, sq, pOverflow);
+                        //s = ((Word32) alpk * sq) << 1;
+
+                        s = L_msu(s, psk, alp, pOverflow);
+                        //s -= (((Word32) psk * alp) << 1);
+
+                        if (s > 0)
+                        {
+                            psk = sq;
+                            alpk = alp;
+                            p_codvec = &codvec[0];
+
+                            *(p_codvec++) = i0;
+                            *(p_codvec++) = i1;
+                            *(p_codvec) = i2;
+                        }
+                    }
+                }
+                /*----------------------------------------------------------------*
+                 * Cyclic permutation of i0, i1 and i2.                           *
+                 *----------------------------------------------------------------*/
+
+                pos = ipos[2];
+                ipos[2] = ipos[1];
+                ipos[1] = ipos[0];
+                ipos[0] = pos;
+            }
+        }
+    }
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME:  build_code()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    codvec[]   Array of type Word16 -- position of pulses
+    dn_sign[]  Array of type Word16 -- sign of pulses
+    h[]        Array of type Word16 -- impulse response of
+                                       weighted synthesis filter
+
+ Outputs:
+    cod[]  Array of type Word16 -- innovative code vector
+    y[]    Array of type Word16 -- filtered innovative code
+    sign[] Array of type Word16 -- sign of 3 pulses
+    pOverflow  Pointer to Flag  -- set when overflow occurs
+
+ Returns:
+    indx
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: Builds the codeword, the filtered codeword and index of the
+          codevector, based on the signs and positions of 3 pulses.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16
+build_code(
+    Word16 codvec[],  /* i : position of pulses                            */
+    Word16 dn_sign[], /* i : sign of pulses                                */
+    Word16 cod[],     /* o : innovative code vector                        */
+    Word16 h[],       /* i : impulse response of weighted synthesis filter */
+    Word16 y[],       /* o : filtered innovative code                      */
+    Word16 sign[],    /* o : sign of 3 pulses                              */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs                 */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 k;
+    Word16 track;
+    Word16 index;
+    Word16 _sign[NB_PULSE];
+    Word16 indx;
+    Word16 rsign;
+
+    Word16 *p0;
+    Word16 *p1;
+    Word16 *p2;
+
+    Word32 s;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        cod[i] = 0;
+    }
+
+    indx = 0;
+    rsign = 0;
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        i = codvec[k];  /* read pulse position */
+        j = dn_sign[i];  /* read sign           */
+
+        /* index = pos/5 */
+        /* index = mult(i, 6554, pOverflow); */
+        index = (Word16)(((Word32) i * 6554) >> 15);
+
+        /* track = pos%5 */
+        /* s = L_mult(index, 5, pOverflow); */
+        s = ((Word32) index * 5) << 1;
+
+        /* s = L_shr(s, 1, pOverflow); */
+        s >>= 1;
+
+        /* track = sub(i, (Word16) s, pOverflow); */
+        track = i - (Word16) s;
+
+        if (track == 1)
+        {
+            /* index = shl(index, 4, pOverflow); */
+            index <<= 4;
+        }
+        else if (track == 2)
+        {
+            track = 2;
+
+            /* index = shl(index, 8, pOverflow); */
+            index <<= 8;
+        }
+        else if (track == 3)
+        {
+            track = 1;
+
+            /* index = shl(index, 4, pOverflow); */
+            index <<= 4;
+
+            /* index = add(index, 8, pOverflow); */
+            index += 8;
+        }
+        else if (track == 4)
+        {
+            track = 2;
+
+            /* index = shl(index, 8, pOverflow); */
+            index <<= 8;
+
+            /* index = add(index, 128, pOverflow); */
+            index += 128;
+        }
+
+        if (j > 0)
+        {
+            cod[i] = 8191;
+            _sign[k] = 32767;
+
+            /* track = shl(1, track, pOverflow); */
+            track = 1 << track;
+
+            /* rsign = add(rsign, track, pOverflow); */
+            rsign += track;
+        }
+        else
+        {
+            cod[i] = -8192;
+            _sign[k] = (Word16) - 32768L;
+        }
+
+        /* indx = add(indx, index, pOverflow); */
+        indx += index;
+    }
+    *sign = rsign;
+
+    p0 = h - codvec[0];
+    p1 = h - codvec[1];
+    p2 = h - codvec[2];
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = 0;
+        s =
+            L_mac(
+                s,
+                *p0++,
+                _sign[0],
+                pOverflow);
+
+        s =
+            L_mac(
+                s,
+                *p1++,
+                _sign[1],
+                pOverflow);
+
+        s =
+            L_mac(
+                s,
+                *p2++,
+                _sign[2],
+                pOverflow);
+
+        y[i] =
+            pv_round(
+                s,
+                pOverflow);
+    }
+
+    return indx;
+}
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.h b/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.h
new file mode 100644
index 0000000..15e2f1a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c3_14pf.h
@@ -0,0 +1,123 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c3_14pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by c3_14pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef c3_14pf_h
+#define c3_14pf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 code_3i40_14bits(
+        Word16 x[], /* (i)   : target vector                                 */
+        Word16 h[], /* (i)   : impulse response of weighted synthesis filter */
+        /*         h[-L_subfr..-1] must be set to zero.          */
+        Word16 T0,  /* (i)   : Pitch lag                                     */
+        Word16 pitch_sharp, /* (i)   : Last quantized pitch gain             */
+        Word16 code[],      /* (o)   : Innovative codebook                   */
+        Word16 y[],         /* (o)   : filtered fixed codebook excitation    */
+        Word16 * sign,      /* (o)   : Signs of 3 pulses                     */
+        Flag   *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _c3_14PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.cpp
new file mode 100644
index 0000000..d52b43b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.cpp
@@ -0,0 +1,891 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c4_17pf.c
+ Functions:
+
+     Date: 05/26/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to pass overflow flag through to basic math function.
+ The flag is passed back to the calling function by pointer reference.
+
+ Description: Optimized functions to further reduce clock cycle usage.
+              Updated copyright year, removed unnecessary include files,
+              and removed unused #defines.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Purpose          : Searches a 17 bit algebraic codebook containing 4 pulses
+                    in a frame of 40 samples
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "c4_17pf.h"
+#include "typedef.h"
+#include "inv_sqrt.h"
+#include "cnst.h"
+#include "cor_h.h"
+#include "set_sign.h"
+#include "basic_op.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define NB_PULSE  4
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    static void search_4i40(
+        Word16 dn[],        /* i : correlation between target and h[]            */
+        Word16 dn2[],       /* i : maximum of corr. in each track.               */
+        Word16 rr[][L_CODE],/* i : matrix of autocorrelation                     */
+        Word16 codvec[],    /* o : algebraic codebook vector                     */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    );
+
+    static Word16 build_code(
+        Word16 codvec[],    /* i : algebraic codebook vector                     */
+        Word16 dn_sign[],   /* i : sign of dn[]                                  */
+        Word16 cod[],       /* o : algebraic (fixed) codebook excitation         */
+        Word16 h[],         /* i : impulse response of weighted synthesis filter */
+        Word16 y[],         /* o : filtered fixed codebook excitation            */
+        Word16 sign[],      /* o : index of 4 pulses (position+sign+ampl)*4      */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 gray[];
+    extern const Word16 dgray[];
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME:  code_4i40_17bits()
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        x[]   Array of type Word16 -- target vector
+        h[]   Array of type Word16 -- impulse response of weighted synthesis filter
+                                      h[-L_subfr..-1] must be set to zero.
+
+        T0           Array of type Word16 -- Pitch lag
+        pitch_sharp, Array of type Word16 --  Last quantized pitch gain
+
+     Outputs:
+        code[]  Array of type Word16 -- Innovative codebook
+        y[]     Array of type Word16 -- filtered fixed codebook excitation
+        * sign  Pointer of type Word16 -- Pointer to the signs of 4 pulses
+        pOverflow    Pointer to Flag      -- set when overflow occurs
+
+     Returns:
+        index
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     PURPOSE:  Searches a 17 bit algebraic codebook containing 4 pulses
+               in a frame of 40 samples.
+
+     DESCRIPTION:
+       The code length is 40, containing 4 nonzero pulses: i0...i3.
+       All pulses can have two possible amplitudes: +1 or -1.
+       Pulse i0 to i2 can have 8 possible positions, pulse i3 can have
+       2x8=16 positions.
+
+          i0 :  0, 5, 10, 15, 20, 25, 30, 35.
+          i1 :  1, 6, 11, 16, 21, 26, 31, 36.
+          i2 :  2, 7, 12, 17, 22, 27, 32, 37.
+          i3 :  3, 8, 13, 18, 23, 28, 33, 38.
+                4, 9, 14, 19, 24, 29, 34, 39.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    Word16 code_4i40_17bits(
+        Word16 x[],         /* i : target vector                                 */
+        Word16 h[],         /* i : impulse response of weighted synthesis filter */
+        /*     h[-L_subfr..-1] must be set to zero.          */
+        Word16 T0,          /* i : Pitch lag                                     */
+        Word16 pitch_sharp, /* i : Last quantized pitch gain                     */
+        Word16 code[],      /* o : Innovative codebook                           */
+        Word16 y[],         /* o : filtered fixed codebook excitation            */
+        Word16 * sign,      /* o : Signs of 4 pulses                             */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs                 */
+    )
+    {
+        Word16 codvec[NB_PULSE];
+        Word16 dn[L_CODE];
+        Word16 dn2[L_CODE];
+        Word16 dn_sign[L_CODE];
+
+        Word16 rr[L_CODE][L_CODE];
+        Word16 i;
+        Word16 index;
+        Word16 sharp;
+        Word16 tempWord;
+
+        sharp = pitch_sharp << 1;
+
+        if (T0 < L_CODE)
+        {
+            for (i = T0; i < L_CODE; i++)
+            {
+                tempWord =
+                    mult(
+                        h[i - T0],
+                        sharp,
+                        pOverflow);
+
+                h[i] =
+                    add(
+                        h[i],
+                        tempWord,
+                        pOverflow);
+            }
+        }
+
+        cor_h_x(
+            h,
+            x,
+            dn,
+            1,
+            pOverflow);
+
+        set_sign(
+            dn,
+            dn_sign,
+            dn2,
+            4);
+
+        cor_h(
+            h,
+            dn_sign,
+            rr,
+            pOverflow);
+
+        search_4i40(
+            dn,
+            dn2,
+            rr,
+            codvec,
+            pOverflow);
+
+        /* function result */
+        index =
+            build_code(
+                codvec,
+                dn_sign,
+                code,
+                h,
+                y,
+                sign,
+                pOverflow);
+
+        /*-----------------------------------------------------------------*
+        * Compute innovation vector gain.                                 *
+        * Include fixed-gain pitch contribution into code[].              *
+        *-----------------------------------------------------------------*/
+
+        tempWord = T0 - L_CODE;
+
+        if (tempWord < 0)
+        {
+            for (i = T0; i < L_CODE; i++)
+            {
+                tempWord =
+                    mult(
+                        code[i - T0],
+                        sharp,
+                        pOverflow);
+
+                code[i] =
+                    add(
+                        code[i],
+                        tempWord,
+                        pOverflow);
+            }
+        }
+
+        return index;
+    }
+    /****************************************************************************/
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: search_4i40()
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        dn[]         Array of type Word16 -- correlation between target and h[]
+        dn2[]        Array of type Word16 -- maximum of corr. in each track.
+        rr[][L_CODE] Double Array of type Word16 -- autocorrelation matrix
+
+     Outputs:
+        codvec[]     Array of type Word16 -- algebraic codebook vector
+        pOverflow    Pointer to Flag      -- set when overflow occurs
+
+     Returns:
+
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     PURPOSE: Search the best codevector; determine positions of the 4 pulses
+              in the 40-sample frame.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c4_17pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+    static void search_4i40(
+        Word16 dn[],         /* i : correlation between target and h[]  */
+        Word16 dn2[],        /* i : maximum of corr. in each track.     */
+        Word16 rr[][L_CODE], /* i : matrix of autocorrelation           */
+        Word16 codvec[],     /* o : algebraic codebook vector           */
+        Flag   * pOverflow   /* o : Flag set when overflow occurs       */
+    )
+    {
+        Word16 i0;
+        Word16 i1;
+        Word16 i2;
+        Word16 i3;
+
+        Word16 ix = 0; /* initialization only needed to keep gcc silent */
+        Word16 ps = 0; /* initialization only needed to keep gcc silent */
+
+        Word16 i;
+        Word16 pos;
+        Word16 track;
+        Word16 ipos[NB_PULSE];
+
+        Word16 psk;
+        Word16 ps0;
+        Word16 ps1;
+        Word16 sq;
+        Word16 sq1;
+
+        Word16 alpk;
+        Word16 alp;
+        Word16 alp_16;
+        Word16 *p_codvec = &codvec[0];
+
+        Word32 s;
+        Word32 alp0;
+        Word32 alp1;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        /* Default value */
+        psk = -1;
+        alpk = 1;
+        for (i = 0; i < NB_PULSE; i++)
+        {
+            *(p_codvec++) = i;
+        }
+
+        for (track = 3; track < 5; track++)
+        {
+            /* fix starting position */
+
+            ipos[0] = 0;
+            ipos[1] = 1;
+            ipos[2] = 2;
+            ipos[3] = track;
+
+            /*------------------------------------------------------------------*
+             * main loop: try 4 tracks.                                         *
+             *------------------------------------------------------------------*/
+
+            for (i = 0; i < NB_PULSE; i++)
+            {
+                /*----------------------------------------------------------------*
+                 * i0 loop: try 4 positions (use position with max of corr.).     *
+                 *----------------------------------------------------------------*/
+
+                for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP)
+                {
+                    if (dn2[i0] >= 0)
+                    {
+                        ps0 = dn[i0];
+
+                        alp0 = (Word32) rr[i0][i0] << 14;
+
+                        /*----------------------------------------------------------------*
+                         * i1 loop: 8 positions.                                          *
+                         *----------------------------------------------------------------*/
+
+                        sq = -1;
+                        alp = 1;
+                        ps = 0;
+                        ix = ipos[1];
+
+                        /* initialize 4 index for next loop. */
+                        /*-------------------------------------------------------------------*
+                         *  These index have low complexity address computation because      *
+                         *  they are, in fact, pointers with fixed increment.  For example,  *
+                         *  "rr[i0][i3]" is a pointer initialized to "&rr[i0][ipos[3]]"      *
+                         *  and incremented by "STEP".                                       *
+                         *-------------------------------------------------------------------*/
+
+                        for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP)
+                        {
+                            /* idx increment = STEP */
+                            /* ps1 = add(ps0, dn[i1], pOverflow); */
+                            ps1 = ps0 + dn[i1];
+
+                            /* alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1]; */
+
+                            /* alp1 = L_mac(alp0, rr[i1][i1], _1_4, pOverflow); */
+                            alp1 = alp0 + ((Word32) rr[i1][i1] << 14);
+
+                            /* alp1 = L_mac(alp1, rr[i0][i1], _1_2, pOverflow); */
+                            alp1 += (Word32) rr[i0][i1] << 15;
+
+                            /* sq1 = mult(ps1, ps1, pOverflow); */
+                            sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                            /* alp_16 = pv_round(alp1, pOverflow); */
+                            alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                            /* s = L_mult(alp, sq1, pOverflow); */
+                            s = ((Word32) alp * sq1) << 1;
+
+                            /* s = L_msu(s, sq, alp_16, pOverflow); */
+                            s -= (((Word32) sq * alp_16) << 1);
+
+                            if (s > 0)
+                            {
+                                sq = sq1;
+                                ps = ps1;
+                                alp = alp_16;
+                                ix = i1;
+                            }
+                        }
+                        i1 = ix;
+
+                        /*----------------------------------------------------------------*
+                         * i2 loop: 8 positions.                                          *
+                         *----------------------------------------------------------------*/
+
+                        ps0 = ps;
+
+                        /* alp0 = L_mult(alp, _1_4, pOverflow); */
+                        alp0 = (Word32) alp << 14;
+
+                        sq = -1;
+                        alp = 1;
+                        ps = 0;
+                        ix = ipos[2];
+
+                        /* initialize 4 index for next loop (see i1 loop) */
+
+                        for (i2 = ipos[2]; i2 < L_CODE; i2 += STEP)
+                        {
+                            /* index increment = STEP */
+                            /* ps1 = add(ps0, dn[i2], pOverflow); */
+                            ps1 = ps0 + dn[i2];
+
+                            /* alp1 = alp0 + rr[i0][i2] + rr[i1][i2] + 1/2*rr[i2][i2]; */
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp0, rr[i2][i2], _1_16, pOverflow); */
+                            alp1 = alp0 + ((Word32) rr[i2][i2] << 12);
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp1, rr[i1][i2], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i1][i2] << 13;
+
+                            /* idx incr = STEP */
+                            /* alp1 = L_mac(alp1,rr[i0][i2], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i0][i2] << 13;
+
+                            /* sq1 = mult(ps1, ps1, pOverflow); */
+                            sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                            /* alp_16 = pv_round(alp1, pOverflow); */
+                            alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                            /* s = L_mult(alp, sq1, pOverflow); */
+                            s = ((Word32) alp * sq1) << 1;
+
+                            /* s = L_msu(s, sq, alp_16, pOverflow); */
+                            s -= (((Word32) sq * alp_16) << 1);
+
+                            if (s > 0)
+                            {
+                                sq = sq1;
+                                ps = ps1;
+                                alp = alp_16;
+                                ix = i2;
+                            }
+                        }
+                        i2 = ix;
+
+                        /*----------------------------------------------------------------*
+                         * i3 loop: 8 positions.                                          *
+                         *----------------------------------------------------------------*/
+
+                        ps0 = ps;
+                        alp0 = L_deposit_h(alp);
+
+                        sq = -1;
+                        alp = 1;
+                        ps = 0;
+                        ix = ipos[3];
+
+                        /* initialize 5 index for next loop (see i1 loop) */
+
+                        for (i3 = ipos[3]; i3 < L_CODE; i3 += STEP)
+                        {
+                            /* ps1 = add(ps0, dn[i3], pOverflow); */
+                            ps1 = ps0 + dn[i3]; /* index increment = STEP */
+
+                            /* alp1 = alp0 + rr[i0][i3] + rr[i1][i3] + rr[i2][i3] + 1/2*rr[i3][i3]; */
+
+                            /* alp1 = L_mac(alp0, rr[i3][i3], _1_16, pOverflow); */
+                            alp1 = alp0 + ((Word32) rr[i3][i3] << 12); /* idx incr = STEP */
+
+                            /* alp1 = L_mac(alp1, rr[i2][i3], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i2][i3] << 13;  /* idx incr = STEP */
+
+                            /* alp1 = L_mac(alp1, rr[i1][i3], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i1][i3] << 13;  /* idx incr = STEP */
+
+                            /* alp1 = L_mac(alp1, rr[i0][i3], _1_8, pOverflow); */
+                            alp1 += (Word32) rr[i0][i3] << 13;  /* idx incr = STEP */
+
+                            /* sq1 = mult(ps1, ps1, pOverflow); */
+                            sq1 = (Word16)(((Word32) ps1 * ps1) >> 15);
+
+                            /* alp_16 = pv_round(alp1, pOverflow); */
+                            alp_16 = (Word16)((alp1 + (Word32) 0x00008000L) >> 16);
+
+                            /* s = L_mult(alp, sq1, pOverflow); */
+                            s = ((Word32) alp * sq1) << 1;
+
+                            /* s = L_msu(s, sq, alp_16, pOverflow); */
+                            s -= (((Word32) sq * alp_16) << 1);
+
+                            if (s > 0)
+                            {
+                                sq = sq1;
+                                ps = ps1;
+                                alp = alp_16;
+                                ix = i3;
+                            }
+                        }
+
+
+                        /*----------------------------------------------------------------*
+                         * memorise codevector if this one is better than the last one.   *
+                         *----------------------------------------------------------------*/
+
+                        /* s = L_mult(alpk, sq, pOverflow); */
+                        s = ((Word32) alpk * sq) << 1;
+
+                        /* s = L_msu(s, psk, alp, pOverflow); */
+                        s -= (((Word32) psk * alp) << 1);
+
+                        if (s > 0)
+                        {
+                            psk = sq;
+                            alpk = alp;
+                            p_codvec = &codvec[0];
+
+                            *(p_codvec++) = i0;
+                            *(p_codvec++) = i1;
+                            *(p_codvec++) = i2;
+                            *(p_codvec) = ix;
+                        }
+                    }
+                }
+
+                /*----------------------------------------------------------------*
+                 * Cyclic permutation of i0,i1,i2 and i3.                         *
+                 *----------------------------------------------------------------*/
+
+                pos = ipos[3];
+                ipos[3] = ipos[2];
+                ipos[2] = ipos[1];
+                ipos[1] = ipos[0];
+                ipos[0] = pos;
+            }
+        }
+
+        return;
+    }
+
+
+
+
+    /****************************************************************************/
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME:  build_code()
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        codvec[]   Array of type Word16 -- position of pulses
+        dn_sign[]  Array of type Word16 -- sign of pulses
+        h[]        Array of type Word16 -- impulse response of
+                                           weighted synthesis filter
+
+     Outputs:
+        cod[]  Array of type Word16 -- innovative code vector
+        y[]    Array of type Word16 -- filtered innovative code
+        sign[] Array of type Word16 -- index of 4 pulses (sign + position)
+        pOverflow  Pointer to Flag  -- set when overflow occurs
+
+     Returns:
+        indx
+
+     Global Variables Used:
+        None
+
+     Local Variables Needed:
+
+    ------------------------------------------------------------------------------
+     FUNCTION DESCRIPTION
+
+     PURPOSE: Builds the codeword, the filtered codeword and index of the
+              codevector, based on the signs and positions of 4 pulses.
+
+    ------------------------------------------------------------------------------
+     REQUIREMENTS
+
+     None
+
+    ------------------------------------------------------------------------------
+     REFERENCES
+
+     [1] c4_17pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+    ------------------------------------------------------------------------------
+     PSEUDO-CODE
+
+    ------------------------------------------------------------------------------
+     RESOURCES USED [optional]
+
+     When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+     HEAP MEMORY USED: x bytes
+
+     STACK MEMORY USED: x bytes
+
+     CLOCK CYCLES: (cycle count equation for this function) + (variable
+                    used to represent cycle count for each subroutine
+                    called)
+         where: (cycle count variable) = cycle count for [subroutine
+                                         name]
+
+    ------------------------------------------------------------------------------
+     CAUTION [optional]
+     [State any special notes, constraints or cautions for users of this function]
+
+    ------------------------------------------------------------------------------
+    */
+
+    static Word16
+    build_code(
+        Word16 codvec[],  /* i : position of pulses                            */
+        Word16 dn_sign[], /* i : sign of pulses                                */
+        Word16 cod[],     /* o : innovative code vector                        */
+        Word16 h[],       /* i : impulse response of weighted synthesis filter */
+        Word16 y[],       /* o : filtered innovative code                      */
+        Word16 sign[],    /* o : index of 4 pulses (sign+position)             */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs               */
+    )
+    {
+        Word16 i;
+        Word16 j;
+        Word16 k;
+        Word16 track;
+        Word16 index;
+        Word16 _sign[NB_PULSE];
+        Word16 indx;
+        Word16 rsign;
+
+        Word16 *p0;
+        Word16 *p1;
+        Word16 *p2;
+        Word16 *p3;
+        Word16 *p_cod = &cod[0];
+
+        Word32 s;
+
+        for (i = 0; i < L_CODE; i++)
+        {
+            *(p_cod++) = 0;
+        }
+
+        indx = 0;
+        rsign = 0;
+
+        for (k = 0; k < NB_PULSE; k++)
+        {
+            i = codvec[k]; /* read pulse position */
+            j = dn_sign[i]; /* read sign          */
+
+            /* index = pos/5 */
+            /* index = mult(i, 6554, pOverflow); */
+            index = (Word16)(((Word32) i * 6554) >> 15);
+
+            /* track = pos%5 */
+            /* s = L_mult(index, 5, pOverflow); */
+            s = ((Word32) index * 5) << 1;
+
+            /* s = L_shr(s, 1, pOverflow); */
+            s >>= 1;
+
+            /* track = sub(i, (Word16) s, pOverflow); */
+            track = i - (Word16) s;
+
+            index = gray[index];
+
+            if (track == 1)
+            {
+                /* index = shl(index, 3, pOverflow); */
+                index <<= 3;
+            }
+            else if (track == 2)
+            {
+                /* index = shl(index, 6, pOverflow); */
+                index <<= 6;
+            }
+            else if (track == 3)
+            {
+                /* index = shl(index, 10, pOverflow); */
+                index <<= 10;
+            }
+            else if (track == 4)
+            {
+                track = 3;
+
+                /* index = shl(index, 10, pOverflow); */
+                index <<= 10;
+
+                /* index = add(index, 512, pOverflow); */
+                index += 512;
+            }
+
+            if (j > 0)
+            {
+                cod[i] = 8191;
+                _sign[k] = 32767;
+
+                /* track = shl(1, track, pOverflow); */
+                track = 1 << track;
+
+                /* rsign = add(rsign, track, pOverflow); */
+                rsign += track;
+            }
+            else
+            {
+                cod[i] = -8192;
+                _sign[k] = (Word16) - 32768L;
+            }
+
+            /* indx = add(indx, index, pOverflow); */
+            indx += index;
+        }
+        *sign = rsign;
+
+        p0 = h - codvec[0];
+        p1 = h - codvec[1];
+        p2 = h - codvec[2];
+        p3 = h - codvec[3];
+
+        for (i = 0; i < L_CODE; i++)
+        {
+            s = 0;
+            s =
+                L_mac(
+                    s,
+                    *p0++,
+                    _sign[0],
+                    pOverflow);
+
+            s =
+                L_mac(
+                    s,
+                    *p1++,
+                    _sign[1],
+                    pOverflow);
+
+            s =
+                L_mac(
+                    s,
+                    *p2++,
+                    _sign[2],
+                    pOverflow);
+
+            s =
+                L_mac(
+                    s,
+                    *p3++,
+                    _sign[3],
+                    pOverflow);
+
+            y[i] =
+                pv_round(
+                    s,
+                    pOverflow);
+
+        } /* for (i = 0; i < L_CODE; i++) */
+
+        return indx;
+
+    } /* build_code */
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.h b/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.h
new file mode 100644
index 0000000..4dc66a9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c4_17pf.h
@@ -0,0 +1,123 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c4_17pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the c4_17pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef c4_17pf_h
+#define c4_17pf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 code_4i40_17bits(
+        Word16 x[], /* (i)   : target vector                                 */
+        Word16 h[], /* (i)   : impulse response of weighted synthesis filter */
+        /*         h[-L_subfr..-1] must be set to zero.          */
+        Word16 T0,  /* (i)   : Pitch lag                                     */
+        Word16 pitch_sharp, /* (i)   : Last quantized pitch gain             */
+        Word16 code[],      /* (o)   : Innovative codebook                   */
+        Word16 y[],         /* (o)   : filtered fixed codebook excitation    */
+        Word16 * sign,      /* (o)   : Signs of 4 pulses                     */
+        Flag   * pOverflow  /* (o)   : Flag set when overflow occurs         */
+    );
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _c4_17PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.cpp
new file mode 100644
index 0000000..07c2efd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.cpp
@@ -0,0 +1,828 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/c8_31pf.c
+ Functions:
+
+     Date: 05/26/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to pass overflow flag through to basic math function.
+ The flag is passed back to the calling function by pointer reference.
+
+ Description: Optimized file to reduce clock cycle usage. Updated copyright
+              year. Removed unnecessary include files and unused #defines.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Purpose          : Searches a 31 bit algebraic codebook containing
+                  : 8 pulses in a frame of 40 samples.
+                  : in the same manner as GSM-EFR
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "c8_31pf.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "inv_sqrt.h"
+#include "cor_h.h"
+#include "cor_h_x2.h"
+#include "set_sign.h"
+#include "s10_8pf.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NB_PULSE 8
+
+/* define values/representation for output codevector and sign */
+#define POS_CODE  8191
+#define NEG_CODE  8191
+#define POS_SIGN  32767
+#define NEG_SIGN  (Word16) (-32768L)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    codvec[]   Array of type Word16 -- position of pulses
+    sign[]     Array of type Word16 -- sign of pulses
+    h[]        Array of type Word16 -- impulse response of
+                                       weighted synthesis filter
+ Outputs:
+    cod[]       Array of type Word16 -- innovative code vector
+    y[]         Array of type Word16 -- filtered innovative code
+    sign_indx[] Array of type Word16 -- signs of 4 pulses (signs only)
+    pos_indx[]  Array of type Word16 --
+                             position index of 8 pulses(position only)
+
+    pOverflow  Pointer to Flag  -- set when overflow occurs
+
+ Returns:
+    indx
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c8_31pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*************************************************************************
+ *
+ *  FUNCTION:  build_code()
+ *
+ *  PURPOSE: Builds the codeword, the filtered codeword and a
+ *   linear uncombined version of  the index of the
+ *           codevector, based on the signs and positions of 8  pulses.
+ *
+ *************************************************************************/
+
+static void build_code(
+    Word16 codvec[],    /* i : position of pulses                           */
+    Word16 sign[],      /* i : sign of d[n]                                 */
+    Word16 cod[],       /* o : innovative code vector                       */
+    Word16 h[],         /* i : impulse response of weighted synthesis filter*/
+    Word16 y[],         /* o : filtered innovative code                     */
+    Word16 sign_indx[], /* o : signs of 4  pulses (signs only)              */
+    Word16 pos_indx[],  /* o : position index of 8 pulses(position only)    */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs                */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 k;
+    Word16 track;
+    Word16 sign_index;
+    Word16 pos_index;
+    Word16 _sign[NB_PULSE];
+
+    Word16 *p0;
+    Word16 *p1;
+    Word16 *p2;
+    Word16 *p3;
+    Word16 *p4;
+    Word16 *p5;
+    Word16 *p6;
+    Word16 *p7;
+
+    Word16 *p_cod = &cod[0];
+    Word16 *p_codvec = &codvec[0];
+
+    Word32 s;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        *(p_cod++) = 0;
+    }
+
+    for (i = 0; i < NB_TRACK_MR102; i++)
+    {
+        pos_indx[i] = -1;
+        sign_indx[i] = -1;
+    }
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        /* read pulse position */
+        i = codvec[k];
+        /* read sign           */
+        j = sign[i];
+
+        pos_index = i >> 2; /* index = pos/4 */
+
+        track = i & 3;     /* track = pos%4 */
+
+        if (j > 0)
+        {
+            cod[i] = (Word16)((Word32) cod[i] + POS_CODE);
+
+            _sign[k] = POS_SIGN;
+            sign_index = 0;  /* bit=0 -> positive pulse */
+        }
+        else
+        {
+            cod[i] = (Word16)((Word32) cod[i] - NEG_CODE);
+
+            _sign[k] = NEG_SIGN;
+            sign_index = 1; /* bit=1 => negative pulse */
+            /* index = add (index, 8); 1 = negative  old code */
+        }
+
+        if (pos_indx[track] < 0)
+        {   /* first set first NB_TRACK pulses  */
+            pos_indx[track] = pos_index;
+            sign_indx[track] = sign_index;
+        }
+        else
+        {   /* 2nd row of pulses , test if positions needs to be switched */
+            if (((sign_index ^ sign_indx[track]) & 1) == 0)
+            {
+                /* sign of 1st pulse == sign of 2nd pulse */
+
+                if (pos_indx[track] <= pos_index)
+                {   /* no swap */
+                    pos_indx[track + NB_TRACK_MR102] = pos_index;
+                }
+                else
+                {   /* swap*/
+                    pos_indx[track + NB_TRACK_MR102] = pos_indx[track];
+
+                    pos_indx[track] = pos_index;
+                    sign_indx[track] = sign_index;
+                }
+            }
+            else
+            {
+                /* sign of 1st pulse != sign of 2nd pulse */
+
+                if (pos_indx[track] <= pos_index)
+                {  /*swap*/
+                    pos_indx[track + NB_TRACK_MR102] = pos_indx[track];
+
+                    pos_indx[track] = pos_index;
+                    sign_indx[track] = sign_index;
+                }
+                else
+                {   /*no swap */
+                    pos_indx[track + NB_TRACK_MR102] = pos_index;
+                }
+            }
+        }
+    }
+
+    p0 = h - *(p_codvec++);
+    p1 = h - *(p_codvec++);
+    p2 = h - *(p_codvec++);
+    p3 = h - *(p_codvec++);
+    p4 = h - *(p_codvec++);
+    p5 = h - *(p_codvec++);
+    p6 = h - *(p_codvec++);
+    p7 = h - *(p_codvec);
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = 0;
+
+        s =
+            L_mac(
+                s,
+                *p0++,
+                _sign[0],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p1++,
+                _sign[1],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p2++,
+                _sign[2],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p3++,
+                _sign[3],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p4++,
+                _sign[4],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p5++,
+                _sign[5],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p6++,
+                _sign[6],
+                pOverflow);
+        s =
+            L_mac(
+                s,
+                *p7++,
+                _sign[7],
+                pOverflow);
+
+        y[i] =
+            pv_round(
+                s,
+                pOverflow);
+
+    } /* for (i = 0; i < L_CODE; i++) */
+
+} /* build_code */
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: compress_code()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+ Outputs:
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ FUNCTION:
+
+ PURPOSE: compression of three indeces [0..9] to one 10 bit index
+          minimizing the phase shift of a bit error.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c8_31pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16 compress10(
+    Word16 pos_indxA,  /* i : signs of 4 pulses (signs only)             */
+    Word16 pos_indxB,  /* i : position index of 8 pulses (pos only)      */
+    Word16 pos_indxC,  /* i : position and sign of 8 pulses (compressed) */
+    Flag  *pOverflow)  /* o : Flag set when overflow occurs              */
+{
+    Word16 indx;
+    Word16 ia;
+    Word16 ib;
+    Word16 ic;
+
+    Word32 tempWord32;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    ia = pos_indxA >> 1;
+
+    ib = pos_indxB >> 1;
+
+    tempWord32 = ((Word32) ib * 5) << 1;
+
+    tempWord32 = tempWord32 >> 1;
+
+    ib = (Word16) tempWord32;
+
+    ic = pos_indxC >> 1;
+
+    tempWord32 = ((Word32) ic * 25) << 1;
+
+    tempWord32 = tempWord32 >> 1;
+
+    ic = (Word16) tempWord32;
+
+    ib += ic;
+
+    ib += ia;
+
+    indx = ib << 3;
+
+    ia = pos_indxA & 1;
+
+    ib = ((Word16)(pos_indxB & 1)) << 1;
+
+    ic = ((Word16)(pos_indxC & 1)) << 2;
+
+    ib += ic;
+
+    ib += ia;
+
+    indx += ib;
+
+    return indx;
+
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: compress_code()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sign_indx   Array of type Word16 -- signs of 4 pulses (signs only)
+    pos_indx    Array of type Word16 -- position index of 8 pulses
+                                            (position only)
+
+ Outputs:
+    indx         Array of type Word16 -- position and sign of 8 pulses
+                                            (compressed)
+    pOverflow    Pointer to Flag      -- set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: compression of the linear codewords to 4+three indeces
+          one bit from each pulse is made robust to errors by
+          minimizing the phase shift of a bit error.
+          4 signs (one for each track)
+          i0,i4,i1 => one index (7+3) bits, 3   LSBs more robust
+          i2,i6,i5 => one index (7+3) bits, 3   LSBs more robust
+          i3,i7    => one index (5+2) bits, 2-3 LSbs more robust
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c3_14pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void compress_code(
+    Word16 sign_indx[], /* i : signs of 4 pulses (signs only)             */
+    Word16 pos_indx[],  /* i : position index of 8 pulses (position only) */
+    Word16 indx[],      /* o : position and sign of 8 pulses (compressed) */
+    Flag  *pOverflow)   /* o : Flag set when overflow occurs              */
+{
+    Word16 i;
+    Word16 ia;
+    Word16 ib;
+    Word16 ic;
+
+    Word16 *p_indx = &indx[0];
+    Word16 *p_sign_indx = &sign_indx[0];
+
+    Word32 tempWord32;
+
+    for (i = 0; i < NB_TRACK_MR102; i++)
+    {
+        *(p_indx++) = *(p_sign_indx++);
+    }
+
+    /* First index
+      indx[NB_TRACK] = (ia/2+(ib/2)*5 +(ic/2)*25)*8 + ia%2 + (ib%2)*2 + (ic%2)*4; */
+
+    indx[NB_TRACK_MR102] =
+        compress10(
+            pos_indx[0],
+            pos_indx[4],
+            pos_indx[1],
+            pOverflow);
+
+    /* Second index
+      indx[NB_TRACK+1] = (ia/2+(ib/2)*5 +(ic/2)*25)*8 + ia%2 + (ib%2)*2 + (ic%2)*4; */
+
+    indx[NB_TRACK_MR102+1] =
+        compress10(
+            pos_indx[2],
+            pos_indx[6],
+            pos_indx[5],
+            pOverflow);
+
+    /*
+      Third index
+      if ((ib/2)%2 == 1)
+        indx[NB_TRACK+2] = ((((4-ia/2) + (ib/2)*5)*32+12)/25)*4 + ia%2 + (ib%2)*2;
+      else
+        indx[NB_TRACK+2] = ((((ia/2) +   (ib/2)*5)*32+12)/25)*4 + ia%2 + (ib%2)*2;
+        */
+
+    ib = pos_indx[7] >> 1;
+
+    ib &= 1;
+
+    ia = pos_indx[3] >> 1;
+
+    if (ib == 1)
+    {
+        ia = 4 - ia;
+    }
+
+    ib = pos_indx[7] >> 1;
+
+    tempWord32 = ((Word32) ib * 5) << 1;
+
+    tempWord32 = tempWord32 >> 1;
+
+    ib = (Word16) tempWord32;
+
+    ib += ia;
+
+    ib <<= 5;
+
+    ib += 12;
+
+    ic = (Word16)(((Word32) ib * 1311) >> 15);
+
+    ic <<= 2;
+
+    ia = pos_indx[3] & 1;
+
+    ib = ((Word16)(pos_indx[7] & 1)) << 1;
+
+    ib += ic;
+
+    ib += ia;
+
+    indx[NB_TRACK_MR102+2] = ib;
+
+} /* compress_code */
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: code_8i40_31bits()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x   Array of type Word16 -- target vector
+    cn  Array of type Word16 -- residual after long term prediction
+    h   Array of type Word16 -- impulse response of weighted synthesis filter
+
+
+ Outputs:
+    cod Array of type Word16 -- algebraic (fixed) codebook excitation
+    y   Array of type Word16 -- filtered fixed codebook excitation
+    indx Array of type Word16 -- index of 8 pulses (signs+positions)
+    pOverflow    Pointer to Flag      -- set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ FUNCTION:
+
+ PURPOSE:  Searches a 31 bit algebraic codebook containing 8 pulses
+           in a frame of 40 samples.
+
+ DESCRIPTION:
+   The code contains 8 nonzero pulses: i0...i7.
+   All pulses can have two possible amplitudes: +1 or -1.
+   The 40 positions in a subframe are divided into 4 tracks of
+   interleaved positions. Each track contains two pulses.
+   The pulses can have the following possible positions:
+
+      i0, i4 :  0, 4, 8,  12, 16, 20, 24, 28, 32, 36
+      i1, i5 :  1, 5, 9,  13, 17, 21, 25, 29, 33, 37
+      i2, i6 :  2, 6, 10, 14, 18, 22, 26, 30, 34, 38
+      i3, i7 :  3, 7, 11, 15, 19, 23, 27, 31, 35, 39
+
+   Each pair of pulses require 1 bit for their signs. The positions
+   are encoded together 3,3 and 2 resulting in
+   (7+3) + (7+3) + (5+2) bits for their
+   positions. This results in a 31 (4 sign and 27 pos) bit codebook.
+   The function determines the optimal pulse signs and positions, builds
+   the codevector, and computes the filtered codevector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] c8_31pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void code_8i40_31bits(
+    Word16 x[],        /* i : target vector                                  */
+    Word16 cn[],       /* i : residual after long term prediction            */
+    Word16 h[],        /* i : impulse response of weighted synthesis
+                             filter                                         */
+    Word16 cod[],      /* o : algebraic (fixed) codebook excitation          */
+    Word16 y[],        /* o : filtered fixed codebook excitation             */
+    Word16 indx[],     /* o : 7 Word16, index of 8 pulses (signs+positions)  */
+    Flag  *pOverflow   /* o : Flag set when overflow occurs                  */
+)
+{
+    Word16 ipos[NB_PULSE];
+    Word16 pos_max[NB_TRACK_MR102];
+    Word16 codvec[NB_PULSE];
+
+    Word16 dn[L_CODE];
+    Word16 sign[L_CODE];
+
+    Word16 rr[L_CODE][L_CODE];
+    Word16 linear_signs[NB_TRACK_MR102];
+    Word16 linear_codewords[NB_PULSE];
+
+    cor_h_x2(
+        h,
+        x,
+        dn,
+        2,
+        NB_TRACK_MR102,
+        STEP_MR102,
+        pOverflow);
+
+    /* 2 = use GSMEFR scaling */
+
+    set_sign12k2(
+        dn,
+        cn,
+        sign,
+        pos_max,
+        NB_TRACK_MR102,
+        ipos,
+        STEP_MR102,
+        pOverflow);
+
+    /* same setsign alg as GSM-EFR new constants though*/
+
+    cor_h(
+        h,
+        sign,
+        rr,
+        pOverflow);
+
+    search_10and8i40(
+        NB_PULSE,
+        STEP_MR102,
+        NB_TRACK_MR102,
+        dn,
+        rr,
+        ipos,
+        pos_max,
+        codvec,
+        pOverflow);
+
+    build_code(
+        codvec,
+        sign,
+        cod,
+        h,
+        y,
+        linear_signs,
+        linear_codewords,
+        pOverflow);
+
+    compress_code(
+        linear_signs,
+        linear_codewords,
+        indx,
+        pOverflow);
+
+} /* code_8i40_31bits */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.h b/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.h
new file mode 100644
index 0000000..03225ce
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/c8_31pf.h
@@ -0,0 +1,122 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/c8_31pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the c8_31pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef c8_31pf_h
+#define c8_31pf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void code_8i40_31bits(
+        Word16 x[],        /* i : target vector                                  */
+        Word16 cn[],       /* i : residual after long term prediction            */
+        Word16 h[],        /* i : impulse response of weighted synthesis
+                              filter                                         */
+        Word16 cod[],      /* o : algebraic (fixed) codebook excitation          */
+        Word16 y[],        /* o : filtered fixed codebook excitation             */
+        Word16 indx[],     /* o : 7 Word16, index of 8 pulses (signs+positions)  */
+        Flag   * pOverflow /* o : Flag set when overflow occurs                  */
+    );
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _c8_31PF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_cor.cpp b/media/libstagefright/codecs/amrnb/enc/src/calc_cor.cpp
new file mode 100644
index 0000000..db786a6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/calc_cor.cpp
@@ -0,0 +1,267 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/calc_cor.c
+
+     Date: 06/12/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Initial Optimization
+
+ Description: Optimize code by calculating two correlation per iteration
+              of the outer loop.
+
+ Description: Delete psedocode
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Defined one local variable per line.
+
+ Description:
+              1. Eliminated unused include file typedef.h.
+              2. Replaced array addressing by pointers
+              3. Unrolled loops to save extra accesses to memory
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Using inline functions from fxp_arithmetic.h for mac operations.
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "calc_cor.h"
+#include "basic_op.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: comp_corr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    scal_sig = array of input samples. (Word16)
+    L_frame = length of frame used to compute pitch(Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    corr = pointer to array of correlations corresponding to the selected
+        lags. (Word32)
+
+ Outputs:
+    corr = pointer to array of correlations corresponding to the selected
+        lags. (Word32)
+
+ Returns:
+    none
+
+ Global Variables Used:
+    none
+
+ Local Variables Needed:
+    none
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates all correlations of scal_sig[] in a given delay
+ range.
+
+ The correlation is given by
+
+         cor[t] = <scal_sig[n],scal_sig[n-t]>,  t=lag_min,...,lag_max
+
+ The function outputs all of the correlations
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ none
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] calc_cor.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void comp_corr (
+    Word16 scal_sig[],  // i   : scaled signal.
+    Word16 L_frame,     // i   : length of frame to compute pitch
+    Word16 lag_max,     // i   : maximum lag
+    Word16 lag_min,     // i   : minimum lag
+    Word32 corr[])      // o   : correlation of selected lag
+{
+    Word16 i, j;
+    Word16 *p, *p1;
+    Word32 t0;
+
+    for (i = lag_max; i >= lag_min; i--)
+    {
+       p = scal_sig;
+       p1 = &scal_sig[-i];
+       t0 = 0;
+
+       for (j = 0; j < L_frame; j++, p++, p1++)
+       {
+          t0 = L_mac (t0, *p, *p1);
+       }
+       corr[-i] = t0;
+    }
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void comp_corr(
+    Word16 scal_sig[],  /* i   : scaled signal.                     */
+    Word16 L_frame,     /* i   : length of frame to compute pitch   */
+    Word16 lag_max,     /* i   : maximum lag                        */
+    Word16 lag_min,     /* i   : minimum lag                        */
+    Word32 corr[])      /* o   : correlation of selected lag        */
+{
+
+
+
+
+    /*---------------------------------------------------
+    ; lag_max and lag_min are typically negative numbers
+    -----------------------------------------------------*/
+
+
+    /* PIT_MIN_MR122 18        Minimum pitch lag (MR122 mode)           */
+    /* PIT_MIN       20        Minimum pitch lag (all other modes)      */
+    /* PIT_MAX       143       Maximum pitch lag                        */
+
+
+    Word16 i;
+    Word16 j;
+    Word16 *p;
+    Word16 *p1;
+    Word16 *p2;
+    Word16 *p_scal_sig;
+    Word32 t1;
+    Word32 t2;
+    Word32 t3;
+    Word32 t4;
+
+    corr = corr - lag_max ;
+    p_scal_sig = &scal_sig[-lag_max];
+
+    for (i = ((lag_max - lag_min) >> 2) + 1; i > 0; i--)
+    {
+        t1 = 0;
+        t2 = 0;
+        t3 = 0;
+        t4 = 0;
+        p  = &scal_sig[0];
+        p1 = p_scal_sig++;
+        p_scal_sig++;
+        p2 = p_scal_sig++;
+        p_scal_sig++;
+        for (j = (L_frame >> 1); j != 0; j--)
+        {
+            t1 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p1++), t1);
+            t2 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p1), t2);
+            t3 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p2++), t3);
+            t4 = amrnb_fxp_mac_16_by_16bb((Word32) * (p++), (Word32) * (p2), t4);
+
+            t1 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p1++), t1);
+            t2 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p1), t2);
+            t3 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p2++), t3);
+            t4 = amrnb_fxp_mac_16_by_16bb((Word32) * (p++), (Word32) * (p2), t4);
+        }
+
+        *(corr++) = t1 << 1;
+        *(corr++) = t2 << 1;
+        *(corr++) = t3 << 1;
+        *(corr++) = t4 << 1;
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_cor.h b/media/libstagefright/codecs/amrnb/enc/src/calc_cor.h
new file mode 100644
index 0000000..d4a694b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/calc_cor.h
@@ -0,0 +1,87 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+********************************************************************************
+*
+*      GSM AMR-NB speech codec   R98   Version 7.5.0   March 2, 2001
+*                                R99   Version 3.2.0
+*                                REL-4 Version 4.0.0
+*
+********************************************************************************
+*
+*      File             : calc_cor.h
+*      Purpose          : Calculate all correlations for prior the OL LTP
+*
+********************************************************************************
+*/
+#ifndef calc_cor_h
+#define calc_cor_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    /*************************************************************************
+     *
+     *  FUNCTION: comp_corr
+     *
+     *  PURPOSE: Calculate all correlations of scal_sig[] in a given delay
+     *           range.
+     *
+     *  DESCRIPTION:
+     *      The correlation is given by
+     *           cor[t] = <scal_sig[n], scal_sig[n-t]>,  t=lag_min,...,lag_max
+     *      The functions outputs all correlations in the given range
+     *
+     *************************************************************************/
+    void comp_corr(Word16 scal_sig[],   /* i   : scaled signal.                     */
+    Word16 L_frame,     /* i   : length of frame to compute pitch   */
+    Word16 lag_max,     /* i   : maximum lag                        */
+    Word16 lag_min,     /* i   : minimum lag                        */
+    Word32 corr[]       /* o   : correlation of selected lag        */
+                  );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_en.cpp b/media/libstagefright/codecs/amrnb/enc/src/calc_en.cpp
new file mode 100644
index 0000000..6cf6867
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/calc_en.cpp
@@ -0,0 +1,825 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/calc_en.c
+ Funtions: calc_unfilt_energies
+           calc_filt_energies
+           calc_target_energy
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that calculate the energy coefficients
+ for unfiltered and filtered excitation signals, the LTP coding gain, and
+ the target energy.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "calc_en.h"
+#include "typedef.h"
+#include "basicop_malloc.h"
+#include "l_comp.h"
+#include "cnst.h"
+#include "log2.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: calc_unfilt_energies
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    res      = LP residual, buffer type Word16
+    exc      = LTP excitation (unfiltered), buffer type Word16
+    code     = CB innovation (unfiltered), buffer type Word16
+    gain_pit = pitch gain,  type Word16
+    L_subfr  = Subframe length, type Word16
+    frac_en  = energy coefficients (4), fraction part, buffer type Word16
+    exp_en   = energy coefficients (4), exponent part, buffer type Word16
+    ltpg     = LTP coding gain (log2()), pointer to type Word16
+    pOverflow= pointer to value indicating existence of overflow (Flag)
+
+ Outputs:
+    frac_en buffer containing new fractional parts of energy coefficients
+    exp_en buffer containing new exponential parts of energy coefficients
+    ltpg points to new LTP coding gain
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates several energy coefficients for unfiltered
+ excitation signals and the LTP coding gain
+
+    frac_en[0]*2^exp_en[0] = <res res>    LP residual energy
+    frac_en[1]*2^exp_en[1] = <exc exc>    LTP residual energy
+    frac_en[2]*2^exp_en[2] = <exc code>   LTP/CB innovation dot product
+    frac_en[3]*2^exp_en[3] = <lres lres>  LTP residual energy
+    (lres = res - gain_pit*exc)
+    ltpg = log2(LP_res_en / LTP_res_en)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+  None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ calc_en.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void
+calc_unfilt_energies(
+    Word16 res[],     // i  : LP residual,                               Q0
+    Word16 exc[],     // i  : LTP excitation (unfiltered),               Q0
+    Word16 code[],    // i  : CB innovation (unfiltered),                Q13
+    Word16 gain_pit,  // i  : pitch gain,                                Q14
+    Word16 L_subfr,   // i  : Subframe length
+
+    Word16 frac_en[], // o  : energy coefficients (4), fraction part,    Q15
+    Word16 exp_en[],  // o  : energy coefficients (4), exponent part,    Q0
+    Word16 *ltpg      // o  : LTP coding gain (log2()),                  Q13
+)
+{
+    Word32 s, L_temp;
+    Word16 i, exp, tmp;
+    Word16 ltp_res_en, pred_gain;
+    Word16 ltpg_exp, ltpg_frac;
+
+    // Compute residual energy
+    s = L_mac((Word32) 0, res[0], res[0]);
+    for (i = 1; i < L_subfr; i++)
+        s = L_mac(s, res[i], res[i]);
+
+    // ResEn := 0 if ResEn < 200.0 (= 400 Q1)
+    if (L_sub (s, 400L) < 0)
+    {
+        frac_en[0] = 0;
+        exp_en[0] = -15;
+    }
+    else
+    {
+        exp = norm_l(s);
+        frac_en[0] = extract_h(L_shl(s, exp));
+        exp_en[0] = sub(15, exp);
+    }
+
+    // Compute ltp excitation energy
+    s = L_mac((Word32) 0, exc[0], exc[0]);
+    for (i = 1; i < L_subfr; i++)
+        s = L_mac(s, exc[i], exc[i]);
+
+    exp = norm_l(s);
+    frac_en[1] = extract_h(L_shl(s, exp));
+    exp_en[1] = sub(15, exp);
+
+    // Compute scalar product <exc[],code[]>
+    s = L_mac((Word32) 0, exc[0], code[0]);
+    for (i = 1; i < L_subfr; i++)
+        s = L_mac(s, exc[i], code[i]);
+
+    exp = norm_l(s);
+    frac_en[2] = extract_h(L_shl(s, exp));
+    exp_en[2] = sub(16-14, exp);
+
+    // Compute energy of LTP residual
+    s = 0L;
+    for (i = 0; i < L_subfr; i++)
+    {
+        L_temp = L_mult(exc[i], gain_pit);
+        L_temp = L_shl(L_temp, 1);
+        tmp = sub(res[i], pv_round(L_temp)); // LTP residual, Q0
+        s = L_mac (s, tmp, tmp);
+    }
+
+    exp = norm_l(s);
+    ltp_res_en = extract_h (L_shl (s, exp));
+    exp = sub (15, exp);
+
+    frac_en[3] = ltp_res_en;
+    exp_en[3] = exp;
+
+    // calculate LTP coding gain, i.e. energy reduction LP res -> LTP res
+    if (ltp_res_en > 0 && frac_en[0] != 0)
+    {
+        // gain = ResEn / LTPResEn
+        pred_gain = div_s (shr (frac_en[0], 1), ltp_res_en);
+        exp = sub (exp, exp_en[0]);
+
+        // L_temp = ltpGain * 2^(30 + exp)
+        L_temp = L_deposit_h (pred_gain);
+        // L_temp = ltpGain * 2^27
+        L_temp = L_shr (L_temp, add (exp, 3));
+
+        // Log2 = log2() + 27
+        Log2(L_temp, &ltpg_exp, &ltpg_frac);
+
+        // ltpg = log2(LtpGain) * 2^13 --> range: +- 4 = +- 12 dB
+        L_temp = L_Comp (sub (ltpg_exp, 27), ltpg_frac);
+        *ltpg = pv_round (L_shl (L_temp, 13)); // Q13
+    }
+    else
+    {
+        *ltpg = 0;
+    }
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void calc_unfilt_energies(
+    Word16 res[],     /* i  : LP residual,                               Q0  */
+    Word16 exc[],     /* i  : LTP excitation (unfiltered),               Q0  */
+    Word16 code[],    /* i  : CB innovation (unfiltered),                Q13 */
+    Word16 gain_pit,  /* i  : pitch gain,                                Q14 */
+    Word16 L_subfr,   /* i  : Subframe length                                */
+
+    Word16 frac_en[], /* o  : energy coefficients (4), fraction part,    Q15 */
+    Word16 exp_en[],  /* o  : energy coefficients (4), exponent part,    Q0  */
+    Word16 *ltpg,     /* o  : LTP coding gain (log2()),                  Q13 */
+    Flag   *pOverflow
+)
+{
+    Word32 s1;      /* Intermediate energy accumulator */
+    Word32 s2;      /* Intermediate energy accumulator */
+    Word32 s3;      /* Intermediate energy accumulator */
+    Word32 s4;      /* Intermediate energy accumulator */
+    Word32 L_temp;      /* temporal 32 bits storage */
+
+    Word16 i;       /* index used in all loops */
+    Word16 exp;     /* nunmber of '0's or '1's before MSB != 0 */
+    Word16 tmp1;        /* temporal storage */
+    Word16 tmp2;        /* temporal storage */
+    Word16 ltp_res_en;
+    Word16 pred_gain;   /* predictor gain */
+    Word16 ltpg_exp;    /* LTP gain (exponent) */
+    Word16 ltpg_frac;   /* LTP gain (mantissa or fractional part) */
+
+    s1 = 0;
+    s2 = 0;
+    s3 = 0;
+    s4 = 0;
+
+    /*----------------------------------------------------------------------------
+    NOTE: Overflow is expected as a result of multiply and accumulated without
+        scale down the inputs. This modification is not made at this point
+        to have bit exact results with the pre-optimization code. (JT 6/20/00)
+
+    ----------------------------------------------------------------------------*/
+
+    for (i = 0; i < L_subfr; i++)
+    {
+        tmp1 = res[i];              /* avoid multiple accesses to memory */
+        tmp2 = exc[i];
+
+        s1 = amrnb_fxp_mac_16_by_16bb((Word32) tmp1, (Word32) tmp1, s1);   /* Compute residual energy */
+        s2 = amrnb_fxp_mac_16_by_16bb((Word32) tmp2, (Word32) tmp2, s2);   /* Compute ltp excitation energy */
+        s3 = amrnb_fxp_mac_16_by_16bb((Word32) tmp2, (Word32) code[i], s3);/* Compute scalar product */
+        /* <exc[],code[]>         */
+
+        L_temp = L_mult(tmp2, gain_pit, pOverflow);
+        L_temp = L_shl(L_temp, 1, pOverflow);
+        tmp2   = sub(tmp1, pv_round(L_temp, pOverflow), pOverflow);
+        /* LTP residual, Q0 */
+        s4     = L_mac(s4, tmp2, tmp2, pOverflow);
+        /* Compute energy of LTP residual */
+    }
+    s1 = s1 << 1;
+    s2 = s2 << 1;
+    s3 = s3 << 1;
+
+    if (s1 & MIN_32)
+    {
+        s1 = MAX_32;
+        *pOverflow = 1;
+    }
+
+    /* ResEn := 0 if ResEn < 200.0 (= 400 Q1) */
+    if (s1 < 400L)
+    {
+        frac_en[0] = 0;
+        exp_en[0] = -15;
+    }
+    else
+    {
+        exp = norm_l(s1);
+        frac_en[0] = (Word16)(L_shl(s1, exp, pOverflow) >> 16);
+        exp_en[0] = (15 - exp);
+    }
+
+    if (s2 & MIN_32)
+    {
+        s2 = MAX_32;
+        *pOverflow = 1;
+    }
+
+    exp = norm_l(s2);
+    frac_en[1] = (Word16)(L_shl(s2, exp, pOverflow) >> 16);
+    exp_en[1] = sub(15, exp, pOverflow);
+
+    /*  s3 is not always sum of squares */
+    exp = norm_l(s3);
+    frac_en[2] = (Word16)(L_shl(s3, exp, pOverflow) >> 16);
+    exp_en[2]  = 2 - exp;
+
+    exp = norm_l(s4);
+    ltp_res_en = (Word16)(L_shl(s4, exp, pOverflow) >> 16);
+    exp = sub(15, exp, pOverflow);
+
+    frac_en[3] = ltp_res_en;
+    exp_en[3] = exp;
+
+    /* calculate LTP coding gain, i.e. energy reduction LP res -> LTP res */
+
+    if (ltp_res_en > 0 && frac_en[0] != 0)
+    {
+        /* gain = ResEn / LTPResEn */
+        pred_gain = div_s(shr(frac_en[0], 1, pOverflow), ltp_res_en);
+        exp = sub(exp, exp_en[0], pOverflow);
+
+        /* L_temp = ltpGain * 2^(30 + exp) */
+        L_temp = (Word32) pred_gain << 16;
+        /* L_temp = ltpGain * 2^27 */
+        L_temp = L_shr(L_temp, (Word16)(exp + 3), pOverflow);
+
+        /* Log2 = log2() + 27 */
+        Log2(L_temp, &ltpg_exp, &ltpg_frac, pOverflow);
+
+        /* ltpg = log2(LtpGain) * 2^13 --> range: +- 4 = +- 12 dB */
+        L_temp = L_Comp(sub(ltpg_exp, 27, pOverflow), ltpg_frac, pOverflow);
+        *ltpg = pv_round(L_shl(L_temp, 13, pOverflow), pOverflow);   /* Q13 */
+    }
+    else
+    {
+        *ltpg = 0;
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: calc_filt_energies
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode = coder mode, type Mode
+    xn = LTP target vector, buffer type Word16
+    xn2 = CB target vector,  buffer type Word16
+    y1 = Adaptive codebook,  buffer type Word16
+    Y2 = Filtered innovative vector,  buffer type Word16
+    g_coeff = Correlations <xn y1> <y1 y1>
+    computed in G_pitch()  buffer type Word16
+    frac_coeff = energy coefficients (5), fraction part, buffer type Word16
+    exp_coeff = energy coefficients (5), exponent part, buffer type Word16
+    cod_gain_frac = optimum codebook gain (fraction part), pointer type Word16
+    cod_gain_exp = optimum codebook gain (exponent part), pointer type Word16
+    pOverflow    = pointer to overflow indicator (Flag)
+
+ Outputs:
+    frac_coeff contains new fraction part energy coefficients
+    exp_coeff contains new exponent part energy coefficients
+    cod_gain_frac points to the new optimum codebook gain (fraction part)
+    cod_gain_exp points to the new optimum codebook gain (exponent part)
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates several energy coefficients for filtered
+ excitation signals
+
+ Compute coefficients need for the quantization and the optimum
+ codebook gain gcu (for MR475 only).
+
+    coeff[0] =    y1 y1
+    coeff[1] = -2 xn y1
+    coeff[2] =    y2 y2
+    coeff[3] = -2 xn y2
+    coeff[4] =  2 y1 y2
+
+    gcu = <xn2, y2> / <y2, y2> (0 if <xn2, y2> <= 0)
+
+ Product <y1 y1> and <xn y1> have been computed in G_pitch() and
+ are in vector g_coeff[].
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ calc_en.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void
+calc_filt_energies(
+    enum Mode mode,     // i  : coder mode
+    Word16 xn[],        // i  : LTP target vector,                       Q0
+    Word16 xn2[],       // i  : CB target vector,                        Q0
+    Word16 y1[],        // i  : Adaptive codebook,                       Q0
+    Word16 Y2[],        // i  : Filtered innovative vector,              Q12
+    Word16 g_coeff[],   // i  : Correlations <xn y1> <y1 y1>
+                        //      computed in G_pitch()
+
+    Word16 frac_coeff[],// o  : energy coefficients (5), fraction part,  Q15
+    Word16 exp_coeff[], // o  : energy coefficients (5), exponent part,  Q0
+    Word16 *cod_gain_frac,// o: optimum codebook gain (fraction part),   Q15
+    Word16 *cod_gain_exp  // o: optimum codebook gain (exponent part),   Q0
+)
+{
+    Word32 s, ener_init;
+    Word16 i, exp, frac;
+    Word16 y2[L_SUBFR];
+
+    if (sub(mode, MR795) == 0 || sub(mode, MR475) == 0)
+    {
+        ener_init = 0L;
+    }
+    else
+    {
+        ener_init = 1L;
+    }
+
+    for (i = 0; i < L_SUBFR; i++) {
+        y2[i] = shr(Y2[i], 3);
+    }
+
+    frac_coeff[0] = g_coeff[0];
+    exp_coeff[0] = g_coeff[1];
+    frac_coeff[1] = negate(g_coeff[2]); // coeff[1] = -2 xn y1
+    exp_coeff[1] = add(g_coeff[3], 1);
+
+
+    // Compute scalar product <y2[],y2[]>
+
+    s = L_mac(ener_init, y2[0], y2[0]);
+    for (i = 1; i < L_SUBFR; i++)
+        s = L_mac(s, y2[i], y2[i]);
+
+    exp = norm_l(s);
+    frac_coeff[2] = extract_h(L_shl(s, exp));
+    exp_coeff[2] = sub(15 - 18, exp);
+
+    // Compute scalar product -2*<xn[],y2[]>
+
+    s = L_mac(ener_init, xn[0], y2[0]);
+    for (i = 1; i < L_SUBFR; i++)
+        s = L_mac(s, xn[i], y2[i]);
+
+    exp = norm_l(s);
+    frac_coeff[3] = negate(extract_h(L_shl(s, exp)));
+    exp_coeff[3] = sub(15 - 9 + 1, exp);
+
+
+    // Compute scalar product 2*<y1[],y2[]>
+
+    s = L_mac(ener_init, y1[0], y2[0]);
+    for (i = 1; i < L_SUBFR; i++)
+        s = L_mac(s, y1[i], y2[i]);
+
+    exp = norm_l(s);
+    frac_coeff[4] = extract_h(L_shl(s, exp));
+    exp_coeff[4] = sub(15 - 9 + 1, exp);
+
+    if (sub(mode, MR475) == 0 || sub(mode, MR795) == 0)
+    {
+        // Compute scalar product <xn2[],y2[]>
+
+        s = L_mac(ener_init, xn2[0], y2[0]);
+        for (i = 1; i < L_SUBFR; i++)
+            s = L_mac(s, xn2[i], y2[i]);
+
+        exp = norm_l(s);
+        frac = extract_h(L_shl(s, exp));
+        exp = sub(15 - 9, exp);
+
+
+        if (frac <= 0)
+        {
+            *cod_gain_frac = 0;
+            *cod_gain_exp = 0;
+        }
+        else
+        {
+            //
+              gcu = <xn2, y2> / c[2]
+                  = (frac>>1)/frac[2]             * 2^(exp+1-exp[2])
+                  = div_s(frac>>1, frac[2])*2^-15 * 2^(exp+1-exp[2])
+                  = div_s * 2^(exp-exp[2]-14)
+
+            *cod_gain_frac = div_s (shr (frac,1), frac_coeff[2]);
+            *cod_gain_exp = sub (sub (exp, exp_coeff[2]), 14);
+
+        }
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void calc_filt_energies(
+    enum Mode mode,     /* i  : coder mode                                   */
+    Word16 xn[],        /* i  : LTP target vector,                       Q0  */
+    Word16 xn2[],       /* i  : CB target vector,                        Q0  */
+    Word16 y1[],        /* i  : Adaptive codebook,                       Q0  */
+    Word16 Y2[],        /* i  : Filtered innovative vector,              Q12 */
+    Word16 g_coeff[],   /* i  : Correlations <xn y1> <y1 y1>                 */
+    /*      computed in G_pitch()                        */
+    Word16 frac_coeff[], /* o  : energy coefficients (5), fraction part, Q15 */
+    Word16 exp_coeff[], /* o  : energy coefficients (5), exponent part,  Q0  */
+    Word16 *cod_gain_frac, /* o  : optimum codebook gain (fraction part),Q15 */
+    Word16 *cod_gain_exp, /* o  : optimum codebook gain (exponent part), Q0  */
+    Flag   *pOverflow
+)
+{
+    Word32 s1;      /* Intermediate energy accumulator  */
+    Word32 s2;      /* Intermediate energy accumulator  */
+    Word32 s3;      /* Intermediate energy accumulator  */
+
+    Word16 i;       /* index used in all loops  */
+    Word16 exp;     /* number of '0's or '1's before MSB != 0   */
+    Word16 frac;        /* fractional part  */
+    Word16 tmp;     /* temporal storage */
+    Word16 scaled_y2[L_SUBFR];
+
+
+    frac_coeff[0] = g_coeff[0];
+    exp_coeff[0]  = g_coeff[1];
+    frac_coeff[1] = negate(g_coeff[2]);    /* coeff[1] = -2 xn y1 */
+    exp_coeff[1]  = add(g_coeff[3], 1, pOverflow);
+
+    if ((mode == MR795) || (mode == MR475))
+    {
+        s1 = 0L;
+        s2 = 0L;
+        s3 = 0L;
+    }
+    else
+    {
+        s1 = 1L;
+        s2 = 1L;
+        s3 = 1L;
+    }
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        /* avoid multiple accesses to memory  */
+        tmp   = (Y2[i] >> 3);
+        scaled_y2[i] = tmp;
+
+        /* Compute scalar product <scaled_y2[],scaled_y2[]> */
+        s1 = L_mac(s1, tmp, tmp, pOverflow);
+
+        /* Compute scalar product -2*<xn[],scaled_y2[]> */
+        s2 = L_mac(s2, xn[i], tmp, pOverflow);
+
+        /* Compute scalar product 2*<y1[],scaled_y2[]> */
+        s3 = L_mac(s3, y1[i], tmp, pOverflow);
+    }
+
+    exp = norm_l(s1);
+    frac_coeff[2] = (Word16)(L_shl(s1, exp, pOverflow) >> 16);
+    exp_coeff[2] = (-3 - exp);
+
+    exp = norm_l(s2);
+    frac_coeff[3] = negate((Word16)(L_shl(s2, exp, pOverflow) >> 16));
+    exp_coeff[3] = (7 - exp);
+
+    exp = norm_l(s3);
+    frac_coeff[4] = (Word16)(L_shl(s3, exp, pOverflow) >> 16);
+    exp_coeff[4] = sub(7, exp, pOverflow);
+
+
+    if ((mode == MR795) || (mode == MR475))
+    {
+        /* Compute scalar product <xn2[],scaled_y2[]> */
+        s1 = 0L;
+
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            s1 = amrnb_fxp_mac_16_by_16bb((Word32) xn2[i], (Word32)scaled_y2[i], s1);
+        }
+
+        s1 = s1 << 1;
+
+        exp = norm_l(s1);
+        frac = (Word16)(L_shl(s1, exp, pOverflow) >> 16);
+        exp = (6 - exp);
+
+        if (frac <= 0)
+        {
+            *cod_gain_frac = 0;
+            *cod_gain_exp = 0;
+        }
+        else
+        {
+            /*
+            gcu = <xn2, scaled_y2> / c[2]
+                = (frac>>1)/frac[2]             * 2^(exp+1-exp[2])
+                = div_s(frac>>1, frac[2])*2^-15 * 2^(exp+1-exp[2])
+                = div_s * 2^(exp-exp[2]-14)
+            */
+            *cod_gain_frac = div_s(shr(frac, 1, pOverflow), frac_coeff[2]);
+            *cod_gain_exp = ((exp - exp_coeff[2]) - 14);
+        }
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: calc_target_energy
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xn =  LTP target vector, buffer to type Word16  Q0
+    en_exp = optimum codebook gain (exponent part) pointer to type Word16
+    en_frac = optimum codebook gain (fraction part) pointer to type Word16
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    en_exp points to new optimum codebook gain (exponent part)
+    en_frac points to new optimum codebook gain (fraction part)
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the target energy using the formula,
+ en = <xn, xn>
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ calc_en.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void
+calc_target_energy(
+    Word16 xn[],     // i: LTP target vector,                       Q0
+    Word16 *en_exp,  // o: optimum codebook gain (exponent part),   Q0
+    Word16 *en_frac  // o: optimum codebook gain (fraction part),   Q15
+)
+{
+    Word32 s;
+    Word16 i, exp;
+
+    // Compute scalar product <xn[], xn[]>
+    s = L_mac(0L, xn[0], xn[0]);
+    for (i = 1; i < L_SUBFR; i++)
+        s = L_mac(s, xn[i], xn[i]);
+
+    // s = SUM 2*xn(i) * xn(i) = <xn xn> * 2
+    exp = norm_l(s);
+    *en_frac = extract_h(L_shl(s, exp));
+    *en_exp = sub(16, exp);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void calc_target_energy(
+    Word16 xn[],     /* i: LTP target vector,                       Q0  */
+    Word16 *en_exp,  /* o: optimum codebook gain (exponent part),   Q0  */
+    Word16 *en_frac, /* o: optimum codebook gain (fraction part),   Q15 */
+    Flag   *pOverflow
+)
+{
+    Word32 s;       /* Intermediate energy accumulator  */
+    Word16 i;       /* index used in all loops  */
+    Word16 exp;
+
+    /* Compute scalar product <xn[], xn[]> */
+    s = 0;
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        s = amrnb_fxp_mac_16_by_16bb((Word32) xn[i], (Word32) xn[i], s);
+    }
+
+    if (s < 0)
+    {
+        *pOverflow = 1;
+        s = MAX_32;
+    }
+
+    /* s = SUM 2*xn(i) * xn(i) = <xn xn> * 2 */
+    exp = norm_l(s);
+    *en_frac = (Word16)(L_shl(s, exp, pOverflow) >> 16);
+    *en_exp = (16 - exp);
+
+    return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/calc_en.h b/media/libstagefright/codecs/amrnb/enc/src/calc_en.h
new file mode 100644
index 0000000..052f5b4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/calc_en.h
@@ -0,0 +1,192 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/c_g_aver.h
+
+     Date: 12/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : calc_en.h
+      Purpose          : calculation of energy coefficients for quantizers
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _CALC_EN_H_
+#define _CALC_EN_H_
+#define calc_en_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+     * FUNCTION: calc_unfilt_energies
+     *
+     * PURPOSE:  calculation of several energy coefficients for unfiltered
+     *           excitation signals and the LTP coding gain
+     *
+     *       frac_en[0]*2^exp_en[0] = <res res>   // LP residual energy
+     *       frac_en[1]*2^exp_en[1] = <exc exc>   // LTP residual energy
+     *       frac_en[2]*2^exp_en[2] = <exc code>  // LTP/CB innovation dot product
+     *       frac_en[3]*2^exp_en[3] = <lres lres> // LTP residual energy
+     *                                            // (lres = res - gain_pit*exc)
+     *       ltpg = log2(LP_res_en / LTP_res_en)
+     */
+    void
+    calc_unfilt_energies(
+        Word16 res[],     /* i  : LP residual,                               Q0  */
+        Word16 exc[],     /* i  : LTP excitation (unfiltered),               Q0  */
+        Word16 code[],    /* i  : CB innovation (unfiltered),                Q13 */
+        Word16 gain_pit,  /* i  : pitch gain,                                Q14 */
+        Word16 L_subfr,   /* i  : Subframe length                                */
+
+        Word16 frac_en[], /* o  : energy coefficients (3), fraction part,    Q15 */
+        Word16 exp_en[],  /* o  : energy coefficients (3), exponent part,    Q0  */
+        Word16 *ltpg,     /* o  : LTP coding gain (log2()),                  Q13 */
+        Flag   *pOverflow
+    );
+
+    /*
+     * FUNCTION: calc_filt_energies
+     *
+     * PURPOSE:  calculation of several energy coefficients for filtered
+     *           excitation signals
+     *
+     *     Compute coefficients need for the quantization and the optimum
+     *     codebook gain gcu (for MR475 only).
+     *
+     *      coeff[0] =    y1 y1
+     *      coeff[1] = -2 xn y1
+     *      coeff[2] =    y2 y2
+     *      coeff[3] = -2 xn y2
+     *      coeff[4] =  2 y1 y2
+     *
+     *
+     *      gcu = <xn2, y2> / <y2, y2> (0 if <xn2, y2> <= 0)
+     *
+     *     Product <y1 y1> and <xn y1> have been computed in G_pitch() and
+     *     are in vector g_coeff[].
+     */
+    void
+    calc_filt_energies(
+        enum Mode mode,     /* i  : coder mode                                   */
+        Word16 xn[],        /* i  : LTP target vector,                       Q0  */
+        Word16 xn2[],       /* i  : CB target vector,                        Q0  */
+        Word16 y1[],        /* i  : Adaptive codebook,                       Q0  */
+        Word16 Y2[],        /* i  : Filtered innovative vector,              Q12 */
+        Word16 g_coeff[],   /* i  : Correlations <xn y1> <y1 y1>                 */
+        /*      computed in G_pitch()                        */
+
+        Word16 frac_coeff[],/* o  : energy coefficients (5), fraction part,  Q15 */
+        Word16 exp_coeff[], /* o  : energy coefficients (5), exponent part,  Q0  */
+        Word16 *cod_gain_frac,/* o: optimum codebook gain (fraction part),   Q15 */
+        Word16 *cod_gain_exp, /* o: optimum codebook gain (exponent part),   Q0  */
+        Flag   *pOverflow
+    );
+
+    /*
+     * FUNCTION: calc_target_energy
+     *
+     * PURPOSE:  calculation of target energy
+     *
+     *      en = <xn, xn>
+     */
+    void
+    calc_target_energy(
+        Word16 xn[],     /* i: LTP target vector,                       Q0  */
+        Word16 *en_exp,  /* o: optimum codebook gain (exponent part),   Q0  */
+        Word16 *en_frac,  /* o: optimum codebook gain (fraction part),   Q15 */
+        Flag   *pOverflow
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _CALC_EN_H_ */
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cbsearch.cpp b/media/libstagefright/codecs/amrnb/enc/src/cbsearch.cpp
new file mode 100644
index 0000000..a02b891
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cbsearch.cpp
@@ -0,0 +1,392 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cbsearch.c
+ Functions: D_plsf_3
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Removed "count.h" and "basic_op.h" and replaced with individual include
+     files (add.h, sub.h, etc.)
+ (2) Added pOverflow parameter to code_10i40_35bits()
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x[] -- array of type Word16 -- target vector, Q0
+    h[] -- array of type Word16 -- impulse response of weighted synthesis
+                                   filter h[-L_subfr..-1] must be set to
+                                   zero. Q12
+    T0  -- Word16 -- Pitch lag
+    pitch_sharp -- Word16 -- Last quantized pitch gain, Q14
+    gain_pit --  Word16 gain_pit -- Pitch gain, Q14
+    res2[] -- array of type Word16 -- Long term prediction residual, Q0
+    mode -- enum Mode --  coder mode
+    subNr -- Word16 -- subframe number
+
+ Outputs:
+    code[] -- array of type Word16 -- Innovative codebook, Q13
+    y[] -- array of type Word16 -- filtered fixed codebook excitation
+                                   Q12
+
+    anap -- Double pointer to Word16 -- Signs of the pulses
+
+
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    Zero
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Purpose          : Inovative codebook search (find index and gain)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cbsearch.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "cbsearch.h"
+
+#include "typedef.h"
+#include "c2_9pf.h"
+#include "c2_11pf.h"
+#include "c3_14pf.h"
+#include "c4_17pf.h"
+#include "c8_31pf.h"
+#include "c1035pf.h"
+#include "mode.h"
+#include "basic_op.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void cbsearch(Word16 x[],        /* i : target vector, Q0                     */
+              Word16 h[],        /* i : impulse response of weighted synthesis*/
+              /*     filter h[-L_subfr..-1] must be set to */
+              /*     zero. Q12                             */
+              Word16 T0,         /* i : Pitch lag                             */
+              Word16 pitch_sharp,/* i : Last quantized pitch gain, Q14        */
+              Word16 gain_pit,   /* i : Pitch gain, Q14                       */
+              Word16 res2[],     /* i : Long term prediction residual, Q0     */
+              Word16 code[],     /* o : Innovative codebook, Q13              */
+              Word16 y[],        /* o : filtered fixed codebook excitation    */
+              /*     Q12                                   */
+              Word16 **anap,     /* o : Signs of the pulses                   */
+              enum Mode mode,    /* i : coder mode                            */
+              Word16 subNr,      /* i : subframe number                       */
+              Flag  *pOverflow)  /* o : Flag set when overflow occurs         */
+{
+    Word16 index;
+    Word16 i;
+    Word16 temp;
+    Word16 pit_sharpTmp;
+
+    /* For MR74, the pre and post CB pitch sharpening is included in the
+     * codebook search routine, while for MR122 is it not.
+     */
+
+    if ((mode == MR475) || (mode == MR515))
+    {
+        /* MR475, MR515 */
+        *(*anap)++ =
+            code_2i40_9bits(
+                subNr,
+                x,
+                h,
+                T0,
+                pitch_sharp,
+                code,
+                y,
+                &index,
+                pOverflow);
+
+        *(*anap)++ = index;    /* sign index */
+    }
+    else if (mode == MR59)
+    {   /* MR59 */
+        *(*anap)++ =
+            code_2i40_11bits(
+                x,
+                h,
+                T0,
+                pitch_sharp,
+                code,
+                y,
+                &index,
+                pOverflow);
+
+        *(*anap)++ = index;    /* sign index */
+    }
+    else if (mode == MR67)
+    {   /* MR67 */
+        *(*anap)++ =
+            code_3i40_14bits(
+                x,
+                h,
+                T0,
+                pitch_sharp,
+                code,
+                y,
+                &index,
+                pOverflow);
+
+        *(*anap)++ = index;    /* sign index */
+    }
+    else if ((mode == MR74) || (mode == MR795))
+    {   /* MR74, MR795 */
+        *(*anap)++ =
+            code_4i40_17bits(
+                x,
+                h,
+                T0,
+                pitch_sharp,
+                code,
+                y,
+                &index,
+                pOverflow);
+
+        *(*anap)++ = index;    /* sign index */
+    }
+    else if (mode == MR102)
+    {   /* MR102 */
+        /*-------------------------------------------------------------*
+         * - include pitch contribution into impulse resp. h1[]        *
+         *-------------------------------------------------------------*/
+        /* pit_sharpTmp = pit_sharp;                     */
+        /* if (pit_sharpTmp > 1.0) pit_sharpTmp = 1.0;   */
+
+        pit_sharpTmp =
+            shl(
+                pitch_sharp,
+                1,
+                pOverflow);
+
+        for (i = T0; i < L_SUBFR; i++)
+        {
+            temp =
+                mult(
+                    h[i - T0],
+                    pit_sharpTmp,
+                    pOverflow);
+
+            h[i] =
+                add(
+                    h[i],
+                    temp,
+                    pOverflow);
+        }
+
+        /*--------------------------------------------------------------*
+         * - Innovative codebook search (find index and gain)           *
+         *--------------------------------------------------------------*/
+        code_8i40_31bits(
+            x,
+            res2,
+            h,
+            code,
+            y,
+            *anap,
+            pOverflow);
+
+        *anap += 7;
+
+        /*-------------------------------------------------------*
+         * - Add the pitch contribution to code[].               *
+         *-------------------------------------------------------*/
+        for (i = T0; i < L_SUBFR; i++)
+        {
+            temp =
+                mult(
+                    code[i - T0],
+                    pit_sharpTmp,
+                    pOverflow);
+
+            code[i] =
+                add(
+                    code[i],
+                    temp,
+                    pOverflow);
+        }
+    }
+    else
+    {  /* MR122 */
+        /*-------------------------------------------------------------*
+         * - include pitch contribution into impulse resp. h1[]        *
+         *-------------------------------------------------------------*/
+
+        /* pit_sharpTmp = gain_pit;                      */
+        /* if (pit_sharpTmp > 1.0) pit_sharpTmp = 1.0;   */
+
+        pit_sharpTmp = shl(gain_pit, 1, pOverflow);
+
+        for (i = T0; i < L_SUBFR; i++)
+        {
+            temp = ((Word32)h[i - T0] * pit_sharpTmp) >> 15;
+            /*
+                     mult(
+                            h[i - T0],
+                            ,
+                            pOverflow);
+            */
+            h[i] =
+                add(
+                    h[i],
+                    temp,
+                    pOverflow);
+        }
+        /*--------------------------------------------------------------*
+         * - Innovative codebook search (find index and gain)           *
+         *--------------------------------------------------------------*/
+
+        code_10i40_35bits(
+            x,
+            res2,
+            h,
+            code,
+            y,
+            *anap,
+            pOverflow);
+
+        *anap += 10;
+
+        /*-------------------------------------------------------*
+         * - Add the pitch contribution to code[].               *
+         *-------------------------------------------------------*/
+        for (i = T0; i < L_SUBFR; i++)
+        {
+            temp =
+                mult(
+                    code[i - T0],
+                    pit_sharpTmp,
+                    pOverflow);
+
+            code[i] =
+                add(
+                    code[i],
+                    temp,
+                    pOverflow);
+        }
+    }
+
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cbsearch.h b/media/libstagefright/codecs/amrnb/enc/src/cbsearch.h
new file mode 100644
index 0000000..46d149b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cbsearch.h
@@ -0,0 +1,136 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/dec_lag3.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the cbsearch.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef cbsearch_h
+#define cbsearch_h "$Id $"
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void cbsearch(Word16 x[],     /* i : target vector, Q0                      */
+    Word16 h[],     /* i : impulse response of weighted synthesis */
+    /*     filter h[-L_subfr..-1] must be set to  */
+    /*    zero. Q12                               */
+    Word16 T0,      /* i : Pitch lag                              */
+    Word16 pitch_sharp, /* i : Last quantized pitch gain, Q14     */
+    Word16 gain_pit,/* i : Pitch gain, Q14                        */
+    Word16 res2[],  /* i : Long term prediction residual, Q0      */
+    Word16 code[],  /* o : Innovative codebook, Q13               */
+    Word16 y[],     /* o : filtered fixed codebook excitation, Q12 */
+    Word16 **anap,  /* o : Signs of the pulses                    */
+    enum Mode mode, /* i : coder mode                             */
+    Word16 subNr,   /* i : subframe number                        */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs        */
+                 );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _CBSEARCH_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.cpp b/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.cpp
new file mode 100644
index 0000000..4a05327
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.cpp
@@ -0,0 +1,763 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cl_ltp.c
+ Funtions: cl_ltp_init
+           cl_ltp_reset
+           cl_ltp_exit
+           cl_ltp
+
+     Date: 06/07/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:   Placed into PV template and optimized.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Removed basic_op.h and oper_32b.h in the include section, and
+              added basicop_malloc.h.
+
+ Description: Fixed typecasting issue in TI C compiler.
+
+ Description: Added pOverflow parameter -- fixed minor template problem.
+
+ Description:
+              1. Eliminated unused include file typedef.h.
+              2. Replaced array addressing by pointers
+              3. Eliminated if-else checks for saturation
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains functions that perform closed-loop fractional pitch
+ search.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "cl_ltp.h"
+#include "basicop_malloc.h"
+#include "cnst.h"
+#include "convolve.h"
+#include "g_pitch.h"
+#include "pred_lt.h"
+#include "pitch_fr.h"
+#include "enc_lag3.h"
+#include "enc_lag6.h"
+#include "q_gain_p.h"
+#include "ton_stab.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cl_ltp_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = Pointer to a pointer to a clLtpState structure
+
+ Outputs:
+    state points to the newly created clLtpState structure.
+
+ Returns:
+    This function returns 0 upon success and -1 upon failure.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cl_ltp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cl_ltp_init (clLtpState **state)
+{
+    clLtpState* s;
+
+    if (state == (clLtpState **) NULL){
+        fprintf(stderr, "cl_ltp_init: invalid parameter\n");
+        return -1;
+    }
+    *state = NULL;
+
+    // allocate memory
+    if ((s= (clLtpState *) malloc(sizeof(clLtpState))) == NULL){
+        fprintf(stderr, "cl_ltp_init: can not malloc state structure\n");
+        return -1;
+  }
+
+    // init the sub state
+    if (Pitch_fr_init(&s->pitchSt)) {
+        cl_ltp_exit(&s);
+        return -1;
+    }
+
+    cl_ltp_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cl_ltp_init(clLtpState **state)
+{
+    clLtpState* s;
+
+    if (state == (clLtpState **) NULL)
+    {
+        /*fprint(stderr, "cl_ltp_init: invalid parameter\n");*/
+        return(-1);
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (clLtpState *) malloc(sizeof(clLtpState))) == NULL)
+    {
+        /*fprint(stderr, "cl_ltp_init: can not malloc state structure\n");*/
+        return(-1);
+    }
+
+    /* init the sub state */
+    if (Pitch_fr_init(&s->pitchSt))
+    {
+        cl_ltp_exit(&s);
+        return(-1);
+    }
+
+    cl_ltp_reset(s);
+
+    *state = s;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cl_ltp_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to the clLtpState structure to be reset
+
+ Outputs:
+    The state structure pointed to by clLtpState *state is reset.
+
+ Returns:
+    The function returns int 0 if successful, -1 otherwise.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Initializes state memory to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cl_ltp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+ ------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cl_ltp_reset (clLtpState *state)
+{
+    if (state == (clLtpState *) NULL){
+        fprintf(stderr, "cl_ltp_reset: invalid parameter\n");
+        return -1;
+    }
+
+    // Reset pitch search states
+    Pitch_fr_reset (state->pitchSt);
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cl_ltp_reset(clLtpState *state)
+{
+    if (state == (clLtpState *) NULL)
+    {
+        /*fprint(stderr, "cl_ltp_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    /* Reset pitch search states */
+    Pitch_fr_reset(state->pitchSt);
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cl_ltp_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    clLtpState **state = Reference to the state object to be freed.
+
+ Outputs:
+    The memory used by the structure which is pointed to by 'state'
+      is freed.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ The memory used for state memory is freed
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cl_ltp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void cl_ltp_exit (clLtpState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    // dealloc members
+    Pitch_fr_exit(&(*state)->pitchSt);
+
+    // deallocate memory
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cl_ltp_exit(clLtpState **state)
+{
+    if (state == NULL || *state == NULL)
+    {
+        return;
+    }
+
+    /* dealloc members */
+    Pitch_fr_exit(&(*state)->pitchSt);
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cl_ltp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    clSt = pointer to the clLtpState struct
+    tonSt = pointer to the tonStabState structure
+    mode = codec mode value, of type enum Mode
+    frameOffset = offset to subframe (Word16)
+    T_op = pointer to buffer of open loop pitch lags (Word16)
+    h1 = pointer to impulse response vector (Word16)
+    exc = pointer to excitation vector (Word16)
+    res2 = pointer to long term prediction residual (Word16)
+    xn = pointer to target vector for pitch search (Word16)
+    lsp_flag = LSP resonance flag (Word16)
+
+ Outputs:
+    clSt = pointer to the clLtpState struct
+    tonSt = pointer to the tonStabState structure
+    exc = pointer to excitation vector (Word16)
+    res2 = pointer to long term prediction residual (Word16)
+    xn2 = pointer to target vector for codebook search (Word16)
+    yl = pointer to buffer of filtered adaptive excitation (Word16)
+    T0 = pointer to pitch delay (integer part) (Word16)
+    T0_frac = pointer to pitch delay (fractional part) (Word16)
+    gain_pit = pointer to pitch gain (Word16)
+    g_coeff = pointer to array of correlations between xn, y1, & y2 (Word16)
+    anap = pointer to pointer to analysis parameters (Word16)
+    gp_limit = pointer to the pitch gain limit (Word16)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs closed-loop fractional pitch search.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cl_ltp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE FOR cl_ltp
+
+int cl_ltp (
+    clLtpState *clSt,    // i/o : State struct
+    tonStabState *tonSt, // i/o : State struct
+    enum Mode mode,      // i   : coder mode
+    Word16 frameOffset,  // i   : Offset to subframe
+    Word16 T_op[],       // i   : Open loop pitch lags
+    Word16 *h1,          // i   : Impulse response vector               Q12
+    Word16 *exc,         // i/o : Excitation vector                      Q0
+    Word16 res2[],       // i/o : Long term prediction residual          Q0
+    Word16 xn[],         // i   : Target vector for pitch search         Q0
+    Word16 lsp_flag,     // i   : LSP resonance flag
+    Word16 xn2[],        // o   : Target vector for codebook search      Q0
+    Word16 y1[],         // o   : Filtered adaptive excitation           Q0
+    Word16 *T0,          // o   : Pitch delay (integer part)
+    Word16 *T0_frac,     // o   : Pitch delay (fractional part)
+    Word16 *gain_pit,    // o   : Pitch gain                            Q14
+    Word16 g_coeff[],    // o   : Correlations between xn, y1, & y2
+    Word16 **anap,       // o   : Analysis parameters
+    Word16 *gp_limit     // o   : pitch gain limit
+)
+{
+    Word16 i;
+    Word16 index;
+    Word32 L_temp;     // temporarily variable
+    Word16 resu3;      // flag for upsample resolution
+    Word16 gpc_flag;
+
+    *----------------------------------------------------------------------*
+    *                 Closed-loop fractional pitch search                  *
+    *----------------------------------------------------------------------*
+   *T0 = Pitch_fr(clSt->pitchSt,
+                  mode, T_op, exc, xn, h1,
+                  L_SUBFR, frameOffset,
+                  T0_frac, &resu3, &index);
+
+   *(*anap)++ = index;
+
+    *-----------------------------------------------------------------*
+    *   - find unity gain pitch excitation (adapitve codebook entry)  *
+    *     with fractional interpolation.                              *
+    *   - find filtered pitch exc. y1[]=exc[] convolve with h1[])     *
+    *   - compute pitch gain and limit between 0 and 1.2              *
+    *   - update target vector for codebook search                    *
+    *   - find LTP residual.                                          *
+    *-----------------------------------------------------------------*
+
+   Pred_lt_3or6(exc, *T0, *T0_frac, L_SUBFR, resu3);
+
+   Convolve(exc, h1, y1, L_SUBFR);
+
+   // gain_pit is Q14 for all modes
+   *gain_pit = G_pitch(mode, xn, y1, g_coeff, L_SUBFR);
+
+
+   // check if the pitch gain should be limit due to resonance in LPC filter
+   gpc_flag = 0;
+   *gp_limit = MAX_16;
+   if ((lsp_flag != 0) &&
+       (sub(*gain_pit, GP_CLIP) > 0))
+   {
+       gpc_flag = check_gp_clipping(tonSt, *gain_pit);
+   }
+
+   // special for the MR475, MR515 mode; limit the gain to 0.85 to
+   // cope with bit errors in the decoder in a better way.
+   if ((sub (mode, MR475) == 0) || (sub (mode, MR515) == 0)) {
+      if ( sub (*gain_pit, 13926) > 0) {
+         *gain_pit = 13926;   // 0.85 in Q14
+      }
+
+      if (gpc_flag != 0) {
+          *gp_limit = GP_CLIP;
+      }
+   }
+   else
+   {
+       if (gpc_flag != 0)
+       {
+           *gp_limit = GP_CLIP;
+           *gain_pit = GP_CLIP;
+       }
+       // For MR122, gain_pit is quantized here and not in gainQuant
+       if (sub(mode, MR122)==0)
+       {
+           *(*anap)++ = q_gain_pitch(MR122, *gp_limit, gain_pit,
+                                     NULL, NULL);
+       }
+   }
+
+   // update target vector und evaluate LTP residual
+   for (i = 0; i < L_SUBFR; i++) {
+       L_temp = L_mult(y1[i], *gain_pit);
+       L_temp = L_shl(L_temp, 1);
+       xn2[i] = sub(xn[i], extract_h(L_temp));
+
+       L_temp = L_mult(exc[i], *gain_pit);
+       L_temp = L_shl(L_temp, 1);
+       res2[i] = sub(res2[i], extract_h(L_temp));
+   }
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cl_ltp(
+    clLtpState *clSt,    /* i/o : State struct                              */
+    tonStabState *tonSt, /* i/o : State struct                              */
+    enum Mode mode,      /* i   : coder mode                                */
+    Word16 frameOffset,  /* i   : Offset to subframe                        */
+    Word16 T_op[],       /* i   : Open loop pitch lags                      */
+    Word16 *h1,          /* i   : Impulse response vector               Q12 */
+    Word16 *exc,         /* i/o : Excitation vector                      Q0 */
+    Word16 res2[],       /* i/o : Long term prediction residual          Q0 */
+    Word16 xn[],         /* i   : Target vector for pitch search         Q0 */
+    Word16 lsp_flag,     /* i   : LSP resonance flag                        */
+    Word16 xn2[],        /* o   : Target vector for codebook search      Q0 */
+    Word16 yl[],         /* o   : Filtered adaptive excitation           Q0 */
+    Word16 *T0,          /* o   : Pitch delay (integer part)                */
+    Word16 *T0_frac,     /* o   : Pitch delay (fractional part)             */
+    Word16 *gain_pit,    /* o   : Pitch gain                            Q14 */
+    Word16 g_coeff[],    /* o   : Correlations between xn, y1, & y2         */
+    Word16 **anap,       /* o   : Analysis parameters                       */
+    Word16 *gp_limit,    /* o   : pitch gain limit                          */
+    Flag   *pOverflow    /* o   : overflow indicator                        */
+)
+{
+    register Word16 i;
+    Word16 index;
+    Word32 L_temp;     /* temporarily variable */
+    Word16 resu3;      /* flag for upsample resolution */
+    Word16 gpc_flag;
+
+    Word16 temp;
+    Word16 *p_exc;
+    Word16 *p_xn;
+    Word16 *p_xn2;
+    Word16 *p_yl;
+
+    /*----------------------------------------------------------------------*
+     *                 Closed-loop fractional pitch search                  *
+     *----------------------------------------------------------------------*/
+    *T0 =
+        Pitch_fr(
+            clSt->pitchSt,
+            mode,
+            T_op,
+            exc,
+            xn,
+            h1,
+            L_SUBFR,
+            frameOffset,
+            T0_frac,
+            &resu3,
+            &index,
+            pOverflow);
+
+    *(*anap)++ = index;
+
+    /*-----------------------------------------------------------------*
+     *   - find unity gain pitch excitation (adapitve codebook entry)  *
+     *     with fractional interpolation.                              *
+     *   - find filtered pitch exc. y1[]=exc[] convolve with h1[])     *
+     *   - compute pitch gain and limit between 0 and 1.2              *
+     *   - update target vector for codebook search                    *
+     *   - find LTP residual.                                          *
+     *-----------------------------------------------------------------*/
+
+    Pred_lt_3or6(
+        exc,
+        *T0,
+        *T0_frac,
+        L_SUBFR,
+        resu3,
+        pOverflow);
+
+    Convolve(exc, h1, yl, L_SUBFR);
+
+    /* gain_pit is Q14 for all modes */
+    *gain_pit =
+        G_pitch(
+            mode,
+            xn,
+            yl,
+            g_coeff,
+            L_SUBFR,
+            pOverflow);
+
+
+    /* check if the pitch gain should be limit due to resonance in LPC filter */
+    gpc_flag = 0;
+    *gp_limit = MAX_16;
+
+    if ((lsp_flag != 0) && ((Word32)(*gain_pit) > GP_CLIP))
+    {
+        gpc_flag = check_gp_clipping(tonSt, *gain_pit, pOverflow);
+    }
+
+    /* special for the MR475, MR515 mode; limit the gain to 0.85 to */
+    /* cope with bit errors in the decoder in a better way.         */
+
+    if ((mode == MR475) || (mode == MR515))
+    {
+        *gain_pit = ((Word32) * gain_pit > 13926) ? 13926 : *gain_pit;
+
+        if (gpc_flag != 0)
+        {
+            *gp_limit = GP_CLIP;
+        }
+    }
+    else
+    {
+        if (gpc_flag != 0)
+        {
+            *gp_limit = GP_CLIP;
+            *gain_pit = GP_CLIP;
+        }
+        /* For MR122, gain_pit is quantized here and not in gainQuant */
+        if (mode == MR122)
+        {
+            *(*anap)++ =
+                q_gain_pitch(
+                    MR122,
+                    *gp_limit,
+                    gain_pit,
+                    NULL,
+                    NULL,
+                    pOverflow);
+        }
+    }
+
+
+    p_exc  = &exc[0];
+    p_xn   =  &xn[0];
+    p_xn2  = &xn2[0];
+    p_yl   =  &yl[0];
+
+    temp = *gain_pit;
+
+    /* update target vector und evaluate LTP residual */
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        L_temp = ((Word32) * (p_yl++) * temp) >> 14;
+        *(p_xn2++) = *(p_xn++) - (Word16)L_temp;
+
+        L_temp   = ((Word32) * (p_exc++) * temp) >> 14;
+        res2[i] -= (Word16)L_temp;
+    }
+
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.h b/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.h
new file mode 100644
index 0000000..3e9b587
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cl_ltp.h
@@ -0,0 +1,163 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/cl_ltp.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the cl_ltp.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef cl_ltp_h
+#define cl_ltp_h "$Id $"
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "pitch_fr.h"
+#include "ton_stab.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /* state variable */
+    typedef struct
+    {
+        Pitch_frState *pitchSt;
+    } clLtpState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 cl_ltp_init(clLtpState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to cl_ltp in each call.
+       returns 0 on success
+     */
+
+    Word16 cl_ltp_reset(clLtpState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void cl_ltp_exit(clLtpState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void cl_ltp(
+        clLtpState *clSt,    /* i/o : State struct                              */
+        tonStabState *tonSt, /* i/o : State struct                              */
+        enum Mode mode,      /* i   : coder mode                                */
+        Word16 frameOffset,  /* i   : Offset to subframe                        */
+        Word16 T_op[],       /* i   : Open loop pitch lags                      */
+        Word16 *h1,          /* i   : Impulse response vector               Q12 */
+        Word16 *exc,         /* i/o : Excitation vector                      Q0 */
+        Word16 res2[],       /* i/o : Long term prediction residual          Q0 */
+        Word16 xn[],         /* i   : Target vector for pitch search         Q0 */
+        Word16 lsp_flag,     /* i   : LSP resonance flag                        */
+        Word16 xn2[],        /* o   : Target vector for codebook search      Q0 */
+        Word16 y1[],         /* o   : Filtered adaptive excitation           Q0 */
+        Word16 *T0,          /* o   : Pitch delay (integer part)                */
+        Word16 *T0_frac,     /* o   : Pitch delay (fractional part)             */
+        Word16 *gain_pit,    /* o   : Pitch gain                            Q14 */
+        Word16 g_coeff[],    /* o   : Correlations between xn, y1, & y2         */
+        Word16 **anap,       /* o   : Analysis parameters                       */
+        Word16 *gp_limit,    /* o   : pitch gain limit                          */
+        Flag   *pOverflow    /* o   : overflow indicator                        */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _CL_LTP_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cod_amr.cpp b/media/libstagefright/codecs/amrnb/enc/src/cod_amr.cpp
new file mode 100644
index 0000000..8468131
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cod_amr.cpp
@@ -0,0 +1,1608 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cod_amr.c
+ Funtions: cod_amr_init
+           cod_amr_reset
+           cod_amr_exit
+           cod_amr_first
+           cod_amr
+
+     Date: 06/09/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made changes based on comments from the review meeting.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Added initialization of the overflow flag in cod_amr_init()
+              and in cod_amr_reset(). This overflow flag is now part of
+              the cod_amrState structure.
+
+ Description: Cleaned up INCLUDES. removed inclusion of basic_op.h and repeat
+              inclusion of copy.h
+
+ Description: Updated function call to dtx_enc
+
+ Description:  For cod_amr_first() and cod_amr()
+              1. Replaced copy() function with memcpy()
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These functions comprise the main encoder routine operating on a frame basis.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+#include <string.h>
+
+#include "cod_amr.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "copy.h"
+#include "qua_gain.h"
+#include "lpc.h"
+#include "lsp.h"
+#include "pre_big.h"
+#include "ol_ltp.h"
+#include "p_ol_wgh.h"
+#include "spreproc.h"
+#include "cl_ltp.h"
+#include "pred_lt.h"
+#include "spstproc.h"
+#include "cbsearch.h"
+#include "gain_q.h"
+#include "convolve.h"
+#include "ton_stab.h"
+#include "vad.h"
+#include "dtx_enc.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* Spectral expansion factors */
+
+static const Word16 gamma1[M] =
+{
+    30802, 28954, 27217, 25584, 24049,
+    22606, 21250, 19975, 18777, 17650
+};
+
+/* gamma1 differs for the 12k2 coder */
+static const Word16 gamma1_12k2[M] =
+{
+    29491, 26542, 23888, 21499, 19349,
+    17414, 15672, 14105, 12694, 11425
+};
+
+static const Word16 gamma2[M] =
+{
+    19661, 11797, 7078, 4247, 2548,
+    1529, 917, 550, 330, 198
+};
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer to a structure of type cod_amrState
+
+ Outputs:
+    Structure pointed to by the pointer pointed to by state is
+      initialized to its reset value
+    state points to the allocated memory
+
+ Returns:
+    Returns 0 if memory was successfully initialized,
+        otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates memory and initializes state variables.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cod_amr_init (cod_amrState **state, Flag dtx)
+{
+  cod_amrState* s;
+
+  if (state == (cod_amrState **) NULL){
+      fprintf(stderr, "cod_amr_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (cod_amrState *) malloc(sizeof(cod_amrState))) == NULL){
+      fprintf(stderr, "cod_amr_init: can not malloc state structure\n");
+      return -1;
+  }
+
+  s->lpcSt = NULL;
+  s->lspSt = NULL;
+  s->clLtpSt = NULL;
+  s->gainQuantSt = NULL;
+  s->pitchOLWghtSt = NULL;
+  s->tonStabSt = NULL;
+  s->vadSt = NULL;
+  s->dtx_encSt = NULL;
+  s->dtx = dtx;
+
+  // Init sub states
+  if (cl_ltp_init(&s->clLtpSt) ||
+      lsp_init(&s->lspSt) ||
+      gainQuant_init(&s->gainQuantSt) ||
+      p_ol_wgh_init(&s->pitchOLWghtSt) ||
+      ton_stab_init(&s->tonStabSt) ||
+#ifndef VAD2
+      vad1_init(&s->vadSt) ||
+#else
+      vad2_init(&s->vadSt) ||
+#endif
+      dtx_enc_init(&s->dtx_encSt) ||
+      lpc_init(&s->lpcSt)) {
+     cod_amr_exit(&s);
+     return -1;
+  }
+
+  cod_amr_reset(s);
+
+  *state = s;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cod_amr_init(cod_amrState **state, Flag dtx)
+{
+    cod_amrState* s;
+
+    if (state == (cod_amrState **) NULL)
+    {
+        /* fprint(stderr, "cod_amr_init: invalid parameter\n");  */
+        return(-1);
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (cod_amrState *) malloc(sizeof(cod_amrState))) == NULL)
+    {
+        /* fprint(stderr, "cod_amr_init:
+                           can not malloc state structure\n");  */
+        return(-1);
+    }
+
+    s->lpcSt = NULL;
+    s->lspSt = NULL;
+    s->clLtpSt = NULL;
+    s->gainQuantSt = NULL;
+    s->pitchOLWghtSt = NULL;
+    s->tonStabSt = NULL;
+    s->vadSt = NULL;
+    s->dtx_encSt = NULL;
+    s->dtx = dtx;
+
+    /* Initialize overflow Flag */
+
+    s->overflow = 0;
+
+
+    /* Init sub states */
+    if (cl_ltp_init(&s->clLtpSt) ||
+            lsp_init(&s->lspSt) ||
+            gainQuant_init(&s->gainQuantSt) ||
+            p_ol_wgh_init(&s->pitchOLWghtSt) ||
+            ton_stab_init(&s->tonStabSt) ||
+#ifndef VAD2
+            vad1_init(&s->vadSt) ||
+#else
+            vad2_init(&s->vadSt) ||
+#endif
+            dtx_enc_init(&s->dtx_encSt) ||
+            lpc_init(&s->lpcSt))
+    {
+        cod_amr_exit(&s);
+        return(-1);
+    }
+
+    cod_amr_reset(s);
+
+    *state = s;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type cod_amrState
+
+ Outputs:
+    Structure pointed to by state is initialized to initial values.
+
+ Returns:
+    Returns 0 if memory was successfully initialized,
+        otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets the state memory for cod_amr.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cod_amr_reset (cod_amrState *st)
+{
+   Word16 i;
+
+   if (st == (cod_amrState *) NULL){
+      fprintf(stderr, "cod_amr_reset: invalid parameter\n");
+      return -1;
+   }
+
+    *-----------------------------------------------------------------------*
+    *          Initialize pointers to speech vector.                        *
+    *-----------------------------------------------------------------------*
+
+   st->new_speech = st->old_speech + L_TOTAL - L_FRAME;   // New speech
+
+   st->speech = st->new_speech - L_NEXT;                  // Present frame
+
+   st->p_window = st->old_speech + L_TOTAL - L_WINDOW;    // For LPC window
+   st->p_window_12k2 = st->p_window - L_NEXT; // EFR LPC window: no lookahead
+
+   // Initialize static pointers
+
+   st->wsp = st->old_wsp + PIT_MAX;
+   st->exc = st->old_exc + PIT_MAX + L_INTERPOL;
+   st->zero = st->ai_zero + MP1;
+   st->error = st->mem_err + M;
+   st->h1 = &st->hvec[L_SUBFR];
+
+   // Static vectors to zero
+
+   Set_zero(st->old_speech, L_TOTAL);
+   Set_zero(st->old_exc,    PIT_MAX + L_INTERPOL);
+   Set_zero(st->old_wsp,    PIT_MAX);
+   Set_zero(st->mem_syn,    M);
+   Set_zero(st->mem_w,      M);
+   Set_zero(st->mem_w0,     M);
+   Set_zero(st->mem_err,    M);
+   Set_zero(st->zero,       L_SUBFR);
+   Set_zero(st->hvec,       L_SUBFR);    // set to zero "h1[-L_SUBFR..-1]"
+
+   // OL LTP states
+   for (i = 0; i < 5; i++)
+   {
+      st->old_lags[i] = 40;
+   }
+
+   // Reset lpc states
+   lpc_reset(st->lpcSt);
+
+   // Reset lsp states
+   lsp_reset(st->lspSt);
+
+   // Reset clLtp states
+   cl_ltp_reset(st->clLtpSt);
+
+   gainQuant_reset(st->gainQuantSt);
+
+   p_ol_wgh_reset(st->pitchOLWghtSt);
+
+   ton_stab_reset(st->tonStabSt);
+
+#ifndef VAD2
+   vad1_reset(st->vadSt);
+#else
+   vad2_reset(st->vadSt);
+#endif
+
+   dtx_enc_reset(st->dtx_encSt);
+
+   st->sharp = SHARPMIN;
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cod_amr_reset(cod_amrState *st)
+{
+    Word16 i;
+
+    if (st == (cod_amrState *) NULL)
+    {
+        /* fprint(stderr, "cod_amr_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    /*-----------------------------------------------------------------------*
+     *          Initialize pointers to speech vector.                        *
+     *-----------------------------------------------------------------------*/
+
+    st->new_speech = st->old_speech + L_TOTAL - L_FRAME;   /* New speech     */
+
+    st->speech = st->new_speech - L_NEXT;                  /* Present frame  */
+
+    st->p_window = st->old_speech + L_TOTAL - L_WINDOW;    /* For LPC window */
+    st->p_window_12k2 = st->p_window - L_NEXT; /* EFR LPC window: no lookahead */
+
+    /* Initialize static pointers */
+
+    st->wsp = st->old_wsp + PIT_MAX;
+    st->exc = st->old_exc + PIT_MAX + L_INTERPOL;
+    st->zero = st->ai_zero + MP1;
+    st->error = st->mem_err + M;
+    st->h1 = &st->hvec[L_SUBFR];
+
+    /* Initialize overflow Flag */
+
+    st->overflow = 0;
+
+    /* Static vectors to zero */
+    memset(st->old_speech, 0, sizeof(Word16)*L_TOTAL);
+    memset(st->old_exc, 0,    sizeof(Word16)*(PIT_MAX + L_INTERPOL));
+    memset(st->old_wsp, 0,    sizeof(Word16)*PIT_MAX);
+    memset(st->mem_syn, 0,    sizeof(Word16)*M);
+    memset(st->mem_w,   0,    sizeof(Word16)*M);
+    memset(st->mem_w0,  0,    sizeof(Word16)*M);
+    memset(st->mem_err, 0,    sizeof(Word16)*M);
+    memset(st->zero, 0,       sizeof(Word16)*L_SUBFR);
+    memset(st->hvec, 0,       sizeof(Word16)*L_SUBFR);    /* set to zero "h1[-L_SUBFR..-1]" */
+
+    /* OL LTP states */
+    for (i = 0; i < 5; i++)
+    {
+        st->old_lags[i] = 40;
+    }
+
+    /* Reset lpc states */
+    lpc_reset(st->lpcSt);
+
+    /* Reset lsp states */
+    lsp_reset(st->lspSt);
+
+    /* Reset clLtp states */
+    cl_ltp_reset(st->clLtpSt);
+
+    gainQuant_reset(st->gainQuantSt);
+
+    p_ol_wgh_reset(st->pitchOLWghtSt);
+
+    ton_stab_reset(st->tonStabSt);
+
+#ifndef VAD2
+    vad1_reset(st->vadSt);
+#else
+    vad2_reset(st->vadSt);
+#endif
+
+    dtx_enc_reset(st->dtx_encSt);
+
+    st->sharp = SHARPMIN;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer to a structure of type cod_amrState
+
+ Outputs:
+    state points to a NULL address
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees the memory used for state memory.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void cod_amr_exit (cod_amrState **state)
+{
+   if (state == NULL || *state == NULL)
+      return;
+
+   // dealloc members
+   lpc_exit(&(*state)->lpcSt);
+   lsp_exit(&(*state)->lspSt);
+   gainQuant_exit(&(*state)->gainQuantSt);
+   cl_ltp_exit(&(*state)->clLtpSt);
+   p_ol_wgh_exit(&(*state)->pitchOLWghtSt);
+   ton_stab_exit(&(*state)->tonStabSt);
+#ifndef VAD2
+   vad1_exit(&(*state)->vadSt);
+#else
+   vad2_exit(&(*state)->vadSt);
+#endif
+   dtx_enc_exit(&(*state)->dtx_encSt);
+
+   // deallocate memory
+   free(*state);
+   *state = NULL;
+
+   return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cod_amr_exit(cod_amrState **state)
+{
+    if (state == NULL || *state == NULL)
+    {
+        return;
+    }
+
+    /* dealloc members */
+    lpc_exit(&(*state)->lpcSt);
+    lsp_exit(&(*state)->lspSt);
+    gainQuant_exit(&(*state)->gainQuantSt);
+    cl_ltp_exit(&(*state)->clLtpSt);
+    p_ol_wgh_exit(&(*state)->pitchOLWghtSt);
+    ton_stab_exit(&(*state)->tonStabSt);
+#ifndef VAD2
+    vad1_exit(&(*state)->vadSt);
+#else
+    vad2_exit(&(*state)->vadSt);
+#endif
+    dtx_enc_exit(&(*state)->dtx_encSt);
+
+    /* deallocate memory */
+    free(*state); // BX
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr_first
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type cod_amrState
+    new_speech = pointer to buffer of length L_FRAME that contains
+                 the speech input (Word16)
+
+ Outputs:
+    The structure of type cod_amrState pointed to by st is updated.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function copes with look-ahead and calls cod_amr.
+ No input argument are passed to this function. However, before
+ calling this function, 40 new speech data should be copied to the
+ vector new_speech[]. This is a global pointer which is declared in
+ this file (it points to the end of speech buffer minus 200).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cod_amr_first(cod_amrState *st,     // i/o : State struct
+                  Word16 new_speech[])  // i   : speech input (L_FRAME)
+{
+   Copy(new_speech,&st->new_speech[-L_NEXT], L_NEXT);
+   //   Copy(new_speech,st->new_speech,L_FRAME);
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cod_amr_first(cod_amrState *st,     /* i/o : State struct           */
+                     Word16 new_speech[])  /* i   : speech input (L_FRAME) */
+{
+
+    memcpy(&st->new_speech[-L_NEXT], new_speech, L_NEXT*sizeof(Word16));
+
+    /*   Copy(new_speech,st->new_speech,L_FRAME); */
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type cod_amrState
+    mode = AMR mode of type enum Mode
+    new_speech = pointer to buffer of length L_FRAME that contains
+             the speech input of type Word16
+    ana = pointer to the analysis parameters of type Word16
+    usedMode = pointer to the used mode of type enum Mode
+    synth = pointer to a buffer containing the local synthesis speech of
+        type Word16
+
+ Outputs:
+    The structure of type cod_amrState pointed to by st is updated.
+    The analysis parameter buffer pointed to by ana is updated.
+    The value pointed to by usedMode is updated.
+    The local synthesis speech buffer pointed to by synth is updated.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is the main encoder routine. It is called every 20 ms speech
+ frame, operating on the newly read 160 speech samples. It performs the
+ principle encoding functions to produce the set of encoded parameters
+ which include the LSP, adaptive codebook, and fixed codebook
+ quantization indices (addresses and gains).
+
+ Before calling this function, 160 new speech data should be copied to the
+ vector new_speech[]. This is a global pointer which is declared in
+ this file (it points to the end of speech buffer minus 160).
+
+ The outputs of the function are:
+     ana[]:     vector of analysis parameters.
+     synth[]:   Local synthesis speech (for debugging purposes)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cod_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int cod_amr(
+    cod_amrState *st,          // i/o : State struct
+    enum Mode mode,            // i   : AMR mode
+    Word16 new_speech[],       // i   : speech input (L_FRAME)
+    Word16 ana[],              // o   : Analysis parameters
+    enum Mode *usedMode,       // o   : used mode
+    Word16 synth[]             // o   : Local synthesis
+)
+{
+   // LPC coefficients
+   Word16 A_t[(MP1) * 4];      // A(z) unquantized for the 4 subframes
+   Word16 Aq_t[(MP1) * 4];     // A(z)   quantized for the 4 subframes
+   Word16 *A, *Aq;             // Pointer on A_t and Aq_t
+   Word16 lsp_new[M];
+
+   // Other vectors
+   Word16 xn[L_SUBFR];         // Target vector for pitch search
+   Word16 xn2[L_SUBFR];        // Target vector for codebook search
+   Word16 code[L_SUBFR];       // Fixed codebook excitation
+   Word16 y1[L_SUBFR];         // Filtered adaptive excitation
+   Word16 y2[L_SUBFR];         // Filtered fixed codebook excitation
+   Word16 gCoeff[6];           // Correlations between xn, y1, & y2:
+   Word16 res[L_SUBFR];        // Short term (LPC) prediction residual
+   Word16 res2[L_SUBFR];       // Long term (LTP) prediction residual
+
+   // Vector and scalars needed for the MR475
+   Word16 xn_sf0[L_SUBFR];     // Target vector for pitch search
+   Word16 y2_sf0[L_SUBFR];     // Filtered codebook innovation
+   Word16 code_sf0[L_SUBFR];   // Fixed codebook excitation
+   Word16 h1_sf0[L_SUBFR];     // The impulse response of sf0
+   Word16 mem_syn_save[M];     // Filter memory
+   Word16 mem_w0_save[M];      // Filter memory
+   Word16 mem_err_save[M];     // Filter memory
+   Word16 sharp_save;          // Sharpening
+   Word16 evenSubfr;           // Even subframe indicator
+   Word16 T0_sf0 = 0;          // Integer pitch lag of sf0
+   Word16 T0_frac_sf0 = 0;     // Fractional pitch lag of sf0
+   Word16 i_subfr_sf0 = 0;     // Position in exc[] for sf0
+   Word16 gain_pit_sf0;        // Quantized pitch gain for sf0
+   Word16 gain_code_sf0;       // Quantized codebook gain for sf0
+
+   // Scalars
+   Word16 i_subfr, subfrNr;
+   Word16 T_op[L_FRAME/L_FRAME_BY2];
+   Word16 T0, T0_frac;
+   Word16 gain_pit, gain_code;
+
+   // Flags
+   Word16 lsp_flag = 0;        // indicates resonance in LPC filter
+   Word16 gp_limit;            // pitch gain limit value
+   Word16 vad_flag;            // VAD decision flag
+   Word16 compute_sid_flag;    // SID analysis  flag
+
+   Copy(new_speech, st->new_speech, L_FRAME);
+
+   *usedMode = mode;
+
+   // DTX processing
+   if (st->dtx)
+   {  // no test() call since this if is only in simulation env
+      // Find VAD decision
+
+#ifdef  VAD2
+      vad_flag = vad2 (st->new_speech,    st->vadSt);
+      vad_flag = vad2 (st->new_speech+80, st->vadSt) || vad_flag;
+#else
+      vad_flag = vad1(st->vadSt, st->new_speech);
+#endif
+
+      // NB! usedMode may change here
+      compute_sid_flag = tx_dtx_handler(st->dtx_encSt,
+                                        vad_flag,
+                                        usedMode);
+   }
+   else
+   {
+      compute_sid_flag = 0;
+   }
+
+    *------------------------------------------------------------------------*
+    *  - Perform LPC analysis:                                               *
+    *       * autocorrelation + lag windowing                                *
+    *       * Levinson-durbin algorithm to find a[]                          *
+    *       * convert a[] to lsp[]                                           *
+    *       * quantize and code the LSPs                                     *
+    *       * find the interpolated LSPs and convert to a[] for all          *
+    *         subframes (both quantized and unquantized)                     *
+    *------------------------------------------------------------------------*
+
+   // LP analysis
+   lpc(st->lpcSt, mode, st->p_window, st->p_window_12k2, A_t);
+
+
+   // From A(z) to lsp. LSP quantization and interpolation
+   lsp(st->lspSt, mode, *usedMode, A_t, Aq_t, lsp_new, &ana);
+
+
+   // Buffer lsp's and energy
+   dtx_buffer(st->dtx_encSt,
+          lsp_new,
+          st->new_speech);
+
+   // Check if in DTX mode
+   if (sub(*usedMode, MRDTX) == 0)
+   {
+      dtx_enc(st->dtx_encSt,
+              compute_sid_flag,
+              st->lspSt->qSt,
+              st->gainQuantSt->gc_predSt,
+              &ana);
+
+      Set_zero(st->old_exc,    PIT_MAX + L_INTERPOL);
+      Set_zero(st->mem_w0,     M);
+      Set_zero(st->mem_err,    M);
+      Set_zero(st->zero,       L_SUBFR);
+      Set_zero(st->hvec,       L_SUBFR);    // set to zero "h1[-L_SUBFR..-1]"
+      // Reset lsp states
+      lsp_reset(st->lspSt);
+      Copy(lsp_new, st->lspSt->lsp_old, M);
+      Copy(lsp_new, st->lspSt->lsp_old_q, M);
+
+      // Reset clLtp states
+      cl_ltp_reset(st->clLtpSt);
+      st->sharp = SHARPMIN;
+   }
+   else
+   {
+       // check resonance in the filter
+      lsp_flag = check_lsp(st->tonStabSt, st->lspSt->lsp_old);
+   }
+
+    *----------------------------------------------------------------------*
+    * - Find the weighted input speech w_sp[] for the whole speech frame   *
+    * - Find the open-loop pitch delay for first 2 subframes               *
+    * - Set the range for searching closed-loop pitch in 1st subframe      *
+    * - Find the open-loop pitch delay for last 2 subframes                *
+    *----------------------------------------------------------------------*
+
+#ifdef VAD2
+   if (st->dtx)
+   {  // no test() call since this if is only in simulation env
+       st->vadSt->L_Rmax = 0;
+       st->vadSt->L_R0 = 0;
+   }
+#endif
+   for(subfrNr = 0, i_subfr = 0;
+       subfrNr < L_FRAME/L_FRAME_BY2;
+       subfrNr++, i_subfr += L_FRAME_BY2)
+   {
+      // Pre-processing on 80 samples
+      pre_big(mode, gamma1, gamma1_12k2, gamma2, A_t, i_subfr, st->speech,
+              st->mem_w, st->wsp);
+
+      if ((sub(mode, MR475) != 0) && (sub(mode, MR515) != 0))
+      {
+         // Find open loop pitch lag for two subframes
+         ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[i_subfr],
+                &T_op[subfrNr], st->old_lags, st->ol_gain_flg, subfrNr,
+                st->dtx);
+      }
+   }
+
+   if ((sub(mode, MR475) == 0) || (sub(mode, MR515) == 0))
+   {
+      // Find open loop pitch lag for ONE FRAME ONLY
+      // search on 160 samples
+
+      ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[0], &T_op[0],
+             st->old_lags, st->ol_gain_flg, 1, st->dtx);
+      T_op[1] = T_op[0];
+   }
+
+#ifdef VAD2
+   if (st->dtx)
+   {  // no test() call since this if is only in simulation env
+      LTP_flag_update(st->vadSt, mode);
+   }
+#endif
+
+#ifndef VAD2
+   // run VAD pitch detection
+   if (st->dtx)
+   {  // no test() call since this if is only in simulation env
+      vad_pitch_detection(st->vadSt, T_op);
+   }
+#endif
+
+   if (sub(*usedMode, MRDTX) == 0)
+   {
+      goto the_end;
+   }
+
+    *------------------------------------------------------------------------*
+    *          Loop for every subframe in the analysis frame                 *
+    *------------------------------------------------------------------------*
+    *  To find the pitch and innovation parameters. The subframe size is     *
+    *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
+    *     - find the weighted LPC coefficients                               *
+    *     - find the LPC residual signal res[]                               *
+    *     - compute the target signal for pitch search                       *
+    *     - compute impulse response of weighted synthesis filter (h1[])     *
+    *     - find the closed-loop pitch parameters                            *
+    *     - encode the pitch dealy                                           *
+    *     - update the impulse response h1[] by including fixed-gain pitch   *
+    *     - find target vector for codebook search                           *
+    *     - codebook search                                                  *
+    *     - encode codebook address                                          *
+    *     - VQ of pitch and codebook gains                                   *
+    *     - find synthesis speech                                            *
+    *     - update states of weighting filter                                *
+    *------------------------------------------------------------------------*
+
+   A = A_t;      // pointer to interpolated LPC parameters
+   Aq = Aq_t;    // pointer to interpolated quantized LPC parameters
+
+   evenSubfr = 0;
+   subfrNr = -1;
+   for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+   {
+      subfrNr = add(subfrNr, 1);
+      evenSubfr = sub(1, evenSubfr);
+
+      // Save states for the MR475 mode
+      if ((evenSubfr != 0) && (sub(*usedMode, MR475) == 0))
+      {
+         Copy(st->mem_syn, mem_syn_save, M);
+         Copy(st->mem_w0, mem_w0_save, M);
+         Copy(st->mem_err, mem_err_save, M);
+         sharp_save = st->sharp;
+      }
+
+       *-----------------------------------------------------------------*
+       * - Preprocessing of subframe                                     *
+       *-----------------------------------------------------------------*
+      if (sub(*usedMode, MR475) != 0)
+      {
+         subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                         gamma2, A, Aq, &st->speech[i_subfr],
+                         st->mem_err, st->mem_w0, st->zero,
+                         st->ai_zero, &st->exc[i_subfr],
+                         st->h1, xn, res, st->error);
+      }
+      else
+      { // MR475
+         subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                         gamma2, A, Aq, &st->speech[i_subfr],
+                         st->mem_err, mem_w0_save, st->zero,
+                         st->ai_zero, &st->exc[i_subfr],
+                         st->h1, xn, res, st->error);
+
+         // save impulse response (modified in cbsearch)
+         if (evenSubfr != 0)
+         {
+             Copy (st->h1, h1_sf0, L_SUBFR);
+         }
+      }
+
+      // copy the LP residual (res2 is modified in the CL LTP search)
+      Copy (res, res2, L_SUBFR);
+
+
+       *-----------------------------------------------------------------*
+       * - Closed-loop LTP search                                        *
+       *-----------------------------------------------------------------*
+      cl_ltp(st->clLtpSt, st->tonStabSt, *usedMode, i_subfr, T_op, st->h1,
+             &st->exc[i_subfr], res2, xn, lsp_flag, xn2, y1,
+             &T0, &T0_frac, &gain_pit, gCoeff, &ana,
+             &gp_limit);
+
+      // update LTP lag history
+      if ((subfrNr == 0) && (st->ol_gain_flg[0] > 0))
+      {
+         st->old_lags[1] = T0;
+      }
+
+      if ((sub(subfrNr, 3) == 0) && (st->ol_gain_flg[1] > 0))
+      {
+         st->old_lags[0] = T0;
+      }
+
+
+       *-----------------------------------------------------------------*
+       * - Inovative codebook search (find index and gain)               *
+       *-----------------------------------------------------------------*
+      cbsearch(xn2, st->h1, T0, st->sharp, gain_pit, res2,
+               code, y2, &ana, *usedMode, subfrNr);
+
+       *------------------------------------------------------*
+       * - Quantization of gains.                             *
+       *------------------------------------------------------*
+      gainQuant(st->gainQuantSt, *usedMode, res, &st->exc[i_subfr], code,
+                xn, xn2,  y1, y2, gCoeff, evenSubfr, gp_limit,
+                &gain_pit_sf0, &gain_code_sf0,
+                &gain_pit, &gain_code, &ana);
+
+      // update gain history
+      update_gp_clipping(st->tonStabSt, gain_pit);
+
+      if (sub(*usedMode, MR475) != 0)
+      {
+         // Subframe Post Porcessing
+         subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                          gain_code, Aq, synth, xn, code, y1, y2, st->mem_syn,
+                          st->mem_err, st->mem_w0, st->exc, &st->sharp);
+      }
+      else
+      {
+         if (evenSubfr != 0)
+         {
+            i_subfr_sf0 = i_subfr;
+            Copy(xn, xn_sf0, L_SUBFR);
+            Copy(y2, y2_sf0, L_SUBFR);
+            Copy(code, code_sf0, L_SUBFR);
+            T0_sf0 = T0;
+            T0_frac_sf0 = T0_frac;
+
+            // Subframe Post Porcessing
+            subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                             gain_code, Aq, synth, xn, code, y1, y2,
+                             mem_syn_save, st->mem_err, mem_w0_save,
+                             st->exc, &st->sharp);
+            st->sharp = sharp_save;
+         }
+         else
+         {
+            // update both subframes for the MR475
+
+            // Restore states for the MR475 mode
+            Copy(mem_err_save, st->mem_err, M);
+
+            // re-build excitation for sf 0
+            Pred_lt_3or6(&st->exc[i_subfr_sf0], T0_sf0, T0_frac_sf0,
+                         L_SUBFR, 1);
+            Convolve(&st->exc[i_subfr_sf0], h1_sf0, y1, L_SUBFR);
+
+            Aq -= MP1;
+            subframePostProc(st->speech, *usedMode, i_subfr_sf0,
+                             gain_pit_sf0, gain_code_sf0, Aq,
+                             synth, xn_sf0, code_sf0, y1, y2_sf0,
+                             st->mem_syn, st->mem_err, st->mem_w0, st->exc,
+                             &sharp_save); // overwrites sharp_save
+            Aq += MP1;
+
+            // re-run pre-processing to get xn right (needed by postproc)
+            // (this also reconstructs the unsharpened h1 for sf 1)
+            subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                            gamma2, A, Aq, &st->speech[i_subfr],
+                            st->mem_err, st->mem_w0, st->zero,
+                            st->ai_zero, &st->exc[i_subfr],
+                            st->h1, xn, res, st->error);
+
+            // re-build excitation sf 1 (changed if lag < L_SUBFR)
+            Pred_lt_3or6(&st->exc[i_subfr], T0, T0_frac, L_SUBFR, 1);
+            Convolve(&st->exc[i_subfr], st->h1, y1, L_SUBFR);
+
+            subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                             gain_code, Aq, synth, xn, code, y1, y2,
+                             st->mem_syn, st->mem_err, st->mem_w0,
+                             st->exc, &st->sharp);
+         }
+      }
+
+
+      A += MP1;    // interpolated LPC parameters for next subframe
+      Aq += MP1;
+   }
+
+   Copy(&st->old_exc[L_FRAME], &st->old_exc[0], PIT_MAX + L_INTERPOL);
+
+the_end:
+
+    *--------------------------------------------------*
+    * Update signal for next frame.                    *
+    *--------------------------------------------------*
+   Copy(&st->old_wsp[L_FRAME], &st->old_wsp[0], PIT_MAX);
+
+   Copy(&st->old_speech[L_FRAME], &st->old_speech[0], L_TOTAL - L_FRAME);
+
+   return 0;
+}
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 cod_amr(
+    cod_amrState *st,          /* i/o : State struct                   */
+    enum Mode mode,            /* i   : AMR mode                       */
+    Word16 new_speech[],       /* i   : speech input (L_FRAME)         */
+    Word16 ana[],              /* o   : Analysis parameters            */
+    enum Mode *usedMode,       /* o   : used mode                      */
+    Word16 synth[]            /* o   : Local synthesis                */
+)
+{
+    /* LPC coefficients */
+    Word16 A_t[(MP1) * 4];      /* A(z) unquantized for the 4 subframes */
+    Word16 Aq_t[(MP1) * 4];     /* A(z)   quantized for the 4 subframes */
+    Word16 *A, *Aq;             /* Pointer on A_t and Aq_t              */
+    Word16 lsp_new[M];
+
+    /* Other vectors */
+    Word16 xn[L_SUBFR];         /* Target vector for pitch search       */
+    Word16 xn2[L_SUBFR];        /* Target vector for codebook search    */
+    Word16 code[L_SUBFR];       /* Fixed codebook excitation            */
+    Word16 y1[L_SUBFR];         /* Filtered adaptive excitation         */
+    Word16 y2[L_SUBFR];         /* Filtered fixed codebook excitation   */
+    Word16 gCoeff[6];           /* Correlations between xn, y1, & y2:   */
+    Word16 res[L_SUBFR];        /* Short term (LPC) prediction residual */
+    Word16 res2[L_SUBFR];       /* Long term (LTP) prediction residual  */
+
+    /* Vector and scalars needed for the MR475 */
+    Word16 xn_sf0[L_SUBFR];     /* Target vector for pitch search       */
+    Word16 y2_sf0[L_SUBFR];     /* Filtered codebook innovation         */
+    Word16 code_sf0[L_SUBFR];   /* Fixed codebook excitation            */
+    Word16 h1_sf0[L_SUBFR];     /* The impulse response of sf0          */
+    Word16 mem_syn_save[M];     /* Filter memory                        */
+    Word16 mem_w0_save[M];      /* Filter memory                        */
+    Word16 mem_err_save[M];     /* Filter memory                        */
+    Word16 sharp_save;          /* Sharpening                           */
+    Word16 evenSubfr;           /* Even subframe indicator              */
+    Word16 T0_sf0 = 0;          /* Integer pitch lag of sf0             */
+    Word16 T0_frac_sf0 = 0;     /* Fractional pitch lag of sf0          */
+    Word16 i_subfr_sf0 = 0;     /* Position in exc[] for sf0            */
+    Word16 gain_pit_sf0;        /* Quantized pitch gain for sf0         */
+    Word16 gain_code_sf0;       /* Quantized codebook gain for sf0      */
+
+    /* Scalars */
+    Word16 i_subfr, subfrNr;
+    Word16 T_op[L_FRAME/L_FRAME_BY2];
+    Word16 T0, T0_frac;
+    Word16 gain_pit, gain_code;
+
+    /* Flags */
+    Word16 lsp_flag = 0;        /* indicates resonance in LPC filter    */
+    Word16 gp_limit;            /* pitch gain limit value               */
+    Word16 vad_flag;            /* VAD decision flag                    */
+    Word16 compute_sid_flag;    /* SID analysis  flag                   */
+    Flag   *pOverflow = &(st->overflow);     /* Overflow flag            */
+
+
+    memcpy(st->new_speech, new_speech, L_FRAME*sizeof(Word16));
+
+    *usedMode = mode;
+
+    /* DTX processing */
+    if (st->dtx)
+    {
+        /* Find VAD decision */
+#ifdef  VAD2
+        vad_flag = vad2(st->new_speech,    st->vadSt, pOverflow);
+        vad_flag = vad2(st->new_speech + 80, st->vadSt, pOverflow) || vad_flag;
+#else
+        vad_flag = vad1(st->vadSt, st->new_speech, pOverflow);
+#endif
+
+        /* NB! usedMode may change here */
+        compute_sid_flag = tx_dtx_handler(st->dtx_encSt,
+                                          vad_flag,
+                                          usedMode, pOverflow);
+    }
+    else
+    {
+        compute_sid_flag = 0;
+    }
+
+    /*------------------------------------------------------------------------*
+    *  - Perform LPC analysis:                                               *
+    *       * autocorrelation + lag windowing                                *
+    *       * Levinson-durbin algorithm to find a[]                          *
+    *       * convert a[] to lsp[]                                           *
+    *       * quantize and code the LSPs                                     *
+    *       * find the interpolated LSPs and convert to a[] for all          *
+    *         subframes (both quantized and unquantized)                     *
+    *------------------------------------------------------------------------*/
+
+    /* LP analysis */
+    lpc(st->lpcSt, mode, st->p_window, st->p_window_12k2, A_t, pOverflow);
+
+    /* From A(z) to lsp. LSP quantization and interpolation */
+    lsp(st->lspSt, mode, *usedMode, A_t, Aq_t, lsp_new, &ana, pOverflow);
+
+    /* Buffer lsp's and energy */
+    dtx_buffer(st->dtx_encSt,
+               lsp_new,
+               st->new_speech, pOverflow);
+
+    /* Check if in DTX mode */
+
+    if (*usedMode == MRDTX)
+    {
+        dtx_enc(st->dtx_encSt,
+                compute_sid_flag,
+                st->lspSt->qSt,
+                &(st->gainQuantSt->gc_predSt),
+                &ana, pOverflow);
+
+        memset(st->old_exc, 0,   sizeof(Word16)*(PIT_MAX + L_INTERPOL));
+        memset(st->mem_w0,  0,   sizeof(Word16)*M);
+        memset(st->mem_err, 0,   sizeof(Word16)*M);
+        memset(st->zero,    0,   sizeof(Word16)*L_SUBFR);
+        memset(st->hvec,    0,   sizeof(Word16)*L_SUBFR);    /* set to zero "h1[-L_SUBFR..-1]" */
+        /* Reset lsp states */
+        lsp_reset(st->lspSt);
+
+        memcpy(st->lspSt->lsp_old,   lsp_new, M*sizeof(Word16));
+        memcpy(st->lspSt->lsp_old_q, lsp_new, M*sizeof(Word16));
+
+        /* Reset clLtp states */
+        cl_ltp_reset(st->clLtpSt);
+        st->sharp = SHARPMIN;
+    }
+    else
+    {
+        /* check resonance in the filter */
+        lsp_flag = check_lsp(st->tonStabSt, st->lspSt->lsp_old, pOverflow);
+    }
+
+    /*----------------------------------------------------------------------*
+    * - Find the weighted input speech w_sp[] for the whole speech frame   *
+    * - Find the open-loop pitch delay for first 2 subframes               *
+    * - Set the range for searching closed-loop pitch in 1st subframe      *
+    * - Find the open-loop pitch delay for last 2 subframes                *
+    *----------------------------------------------------------------------*/
+
+#ifdef VAD2
+    if (st->dtx)
+    {
+        st->vadSt->L_Rmax = 0;
+        st->vadSt->L_R0 = 0;
+    }
+#endif
+
+    for (subfrNr = 0, i_subfr = 0;
+            subfrNr < L_FRAME / L_FRAME_BY2;
+            subfrNr++, i_subfr += L_FRAME_BY2)
+    {
+        /* Pre-processing on 80 samples */
+        pre_big(mode, gamma1, gamma1_12k2, gamma2, A_t, i_subfr, st->speech,
+                st->mem_w, st->wsp, pOverflow);
+
+
+        if ((mode != MR475) && (mode != MR515))
+        {
+            /* Find open loop pitch lag for two subframes */
+            ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[i_subfr],
+                   &T_op[subfrNr], st->old_lags, st->ol_gain_flg, subfrNr,
+                   st->dtx, pOverflow);
+        }
+    }
+
+    if ((mode == MR475) || (mode == MR515))
+    {
+        /* Find open loop pitch lag for ONE FRAME ONLY */
+        /* search on 160 samples */
+
+        ol_ltp(st->pitchOLWghtSt, st->vadSt, mode, &st->wsp[0], &T_op[0],
+               st->old_lags, st->ol_gain_flg, 1, st->dtx, pOverflow);
+        T_op[1] = T_op[0];
+    }
+
+#ifdef VAD2
+    if (st->dtx)
+    {
+        LTP_flag_update(st->vadSt, (Word16) mode, pOverflow);
+    }
+#endif
+
+#ifndef VAD2
+    /* run VAD pitch detection */
+    if (st->dtx)
+    {
+        vad_pitch_detection(st->vadSt, T_op, pOverflow);
+    }
+#endif
+
+    if (*usedMode == MRDTX)
+    {
+        goto the_end;
+    }
+
+    /*------------------------------------------------------------------------*
+    *          Loop for every subframe in the analysis frame                 *
+    *------------------------------------------------------------------------*
+    *  To find the pitch and innovation parameters. The subframe size is     *
+    *  L_SUBFR and the loop is repeated L_FRAME/L_SUBFR times.               *
+    *     - find the weighted LPC coefficients                               *
+    *     - find the LPC residual signal res[]                               *
+    *     - compute the target signal for pitch search                       *
+    *     - compute impulse response of weighted synthesis filter (h1[])     *
+    *     - find the closed-loop pitch parameters                            *
+    *     - encode the pitch dealy                                           *
+    *     - update the impulse response h1[] by including fixed-gain pitch   *
+    *     - find target vector for codebook search                           *
+    *     - codebook search                                                  *
+    *     - encode codebook address                                          *
+    *     - VQ of pitch and codebook gains                                   *
+    *     - find synthesis speech                                            *
+    *     - update states of weighting filter                                *
+    *------------------------------------------------------------------------*/
+
+    A = A_t;      /* pointer to interpolated LPC parameters */
+    Aq = Aq_t;    /* pointer to interpolated quantized LPC parameters */
+
+    evenSubfr = 0;
+    subfrNr = -1;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        subfrNr++;
+        evenSubfr = 1 - evenSubfr;
+
+        /* Save states for the MR475 mode */
+
+        if ((evenSubfr != 0) && (*usedMode == MR475))
+        {
+            memcpy(mem_syn_save, st->mem_syn, M*sizeof(Word16));
+            memcpy(mem_w0_save, st->mem_w0, M*sizeof(Word16));
+            memcpy(mem_err_save, st->mem_err, M*sizeof(Word16));
+
+            sharp_save = st->sharp;
+        }
+
+        /*-----------------------------------------------------------------*
+        * - Preprocessing of subframe                                     *
+        *-----------------------------------------------------------------*/
+
+        if (*usedMode != MR475)
+        {
+            subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                            gamma2, A, Aq, &st->speech[i_subfr],
+                            st->mem_err, st->mem_w0, st->zero,
+                            st->ai_zero, &st->exc[i_subfr],
+                            st->h1, xn, res, st->error);
+        }
+        else
+        { /* MR475 */
+            subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                            gamma2, A, Aq, &st->speech[i_subfr],
+                            st->mem_err, mem_w0_save, st->zero,
+                            st->ai_zero, &st->exc[i_subfr],
+                            st->h1, xn, res, st->error);
+
+            /* save impulse response (modified in cbsearch) */
+
+            if (evenSubfr != 0)
+            {
+                memcpy(h1_sf0, st->h1, L_SUBFR*sizeof(Word16));
+
+            }
+        }
+
+        /* copy the LP residual (res2 is modified in the CL LTP search)    */
+        memcpy(res2, res, L_SUBFR*sizeof(Word16));
+
+        /*-----------------------------------------------------------------*
+        * - Closed-loop LTP search                                        *
+        *-----------------------------------------------------------------*/
+        cl_ltp(st->clLtpSt, st->tonStabSt, *usedMode, i_subfr, T_op, st->h1,
+               &st->exc[i_subfr], res2, xn, lsp_flag, xn2, y1,
+               &T0, &T0_frac, &gain_pit, gCoeff, &ana,
+               &gp_limit, pOverflow);
+
+        /* update LTP lag history */
+
+        if ((subfrNr == 0) && (st->ol_gain_flg[0] > 0))
+        {
+            st->old_lags[1] = T0;
+        }
+
+
+        if ((subfrNr == 3) && (st->ol_gain_flg[1] > 0))
+        {
+            st->old_lags[0] = T0;
+        }
+
+        /*-----------------------------------------------------------------*
+        * - Inovative codebook search (find index and gain)               *
+        *-----------------------------------------------------------------*/
+        cbsearch(xn2, st->h1, T0, st->sharp, gain_pit, res2,
+                 code, y2, &ana, *usedMode, subfrNr, pOverflow);
+
+        /*------------------------------------------------------*
+        * - Quantization of gains.                             *
+        *------------------------------------------------------*/
+        gainQuant(st->gainQuantSt, *usedMode, res, &st->exc[i_subfr], code,
+                  xn, xn2,  y1, y2, gCoeff, evenSubfr, gp_limit,
+                  &gain_pit_sf0, &gain_code_sf0,
+                  &gain_pit, &gain_code, &ana, pOverflow);
+
+        /* update gain history */
+        update_gp_clipping(st->tonStabSt, gain_pit, pOverflow);
+
+
+        if (*usedMode != MR475)
+        {
+            /* Subframe Post Porcessing */
+            subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                             gain_code, Aq, synth, xn, code, y1, y2, st->mem_syn,
+                             st->mem_err, st->mem_w0, st->exc, &st->sharp, pOverflow);
+        }
+        else
+        {
+
+            if (evenSubfr != 0)
+            {
+                i_subfr_sf0 = i_subfr;
+
+                memcpy(xn_sf0, xn, L_SUBFR*sizeof(Word16));
+                memcpy(y2_sf0, y2, L_SUBFR*sizeof(Word16));
+                memcpy(code_sf0, code, L_SUBFR*sizeof(Word16));
+
+                T0_sf0 = T0;
+                T0_frac_sf0 = T0_frac;
+
+                /* Subframe Post Porcessing */
+                subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                                 gain_code, Aq, synth, xn, code, y1, y2,
+                                 mem_syn_save, st->mem_err, mem_w0_save,
+                                 st->exc, &st->sharp, pOverflow);
+                st->sharp = sharp_save;
+            }
+            else
+            {
+                /* update both subframes for the MR475 */
+
+                /* Restore states for the MR475 mode */
+                memcpy(st->mem_err, mem_err_save, M*sizeof(Word16));
+
+
+                /* re-build excitation for sf 0 */
+                Pred_lt_3or6(&st->exc[i_subfr_sf0], T0_sf0, T0_frac_sf0,
+                             L_SUBFR, 1, pOverflow);
+                Convolve(&st->exc[i_subfr_sf0], h1_sf0, y1, L_SUBFR);
+
+                Aq -= MP1;
+                subframePostProc(st->speech, *usedMode, i_subfr_sf0,
+                                 gain_pit_sf0, gain_code_sf0, Aq,
+                                 synth, xn_sf0, code_sf0, y1, y2_sf0,
+                                 st->mem_syn, st->mem_err, st->mem_w0, st->exc,
+                                 &sharp_save, pOverflow); /* overwrites sharp_save */
+                Aq += MP1;
+
+                /* re-run pre-processing to get xn right (needed by postproc) */
+                /* (this also reconstructs the unsharpened h1 for sf 1)       */
+                subframePreProc(*usedMode, gamma1, gamma1_12k2,
+                                gamma2, A, Aq, &st->speech[i_subfr],
+                                st->mem_err, st->mem_w0, st->zero,
+                                st->ai_zero, &st->exc[i_subfr],
+                                st->h1, xn, res, st->error);
+
+                /* re-build excitation sf 1 (changed if lag < L_SUBFR) */
+                Pred_lt_3or6(&st->exc[i_subfr], T0, T0_frac, L_SUBFR, 1, pOverflow);
+                Convolve(&st->exc[i_subfr], st->h1, y1, L_SUBFR);
+
+                subframePostProc(st->speech, *usedMode, i_subfr, gain_pit,
+                                 gain_code, Aq, synth, xn, code, y1, y2,
+                                 st->mem_syn, st->mem_err, st->mem_w0,
+                                 st->exc, &st->sharp, pOverflow);
+            }
+        }
+
+        A += MP1;    /* interpolated LPC parameters for next subframe */
+        Aq += MP1;
+    }
+
+    memcpy(&st->old_exc[0], &st->old_exc[L_FRAME], (PIT_MAX + L_INTERPOL)*sizeof(Word16));
+
+the_end:
+
+    /*--------------------------------------------------*
+    * Update signal for next frame.                    *
+    *--------------------------------------------------*/
+
+    memcpy(&st->old_wsp[0], &st->old_wsp[L_FRAME], PIT_MAX*sizeof(Word16));
+    memcpy(&st->old_speech[0], &st->old_speech[L_FRAME], (L_TOTAL - L_FRAME)*sizeof(Word16));
+
+    return(0);
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cod_amr.h b/media/libstagefright/codecs/amrnb/enc/src/cod_amr.h
new file mode 100644
index 0000000..7360c0a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cod_amr.h
@@ -0,0 +1,275 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/cod_amr.h
+
+     Date: 02/07/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added overflow flag as an element to the cod_amrState data
+              structure. Corrected the function prototype declaration for
+              cod_amr().
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : cod_amr.h
+       Purpose          : Main encoder routine operating on a frame basis.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef cod_amr_h
+#define cod_amr_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "mode.h"
+#include "lpc.h"
+#include "lsp.h"
+#include "cl_ltp.h"
+#include "gain_q.h"
+#include "p_ol_wgh.h"
+#include "ton_stab.h"
+#include "vad.h"
+#include "dtx_enc.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*-----------------------------------------------------------*
+     *    Coder constant parameters (defined in "cnst.h")        *
+     *-----------------------------------------------------------*
+     *   L_WINDOW    : LPC analysis window size.                 *
+     *   L_NEXT      : Samples of next frame needed for autocor. *
+     *   L_FRAME     : Frame size.                               *
+     *   L_FRAME_BY2 : Half the frame size.                      *
+     *   L_SUBFR     : Sub-frame size.                           *
+     *   M           : LPC order.                                *
+     *   MP1         : LPC order+1                               *
+     *   L_TOTAL7k4  : Total size of speech buffer.              *
+     *   PIT_MIN7k4  : Minimum pitch lag.                        *
+     *   PIT_MAX     : Maximum pitch lag.                        *
+     *   L_INTERPOL  : Length of filter for interpolation        *
+     *-----------------------------------------------------------*/
+    typedef struct
+    {
+        /* Speech vector */
+        Word16 old_speech[L_TOTAL];
+        Word16 *speech, *p_window, *p_window_12k2;
+        Word16 *new_speech;             /* Global variable */
+
+        /* Weight speech vector */
+        Word16 old_wsp[L_FRAME + PIT_MAX];
+        Word16 *wsp;
+
+        /* OL LTP states */
+        Word16 old_lags[5];
+        Word16 ol_gain_flg[2];
+
+        /* Excitation vector */
+        Word16 old_exc[L_FRAME + PIT_MAX + L_INTERPOL];
+        Word16 *exc;
+
+        /* Zero vector */
+        Word16 ai_zero[L_SUBFR + MP1];
+        Word16 *zero;
+
+        /* Impulse response vector */
+        Word16 *h1;
+        Word16 hvec[L_SUBFR * 2];
+
+        /* Substates */
+        lpcState   *lpcSt;
+        lspState   *lspSt;
+        clLtpState *clLtpSt;
+        gainQuantState  *gainQuantSt;
+        pitchOLWghtState *pitchOLWghtSt;
+        tonStabState *tonStabSt;
+        vadState *vadSt;
+        Flag dtx;
+        dtx_encState *dtx_encSt;
+
+        /* Filter's memory */
+        Word16 mem_syn[M], mem_w0[M], mem_w[M];
+        Word16 mem_err[M + L_SUBFR], *error;
+
+        Word16 sharp;
+
+        /* Overflow flag */
+        Flag   overflow;
+
+    } cod_amrState;
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+    **************************************************************************
+    *
+    *  Function    : cod_amr_init
+    *  Purpose     : Allocates memory and initializes state variables
+    *  Description : Stores pointer to filter status struct in *st. This
+    *                pointer has to be passed to cod_amr in each call.
+    *                 - initilize pointers to speech buffer
+    *                 - initialize static  pointers
+    *                 - set static vectors to zero
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 cod_amr_init(cod_amrState **st, Flag dtx);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : cod_amr_reset
+    *  Purpose     : Resets state memory
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 cod_amr_reset(cod_amrState *st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : cod_amr_exit
+    *  Purpose     : The memory used for state memory is freed
+    *  Description : Stores NULL in *st
+    *
+    **************************************************************************
+    */
+    void cod_amr_exit(cod_amrState **st);
+
+    /***************************************************************************
+     *   FUNCTION:   cod_amr_first
+     *
+     *   PURPOSE:  Copes with look-ahead.
+     *
+     *   INPUTS:
+     *       No input argument are passed to this function. However, before
+     *       calling this function, 40 new speech data should be copied to the
+     *       vector new_speech[]. This is a global pointer which is declared in
+     *       this file (it points to the end of speech buffer minus 200).
+     *
+     ***************************************************************************/
+
+    Word16 cod_amr_first(cod_amrState *st,     /* i/o : State struct            */
+                         Word16 new_speech[]   /* i   : speech input (L_FRAME)  */
+                        );
+
+    /***************************************************************************
+     *   FUNCTION:   cod_amr
+     *
+     *   PURPOSE:  Main encoder routine.
+     *
+     *   DESCRIPTION: This function is called every 20 ms speech frame,
+     *       operating on the newly read 160 speech samples. It performs the
+     *       principle encoding functions to produce the set of encoded parameters
+     *       which include the LSP, adaptive codebook, and fixed codebook
+     *       quantization indices (addresses and gains).
+     *
+     *   INPUTS:
+     *       No input argument are passed to this function. However, before
+     *       calling this function, 160 new speech data should be copied to the
+     *       vector new_speech[]. This is a global pointer which is declared in
+     *       this file (it points to the end of speech buffer minus 160).
+     *
+     *   OUTPUTS:
+     *
+     *       ana[]:     vector of analysis parameters.
+     *       synth[]:   Local synthesis speech (for debugging purposes)
+     *
+     ***************************************************************************/
+
+    Word16 cod_amr(cod_amrState *st,         /* i/o : State struct                 */
+                   enum Mode mode,           /* i   : AMR mode                     */
+                   Word16 new_speech[],      /* i   : speech input (L_FRAME)       */
+                   Word16 ana[],             /* o   : Analysis parameters          */
+                   enum Mode *usedMode,      /* o   : used mode                    */
+                   Word16 synth[]            /* o   : Local synthesis              */
+                  );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _cod_amr_h_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/convolve.cpp b/media/libstagefright/codecs/amrnb/enc/src/convolve.cpp
new file mode 100644
index 0000000..e9ce7ba
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/convolve.cpp
@@ -0,0 +1,245 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/convolve.c
+
+     Date: 06/19/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Optimize for speed. Update to code template.
+
+ Description: Added author name and date, fixed tabs, and added missing
+          sections. Updated Input/Output section.
+
+ Description: Optimized code by calculating two convolution sums per iteration
+          of the outer loop, thereby, decreasing outer loop count by 2.
+          Updated input/output definitions to be the same as the assembly
+          file (convolve.asm). Left Pseudo-code section blank.
+
+ Description: Deleted semi-colon in the Pointers modified section.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Fixed typecasting issue with TI C compiler.
+              2. Modified FOR loop to count down, wherever applicable.
+
+ Description: Made the following changes
+              1. Unrolled the correlation loop.
+              2. Performed 2 correlation per pass per sample to avoid recalling
+                 the same data twice.
+              3. Eliminated math operations that check for saturation.
+
+ Description:
+              1. Modified loop counter, extra unrolling did speed up code
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Using inlines from fxp_arithmetic.h .
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "convolve.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Convolve
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x = pointer to input vector of L elements of type Word16
+    h = pointer to the filter's impulse response vector of L elements
+        of type Word16
+    y = pointer to the output vector of L elements of type Word16 used for
+        storing the convolution of x and h;
+    L = Length of the convolution; type definition is Word16
+
+ Outputs:
+    y buffer contains the new convolution output
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Perform the convolution between two vectors x[] and h[] and write the result
+ in the vector y[]. All vectors are of length L and only the first L samples
+ of the convolution are computed.
+
+ The convolution is given by:
+
+    y[n] = sum_{i=0}^{n} x[i] h[n-i],        n=0,...,L-1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ convolve.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Convolve (
+    Word16 x[],        // (i)     : input vector
+    Word16 h[],        // (i)     : impulse response
+    Word16 y[],        // (o)     : output vector
+    Word16 L           // (i)     : vector size
+)
+{
+    Word16 i, n;
+    Word32 s;
+
+    for (n = 0; n < L; n++)
+    {
+        s = 0;                  move32 ();
+        for (i = 0; i <= n; i++)
+        {
+            s = L_mac (s, x[i], h[n - i]);
+        }
+        s = L_shl (s, 3);
+        y[n] = extract_h (s);   move16 ();
+    }
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void Convolve(
+    Word16 x[],        /* (i)     : input vector                           */
+    Word16 h[],        /* (i)     : impulse response                       */
+    Word16 y[],        /* (o)     : output vector                          */
+    Word16 L           /* (i)     : vector size                            */
+)
+{
+    register Word16 i, n;
+    Word32 s1, s2;
+
+
+    for (n = 1; n < L; n = n + 2)
+    {
+
+        h = h + n;
+
+        s2 = ((Word32) * (x)) * *(h--);
+        s1 = ((Word32) * (x++)) * *(h);
+
+        for (i = (n - 1) >> 1; i != 0; i--)
+        {
+            s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (x), (Word32) * (h--), s2);
+            s1 = amrnb_fxp_mac_16_by_16bb((Word32) * (x++), (Word32) * (h), s1);
+            s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (x), (Word32) * (h--), s2);
+            s1 = amrnb_fxp_mac_16_by_16bb((Word32) * (x++), (Word32) * (h), s1);
+        }
+
+        s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (x), (Word32) * (h), s2);
+
+        *(y++) = (Word16)(s1 >> 12);
+        *(y++) = (Word16)(s2 >> 12);
+
+        x = x - n;
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/convolve.h b/media/libstagefright/codecs/amrnb/enc/src/convolve.h
new file mode 100644
index 0000000..1f2b503
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/convolve.h
@@ -0,0 +1,83 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+********************************************************************************
+*
+*      GSM AMR-NB speech codec   R98   Version 7.5.0   March 2, 2001
+*                                R99   Version 3.2.0
+*                                REL-4 Version 4.0.0
+*
+********************************************************************************
+*
+*      File             : convolve.h
+*      Purpose          : Perform the convolution between two vectors x[]
+*                       : and h[] and write the result in the vector y[].
+*                       : All vectors are of length L and only the first
+*                       : L samples of the convolution are computed.
+*
+********************************************************************************
+*/
+#ifndef convolve_h
+#define convolve_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Convolve(
+        Word16 x[],        /* (i)  : input vector                               */
+        Word16 h[],        /* (i)  : impulse response                           */
+        Word16 y[],        /* (o)  : output vector                              */
+        Word16 L           /* (i)  : vector size                                */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h.cpp b/media/libstagefright/codecs/amrnb/enc/src/cor_h.cpp
new file mode 100644
index 0000000..e46d99f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h.cpp
@@ -0,0 +1,429 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cor_h.c
+
+     Date: 06/12/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Used MAX_16 and MIN_16 when checking the result of Inv_sqrt.
+          Synced up to the new template.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Took out cor_h_x function and put it in its own file. Sync'ed
+          up with the single_func_template.c template. Delete version
+          ID variable.
+
+ Description: Synchronized file with UTMS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Fixed portion of the code that builds the rr[] matrix. There
+              was an error in the original inlining of code that caused
+              the code to be not bit-exact with UMTS version 3.2.0.
+
+ Description: Added calls to L_add() and mult() in the code to handle overflow
+              scenario. Moved cor_h.h after cnst.h in the Include section.
+              Doing this allows the unit test to build using the cnst.h in the
+              /test/include directory. Fixed initialization of the accumulator
+              in the first calculation of the sum of squares.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Used #define value instead of hard-coded numbers in the code.
+              2. Fixed typecasting issue with TI C compiler.
+              3. Removed typecasting of 0x00008000L in the call to L_add.
+
+ Description: Changed pOverflow from a global variable into a function
+ parameter.
+
+ Description:
+            1. Added pointer to avoid adding offsets in every pass
+            2. Eliminate variables defined as registers
+            3. Removed extra check for overflow by doing scaling right
+               after overflow is detected.
+            4. Eliminated calls to basic operations (like extract) not
+               needed because of the nature of the number (all bounded)
+            5. Eliminated duplicate loop accessing same data
+            6. Simplified matrix addressing by use of pointers
+
+ Description:
+              1. Eliminated unused include files.
+              2. Access twice the number of points when delaing with matrices
+                 and in the process only 3 pointers (instead of 4) are needed
+              3. Replaced array addressing (array sign[]) by pointers
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Using inlines from fxp_arithmetic.h .
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "cnst.h"
+#include "cor_h.h"
+#include "basicop_malloc.h"
+#include "inv_sqrt.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cor_h
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    h = vector containing the impulse response of the weighted synthesis
+        filter; vector contents are of type Word16; vector length is
+        2 * L_SUBFR
+    sign = vector containing the sign information for the correlation
+           values; vector contents are of type Word16; vector length is
+           L_CODE
+    rr = autocorrelation matrix; matrix contents are of type Word16;
+         matrix dimension is L_CODE by L_CODE
+
+ Outputs:
+    rr contents are the newly calculated autocorrelation values
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes correlations of the impulse response (h) needed for
+ the codebook search, and includes the sign information into the correlations.
+
+ The correlations are given by:
+    rr[i][j] = sum_{n=i}^{L-1} h[n-i] h[n-j];   i>=j; i,j=0,...,L-1
+
+ The sign information is included by:
+    rr[i][j] = rr[i][j]*sign[i]*sign[j]
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cor_h.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void cor_h (
+    Word16 h[],         // (i) : impulse response of weighted synthesis
+                                 filter
+    Word16 sign[],      // (i) : sign of d[n]
+    Word16 rr[][L_CODE] // (o) : matrix of autocorrelation
+)
+{
+    Word16 i, j, k, dec, h2[L_CODE];
+    Word32 s;
+
+    // Scaling for maximum precision
+
+    s = 2;
+    for (i = 0; i < L_CODE; i++)
+        s = L_mac (s, h[i], h[i]);
+
+    j = sub (extract_h (s), 32767);
+    if (j == 0)
+    {
+        for (i = 0; i < L_CODE; i++)
+        {
+            h2[i] = shr (h[i], 1);
+        }
+    }
+    else
+    {
+        s = L_shr (s, 1);
+        k = extract_h (L_shl (Inv_sqrt (s), 7));
+        k = mult (k, 32440);                     // k = 0.99*k
+
+        for (i = 0; i < L_CODE; i++)
+        {
+            h2[i] = pv_round (L_shl (L_mult (h[i], k), 9));
+        }
+    }
+
+    // build matrix rr[]
+    s = 0;
+    i = L_CODE - 1;
+    for (k = 0; k < L_CODE; k++, i--)
+    {
+        s = L_mac (s, h2[k], h2[k]);
+        rr[i][i] = pv_round (s);
+    }
+
+    for (dec = 1; dec < L_CODE; dec++)
+    {
+        s = 0;
+        j = L_CODE - 1;
+        i = sub (j, dec);
+        for (k = 0; k < (L_CODE - dec); k++, i--, j--)
+        {
+            s = L_mac (s, h2[k], h2[k + dec]);
+            rr[j][i] = mult (pv_round (s), mult (sign[i], sign[j]));
+            rr[i][j] = rr[j][i];
+        }
+    }
+}
+
+---------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cor_h(
+    Word16 h[],          /* (i) : impulse response of weighted synthesis
+                                  filter                                  */
+    Word16 sign[],       /* (i) : sign of d[n]                            */
+    Word16 rr[][L_CODE], /* (o) : matrix of autocorrelation               */
+    Flag  *pOverflow
+)
+{
+    register Word16 i;
+    register Word16 dec;
+
+    Word16 h2[L_CODE];
+    Word32 s;
+    Word32 s2;
+    Word16 tmp1;
+    Word16 tmp2;
+    Word16 tmp11;
+    Word16 tmp22;
+
+    Word16 *p_h;
+    Word16 *p_h2;
+    Word16 *rr1;
+    Word16 *rr2;
+    Word16 *rr3;
+    Word16 *p_rr_ref1;
+    Word16 *p_sign1;
+    Word16 *p_sign2;
+
+    /* Scaling for maximum precision */
+
+    /* Initialize accumulator to 1 since left shift happens    */
+    /* after the accumulation of the sum of squares (original  */
+    /* code initialized s to 2)                                */
+    s = 1;
+    p_h = h;
+
+    for (i = (L_CODE >> 1); i != 0 ; i--)
+    {
+        tmp1 = *(p_h++);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) tmp1, (Word32) tmp1, s);
+        tmp1 = *(p_h++);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) tmp1, (Word32) tmp1, s);
+
+    }
+
+    s <<= 1;
+
+    if (s & MIN_32)
+    {
+        p_h2 = h2;
+        p_h  = h;
+
+        for (i = (L_CODE >> 1); i != 0; i--)
+        {
+            *(p_h2++) =  *(p_h++)  >> 1;
+            *(p_h2++) =  *(p_h++)  >> 1;
+        }
+    }
+    else
+    {
+
+        s >>= 1;
+
+        s = Inv_sqrt(s, pOverflow);
+
+        if (s < (Word32) 0x00ffffffL)
+        {
+            /* k = 0.99*k */
+            dec = (Word16)(((s >> 9) * 32440) >> 15);
+        }
+        else
+        {
+            dec = 32440;  /* 0.99 */
+        }
+
+        p_h  = h;
+        p_h2 = h2;
+
+        for (i = (L_CODE >> 1); i != 0; i--)
+        {
+            *(p_h2++) = (Word16)((amrnb_fxp_mac_16_by_16bb((Word32) * (p_h++), (Word32) dec, 0x020L)) >> 6);
+            *(p_h2++) = (Word16)((amrnb_fxp_mac_16_by_16bb((Word32) * (p_h++), (Word32) dec, 0x020L)) >> 6);
+        }
+    }
+    /* build matrix rr[] */
+
+    s = 0;
+
+    p_h2 = h2;
+
+    rr1 = &rr[L_CODE-1][L_CODE-1];
+
+    for (i = L_CODE >> 1; i != 0 ; i--)
+    {
+        tmp1   = *(p_h2++);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) tmp1, (Word32) tmp1, s);
+        *rr1 = (Word16)((s + 0x00004000L) >> 15);
+        rr1 -= (L_CODE + 1);
+        tmp1   = *(p_h2++);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) tmp1, (Word32) tmp1, s);
+        *rr1 = (Word16)((s + 0x00004000L) >> 15);
+        rr1 -= (L_CODE + 1);
+    }
+
+
+    p_rr_ref1 = rr[L_CODE-1];
+
+    for (dec = 1; dec < L_CODE; dec += 2)
+    {
+        rr1 = &p_rr_ref1[L_CODE-1-dec];
+
+        rr2 = &rr[L_CODE-1-dec][L_CODE-1];
+        rr3 = &rr[L_CODE-1-(dec+1)][L_CODE-1];
+
+        s  = 0;
+        s2 = 0;
+
+        p_sign1 = &sign[L_CODE - 1];
+        p_sign2 = &sign[L_CODE - 1 - dec];
+
+        p_h2 = h2;
+        p_h  = &h2[dec];
+
+        for (i = (L_CODE - dec - 1); i != 0 ; i--)
+        {
+            s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_h2), (Word32) * (p_h++), s);
+            s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (p_h2++), (Word32) * (p_h), s2);
+
+            tmp1  = (Word16)((s + 0x00004000L) >> 15);
+            tmp11 = (Word16)((s2 + 0x00004000L) >> 15);
+
+            tmp2  = ((Word32) * (p_sign1) * *(p_sign2--)) >> 15;
+            tmp22 = ((Word32) * (p_sign1--) * *(p_sign2)) >> 15;
+
+            *rr2 = ((Word32) tmp1 * tmp2) >> 15;
+            *(rr1--) = *rr2;
+            *rr1 = ((Word32) tmp11 * tmp22) >> 15;
+            *rr3 = *rr1;
+
+            rr1 -= (L_CODE);
+            rr2 -= (L_CODE + 1);
+            rr3 -= (L_CODE + 1);
+
+        }
+
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_h2), (Word32) * (p_h), s);
+
+        tmp1 = (Word16)((s + 0x00004000L) >> 15);
+
+        tmp2 = ((Word32) * (p_sign1) * *(p_sign2)) >> 15;
+        *rr1 = ((Word32) tmp1 * tmp2) >> 15;
+
+        *rr2 = *rr1;
+
+        rr1 -= (L_CODE + 1);
+        rr2 -= (L_CODE + 1);
+
+    }
+
+    return;
+
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h.h b/media/libstagefright/codecs/amrnb/enc/src/cor_h.h
new file mode 100644
index 0000000..59b9d68
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h.h
@@ -0,0 +1,96 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef COR_H_H
+#define COR_H_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+#include "cor_h_x.h"                /* Used by legacy files */
+#include "cor_h_x2.h"               /* Used by legacy files */
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void cor_h(
+        Word16 h[],          /* (i) : impulse response of weighted synthesis
+                                  filter                                  */
+        Word16 sign[],       /* (i) : sign of d[n]                            */
+        Word16 rr[][L_CODE], /* (o) : matrix of autocorrelation               */
+        Flag  *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.cpp b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.cpp
new file mode 100644
index 0000000..beb2aec
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.cpp
@@ -0,0 +1,320 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cor_h_x.c
+
+     Date: 09/07/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created a separate file for cor_h_x function.
+
+ Description: Synchronized file with UMTS versin 3.2.0. Updated coding
+              template.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Modified FOR loop in the code to count down.
+              2. Fixed typecasting issue with TI C compiler.
+
+ Description: Added call to round() and L_shl() functions in the last FOR
+              loop to make code bit-exact. Updated copyright year.
+
+ Description: Modified to pass pOverflow in via a pointer, rather than
+ invoking it as a global variable.
+
+ Description: Made the following changes
+              1. Unrolled the correlation loop and add mechanism control
+                 to compute odd or even number of computations.
+              2. Use pointer to avoid continuos addresses calculation
+              2. Eliminated math operations that check for saturation.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "cor_h_x.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cor_h_x
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    h = vector containing the impulse response of the weighted synthesis
+        filter; vector contents are of type Word16; vector length is
+        2 * L_SUBFR
+    x = target signal vector; vector contents are of type Word16; vector
+        length is L_SUBFR
+    dn = vector containing the correlation between the target and the
+         impulse response; vector contents are of type Word16; vector
+         length is L_CODE
+    sf = scaling factor of type Word16 ; 2 when mode is MR122, 1 for all
+         other modes
+
+ Outputs:
+    dn contents are the newly calculated correlation values
+
+    pOverflow = pointer of type Flag * to overflow indicator.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the correlation between the target signal (x) and the
+ impulse response (h).
+
+ The correlation is given by: d[n] = sum_{i=n}^{L-1} x[i] h[i-n],
+ where: n=0,...,L-1
+
+ d[n] is normalized such that the sum of 5 maxima of d[n] corresponding to
+ each position track does not saturate.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cor_h.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void cor_h_x (
+    Word16 h[],    // (i): impulse response of weighted synthesis filter
+    Word16 x[],    // (i): target
+    Word16 dn[],   // (o): correlation between target and h[]
+    Word16 sf      // (i): scaling factor: 2 for 12.2, 1 for others
+)
+{
+    cor_h_x2(h, x, dn, sf, NB_TRACK, STEP);
+}
+
+
+void cor_h_x2 (
+    Word16 h[],    // (i): impulse response of weighted synthesis filter
+    Word16 x[],    // (i): target
+    Word16 dn[],   // (o): correlation between target and h[]
+    Word16 sf,     // (i): scaling factor: 2 for 12.2, 1 for others
+    Word16 nb_track,// (i): the number of ACB tracks
+    Word16 step    // (i): step size from one pulse position to the next
+                           in one track
+)
+{
+    Word16 i, j, k;
+    Word32 s, y32[L_CODE], max, tot;
+
+    // first keep the result on 32 bits and find absolute maximum
+
+    tot = 5;
+
+    for (k = 0; k < nb_track; k++)
+    {
+        max = 0;
+        for (i = k; i < L_CODE; i += step)
+        {
+            s = 0;
+            for (j = i; j < L_CODE; j++)
+                s = L_mac (s, x[j], h[j - i]);
+
+            y32[i] = s;
+
+            s = L_abs (s);
+            if (L_sub (s, max) > (Word32) 0L)
+                max = s;
+        }
+        tot = L_add (tot, L_shr (max, 1));
+    }
+
+    j = sub (norm_l (tot), sf);
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        dn[i] = pv_round (L_shl (y32[i], j));
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cor_h_x(
+    Word16 h[],       /* (i): impulse response of weighted synthesis filter */
+    Word16 x[],       /* (i): target                                        */
+    Word16 dn[],      /* (o): correlation between target and h[]            */
+    Word16 sf,        /* (i): scaling factor: 2 for 12.2, 1 for others      */
+    Flag   *pOverflow /* (o): pointer to overflow flag                      */
+)
+{
+    register Word16 i;
+    register Word16 j;
+    register Word16 k;
+
+    Word32 s;
+    Word32 y32[L_CODE];
+    Word32 max;
+    Word32 tot;
+
+    Word16 *p_x;
+    Word16 *p_ptr;
+    Word32 *p_y32;
+
+
+    tot = 5;
+    for (k = 0; k < NB_TRACK; k++)              /* NB_TRACK = 5 */
+    {
+        max = 0;
+        for (i = k; i < L_CODE; i += STEP)      /* L_CODE = 40; STEP = 5 */
+        {
+            s = 0;
+            p_x = &x[i];
+            p_ptr = h;
+
+            for (j = (L_CODE - i - 1) >> 1; j != 0; j--)
+            {
+                s += ((Word32) * (p_x++) * *(p_ptr++)) << 1;
+                s += ((Word32) * (p_x++) * *(p_ptr++)) << 1;
+            }
+
+            s += ((Word32) * (p_x++) * *(p_ptr++)) << 1;
+
+            if (!((L_CODE - i) & 1))    /* if even number of iterations */
+            {
+                s += ((Word32) * (p_x++) * *(p_ptr++)) << 1;
+            }
+
+            y32[i] = s;
+
+            if (s < 0)
+            {
+                s = -s;
+            }
+
+            if (s > max)
+            {
+                max = s;
+            }
+        }
+
+        tot += (max >> 1);
+    }
+
+
+    j = norm_l(tot) - sf;
+
+    p_ptr = dn;
+    p_y32 = y32;;
+
+    for (i = L_CODE >> 1; i != 0; i--)
+    {
+        s = L_shl(*(p_y32++), j, pOverflow);
+        *(p_ptr++) = (s + 0x00008000) >> 16;
+        s = L_shl(*(p_y32++), j, pOverflow);
+        *(p_ptr++) = (s + 0x00008000) >> 16;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.h b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.h
new file mode 100644
index 0000000..66ada72
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x.h
@@ -0,0 +1,103 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains prototype declaration for cor_h_x function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef COR_H_X_H
+#define COR_H_X_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void cor_h_x(
+        Word16 h[],       /* (i): impulse response of weighted synthesis filter */
+        Word16 x[],       /* (i): target                                        */
+        Word16 dn[],      /* (o): correlation between target and h[]            */
+        Word16 sf,        /* (i): scaling factor: 2 for 12.2, 1 for others      */
+        Flag   *pOverflow /* (o): pointer to overflow flag                      */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp
new file mode 100644
index 0000000..da60640
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.cpp
@@ -0,0 +1,282 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/cor_h_x2.c
+
+     Date: 11/07/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created a separate file for cor_h_x2 function.
+
+ Description: Fixed typecasting issue with TI C compiler and defined one
+              local variable per line. Updated copyright year.
+
+ Description: Added #define for log2(32) = 5.
+
+ Description: Added call to round() and L_shl() functions in the last FOR
+              loop to make code bit-exact.
+
+ Description: Added pOverflow as a variable that's passed in for the EPOC
+              modifications.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Using intrinsics from fxp_arithmetic.h .
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "cor_h_x.h"
+#include "cor_h_x2.h" // BX
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LOG2_OF_32  5
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cor_h_x2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    h = vector containing the impulse response of the weighted synthesis
+        filter; vector contents are of type Word16; vector length is
+        2 * L_SUBFR
+    x = target signal vector; vector contents are of type Word16; vector
+        length is L_SUBFR
+    dn = vector containing the correlation between the target and the
+         impulse response; vector contents are of type Word16; vector
+         length is L_CODE
+    sf = scaling factor of type Word16 ; 2 when mode is MR122, 1 for all
+         other modes
+    nb_track = number of ACB tracks (Word16)
+    step = step size between pulses in one track (Word16)
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    dn contents are the newly calculated correlation values
+    pOverflow = 1 if the math functions called by cor_h_x2 result in overflow
+    else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the correlation between the target signal (x) and the
+ impulse response (h).
+
+ The correlation is given by: d[n] = sum_{i=n}^{L-1} x[i] h[i-n],
+ where: n=0,...,L-1
+
+ d[n] is normalized such that the sum of 5 maxima of d[n] corresponding to
+ each position track does not saturate.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ cor_h.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+The original etsi reference code uses a global flag Overflow. However, in the
+actual implementation a pointer to a the overflow flag is passed in.
+
+void cor_h_x2 (
+    Word16 h[],    // (i): impulse response of weighted synthesis filter
+    Word16 x[],    // (i): target
+    Word16 dn[],   // (o): correlation between target and h[]
+    Word16 sf,     // (i): scaling factor: 2 for 12.2, 1 for others
+    Word16 nb_track,// (i): the number of ACB tracks
+    Word16 step    // (i): step size from one pulse position to the next
+                           in one track
+)
+{
+    Word16 i, j, k;
+    Word32 s, y32[L_CODE], max, tot;
+
+    // first keep the result on 32 bits and find absolute maximum
+
+    tot = 5;
+
+    for (k = 0; k < nb_track; k++)
+    {
+        max = 0;
+        for (i = k; i < L_CODE; i += step)
+        {
+            s = 0;
+            for (j = i; j < L_CODE; j++)
+                s = L_mac (s, x[j], h[j - i]);
+
+            y32[i] = s;
+
+            s = L_abs (s);
+            if (L_sub (s, max) > (Word32) 0L)
+                max = s;
+        }
+        tot = L_add (tot, L_shr (max, 1));
+    }
+
+    j = sub (norm_l (tot), sf);
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        dn[i] = pv_round (L_shl (y32[i], j));
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void cor_h_x2(
+    Word16 h[],    /* (i): impulse response of weighted synthesis filter */
+    Word16 x[],    /* (i): target                                        */
+    Word16 dn[],   /* (o): correlation between target and h[]            */
+    Word16 sf,     /* (i): scaling factor: 2 for 12.2, 1 for others      */
+    Word16 nb_track,/* (i): the number of ACB tracks                     */
+    Word16 step,   /* (i): step size from one pulse position to the next
+                           in one track                                  */
+    Flag *pOverflow
+)
+{
+    register Word16 i;
+    register Word16 j;
+    register Word16 k;
+    Word32 s;
+    Word32 y32[L_CODE];
+    Word32 max;
+    Word32 tot;
+
+
+    /* first keep the result on 32 bits and find absolute maximum */
+    tot = LOG2_OF_32;
+    for (k = 0; k < nb_track; k++)
+    {
+        max = 0;
+        for (i = k; i < L_CODE; i += step)
+        {
+            s = 0;
+
+            for (j = i; j < L_CODE; j++)
+            {
+                s = amrnb_fxp_mac_16_by_16bb((Word32)x[j], (Word32)h[j-i], s);
+            }
+
+            s = s << 1;
+            y32[i] = s;
+            s = L_abs(s);
+
+            if (s > max)
+            {
+                max = s;
+            }
+        }
+        tot = (tot + (max >> 1));
+    }
+
+    j = sub(norm_l(tot), sf, pOverflow);
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        dn[i] = pv_round(L_shl(y32[i], j, pOverflow), pOverflow);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.h b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.h
new file mode 100644
index 0000000..f2b482c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/cor_h_x2.h
@@ -0,0 +1,121 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/include/cor_h_x2.h
+
+     Date: 11/07/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for cor_h_x2.
+
+ Description: Added pOverflow for EPOC modifications
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains prototype declaration for cor_h_x2 function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef COR_H_X2_H
+#define COR_H_X2_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void cor_h_x2(
+        Word16 h[],    /* (i): impulse response of weighted synthesis filter */
+        Word16 x[],    /* (i): target                                        */
+        Word16 dn[],   /* (o): correlation between target and h[]            */
+        Word16 sf,     /* (i): scaling factor: 2 for 12.2, 1 for others      */
+        Word16 nb_track,/* (i): the number of ACB tracks                     */
+        Word16 step,   /* (i): step size from one pulse position to the next
+                           in one track                                  */
+        Flag *pOverflow
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _COR_H_X2_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/corrwght_tab.cpp b/media/libstagefright/codecs/amrnb/enc/src/corrwght_tab.cpp
new file mode 100644
index 0000000..769e7ba
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/corrwght_tab.cpp
@@ -0,0 +1,198 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+
+
+
+
+ Filename: /audio/gsm_amr/c/src/corrwght_tab.c
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the tables for correlation weights
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here. Include conditional
+    ; compile variables also.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; [Variable declaration - defined here and used outside this module]
+    ----------------------------------------------------------------------------*/
+    extern const Word16 corrweight[251] =
+    {
+        20473,  20506,  20539,  20572,  20605,  20644,  20677,
+        20716,  20749,  20788,  20821,  20860,  20893,  20932,
+        20972,  21011,  21050,  21089,  21129,  21168,  21207,
+        21247,  21286,  21332,  21371,  21417,  21456,  21502,
+        21542,  21588,  21633,  21679,  21725,  21771,  21817,
+        21863,  21909,  21961,  22007,  22059,  22105,  22158,
+        22210,  22263,  22315,  22367,  22420,  22472,  22531,
+        22584,  22643,  22702,  22761,  22820,  22879,  22938,
+        23003,  23062,  23128,  23193,  23252,  23324,  23390,
+        23455,  23527,  23600,  23665,  23744,  23816,  23888,
+        23967,  24045,  24124,  24202,  24288,  24366,  24451,
+        24537,  24628,  24714,  24805,  24904,  24995,  25094,
+        25192,  25297,  25395,  25500,  25611,  25723,  25834,
+        25952,  26070,  26188,  26313,  26444,  26575,  26706,
+        26844,  26988,  27132,  27283,  27440,  27597,  27761,
+        27931,  28108,  28285,  28475,  28665,  28869,  29078,
+        29295,  29524,  29760,  30002,  30258,  30527,  30808,
+        31457,  32767,  32767,  32767,  32767,  32767,
+        32767,  32767,  31457,  30808,  30527,  30258,  30002,
+        29760,  29524,  29295,  29078,  28869,  28665,  28475,
+        28285,  28108,  27931,  27761,  27597,  27440,  27283,
+        27132,  26988,  26844,  26706,  26575,  26444,  26313,
+        26188,  26070,  25952,  25834,  25723,  25611,  25500,
+        25395,  25297,  25192,  25094,  24995,  24904,  24805,
+        24714,  24628,  24537,  24451,  24366,  24288,  24202,
+        24124,  24045,  23967,  23888,  23816,  23744,  23665,
+        23600,  23527,  23455,  23390,  23324,  23252,  23193,
+        23128,  23062,  23003,  22938,  22879,  22820,  22761,
+        22702,  22643,  22584,  22531,  22472,  22420,  22367,
+        22315,  22263,  22210,  22158,  22105,  22059,  22007,
+        21961,  21909,  21863,  21817,  21771,  21725,  21679,
+        21633,  21588,  21542,  21502,  21456,  21417,  21371,
+        21332,  21286,  21247,  21207,  21168,  21129,  21089,
+        21050,  21011,  20972,  20932,  20893,  20860,  20821,
+        20788,  20749,  20716,  20677,  20644,  20605,  20572,
+        20539,  20506,  20473,  20434,  20401,  20369,  20336
+    };
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    None
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ None
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] corrwght.tab, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.cpp b/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.cpp
new file mode 100644
index 0000000..276e590
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.cpp
@@ -0,0 +1,1163 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/dtx_enc.c
+ Funtions: dtx_enc_init
+           dtx_enc_reset
+           dtx_enc_exit
+           dtx_enc
+           dtx_buffer
+           tx_dtx_handler
+
+     Date: 06/08/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Updated file per comments gathered from Phase 2/3 review.
+          Synched up with new template (Inputs/Outputs section). Deleted
+          lines leftover from original code prior to the code section of
+          dtx_enc_exit function. Deleted confusing comment in the log_en
+          calculation in dtx_enc function. Restructured IF statement in
+          the calculation of the sum of squares of speech signals in
+          dtx_buffer.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Synchronized file with UTMS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Modified FOR loops to count down.
+              2. Fixed typecasting issue with TI C compiler.
+              3. Fixed comment in dtx_enc pseudo-code.
+              4. Added dtx_enc code comment pertaining to possible assembly
+                 implementation.
+
+ Description: Added calls to add() in tx_dtx_handler. Updated copyright year.
+
+ Description: Pass in pointer to overflow flag to all functions requiring this
+              flag. This is to make the library EPOC compatible.
+
+ Description:  For dtx_enc_reset() only
+              1. Replaced copy() with memcpy.
+              2. Eliminated include file copy.h
+              3. Eliminated printf statement
+              For dtx_buffer()
+              1. Replaced copy() with memcpy.
+              2. Eliminated math operations that unnecessary checked for
+                 saturation, in some cases this by shifting before adding and
+                 in other cases by evaluating the operands
+              3. Unrolled loop to speed up execution
+
+ Description:  For dtx_buffer()
+              1. Modified scaling and added check for saturation. Previous
+                 scaling was correct but altered precision, this cause bit
+                 exactness test failure.
+
+ Description:  For dtx_buffer()
+              1. Modified scaling and saturation checks. Previous
+                 scaling was correct but altered precision, this cause bit
+                 exactness test failure for dtx vad2.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the various functions that perform the computation of the
+ Silence Indicator (SID) parameters when in Discontinuous Transmission (DTX)
+ mode.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+#include <string.h>
+
+#include "dtx_enc.h"
+#include "q_plsf.h"
+#include "typedef.h"
+#include "mode.h"
+#include "basic_op.h"
+#include "log2.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+extern Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow);
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_enc_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to an array of pointers to structures of type
+         dtx_encState
+
+ Outputs:
+    pointer pointed to by st is set to the address of the allocated
+      memory
+
+ Returns:
+    return_value = 0, if initialization was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates the state memory used by the dtx_enc function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_enc_init (dtx_encState **st)
+{
+  dtx_encState* s;
+
+  if (st == (dtx_encState **) NULL){
+    fprintf(stderr, "dtx_enc_init: invalid parameter\n");
+    return -1;
+  }
+
+  *st = NULL;
+
+  // allocate memory
+  if ((s= (dtx_encState *) malloc(sizeof(dtx_encState))) == NULL){
+    fprintf(stderr, "dtx_enc_init: can not malloc state structure\n");
+    return -1;
+  }
+
+  dtx_enc_reset(s);
+  *st = s;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 dtx_enc_init(dtx_encState **st)
+{
+    dtx_encState* s;
+
+    if (st == (dtx_encState **) NULL)
+    {
+        return(-1);
+    }
+
+    *st = NULL;
+
+    /* allocate memory */
+    if ((s = (dtx_encState *) malloc(sizeof(dtx_encState))) == NULL)
+    {
+        return(-1);
+    }
+
+    dtx_enc_reset(s);
+    *st = s;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_enc_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type dtx_encState
+
+ Outputs:
+    structure pointed to by st is initialized to its reset value
+
+ Returns:
+    return_value = 1, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    lsp_init_data = table containing LSP initialization values;
+            table elements are constants of type Word16;
+            table length is M
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the fields of the state memory used by dtx_enc
+ to their reset values.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_enc_reset (dtx_encState *st)
+{
+  Word16 i;
+
+  if (st == (dtx_encState *) NULL){
+    fprintf(stderr, "dtx_enc_reset: invalid parameter\n");
+    return -1;
+  }
+
+  st->hist_ptr = 0;
+  st->log_en_index = 0;
+  st->init_lsf_vq_index = 0;
+  st->lsp_index[0] = 0;
+  st->lsp_index[1] = 0;
+  st->lsp_index[2] = 0;
+
+  // Init lsp_hist[]
+  for(i = 0; i < DTX_HIST_SIZE; i++)
+  {
+    Copy(lsp_init_data, &st->lsp_hist[i * M], M);
+  }
+
+  // Reset energy history
+  Set_zero(st->log_en_hist, M);
+
+  st->dtxHangoverCount = DTX_HANG_CONST;
+  st->decAnaElapsedCount = 32767;
+
+  return 1;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 dtx_enc_reset(dtx_encState *st)
+{
+    Word16 i;
+
+    if (st == (dtx_encState *) NULL)
+    {
+        return(-1);
+    }
+
+    st->hist_ptr = 0;
+    st->log_en_index = 0;
+    st->init_lsf_vq_index = 0;
+    st->lsp_index[0] = 0;
+    st->lsp_index[1] = 0;
+    st->lsp_index[2] = 0;
+
+    /* Init lsp_hist[] */
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        memcpy(&st->lsp_hist[i * M], lsp_init_data, M*sizeof(Word16));
+    }
+
+    /* Reset energy history */
+    memset(st->log_en_hist, 0, sizeof(Word16)*M);
+    st->dtxHangoverCount = DTX_HANG_CONST;
+    st->decAnaElapsedCount = 32767;
+
+    return(1);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_enc_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to an array of pointers to structures of type
+         dtx_encState
+
+ Outputs:
+    st points to the NULL address
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function deallocates the state memory used by dtx_enc function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void dtx_enc_exit (dtx_encState **st)
+{
+   if (st == NULL || *st == NULL)
+      return;
+
+   // deallocate memory
+   free(*st);
+   *st = NULL;
+
+   return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void dtx_enc_exit(dtx_encState **st)
+{
+    if (st == NULL || *st == NULL)
+    {
+        return;
+    }
+
+    /* deallocate memory */
+    free(*st);
+    *st = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_enc
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type dtx_encState
+    computeSidFlag = compute SID flag of type Word16
+    qSt = pointer to structures of type Q_plsfState
+    predState = pointer to structures of type gc_predState
+    anap = pointer to an array of pointers to analysis parameters of
+           type Word16
+
+ Outputs:
+    structure pointed to by st contains the newly calculated SID
+      parameters
+    structure pointed to by predState contains the new logarithmic frame
+      energy
+    pointer pointed to by anap points to the location of the new
+      logarithmic frame energy and new LSPs
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the SID parameters when in the DTX mode.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_enc(dtx_encState *st,        // i/o : State struct
+            Word16 computeSidFlag,   // i   : compute SID
+            Q_plsfState *qSt,        // i/o : Qunatizer state struct
+            gc_predState* predState, // i/o : State struct
+        Word16 **anap            // o   : analysis parameters
+        )
+{
+   Word16 i,j;
+   Word16 log_en;
+   Word16 lsf[M];
+   Word16 lsp[M];
+   Word16 lsp_q[M];
+   Word32 L_lsp[M];
+
+   // VOX mode computation of SID parameters
+   if ((computeSidFlag != 0)  ||
+        (st->log_en_index == 0))
+   {
+      // compute new SID frame if safe i.e don't
+      // compute immediately after a talk spurt
+      log_en = 0;
+      for (i = 0; i < M; i++)
+      {
+         L_lsp[i] = 0;
+      }
+
+      // average energy and lsp
+      for (i = 0; i < DTX_HIST_SIZE; i++)
+      {
+         log_en = add(log_en,
+                      shr(st->log_en_hist[i],2));
+
+         for (j = 0; j < M; j++)
+         {
+            L_lsp[j] = L_add(L_lsp[j],
+                             L_deposit_l(st->lsp_hist[i * M + j]));
+         }
+      }
+
+      log_en = shr(log_en, 1);
+      for (j = 0; j < M; j++)
+      {
+         lsp[j] = extract_l(L_shr(L_lsp[j], 3));   // divide by 8
+      }
+
+      //  quantize logarithmic energy to 6 bits
+      st->log_en_index = add(log_en, 2560);          // +2.5 in Q10
+      st->log_en_index = add(st->log_en_index, 128); // add 0.5/4 in Q10
+      st->log_en_index = shr(st->log_en_index, 8);
+
+      if (sub(st->log_en_index, 63) > 0)
+      {
+         st->log_en_index = 63;
+      }
+      if (st->log_en_index < 0)
+      {
+         st->log_en_index = 0;
+      }
+
+      // update gain predictor memory
+      log_en = shl(st->log_en_index, -2+10); // Q11 and divide by 4
+      log_en = sub(log_en, 2560);            // add 2.5 in Q11
+
+      log_en = sub(log_en, 9000);
+      if (log_en > 0)
+      {
+         log_en = 0;
+      }
+      if (sub(log_en, -14436) < 0)
+      {
+         log_en = -14436;
+      }
+
+      // past_qua_en for other modes than MR122
+      predState->past_qua_en[0] = log_en;
+      predState->past_qua_en[1] = log_en;
+      predState->past_qua_en[2] = log_en;
+      predState->past_qua_en[3] = log_en;
+
+      // scale down by factor 20*log10(2) in Q15
+      log_en = mult(5443, log_en);
+
+      // past_qua_en for mode MR122
+      predState->past_qua_en_MR122[0] = log_en;
+      predState->past_qua_en_MR122[1] = log_en;
+      predState->past_qua_en_MR122[2] = log_en;
+      predState->past_qua_en_MR122[3] = log_en;
+
+      // make sure that LSP's are ordered
+      Lsp_lsf(lsp, lsf, M);
+      Reorder_lsf(lsf, LSF_GAP, M);
+      Lsf_lsp(lsf, lsp, M);
+
+      // Quantize lsp and put on parameter list
+      Q_plsf_3(qSt, MRDTX, lsp, lsp_q, st->lsp_index,
+               &st->init_lsf_vq_index);
+   }
+
+   *(*anap)++ = st->init_lsf_vq_index; // 3 bits
+
+   *(*anap)++ = st->lsp_index[0];      // 8 bits
+   *(*anap)++ = st->lsp_index[1];      // 9 bits
+   *(*anap)++ = st->lsp_index[2];      // 9 bits
+
+
+   *(*anap)++ = st->log_en_index;      // 6 bits
+                                       // = 35 bits
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void dtx_enc(dtx_encState *st,        /* i/o : State struct                  */
+             Word16 computeSidFlag,   /* i   : compute SID                   */
+             Q_plsfState *qSt,        /* i/o : Qunatizer state struct        */
+             gc_predState* predState, /* i/o : State struct                  */
+             Word16 **anap,           /* o   : analysis parameters           */
+             Flag   *pOverflow        /* i/o : overflow indicator            */
+            )
+{
+    register Word16 i, j;
+    Word16 temp;
+    Word16 log_en;
+    Word16 lsf[M];
+    Word16 lsp[M];
+    Word16 lsp_q[M];
+    Word32 L_lsp[M];
+
+    /* VOX mode computation of SID parameters */
+
+    if ((computeSidFlag != 0)  ||
+            (st->log_en_index == 0))
+    {
+        /* compute new SID frame if safe i.e don't
+         * compute immediately after a talk spurt  */
+        log_en = 0;
+        for (i = M - 1; i >= 0; i--)
+        {
+            L_lsp[i] = 0;
+        }
+
+        /* average energy and lsp */
+        for (i = DTX_HIST_SIZE - 1; i >= 0; i--)
+        {
+            if (st->log_en_hist[i] < 0)
+            {
+                temp = ~((~(st->log_en_hist[i])) >> 2);
+            }
+            else
+            {
+                temp = st->log_en_hist[i] >> 2;
+            }
+            log_en = add(log_en, temp, pOverflow);
+
+            for (j = M - 1; j >= 0; j--)
+            {
+                L_lsp[j] = L_add(L_lsp[j],
+                                 (Word32)(st->lsp_hist[i * M + j]),
+                                 pOverflow);
+            }
+        }
+
+        if (log_en < 0)
+        {
+            log_en = ~((~log_en) >> 1);
+        }
+        else
+        {
+            log_en = log_en >> 1;
+        }
+
+        for (j = M - 1; j >= 0; j--)
+        {
+            /* divide by 8 */
+            if (L_lsp[j] < 0)
+            {
+                lsp[j] = (Word16)(~((~L_lsp[j]) >> 3));
+            }
+            else
+            {
+                lsp[j] = (Word16)(L_lsp[j] >> 3);
+            }
+        }
+
+        /*  quantize logarithmic energy to 6 bits */
+        /* +2.5 in Q10 */
+        st->log_en_index = add(log_en, 2560, pOverflow);
+        /* add 0.5/4 in Q10 */
+        st->log_en_index = add(st->log_en_index, 128, pOverflow);
+        if (st->log_en_index < 0)
+        {
+            st->log_en_index = ~((~st->log_en_index) >> 8);
+        }
+        else
+        {
+            st->log_en_index = st->log_en_index >> 8;
+        }
+
+        /*---------------------------------------------*/
+        /* Limit to max and min allowable 6-bit values */
+        /* Note: For assembly implementation, use the  */
+        /*       following:                            */
+        /*       if(st->long_en_index >> 6 != 0)       */
+        /*       {                                     */
+        /*           if(st->long_en_index < 0)         */
+        /*           {                                 */
+        /*               st->long_en_index = 0         */
+        /*           }                                 */
+        /*           else                              */
+        /*           {                                 */
+        /*               st->long_en_index = 63        */
+        /*           }                                 */
+        /*       }                                     */
+        /*---------------------------------------------*/
+        if (st->log_en_index > 63)
+        {
+            st->log_en_index = 63;
+        }
+        else if (st->log_en_index < 0)
+        {
+            st->log_en_index = 0;
+        }
+
+        /* update gain predictor memory */
+        /* Q11 and divide by 4 */
+        log_en = (Word16)(((Word32) st->log_en_index) << (-2 + 10));
+
+        log_en = sub(log_en, 11560, pOverflow);
+
+        if (log_en > 0)
+        {
+            log_en = 0;
+        }
+        else if (log_en < -14436)
+        {
+            log_en = -14436;
+        }
+
+        /* past_qua_en for other modes than MR122 */
+        predState->past_qua_en[0] = log_en;
+        predState->past_qua_en[1] = log_en;
+        predState->past_qua_en[2] = log_en;
+        predState->past_qua_en[3] = log_en;
+
+        /* scale down by factor 20*log10(2) in Q15 */
+        log_en = (Word16)(((Word32)(5443 * log_en)) >> 15);
+
+        /* past_qua_en for mode MR122 */
+        predState->past_qua_en_MR122[0] = log_en;
+        predState->past_qua_en_MR122[1] = log_en;
+        predState->past_qua_en_MR122[2] = log_en;
+        predState->past_qua_en_MR122[3] = log_en;
+
+        /* make sure that LSP's are ordered */
+        Lsp_lsf(lsp, lsf, M, pOverflow);
+        Reorder_lsf(lsf, LSF_GAP, M, pOverflow);
+        Lsf_lsp(lsf, lsp, M, pOverflow);
+
+        /* Quantize lsp and put on parameter list */
+        Q_plsf_3(qSt, MRDTX, lsp, lsp_q, st->lsp_index,
+                 &st->init_lsf_vq_index, pOverflow);
+    }
+
+    *(*anap)++ = st->init_lsf_vq_index; /* 3 bits */
+    *(*anap)++ = st->lsp_index[0];      /* 8 bits */
+    *(*anap)++ = st->lsp_index[1];      /* 9 bits */
+    *(*anap)++ = st->lsp_index[2];      /* 9 bits */
+    *(*anap)++ = st->log_en_index;      /* 6 bits    */
+    /* = 35 bits */
+
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_buffer
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type dtx_encState
+    lsp_new = LSP vector whose elements are of type Word16; vector
+          length is M
+    speech = vector of speech samples of type Word16; vector length is
+         BFR_SIZE_GSM
+
+ Outputs:
+    structure pointed to by st contains the new LSPs and logarithmic
+      frame energy
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function handles the DTX buffer.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_buffer(dtx_encState *st,   // i/o : State struct
+               Word16 lsp_new[],   // i   : LSP vector
+               Word16 speech[]     // i   : speech samples
+)
+{
+   Word16 i;
+   Word32 L_frame_en;
+   Word16 log_en_e;
+   Word16 log_en_m;
+   Word16 log_en;
+
+   // update pointer to circular buffer
+   st->hist_ptr = add(st->hist_ptr, 1);
+   if (sub(st->hist_ptr, DTX_HIST_SIZE) == 0)
+   {
+      st->hist_ptr = 0;
+   }
+
+   // copy lsp vector into buffer
+   Copy(lsp_new, &st->lsp_hist[st->hist_ptr * M], M);
+
+   // compute log energy based on frame energy
+   L_frame_en = 0;     // Q0
+   for (i=0; i < L_FRAME; i++)
+   {
+      L_frame_en = L_mac(L_frame_en, speech[i], speech[i]);
+   }
+   Log2(L_frame_en, &log_en_e, &log_en_m);
+
+   // convert exponent and mantissa to Word16 Q10
+   log_en = shl(log_en_e, 10);  // Q10
+   log_en = add(log_en, shr(log_en_m, 15-10));
+
+   // divide with L_FRAME i.e subtract with log2(L_FRAME) = 7.32193
+   log_en = sub(log_en, 8521);
+
+   // insert into log energy buffer with division by 2
+   log_en = shr(log_en, 1);
+   st->log_en_hist[st->hist_ptr] = log_en; // Q10
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void dtx_buffer(dtx_encState *st,   /* i/o : State struct                    */
+                Word16 lsp_new[],   /* i   : LSP vector                      */
+                Word16 speech[],    /* i   : speech samples                  */
+                Flag   *pOverflow   /* i/o : overflow indicator              */
+               )
+{
+
+    register Word16 i;
+    Word32 L_frame_en;
+    Word32 L_temp;
+    Word16 log_en_e;
+    Word16 log_en_m;
+    Word16 log_en;
+    Word16 *p_speech = &speech[0];
+
+    /* update pointer to circular buffer      */
+    st->hist_ptr += 1;
+
+    if (st->hist_ptr == DTX_HIST_SIZE)
+    {
+        st->hist_ptr = 0;
+    }
+
+    /* copy lsp vector into buffer */
+    memcpy(&st->lsp_hist[st->hist_ptr * M], lsp_new, M*sizeof(Word16));
+
+    /* compute log energy based on frame energy */
+    L_frame_en = 0;     /* Q0 */
+
+    for (i = L_FRAME; i != 0; i--)
+    {
+        L_frame_en += (((Word32) * p_speech) * *(p_speech)) << 1;
+        p_speech++;
+        if (L_frame_en < 0)
+        {
+            L_frame_en = MAX_32;
+            break;
+        }
+    }
+
+    Log2(L_frame_en, &log_en_e, &log_en_m, pOverflow);
+
+    /* convert exponent and mantissa to Word16 Q10 */
+    /* Q10 */
+    L_temp = ((Word32) log_en_e) << 10;
+    if (L_temp != (Word32)((Word16) L_temp))
+    {
+        *pOverflow = 1;
+        log_en = (log_en_e > 0) ? MAX_16 : MIN_16;
+    }
+    else
+    {
+        log_en = (Word16) L_temp;
+    }
+
+    log_en += log_en_m >> (15 - 10);
+
+    /* divide with L_FRAME i.e subtract with log2(L_FRAME) = 7.32193 */
+    log_en -= 8521;
+
+    /* insert into log energy buffer with division by 2 */
+
+    st->log_en_hist[st->hist_ptr] = log_en >> 1; /* Q10 */
+
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: tx_dtx_handler
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type dtx_encState
+    vad_flag = VAD decision flag of type Word16
+    usedMode = pointer to the currently used mode of type enum Mode
+
+ Outputs:
+    structure pointed to by st contains the newly calculated speech
+      hangover
+
+ Returns:
+    compute_new_sid_possible = flag to indicate a change in the
+                   used mode; store type is Word16
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function adds extra speech hangover to analyze speech on the decoding
+ side.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 tx_dtx_handler(dtx_encState *st,      // i/o : State struct
+                      Word16 vad_flag,       // i   : vad decision
+                      enum Mode *usedMode    // i/o : mode changed or not
+                      )
+{
+   Word16 compute_new_sid_possible;
+
+   // this state machine is in synch with the GSMEFR txDtx machine
+   st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);
+
+   compute_new_sid_possible = 0;
+
+   if (vad_flag != 0)
+   {
+      st->dtxHangoverCount = DTX_HANG_CONST;
+   }
+   else
+   {  // non-speech
+      if (st->dtxHangoverCount == 0)
+      {  // out of decoder analysis hangover
+         st->decAnaElapsedCount = 0;
+         *usedMode = MRDTX;
+         compute_new_sid_possible = 1;
+      }
+      else
+      { // in possible analysis hangover
+         st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);
+
+         // decAnaElapsedCount + dtxHangoverCount < DTX_ELAPSED_FRAMES_THRESH
+         if (sub(add(st->decAnaElapsedCount, st->dtxHangoverCount),
+                 DTX_ELAPSED_FRAMES_THRESH) < 0)
+         {
+            *usedMode = MRDTX;
+            // if short time since decoder update, do not add extra HO
+         }
+         // else
+         //   override VAD and stay in
+         //   speech mode *usedMode
+         //   and add extra hangover
+      }
+   }
+
+   return compute_new_sid_possible;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 tx_dtx_handler(dtx_encState *st,      /* i/o : State struct           */
+                      Word16 vad_flag,       /* i   : vad decision           */
+                      enum Mode *usedMode,   /* i/o : mode changed or not    */
+                      Flag   *pOverflow      /* i/o : overflow indicator     */
+                     )
+{
+    Word16 compute_new_sid_possible;
+    Word16 count;
+
+    /* this state machine is in synch with the GSMEFR txDtx machine */
+    st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1, pOverflow);
+
+    compute_new_sid_possible = 0;
+
+    if (vad_flag != 0)
+    {
+        st->dtxHangoverCount = DTX_HANG_CONST;
+    }
+    else
+    {  /* non-speech */
+        if (st->dtxHangoverCount == 0)
+        {  /* out of decoder analysis hangover  */
+            st->decAnaElapsedCount = 0;
+            *usedMode = MRDTX;
+            compute_new_sid_possible = 1;
+        }
+        else
+        { /* in possible analysis hangover */
+            st->dtxHangoverCount -= 1;
+
+            /* decAnaElapsedCount + dtxHangoverCount < */
+            /* DTX_ELAPSED_FRAMES_THRESH               */
+            count = add(st->decAnaElapsedCount, st->dtxHangoverCount,
+                        pOverflow);
+            if (count < DTX_ELAPSED_FRAMES_THRESH)
+            {
+                *usedMode = MRDTX;
+                /* if short time since decoder update, */
+                /* do not add extra HO                 */
+            }
+        }
+    }
+
+    return(compute_new_sid_possible);
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.h b/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.h
new file mode 100644
index 0000000..5bb168d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/dtx_enc.h
@@ -0,0 +1,209 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/dtx_enc.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : dtx_enc.h
+      Purpose          : DTX mode computation of SID parameters
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef dtx_enc_h
+#define dtx_enc_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "q_plsf.h"
+#include "gc_pred.h"
+#include "mode.h"
+#include "dtx_common_def.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+    extern const Word16 lsp_init_data[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 lsp_hist[M * DTX_HIST_SIZE];
+        Word16 log_en_hist[DTX_HIST_SIZE];
+        Word16 hist_ptr;
+        Word16 log_en_index;
+        Word16 init_lsf_vq_index;
+        Word16 lsp_index[3];
+
+        /* DTX handler stuff */
+        Word16 dtxHangoverCount;
+        Word16 decAnaElapsedCount;
+
+    } dtx_encState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+    **************************************************************************
+    *  Function    : dtx_enc_init
+    *  Purpose     : Allocates memory and initializes state variables
+    *  Description : Stores pointer to filter status struct in *st. This
+    *                pointer has to be passed to dtx_enc in each call.
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 dtx_enc_init(dtx_encState **st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : dtx_enc_reset
+    *  Purpose     : Resets state memory
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 dtx_enc_reset(dtx_encState *st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : dtx_enc_exit
+    *  Purpose     : The memory used for state memory is freed
+    *  Description : Stores NULL in *st
+    *
+    **************************************************************************
+    */
+    void dtx_enc_exit(dtx_encState **st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : dtx_enc
+    *  Purpose     :
+    *  Description :
+    *
+    **************************************************************************
+    */
+    void dtx_enc(dtx_encState *st,        /* i/o : State struct                  */
+                 Word16 computeSidFlag,   /* i   : compute SID                   */
+                 Q_plsfState *qSt,        /* i/o : Qunatizer state struct        */
+                 gc_predState* predState, /* i/o : State struct                  */
+                 Word16 **anap,           /* o   : analysis parameters           */
+                 Flag   *pOverflow        /* i/o : overflow indicator            */
+                );
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : dtx_buffer
+    *  Purpose     : handles the DTX buffer
+    *
+    **************************************************************************
+    */
+    void dtx_buffer(dtx_encState *st,   /* i/o : State struct                    */
+                    Word16 lsp_new[],   /* i   : LSP vector                      */
+                    Word16 speech[],    /* i   : speech samples                  */
+                    Flag   *pOverflow   /* i/o : overflow indicator              */
+                   );
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : tx_dtx_handler
+    *  Purpose     : adds extra speech hangover to analyze speech on the decoding side.
+    *  Description : returns 1 when a new SID analysis may be made
+    *                otherwise it adds the appropriate hangover after a sequence
+    *                with out updates of SID parameters .
+    *
+    **************************************************************************
+    */
+    Word16 tx_dtx_handler(dtx_encState *st,      /* i/o : State struct           */
+                          Word16 vad_flag,       /* i   : vad decision           */
+                          enum Mode *usedMode,   /* i/o : mode changed or not    */
+                          Flag   *pOverflow      /* i/o : overflow indicator     */
+                         );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _dtx_enc_h_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.cpp b/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.cpp
new file mode 100644
index 0000000..a1fc008
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.cpp
@@ -0,0 +1,356 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/enc_lag3.c
+ Functions:
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "enc_lag3.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: enc_lag3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  T0 = Pitch delay of type Word16
+  T0_frac = Fractional pitch delay of type Word16
+  T0_prev = Integer pitch delay of last subframe of type Word16
+  T0_min  = minimum of search range of type Word16
+  T0_max  = maximum of search range of type Word16
+  delta_flag = Flag for 1st (or 3rd) subframe of type Word16
+  flag4   = Flag for encoding with 4 bits of type Word16
+  pOverflow = pointer indicating overflow of type Flag
+
+ Outputs:
+  pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+  None
+
+ Global Variables Used:
+  None
+
+ Local Variables Needed:
+  None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function implements the encoding of fractional pitch lag with
+ 1/3 resolution.
+
+ *   FUNCTION:  Enc_lag3
+ *
+ *   PURPOSE:  Encoding of fractional pitch lag with 1/3 resolution.
+ *
+ *   DESCRIPTION:
+ *                    First and third subframes:
+ *                    --------------------------
+ *   The pitch range is divided as follows:
+ *           19 1/3  to   84 2/3   resolution 1/3
+ *           85      to   143      resolution 1
+ *
+ *   The period is encoded with 8 bits.
+ *   For the range with fractions:
+ *     index = (T-19)*3 + frac - 1;
+ *                         where T=[19..85] and frac=[-1,0,1]
+ *   and for the integer only range
+ *     index = (T - 85) + 197;        where T=[86..143]
+ *
+ *                    Second and fourth subframes:
+ *                    ----------------------------
+ *   For the 2nd and 4th subframes a resolution of 1/3 is always used,
+ *   and the search range is relative to the lag in previous subframe.
+ *   If t0 is the lag in the previous subframe then
+ *   t_min=t0-5   and  t_max=t0+4   and  the range is given by
+ *        t_min - 2/3   to  t_max + 2/3
+ *
+ *   The period in the 2nd (and 4th) subframe is encoded with 5 bits:
+ *     index = (T-(t_min-1))*3 + frac - 1;
+ *                 where T=[t_min-1..t_max+1]
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ enc_lag3.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+   Word16 index, i, tmp_ind, uplag;
+   Word16 tmp_lag;
+
+   if (delta_flag == 0)
+   {  // if 1st or 3rd subframe
+
+      // encode pitch delay (with fraction)
+
+      if (sub (T0, 85) <= 0)
+      {
+         // index = T0*3 - 58 + T0_frac
+         i = add (add (T0, T0), T0);
+         index = add (sub (i, 58), T0_frac);
+      }
+      else
+      {
+         index = add (T0, 112);
+      }
+   }
+   else
+   {   // if second or fourth subframe
+      if (flag4 == 0) {
+
+         // 'normal' encoding: either with 5 or 6 bit resolution
+
+         // index = 3*(T0 - T0_min) + 2 + T0_frac
+         i = sub (T0, T0_min);
+         i = add (add (i, i), i);
+         index = add (add (i, 2), T0_frac);
+      }
+      else {
+
+         // encoding with 4 bit resolution
+
+         tmp_lag = T0_prev;
+
+         if ( sub( sub(tmp_lag, T0_min), 5) > 0)
+            tmp_lag = add (T0_min, 5);
+         if ( sub( sub(T0_max, tmp_lag), 4) > 0)
+            tmp_lag = sub (T0_max, 4);
+
+         uplag = add (add (add (T0, T0), T0), T0_frac);
+
+         i = sub (tmp_lag, 2);
+         tmp_ind = add (add (i, i), i);
+
+         if (sub (tmp_ind, uplag) >= 0) {
+            index = add (sub (T0, tmp_lag), 5);
+         }
+         else {
+
+            i = add (tmp_lag, 1);
+            i = add (add (i, i), i);
+
+            if (sub (i, uplag) > 0) {
+
+                index = add ( sub (uplag, tmp_ind), 3);
+            }
+            else {
+
+               index = add (sub (T0, tmp_lag), 11);
+            }
+         }
+
+      } // end if (encoding with 4 bit resolution)
+   }   // end if (second of fourth subframe)
+
+   return index;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+
+Word16 Enc_lag3(         /* o  : Return index of encoding             */
+    Word16 T0,           /* i  : Pitch delay                          */
+    Word16 T0_frac,      /* i  : Fractional pitch delay               */
+    Word16 T0_prev,      /* i  : Integer pitch delay of last subframe */
+    Word16 T0_min,       /* i  : minimum of search range              */
+    Word16 T0_max,       /* i  : maximum of search range              */
+    Word16 delta_flag,   /* i  : Flag for 1st (or 3rd) subframe       */
+    Word16 flag4,        /* i  : Flag for encoding with 4 bits        */
+    Flag   *pOverflow
+)
+{
+    Word16 index, i, tmp_ind, uplag;
+    Word16 tmp_lag;
+    Word16 temp1;
+    Word16 temp2;
+
+
+
+    if (delta_flag == 0)
+    {  /* if 1st or 3rd subframe */
+
+        /* encode pitch delay (with fraction) */
+        temp1 = sub(T0, 85, pOverflow);
+        if (temp1 <= 0)
+        {
+            /* index = T0*3 - 58 + T0_frac   */
+            temp2 = add(T0, T0, pOverflow);
+            i = add(temp2, T0, pOverflow);
+            temp2 = sub(i, 58, pOverflow);
+            index = add(temp2, T0_frac, pOverflow);
+        }
+        else
+        {
+            index = add(T0, 112, pOverflow);
+        }
+    }
+    else
+    {   /* if second or fourth subframe */
+        if (flag4 == 0)
+        {
+
+            /* 'normal' encoding: either with 5 or 6 bit resolution */
+
+            /* index = 3*(T0 - T0_min) + 2 + T0_frac */
+            i = sub(T0, T0_min, pOverflow);
+            temp2 = add(i, i, pOverflow);
+            i = add(temp2, i, pOverflow);
+            temp2 = add(i, 2, pOverflow);
+            index = add(temp2, T0_frac, pOverflow);
+        }
+        else
+        {
+
+            /* encoding with 4 bit resolution */
+
+            tmp_lag = T0_prev;
+            temp1 = sub(tmp_lag, T0_min, pOverflow);
+            temp2 = sub(temp1, 5, pOverflow);
+            if (temp2 > 0)
+                tmp_lag = add(T0_min, 5, pOverflow);
+            temp1 = sub(T0_max, tmp_lag, pOverflow);
+            temp2 = sub(temp1, 4, pOverflow);
+            if (temp2 > 0)
+                tmp_lag = sub(T0_max, 4, pOverflow);
+
+            temp1 = add(T0, T0, pOverflow);
+            temp2 = add(temp1, T0, pOverflow);
+            uplag = add(temp2, T0_frac, pOverflow);
+
+            i = sub(tmp_lag, 2, pOverflow);
+            temp1 = add(i, i, pOverflow);
+            tmp_ind = add(temp1, i, pOverflow);
+
+            temp1 = sub(tmp_ind, uplag, pOverflow);
+            if (temp1 >= 0)
+            {
+                temp1 = sub(T0, tmp_lag, pOverflow);
+                index = add(temp1, 5, pOverflow);
+            }
+            else
+            {
+
+                i = add(tmp_lag, 1, pOverflow);
+                temp1 = add(i, i, pOverflow);
+                i = add(temp1, i, pOverflow);
+
+                if (sub(i, uplag, pOverflow) > 0)
+                {
+                    temp1 = sub(uplag, tmp_ind, pOverflow);
+                    index = add(temp1, 3, pOverflow);
+                }
+                else
+                {
+                    temp1 = sub(T0, tmp_lag, pOverflow);
+                    index = add(temp1, 11, pOverflow);
+                }
+            }
+
+        } /* end if (encoding with 4 bit resolution) */
+    }   /* end if (second of fourth subframe) */
+
+    return index;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.h b/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.h
new file mode 100644
index 0000000..949cd97
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/enc_lag3.h
@@ -0,0 +1,125 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/enc_lag3.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : enc_lag3.h
+      Purpose          : Encoding of fractional pitch lag with 1/3 resolution.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _ENC_LAG3_H_
+#define _ENC_LAG3_H_
+#define enc_lag3_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 past_gain;
+    } agcState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16
+    Enc_lag3(                /* o  : Return index of encoding     */
+        Word16 T0,           /* i  : Pitch delay                          */
+        Word16 T0_frac,      /* i  : Fractional pitch delay               */
+        Word16 T0_prev,      /* i  : Integer pitch delay of last subframe */
+        Word16 T0_min,       /* i  : minimum of search range              */
+        Word16 T0_max,       /* i  : maximum of search range              */
+        Word16 delta_flag,   /* i  : Flag for 1st (or 3rd) subframe       */
+        Word16 flag4,        /* i  : Flag for encoding with 4 bits        */
+        Flag   *pOverflow
+    );
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _ENC_LAG3_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.cpp b/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.cpp
new file mode 100644
index 0000000..2c7863e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.cpp
@@ -0,0 +1,230 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/enc_lag6.c
+ Functions:
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:
+ (1) Removed optimization -- mult(i, 6, pOverflow) is NOT the same as adding
+     i to itself 6 times.  The reason is because the mult function does a
+     right shift by 15, which will obliterate smaller numbers.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "enc_lag6.h"
+#include "typedef.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Enc_lag6
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    T0 -- Word16 -- Pitch delay
+    T0_frac -- Word16 -- Fractional pitch delay
+    T0_min -- Word16 -- minimum of search range
+    delta_flag -- Word16 -- Flag for 1st (or 3rd) subframe
+
+ Outputs:
+    pOverflow -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    Word16 -- Return index of encoding
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Encoding of fractional pitch lag with 1/6 resolution.
+
+ DESCRIPTION:
+                  First and third subframes:
+                  --------------------------
+ The pitch range is divided as follows:
+         17 3/6  to   94 3/6   resolution 1/6
+         95      to   143      resolution 1
+
+ The period is encoded with 9 bits.
+ For the range with fractions:
+   index = (T-17)*6 + frac - 3;
+                       where T=[17..94] and frac=[-2,-1,0,1,2,3]
+ and for the integer only range
+   index = (T - 95) + 463;        where T=[95..143]
+
+                  Second and fourth subframes:
+                  ----------------------------
+ For the 2nd and 4th subframes a resolution of 1/6 is always used,
+ and the search range is relative to the lag in previous subframe.
+ If t0 is the lag in the previous subframe then
+ t_min=t0-5   and  t_max=t0+4   and  the range is given by
+     (t_min-1) 3/6   to  (t_max) 3/6
+
+ The period in the 2nd (and 4th) subframe is encoded with 6 bits:
+   index = (T-(t_min-1))*6 + frac - 3;
+               where T=[t_min-1..t_max] and frac=[-2,-1,0,1,2,3]
+
+ Note that only 61 values are used. If the decoder receives 61, 62,
+ or 63 as the relative pitch index, it means that a transmission
+ error occurred and the pitch from previous subframe should be used.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ enc_lag6.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Enc_lag6(         /* o : Return index of encoding             */
+    Word16 T0,           /* i : Pitch delay                          */
+    Word16 T0_frac,      /* i : Fractional pitch delay               */
+    Word16 T0_min,       /* i : minimum of search range              */
+    Word16 delta_flag,   /* i : Flag for 1st (or 3rd) subframe       */
+    Flag   *pOverflow    /* o : overflow indicator                   */
+)
+{
+    Word16 index;
+    Word16 i;
+    Word16 temp;
+
+    if (delta_flag == 0)          /* if 1st or 3rd subframe */
+    {
+        /* encode pitch delay (with fraction) */
+        if (T0 <= 94)
+        {
+            /* index = T0*6 - 105 + T0_frac */
+            i = 6 * T0 - 105;
+
+            index = add(i, T0_frac, pOverflow);
+        }
+        else
+        {
+            index = add(T0, 368, pOverflow);
+        }
+
+    }
+    else
+        /* if second or fourth subframe */
+    {
+        /* index = 6*(T0-T0_min) + 3 + T0_frac  */
+        temp = sub(T0, T0_min, pOverflow);
+
+        i = add(temp, temp, pOverflow);
+        i = add(temp, i, pOverflow);
+        i = add(i, i, pOverflow);
+
+        i = add(i, 3, pOverflow);
+
+        index = add(i, T0_frac, pOverflow);
+    }
+
+    return index;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.h b/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.h
new file mode 100644
index 0000000..0438321
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/enc_lag6.h
@@ -0,0 +1,122 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/enc_lag6.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, enc_lag6.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef enc_lag6_h
+#define enc_lag6_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 Enc_lag6(         /* o  : Return index of encoding             */
+        Word16 T0,           /* i  : Pitch delay                          */
+        Word16 T0_frac,      /* i  : Fractional pitch delay               */
+        Word16 T0_min,       /* i  : minimum of search range              */
+        Word16 delta_flag,   /* i  : Flag for 1st (or 3rd) subframe       */
+        Flag   *pOverflow    /* o  : Overflow indicator                   */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* enc_lag6_h */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/enc_output_format_tab.cpp b/media/libstagefright/codecs/amrnb/enc/src/enc_output_format_tab.cpp
new file mode 100644
index 0000000..147989f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/enc_output_format_tab.cpp
@@ -0,0 +1,231 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+ Pathname: .audio/gsm-amr/c/src/enc_output_format_tab.c
+
+     Date: 03/08/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved WMFBytesUsed and IF2BytesUsed tables from gsmamr_enc.h.
+              Changed their type definition to 'const int'. Renamed tables to
+              WmfEncBytesPerFrame and If2EncBytesPerFrame.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    None
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This file contains the tables of the number of data bytes per codec mode in
+ both WMF and IF2 output formats.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] AMR Speech Codec Frame Structure, 3GPP TS 26.101 version 4.1.0 Release 4,
+     June 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    /* Number of data bytes in an encoder frame for each codec mode */
+    /* for WMF output format.                                       */
+    /* Each entry is the sum of the 3GPP frame type byte and the    */
+    /* number of packed core AMR data bytes                         */
+    extern const Word16 WmfEncBytesPerFrame[16] =
+    {
+        13, /* 4.75 */
+        14, /* 5.15 */
+        16, /* 5.90 */
+        18, /* 6.70 */
+        20, /* 7.40 */
+        21, /* 7.95 */
+        27, /* 10.2 */
+        32, /* 12.2 */
+        6,  /* GsmAmr comfort noise */
+        7,  /* Gsm-Efr comfort noise */
+        6,  /* IS-641 comfort noise */
+        6,  /* Pdc-Efr comfort noise */
+        0,  /* future use */
+        0,  /* future use */
+        0,  /* future use */
+        1   /* No transmission */
+    };
+
+
+    /* Number of data bytes in an encoder frame for each codec mode */
+    /* for IF2 output format                                        */
+    extern const Word16 If2EncBytesPerFrame[16] =
+    {
+        13, /* 4.75 */
+        14, /* 5.15 */
+        16, /* 5.90 */
+        18, /* 6.70 */
+        19, /* 7.40 */
+        21, /* 7.95 */
+        26, /* 10.2 */
+        31, /* 12.2 */
+        6, /* GsmAmr comfort noise */
+        6, /* Gsm-Efr comfort noise */
+        6, /* IS-641 comfort noise */
+        6, /* Pdc-Efr comfort noise */
+        0, /* future use */
+        0, /* future use */
+        0, /* future use */
+        1  /* No transmission */
+    };
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL FUNCTION REFERENCES
+    ; Declare functions defined elsewhere and referenced in this module
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.cpp b/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.cpp
new file mode 100644
index 0000000..01b8627
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.cpp
@@ -0,0 +1,242 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Pathname: ./audio/gsm-amr/c/src/ets_to_if2.c
+ Funtions: ets_to_if2
+
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "frame_type_3gpp.h"
+#include "ets_to_if2.h"
+#include "typedef.h"
+#include "bitreorder_tab.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ets_to_if2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    frame_type_3gpp = decoder speech bit rate (enum Frame_Type_3GPP)
+    ets_input_ptr   = pointer to input encoded speech bits in ETS format (Word16)
+    if2_output_ptr  = pointer to output encoded speech bits in IF2 format (UWord8)
+
+ Outputs:
+    if2_output_ptr  = pointer to encoded speech bits in the IF2 format (UWord8)
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs a transformation on the data buffers. It converts the
+ data format from ETS (European Telecommunication Standard) to IF2. ETS format
+ has the encoded speech bits each separate with only one bit stored in each
+ word. IF2 is the storage format where the frame type is in the first four bits
+ of the first byte. The upper four bits of that byte contain the first four
+ encoded speech bits for the frame. The following bytes contain the rest of
+ the encoded speech bits. The final byte has padded zeros  to make the frame
+ byte aligned.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+AMR Speech Codec Frame Structure", 3GPP TS 26.101 version 4.1.0 Release 4, June 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void ets_to_if2(
+    enum Frame_Type_3GPP frame_type_3gpp,
+    Word16 *ets_input_ptr,
+    UWord8 *if2_output_ptr)
+{
+    Word16  i;
+    Word16  k;
+    Word16  j = 0;
+    Word16 *ptr_temp;
+    Word16  bits_left;
+    UWord8  accum;
+
+    if (frame_type_3gpp < AMR_SID)
+    {
+        if2_output_ptr[j++] = (UWord8)(frame_type_3gpp) |
+                              (ets_input_ptr[reorderBits[frame_type_3gpp][0]] << 4) |
+                              (ets_input_ptr[reorderBits[frame_type_3gpp][1]] << 5) |
+                              (ets_input_ptr[reorderBits[frame_type_3gpp][2]] << 6) |
+                              (ets_input_ptr[reorderBits[frame_type_3gpp][3]] << 7);
+
+        for (i = 4; i < numOfBits[frame_type_3gpp] - 7;)
+        {
+            if2_output_ptr[j]  =
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]];
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 1;
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 2;
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 3;
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 4;
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 5;
+            if2_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 6;
+            if2_output_ptr[j++] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 7;
+        }
+
+        bits_left = 4 + numOfBits[frame_type_3gpp] -
+                    ((4 + numOfBits[frame_type_3gpp]) & 0xFFF8);
+
+        if (bits_left != 0)
+        {
+            if2_output_ptr[j] = 0;
+
+            for (k = 0; k < bits_left; k++)
+            {
+                if2_output_ptr[j] |=
+                    (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << k;
+            }
+        }
+    }
+    else
+    {
+        if (frame_type_3gpp != AMR_NO_DATA)
+        {
+            /* First octet contains 3GPP frame type and */
+            /* first 4 bits of encoded parameters       */
+            if2_output_ptr[j++] = (UWord8)(frame_type_3gpp) |
+                                  (ets_input_ptr[0] << 4) | (ets_input_ptr[1] << 5) |
+                                  (ets_input_ptr[2] << 6) | (ets_input_ptr[3] << 7);
+            ptr_temp = &ets_input_ptr[4];
+
+            bits_left = ((4 + numOfBits[frame_type_3gpp]) & 0xFFF8);
+
+            for (i = (bits_left - 7) >> 3; i > 0; i--)
+            {
+                accum  = (UWord8) * (ptr_temp++);
+                accum |= (UWord8) * (ptr_temp++) << 1;
+                accum |= (UWord8) * (ptr_temp++) << 2;
+                accum |= (UWord8) * (ptr_temp++) << 3;
+                accum |= (UWord8) * (ptr_temp++) << 4;
+                accum |= (UWord8) * (ptr_temp++) << 5;
+                accum |= (UWord8) * (ptr_temp++) << 6;
+                accum |= (UWord8) * (ptr_temp++) << 7;
+
+                if2_output_ptr[j++] = accum;
+            }
+
+            bits_left = 4 + numOfBits[frame_type_3gpp] - bits_left;
+
+            if (bits_left != 0)
+            {
+                if2_output_ptr[j] = 0;
+
+                for (i = 0; i < bits_left; i++)
+                {
+                    if2_output_ptr[j] |= (ptr_temp[i] << i);
+                }
+            }
+        }
+        else
+        {
+            /* When there is no data, LSnibble of first octet */
+            /* is the 3GPP frame type, MSnibble is zeroed out */
+            if2_output_ptr[j++] = (UWord8)(frame_type_3gpp);
+        }
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.h b/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.h
new file mode 100644
index 0000000..d85bcc9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ets_to_if2.h
@@ -0,0 +1,121 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/include/src/ets_to_if2.h
+
+     Date: 01/23/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the ets_to_if2 function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ETS_TO_IF2_H
+#define ETS_TO_IF2_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mode.h"
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void ets_to_if2(enum Frame_Type_3GPP mode,
+    Word16   *ets_input_ptr,
+    UWord8   *if2_output_ptr);
+
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.cpp b/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.cpp
new file mode 100644
index 0000000..9da3fb8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.cpp
@@ -0,0 +1,244 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/ets_to_wmf.c
+ Funtions: ets_to_wmf
+
+     Date: 01/23/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified code as per review comments regarding things such as
+              adding the tables in bitreorder_tab.c to the Global section of
+              the input/output section of the template and removing the #define
+              of 244 since it wasn't needed in this function.
+
+ Description: Fixed the loop that packs the last octet of the WMF output.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "ets_to_wmf.h"
+#include "typedef.h"
+#include "bitreorder_tab.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ets_to_wmf
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    frame_type_3gpp = decoder speech bit rate (enum Frame_Type_3GPP)
+    ets_input_ptr   = pointer to input encoded speech bits in ETS format (Word16)
+    wmf_output_ptr  = pointer to output encoded speech bits in WMF format(UWord8)
+
+ Outputs:
+    wmf_output_ptr  = pointer to encoded speech bits in the WMF format (UWord8)
+
+ Returns:
+    None
+
+ Global Variables Used:
+    numOfBits = table of values that describe the number of bits per frame for
+                each 3GPP frame type mode. The table is type const Word16 and has
+                NUM_MODES elements. This table is located in bitreorder_tab.c.
+    reorderBits = table of pointers that point to tables used to reorder the
+                  encoded speech bits when converting from ETS to WMF or IF2
+                  format. The table is of type const Word16 * and contains
+                  NUM_MODES-1 elements. This table is located in bitreorder_tab.c.
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs a transformation on the data buffers. It converts the
+ data format from ETS (European Telecommunication Standard) to WMF (wireless
+ multimedia forum). ETS format has the encoded speech bits each separate with
+ only one bit stored in each word. WMF is the storage format where the frame
+ type is in the first four bits of the first byte. This first byte has the
+ upper four bits as padded zeroes. The following bytes contain the rest of the
+ encoded speech bits. The final byte has padded zeros to make the frame byte
+ aligned.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void ets_to_wmf(
+    enum Frame_Type_3GPP frame_type_3gpp,
+    Word16 *ets_input_ptr,
+    UWord8 *wmf_output_ptr)
+{
+    Word16  i;
+    Word16  k = 0;
+    Word16  j = 0;
+    Word16 *ptr_temp;
+    Word16  bits_left;
+    UWord8  accum;
+
+    if (frame_type_3gpp < AMR_SID)
+    {
+        wmf_output_ptr[j++] = (UWord8)(frame_type_3gpp) & 0x0f;
+
+        for (i = 0; i < numOfBits[frame_type_3gpp] - 7;)
+        {
+            wmf_output_ptr[j]  =
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 7;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 6;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 5;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 4;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 3;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 2;
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << 1;
+            wmf_output_ptr[j++] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]];
+        }
+
+        bits_left = numOfBits[frame_type_3gpp] -
+                    (numOfBits[frame_type_3gpp] & 0xFFF8);
+
+        wmf_output_ptr[j] = 0;
+
+        for (k = 0; k < bits_left; k++)
+        {
+            wmf_output_ptr[j] |=
+                (UWord8) ets_input_ptr[reorderBits[frame_type_3gpp][i++]] << (7 - k);
+
+        }
+    }
+    else
+    {
+        wmf_output_ptr[j++] = (UWord8)(frame_type_3gpp) & 0x0f;
+
+        ptr_temp = &ets_input_ptr[0];
+
+        for (i = numOfBits[frame_type_3gpp] - 7; i > 0; i -= 8)
+        {
+            accum  = (UWord8) * (ptr_temp++) << 7;
+            accum |= (UWord8) * (ptr_temp++) << 6;
+            accum |= (UWord8) * (ptr_temp++) << 5;
+            accum |= (UWord8) * (ptr_temp++) << 4;
+            accum |= (UWord8) * (ptr_temp++) << 3;
+            accum |= (UWord8) * (ptr_temp++) << 2;
+            accum |= (UWord8) * (ptr_temp++) << 1;
+            accum |= (UWord8) * (ptr_temp++);
+
+            wmf_output_ptr[j++] = accum;
+        }
+
+        bits_left = numOfBits[frame_type_3gpp] -
+                    (numOfBits[frame_type_3gpp] & 0xFFF8);
+
+        wmf_output_ptr[j] = 0;
+
+        for (i = 0; i < bits_left; i++)
+        {
+            wmf_output_ptr[j] |= *(ptr_temp++) << (7 - i);
+        }
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.h b/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.h
new file mode 100644
index 0000000..a018fcf
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ets_to_wmf.h
@@ -0,0 +1,123 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/include/src/ets_to_wmf.h
+
+     Date: 02/22/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Corrected the copyright year.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the ets_to_wmf function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ETS_TO_WMF_H
+#define ETS_TO_WMF_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "frame_type_3gpp.h"
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void ets_to_wmf(enum Frame_Type_3GPP frame_type_3gpp,
+    Word16   *ets_input_ptr,
+    UWord8   *wmf_output_ptr);
+
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_adapt.cpp b/media/libstagefright/codecs/amrnb/enc/src/g_adapt.cpp
new file mode 100644
index 0000000..712a7fd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_adapt.cpp
@@ -0,0 +1,522 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/g_adapt.c
+ Functions:
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "g_adapt.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "cnst.h"
+#include "gmed_n.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LTP_GAIN_THR1 2721 /* 2721 Q13 = 0.3322 ~= 1.0 / (10*log10(2)) */
+#define LTP_GAIN_THR2 5443 /* 5443 Q13 = 0.6644 ~= 2.0 / (10*log10(2)) */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gain_adapt_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to GainAdaptState
+
+ Outputs:
+    st -- double ponter to GainAdaptState
+
+ Returns:
+    -1 if an error occurs during memory initialization
+     0 if OK
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ g_adapt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 gain_adapt_init(GainAdaptState **st)
+{
+    GainAdaptState* s;
+
+    if (st == (GainAdaptState **) NULL)
+    {
+        /* fprintf(stderr, "gain_adapt_init: invalid parameter\n"); */
+        return -1;
+    }
+    *st = NULL;
+
+    /* allocate memory */
+    if ((s = (GainAdaptState *) malloc(sizeof(GainAdaptState))) == NULL)
+    {
+        /* fprintf(stderr, "gain_adapt_init: can't malloc state structure\n"); */
+        return -1;
+    }
+    gain_adapt_reset(s);
+    *st = s;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gain_adapt_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to GainAdaptState
+
+ Outputs:
+    st -- double ponter to GainAdaptState
+
+ Returns:
+    -1 if an error occurs
+     0 if OK
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Initializes state memory to zero
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ g_adapt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 gain_adapt_reset(GainAdaptState *st)
+{
+    Word16 i;
+
+    if (st == (GainAdaptState *) NULL)
+    {
+        /* fprintf(stderr, "gain_adapt_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    st->onset = 0;
+    st->prev_alpha = 0;
+    st->prev_gc = 0;
+
+    for (i = 0; i < LTPG_MEM_SIZE; i++)
+    {
+        st->ltpg_mem[i] = 0;
+    }
+
+    return 0;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gain_adapt_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to GainAdaptState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    The memory used for state memory is freed
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ g_adapt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void gain_adapt_exit(GainAdaptState **st)
+{
+    if (st == NULL || *st == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*st);
+    *st = NULL;
+
+    return;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gain_adapt
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to GainAdaptState
+    ltpg -- Word16 -- ltp coding gain (log2()), Q13
+    gain_cod -- Word16 -- code gain, Q1
+
+ Outputs:
+    alpha -- Pointer to Word16 --  gain adaptation factor,   Q15
+    pOverflow -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose:    calculate pitch/codebook gain adaptation factor alpha
+             (and update the adaptor state)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ g_adapt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void gain_adapt(
+    GainAdaptState *st,  /* i  : state struct                  */
+    Word16 ltpg,         /* i  : ltp coding gain (log2()), Q13 */
+    Word16 gain_cod,     /* i  : code gain,                Q1  */
+    Word16 *alpha,       /* o  : gain adaptation factor,   Q15 */
+    Flag   *pOverflow
+)
+{
+    Word16 adapt;      /* adaptdation status; 0, 1, or 2       */
+    Word16 result;     /* alpha factor, Q13                    */
+    Word16 filt;       /* median-filtered LTP coding gain, Q13 */
+    Word16 tmp;
+    Word16 i;
+
+    /* basic adaptation */
+    if (ltpg <= LTP_GAIN_THR1)
+    {
+        adapt = 0;
+    }
+    else
+    {
+        if (ltpg <= LTP_GAIN_THR2)
+        {
+            adapt = 1;
+        }
+        else
+        {
+            adapt = 2;
+        }
+    }
+
+    /*
+     * // onset indicator
+     * if ((cbGain > onFact * cbGainMem[0]) && (cbGain > 100.0))
+     *     onset = 8;
+     * else
+     *     if (onset)
+     *         onset--;
+     */
+    /* tmp = cbGain / onFact; onFact = 2.0; 200 Q1 = 100.0 */
+    tmp = shr_r(gain_cod, 1, pOverflow);
+
+    if ((tmp > st->prev_gc) && (gain_cod > 200))
+    {
+        st->onset = 8;
+    }
+    else
+    {
+        if (st->onset != 0)
+        {
+            st->onset = sub(st->onset, 1, pOverflow);
+        }
+    }
+
+    /*
+     *  // if onset, increase adaptor state
+     *  if (onset && (gainAdapt < 2)) gainAdapt++;
+     */
+    if ((st->onset != 0) && (adapt < 2))
+    {
+        adapt = add(adapt, 1, pOverflow);
+    }
+
+    st->ltpg_mem[0] = ltpg;
+    filt = gmed_n(st->ltpg_mem, 5);  /* function result */
+
+    if (adapt == 0)
+    {
+        if (filt > 5443) /* 5443 Q13 = 0.66443... */
+        {
+            result = 0;
+        }
+        else
+        {
+            if (filt < 0)
+            {
+                result = 16384;  /* 16384 Q15 = 0.5 */
+            }
+            else
+            {   /* result       =   0.5 - 0.75257499*filt     */
+                /* result (Q15) = 16384 - 24660 * (filt << 2) */
+                filt = shl(filt, 2, pOverflow);  /* Q15 */
+                result = mult(24660, filt, pOverflow);
+                result = sub(16384, result, pOverflow);
+            }
+        }
+    }
+    else
+    {
+        result = 0;
+    }
+    /*
+     *  if (prevAlpha == 0.0) result = 0.5 * (result + prevAlpha);
+     */
+    if (st->prev_alpha == 0)
+    {
+        result = shr(result, 1, pOverflow);
+    }
+
+    /* store the result */
+    *alpha = result;
+
+    /* update adapter state memory */
+    st->prev_alpha = result;
+    st->prev_gc = gain_cod;
+
+    for (i = LTPG_MEM_SIZE - 1; i > 0; i--)
+    {
+        st->ltpg_mem[i] = st->ltpg_mem[i-1];
+    }
+    /* mem[0] is just present for convenience in calling the gmed_n[5]
+     * function above. The memory depth is really LTPG_MEM_SIZE-1.
+     */
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_adapt.h b/media/libstagefright/codecs/amrnb/enc/src/g_adapt.h
new file mode 100644
index 0000000..2ea508b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_adapt.h
@@ -0,0 +1,159 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/g_adapt.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, g_adapt.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef g_adapt_h
+#define g_adapt_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define LTPG_MEM_SIZE 5 /* number of stored past LTP coding gains + 1 */
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 onset;                   /* onset state,                   Q0  */
+        Word16 prev_alpha;              /* previous adaptor output,       Q15 */
+        Word16 prev_gc;                 /* previous code gain,            Q1  */
+
+        Word16 ltpg_mem[LTPG_MEM_SIZE]; /* LTP coding gain history,       Q13 */
+        /* (ltpg_mem[0] not used for history) */
+    } GainAdaptState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 gain_adapt_init(GainAdaptState **st);
+    /* initialize one instance of the gain adaptor
+       Stores pointer to state struct in *st. This pointer has to
+       be passed to gain_adapt and gain_adapt_update in each call.
+       returns 0 on success
+     */
+
+    Word16 gain_adapt_reset(GainAdaptState *st);
+    /* reset of gain adaptor state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void gain_adapt_exit(GainAdaptState **st);
+    /* de-initialize gain adaptor state (i.e. free state struct)
+       stores NULL in *st
+     */
+
+    /*************************************************************************
+     *
+     *  Function:   gain_adapt()
+     *  Purpose:    calculate pitch/codebook gain adaptation factor alpha
+     *              (and update the adaptor state)
+     *
+     **************************************************************************
+     */
+    void gain_adapt(
+        GainAdaptState *st,  /* i  : state struct                  */
+        Word16 ltpg,         /* i  : ltp coding gain (log2()), Q   */
+        Word16 gain_cod,     /* i  : code gain,                Q13 */
+        Word16 *alpha,       /* o  : gain adaptation factor,   Q15 */
+        Flag   *pOverflow    /* o  : overflow indicator            */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_code.cpp b/media/libstagefright/codecs/amrnb/enc/src/g_code.cpp
new file mode 100644
index 0000000..f937cb7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_code.cpp
@@ -0,0 +1,322 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/g_code.c
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: The return of L_mult was being stored in a Word16 before it was
+              being operated on (extract_h). Data loss happened here.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation, in some cases this by shifting before adding and
+                 in other cases by evaluating the operands
+              4. Unrolled loops to speed up processing
+              5. Eliminated calls to shifts left and right functions by adding
+                 if-else statements that do the same faster.
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: 1. Using inlines from fxp_arithmetic.h
+              2. Removing a compiler warning.
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "g_code.h"
+#include    "cnst.h"
+#include    "basic_op.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: G_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xn2[] = target vector (Word16)
+    y2[] = filtered innovation vector
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the innovative gain calculation resulted in overflow
+
+ Returns:
+    gain = Gain of Innovation code (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the innovative codebook gain.
+
+ The innovative codebook gain is given by
+    g = <x[], y[]> / <y[], y[]>
+
+ where x[] is the target vector, y[] is the filtered innovative codevector,
+ and <> denotes dot product.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] g_code.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 G_code (         // out   : Gain of innovation code
+    Word16 xn2[],       // in    : target vector
+    Word16 y2[]         // in    : filtered innovation vector
+)
+{
+    Word16 i;
+    Word16 xy, yy, exp_xy, exp_yy, gain;
+    Word16 scal_y2[L_SUBFR];
+    Word32 s;
+
+// The original ETSI implementation uses a global overflow flag. However in
+// actual implementation a pointer to Overflow flag is passed into the
+// function for access by the low level math functions.
+
+    // Scale down Y[] by 2 to avoid overflow
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        scal_y2[i] = shr (y2[i], 1);
+    }
+
+    // Compute scalar product <X[],Y[]>
+
+    s = 1L; // Avoid case of all zeros
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        s = L_mac (s, xn2[i], scal_y2[i]);
+    }
+    exp_xy = norm_l (s);
+    xy = extract_h (L_shl (s, exp_xy));
+
+    // If (xy < 0) gain = 0
+
+    if (xy <= 0)
+        return ((Word16) 0);
+
+    // Compute scalar product <Y[],Y[]>
+
+    s = 0L;
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        s = L_mac (s, scal_y2[i], scal_y2[i]);
+    }
+    exp_yy = norm_l (s);
+    yy = extract_h (L_shl (s, exp_yy));
+
+    // compute gain = xy/yy
+
+    xy = shr (xy, 1);                 // Be sure xy < yy
+    gain = div_s (xy, yy);
+
+    // Denormalization of division
+    i = add (exp_xy, 5);              // 15-1+9-18 = 5
+    i = sub (i, exp_yy);
+
+    gain = shl (shr (gain, i), 1);    // Q0 -> Q1/
+
+    return (gain);
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+Word16 G_code(          /* o     : Gain of innovation code         */
+    Word16 xn2[],       /* i     : target vector                   */
+    Word16 y2[],        /* i     : filtered innovation vector      */
+    Flag   *pOverflow   /* i/o   : overflow flag                   */
+)
+{
+    Word16 i;
+    Word16 xy, yy, exp_xy, exp_yy, gain;
+    Word32 s;
+
+    Word16 *p_xn2 = xn2;
+    Word16 *p_y2  = y2;
+    Word16 temp;
+    Word32 temp2;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    /* Compute scalar product <X[],Y[]> */
+    s = 0;
+
+    for (i = (L_SUBFR >> 2); i != 0 ; i--)
+    {
+        temp2 = (Word32)(*(p_y2++) >> 1);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn2++), temp2, s);
+        temp2 = (Word32)(*(p_y2++) >> 1);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn2++), temp2, s);
+        temp2 = (Word32)(*(p_y2++) >> 1);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn2++), temp2, s);
+        temp2 = (Word32)(*(p_y2++) >> 1);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn2++), temp2, s);
+    }
+    s <<= 1;
+    exp_xy = norm_l(s + 1); /* Avoid case of all zeros, add 1 */
+
+    if (exp_xy < 17)        /* extra right shift to be sure xy < yy */
+    {
+        xy = (Word16)(s >> (17 - exp_xy));
+    }
+    else
+    {
+        xy = (Word16)(s << (exp_xy - 17));
+    }
+
+    /* If (xy < 0) gain = 0  */
+
+    if (xy <= 0)
+    {
+        return ((Word16) 0);
+    }
+
+    /* Compute scalar product <Y[],Y[]> */
+
+    s = 0L;
+    p_y2  = y2;
+
+    for (i = (L_SUBFR >> 1); i != 0 ; i--)
+    {
+        temp = *(p_y2++) >> 1;
+        s += ((Word32) temp * temp) >> 2;
+        temp = *(p_y2++) >> 1;
+        s += ((Word32) temp * temp) >> 2;
+    }
+    s <<= 3;
+    exp_yy = norm_l(s);
+
+    if (exp_yy < 16)
+    {
+        yy = (Word16)(s >> (16 - exp_yy));
+    }
+    else
+    {
+        yy = (Word16)(s << (exp_yy - 16));
+    }
+
+    gain = div_s(xy, yy);
+
+    /* Denormalization of division */
+    i  = exp_xy + 5;                                /* 15-1+9-18 = 5 */
+    i -= exp_yy;
+
+    // gain = shl (shr (gain, i), 1);    /* Q0 -> Q1 */
+
+    if (i > 1)
+    {
+        gain >>= i - 1;
+    }
+    else
+    {
+        gain <<= 1 - i;
+    }
+
+
+    return (gain);
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_code.h b/media/libstagefright/codecs/amrnb/enc/src/g_code.h
new file mode 100644
index 0000000..c62cba6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_code.h
@@ -0,0 +1,116 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/g_code.h
+
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the G_code() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef G_CODE_H
+#define G_CODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basicop_malloc.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 G_code(          /* o     : Gain of innovation code         */
+        Word16 xn2[],       /* i     : target vector                   */
+        Word16 y2[],        /* i     : filtered innovation vector      */
+        Flag   *pOverflow   /* i/o   : overflow flag                   */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _G_CODE_H */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_pitch.cpp b/media/libstagefright/codecs/amrnb/enc/src/g_pitch.cpp
new file mode 100644
index 0000000..f6235ad
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_pitch.cpp
@@ -0,0 +1,464 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/g_pitch.c
+
+     Date: 06/12/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Placed into template and began to optimize.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h and oper_32b.h with the header files of the
+              math functions used in the file. Fixed typecasting issue with
+              TI compiler.
+
+ Description: Passing in pointer to overflow flag for EPOC compatibility. .
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation, in some cases this by shifting before adding and
+                 in other cases by evaluating the operands
+              4. Unrolled loops to speed up processing
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Using inlines from fxp_arithmetic.h .
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "g_pitch.h"
+#include "mode.h"
+#include "cnst.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: G_pitch
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode = AMR mode (enum Mode)
+    xn = pointer to pitch target buffer (Word16)
+    y1 = pointer to filtered adaptive codebook buffer (Word16)
+    g_coeff  = pointer to buffer of correlations needed for gain quantization
+               (Word16)
+    L_subfr = length of subframe (Word16)
+    pOverflow = pointer to overflow flag (Flag)
+
+ Outputs:
+    g_coeff contains the mantissa and exponent of the two dot products.
+    pOverflow -> 1 if an overflow occurs
+
+ Returns:
+    gain =  ratio of dot products.(Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the pitch (adaptive codebook) gain. The adaptive
+ codebook gain is given by
+
+    g = <x[], y[]> / <y[], y[]>
+
+    where:  x[] is the target vector
+            y[] is the filtered adaptive codevector
+            <> denotes dot product.
+
+ The gain is limited to the range [0,1.2] (=0..19661 Q14)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ g_pitch.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 G_pitch     (    // o : Gain of pitch lag saturated to 1.2
+    enum Mode mode,     // i : AMR mode
+    Word16 xn[],        // i : Pitch target.
+    Word16 y1[],        // i : Filtered adaptive codebook.
+    Word16 g_coeff[],   // i : Correlations need for gain quantization
+    Word16 L_subfr      // i : Length of subframe.
+)
+{
+    Word16 i;
+    Word16 xy, yy, exp_xy, exp_yy, gain;
+    Word32 s;
+
+    Word16 scaled_y1[L_SUBFR];   // Usually dynamic allocation of (L_subfr)
+
+    // divide "y1[]" by 4 to avoid overflow
+
+// The reference ETSI code uses a global overflow Flag. However in the actual
+// implementation a pointer to the overflow flag is passed into the function.
+
+    for (i = 0; i < L_subfr; i++)
+    {
+        scaled_y1[i] = shr (y1[i], 2);
+    }
+
+    // Compute scalar product <y1[],y1[]>
+
+    // Q12 scaling / MR122
+    Overflow = 0;
+    s = 1L; // Avoid case of all zeros
+    for (i = 0; i < L_subfr; i++)
+    {
+        s = L_mac (s, y1[i], y1[i]);
+    }
+    if (Overflow == 0)       // Test for overflow
+    {
+        exp_yy = norm_l (s);
+        yy = pv_round (L_shl (s, exp_yy));
+    }
+    else
+    {
+        s = 1L; // Avoid case of all zeros
+        for (i = 0; i < L_subfr; i++)
+        {
+            s = L_mac (s, scaled_y1[i], scaled_y1[i]);
+        }
+        exp_yy = norm_l (s);
+        yy = pv_round (L_shl (s, exp_yy));
+        exp_yy = sub (exp_yy, 4);
+    }
+
+    // Compute scalar product <xn[],y1[]>
+
+    Overflow = 0;
+    s = 1L; // Avoid case of all zeros
+
+    for (i = 0; i < L_subfr; i++)
+    {
+        s = L_mac(s, xn[i], y1[i]);
+    }
+    if (Overflow == 0)
+    {
+        exp_xy = norm_l (s);
+        xy = pv_round (L_shl (s, exp_xy));
+    }
+    else
+    {
+        s = 1L; // Avoid case of all zeros
+        for (i = 0; i < L_subfr; i++)
+        {
+            s = L_mac (s, xn[i], scaled_y1[i]);
+        }
+        exp_xy = norm_l (s);
+        xy = pv_round (L_shl (s, exp_xy));
+        exp_xy = sub (exp_xy, 2);
+    }
+
+    g_coeff[0] = yy;
+    g_coeff[1] = sub (15, exp_yy);
+    g_coeff[2] = xy;
+    g_coeff[3] = sub (15, exp_xy);
+
+    // If (xy < 4) gain = 0
+
+    i = sub (xy, 4);
+
+    if (i < 0)
+        return ((Word16) 0);
+
+    // compute gain = xy/yy
+
+    xy = shr (xy, 1);                  // Be sure xy < yy
+    gain = div_s (xy, yy);
+
+    i = sub (exp_xy, exp_yy);      // Denormalization of division
+    gain = shr (gain, i);
+
+    // if(gain >1.2) gain = 1.2
+
+    if (sub (gain, 19661) > 0)
+    {
+        gain = 19661;
+    }
+
+    if (sub(mode, MR122) == 0)
+    {
+       // clear 2 LSBits
+       gain = gain & 0xfffC;
+    }
+
+    return (gain);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 G_pitch(         /* o : Gain of pitch lag saturated to 1.2       */
+    enum Mode mode,     /* i : AMR mode                                 */
+    Word16 xn[],        /* i : Pitch target.                            Q0  */
+    Word16 y1[],        /* i : Filtered adaptive codebook.              Q12 */
+    Word16 g_coeff[],   /* i : Correlations need for gain quantization  */
+    Word16 L_subfr,     /* i : Length of subframe.                      */
+    Flag   *pOverflow   /* i/o : Overflow flag                          */
+)
+{
+
+    Word16 i;
+    Word16 xy;
+    Word16 yy;
+    Word16 exp_xy;
+    Word16 exp_yy;
+    Word16 gain;
+    Word16 tmp;
+    Word32 s;
+    Word32 s1;
+    Word32 L_temp;                      /* Use this as an intermediate value */
+    Word16 *p_xn = &xn[0];
+    Word16 *p_y1 = &y1[0];
+
+    /* Compute scalar product <y1[],y1[]> */
+
+    /* Q12 scaling / MR122 */
+    *pOverflow = 0;
+    s = 0;
+
+    for (i = L_subfr >> 2; i != 0; i--)
+    {
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y1), (Word32) * (p_y1), s);
+        p_y1++;
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y1), (Word32) * (p_y1), s);
+        p_y1++;
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y1), (Word32) * (p_y1), s);
+        p_y1++;
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_y1), (Word32) * (p_y1), s);
+        p_y1++;
+    }
+    if ((s >= 0) & (s < 0x40000000))
+    {
+        s <<= 1;
+        s  += 1;            /* Avoid case of all zeros */
+
+        exp_yy = norm_l(s);             /* Note 0<=exp_yy <= 31 */
+        L_temp = s << exp_yy;
+        yy = pv_round(L_temp, pOverflow);
+    }
+    else
+    {
+        s = 0;                      /* Avoid case of all zeros */
+        p_y1 = &y1[0];
+        for (i = (L_subfr >> 1); i != 0; i--)
+        {
+            tmp = *(p_y1++) >> 2;
+            s = amrnb_fxp_mac_16_by_16bb((Word32) tmp, (Word32) tmp, s);
+            tmp = *(p_y1++) >> 2;
+            s = amrnb_fxp_mac_16_by_16bb((Word32) tmp, (Word32) tmp, s);
+        }
+
+        s <<= 1;
+        s  += 1;            /* Avoid case of all zeros */
+
+        exp_yy = norm_l(s);
+        L_temp = s << exp_yy;
+        yy = pv_round(L_temp, pOverflow);
+        exp_yy = exp_yy - 4;
+
+    }
+
+    /* Compute scalar product <xn[],y1[]> */
+
+    s = 0;
+    p_y1 = &y1[0];
+    *pOverflow = 0;
+
+    for (i = L_subfr; i != 0; i--)
+    {
+        L_temp = ((Word32) * (p_xn++) * *(p_y1++));
+        s1 = s;
+        s = s1 + L_temp;
+
+        if ((s1 ^ L_temp) > 0)
+        {
+            if ((s1 ^ s) < 0)
+            {
+                *pOverflow = 1;
+                break;
+            }
+        }
+    }
+
+    if (!(*pOverflow))
+    {
+
+        s <<= 1;
+        s  += 1;            /* Avoid case of all zeros */
+
+        exp_xy = norm_l(s);             /* Note 0<=exp_yy <= 31 */
+        L_temp = s << exp_xy;
+        xy = pv_round(L_temp, pOverflow);
+    }
+    else
+    {
+        s = 0;                      /* Avoid case of all zeros */
+        p_y1 = &y1[0];
+        for (i = (L_subfr >> 2); i != 0; i--)
+        {
+            L_temp = (Word32)(*(p_y1++) >> 2);
+            s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn++), L_temp, s);
+            L_temp = (Word32)(*(p_y1++) >> 2);
+            s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn++), L_temp, s);
+            L_temp = (Word32)(*(p_y1++) >> 2);
+            s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn++), L_temp, s);
+            L_temp = (Word32)(*(p_y1++) >> 2);
+            s = amrnb_fxp_mac_16_by_16bb((Word32) * (p_xn++), L_temp, s);
+        }
+
+        s <<= 1;
+        s  += 1;            /* Avoid case of all zeros */
+
+        exp_xy = norm_l(s);
+        L_temp = s << exp_xy;
+        xy = pv_round(L_temp, pOverflow);
+        exp_xy = exp_xy - 4;
+
+    }
+
+    g_coeff[0] = yy;
+    g_coeff[1] = 15 - exp_yy;
+    g_coeff[2] = xy;
+    g_coeff[3] = 15 - exp_xy;
+
+    /* If (xy < 4) gain = 0 */
+    if (xy < 4)
+    {
+        return ((Word16) 0);
+    }
+
+    /* compute gain = xy/yy */
+    /* Be sure xy < yy */
+
+    xy = xy >> 1;
+
+    gain = div_s(xy, yy);
+
+    i = exp_xy - exp_yy;               /* Denormalization of division */
+
+    gain = shr(gain, i, pOverflow);
+
+
+    /* if(gain >1.2) gain = 1.2 */
+    if (gain > 19661)
+    {
+        gain = 19661;
+    }
+
+    if (mode == MR122)
+    {
+        /* clear 2 LSBits */
+        gain = gain & 0xfffC;
+    }
+
+    return(gain);
+
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/g_pitch.h b/media/libstagefright/codecs/amrnb/enc/src/g_pitch.h
new file mode 100644
index 0000000..6ea06ea
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/g_pitch.h
@@ -0,0 +1,119 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/g_pitch.h
+
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the G_pitch() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef G_PITCH_H
+#define G_PITCH_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mode.h"
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 G_pitch(         /* o : Gain of pitch lag saturated to 1.2       */
+        enum Mode mode,     /* i : AMR mode                                 */
+        Word16 xn[],        /* i : Pitch target.                            */
+        Word16 y1[],        /* i : Filtered adaptive codebook.              */
+        Word16 g_coeff[],   /* i : Correlations need for gain quantization  */
+        Word16 L_subfr,     /* i : Length of subframe.                      */
+        Flag   *pOverflow   /* i/o : Overflow flag                          */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _G_PITCH_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gain_q.cpp b/media/libstagefright/codecs/amrnb/enc/src/gain_q.cpp
new file mode 100644
index 0000000..e44e4bc
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/gain_q.cpp
@@ -0,0 +1,747 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/gain_q.c
+ Functions:
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Removed everything associated with gc_pred_init
+ and gc_pred_exit.  gc_pred_exit was simply removed -- gc_pred_init
+ was replaced with calls to gc_pred_reset.  This is because the gc_pred
+ related structures are no longer dynamically allocated via malloc.
+
+ Description:  For gainQuant()
+              1. Replaced gc_pred_copy() with memcpy.
+              2. Eliminated unused include file gc_pred.h.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Quantazation of gains
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+#include <string.h>
+
+#include "gain_q.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "qua_gain.h"
+#include "cnst.h"
+#include "mode.h"
+#include "g_code.h"
+#include "q_gain_c.h"
+#include "calc_en.h"
+#include "qgain795.h"
+#include "qgain475.h"
+#include "set_zero.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NPRED 4  /* number of prediction taps */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gainQuant_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to gainQuantState
+
+ Outputs:
+    st -- double ponter to gainQuantState
+
+ Returns:
+    -1 if an error occurs during memory initialization
+     0 if OK
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gain_q.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 gainQuant_init(gainQuantState **state)
+{
+    gainQuantState* s;
+
+    if (state == (gainQuantState **) NULL)
+    {
+        /* fprintf(stderr, "gainQuant_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (gainQuantState *) malloc(sizeof(gainQuantState))) == NULL)
+    {
+        /* fprintf(stderr, "gainQuant_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    s->gain_idx_ptr = NULL;
+
+    s->adaptSt = NULL;
+
+    /* Init sub states */
+    if (gc_pred_reset(&s->gc_predSt)
+            || gc_pred_reset(&s->gc_predUnqSt)
+            || gain_adapt_init(&s->adaptSt))
+    {
+        gainQuant_exit(&s);
+        return -1;
+    }
+
+    gainQuant_reset(s);
+    *state = s;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gainQuant_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to gainQuantState
+
+ Outputs:
+    st -- double ponter to gainQuantState
+
+ Returns:
+    -1 if an error occurs
+     0 if OK
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Initializes state memory to zero
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gain_q.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 gainQuant_reset(gainQuantState *state)
+{
+
+    if (state == (gainQuantState *) NULL)
+    {
+        /* fprintf(stderr, "gainQuant_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    state->sf0_exp_gcode0 = 0;
+    state->sf0_frac_gcode0 = 0;
+    state->sf0_exp_target_en = 0;
+    state->sf0_frac_target_en = 0;
+
+    Set_zero(state->sf0_exp_coeff, 5);
+    Set_zero(state->sf0_frac_coeff, 5);
+    state->gain_idx_ptr = NULL;
+
+    gc_pred_reset(&(state->gc_predSt));
+    gc_pred_reset(&(state->gc_predUnqSt));
+    gain_adapt_reset(state->adaptSt);
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gainQuant_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to gainQuantState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    The memory used for state memory is freed
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gain_q.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void gainQuant_exit(gainQuantState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    gain_adapt_exit(&(*state)->adaptSt);
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gainQuant
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st   -- pointer to gainQuantState
+    mode -- enum Mode -- coder mode
+    res  -- Word16 array -- LP residual,                 Q0
+    exc  -- Word16 array -- LTP excitation (unfiltered), Q0
+    code -- Word16 array -- CB innovation (unfiltered),  Q13
+                            (unsharpened for MR475)
+    xn  -- Word16 array -- Target vector.
+    xn2 -- Word16 array -- Target vector.
+    y1  -- Word16 array -- Adaptive codebook.
+    Y2  -- Word16 array -- Filtered innovative vector.
+    g_coeff -- Word16 array -- Correlations <xn y1> <y1 y1>
+                               Compute in G_pitch().
+
+    even_subframe -- Word16 -- even subframe indicator flag
+    gp_limit -- Word16 -- pitch gain limit
+    gain_pit -- Word16 Pointer -- Pitch gain.
+
+ Outputs:
+    st -- pointer to gainQuantState
+    sf0_gain_pit -- Word16 Pointer -- Pitch gain sf 0.   MR475
+    sf0_gain_cod -- Word16 Pointer -- Code gain sf 0.    MR475
+    gain_pit -- Word16 Pointer -- Pitch gain.
+    gain_cod -- Word16 Pointer -- Code gain.
+                                  MR475: gain_* unquantized in even
+                                  subframes, quantized otherwise
+
+    anap -- Word16 Double Pointer -- Index of quantization
+
+    pOverflow -- Flag Pointer -- overflow indicator
+
+ Returns:
+    Zero
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Quantazation of gains
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gain_q.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+
+
+void gainQuant(
+    gainQuantState *st,   /* i/o : State struct                      */
+    enum Mode mode,       /* i   : coder mode                        */
+    Word16 res[],         /* i   : LP residual,                 Q0   */
+    Word16 exc[],         /* i   : LTP excitation (unfiltered), Q0   */
+    Word16 code[],        /* i   : CB innovation (unfiltered),  Q13  */
+    /*       (unsharpened for MR475)           */
+    Word16 xn[],          /* i   : Target vector.                    */
+    Word16 xn2[],         /* i   : Target vector.                    */
+    Word16 y1[],          /* i   : Adaptive codebook.                */
+    Word16 Y2[],          /* i   : Filtered innovative vector.       */
+    Word16 g_coeff[],     /* i   : Correlations <xn y1> <y1 y1>      */
+    /*       Compute in G_pitch().             */
+    Word16 even_subframe, /* i   : even subframe indicator flag      */
+    Word16 gp_limit,      /* i   : pitch gain limit                  */
+    Word16 *sf0_gain_pit, /* o   : Pitch gain sf 0.   MR475          */
+    Word16 *sf0_gain_cod, /* o   : Code gain sf 0.    MR475          */
+    Word16 *gain_pit,     /* i/o : Pitch gain.                       */
+    Word16 *gain_cod,     /* o   : Code gain.                        */
+    /*       MR475: gain_* unquantized in even */
+    /*       subframes, quantized otherwise    */
+    Word16 **anap,        /* o   : Index of quantization             */
+    Flag   *pOverflow     /* o   : overflow indicator                */
+)
+{
+    Word16 exp_gcode0;
+    Word16 frac_gcode0;
+    Word16 qua_ener_MR122;
+    Word16 qua_ener;
+    Word16 frac_coeff[5];
+    Word16 exp_coeff[5];
+    Word16 exp_en;
+    Word16 frac_en;
+    Word16 cod_gain_exp;
+    Word16 cod_gain_frac;
+    Word16 temp;
+
+    if (mode == MR475)
+    {
+        if (even_subframe != 0)
+        {
+            /* save position in output parameter stream and current
+               state of codebook gain predictor */
+            st->gain_idx_ptr = (*anap)++;
+
+//            gc_pred_copy(&(st->gc_predSt), &(st->gc_predUnqSt));
+
+            memcpy(st->gc_predUnqSt.past_qua_en,
+                        st->gc_predSt.past_qua_en,
+                        NPRED*sizeof(Word16));
+            memcpy(st->gc_predUnqSt.past_qua_en_MR122,
+                        st->gc_predSt.past_qua_en_MR122,
+                        NPRED*sizeof(Word16));
+
+
+            /* predict codebook gain (using "unquantized" predictor)*/
+            /* (note that code[] is unsharpened in MR475)           */
+            gc_pred(
+                &(st->gc_predUnqSt),
+                mode,
+                code,
+                &st->sf0_exp_gcode0,
+                &st->sf0_frac_gcode0,
+                &exp_en,
+                &frac_en,
+                pOverflow);
+
+            /* calculate energy coefficients for quantization
+               and store them in state structure (will be used
+               in next subframe when real quantizer is run) */
+            calc_filt_energies(
+                mode,
+                xn,
+                xn2,
+                y1,
+                Y2,
+                g_coeff,
+                st->sf0_frac_coeff,
+                st->sf0_exp_coeff,
+                &cod_gain_frac,
+                &cod_gain_exp,
+                pOverflow);
+
+            /* store optimum codebook gain (Q1) */
+            temp =
+                add(
+                    cod_gain_exp,
+                    1,
+                    pOverflow);
+
+            *gain_cod =
+                shl(
+                    cod_gain_frac,
+                    temp,
+                    pOverflow);
+
+            calc_target_energy(
+                xn,
+                &st->sf0_exp_target_en,
+                &st->sf0_frac_target_en,
+                pOverflow);
+
+            /* calculate optimum codebook gain and update
+               "unquantized" predictor                    */
+            MR475_update_unq_pred(
+                &(st->gc_predUnqSt),
+                st->sf0_exp_gcode0,
+                st->sf0_frac_gcode0,
+                cod_gain_exp,
+                cod_gain_frac,
+                pOverflow);
+
+            /* the real quantizer is not run here... */
+        }
+        else
+        {
+            /* predict codebook gain (using "unquantized" predictor) */
+            /* (note that code[] is unsharpened in MR475)            */
+            gc_pred(
+                &(st->gc_predUnqSt),
+                mode,
+                code,
+                &exp_gcode0,
+                &frac_gcode0,
+                &exp_en,
+                &frac_en,
+                pOverflow);
+
+            /* calculate energy coefficients for quantization */
+            calc_filt_energies(
+                mode,
+                xn,
+                xn2,
+                y1,
+                Y2,
+                g_coeff,
+                frac_coeff,
+                exp_coeff,
+                &cod_gain_frac,
+                &cod_gain_exp,
+                pOverflow);
+
+            calc_target_energy(
+                xn,
+                &exp_en,
+                &frac_en,
+                pOverflow);
+
+            /* run real (4-dim) quantizer and update real gain predictor */
+            *st->gain_idx_ptr =
+                MR475_gain_quant(
+                    &(st->gc_predSt),
+                    st->sf0_exp_gcode0,
+                    st->sf0_frac_gcode0,
+                    st->sf0_exp_coeff,
+                    st->sf0_frac_coeff,
+                    st->sf0_exp_target_en,
+                    st->sf0_frac_target_en,
+                    code,
+                    exp_gcode0,
+                    frac_gcode0,
+                    exp_coeff,
+                    frac_coeff,
+                    exp_en,
+                    frac_en,
+                    gp_limit,
+                    sf0_gain_pit,
+                    sf0_gain_cod,
+                    gain_pit,
+                    gain_cod,
+                    pOverflow);
+        }
+    }
+    else
+    {
+        /*-------------------------------------------------------------------*
+         *  predict codebook gain and quantize                               *
+         *  (also compute normalized CB innovation energy for MR795)         *
+         *-------------------------------------------------------------------*/
+        gc_pred(
+            &(st->gc_predSt),
+            mode,
+            code,
+            &exp_gcode0,
+            &frac_gcode0,
+            &exp_en,
+            &frac_en,
+            pOverflow);
+
+        if (mode == MR122)
+        {
+            *gain_cod =
+                G_code(
+                    xn2,
+                    Y2,
+                    pOverflow);
+
+            *(*anap)++ =
+                q_gain_code(
+                    mode,
+                    exp_gcode0,
+                    frac_gcode0,
+                    gain_cod,
+                    &qua_ener_MR122,
+                    &qua_ener,
+                    pOverflow);
+        }
+        else
+        {
+            /* calculate energy coefficients for quantization */
+            calc_filt_energies(
+                mode,
+                xn,
+                xn2,
+                y1,
+                Y2,
+                g_coeff,
+                frac_coeff,
+                exp_coeff,
+                &cod_gain_frac,
+                &cod_gain_exp,
+                pOverflow);
+
+            if (mode == MR795)
+            {
+                MR795_gain_quant(
+                    st->adaptSt,
+                    res,
+                    exc,
+                    code,
+                    frac_coeff,
+                    exp_coeff,
+                    exp_en,
+                    frac_en,
+                    exp_gcode0,
+                    frac_gcode0,
+                    L_SUBFR,
+                    cod_gain_frac,
+                    cod_gain_exp,
+                    gp_limit,
+                    gain_pit,
+                    gain_cod,
+                    &qua_ener_MR122,
+                    &qua_ener,
+                    anap,
+                    pOverflow);
+            }
+            else
+            {
+                *(*anap)++ =
+                    Qua_gain(
+                        mode,
+                        exp_gcode0,
+                        frac_gcode0,
+                        frac_coeff,
+                        exp_coeff,
+                        gp_limit,
+                        gain_pit,
+                        gain_cod,
+                        &qua_ener_MR122,
+                        &qua_ener,
+                        pOverflow);
+            }
+        }
+
+        /*------------------------------------------------------------------*
+         *  update table of past quantized energies                         *
+         *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                         *
+         *  st->past_qua_en(Q10) = 20 * Log10(qua_gain_code) / constant     *
+         *                       = Log2(qua_gain_code)                      *
+         *                       = qua_ener                                 *
+         *                                           constant = 20*Log10(2) *
+         *------------------------------------------------------------------*/
+        gc_pred_update(
+            &(st->gc_predSt),
+            qua_ener_MR122,
+            qua_ener);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gain_q.h b/media/libstagefright/codecs/amrnb/enc/src/gain_q.h
new file mode 100644
index 0000000..a5c7f4e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/gain_q.h
@@ -0,0 +1,182 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/gain_q.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow.
+
+ Description: Changed definition of...
+
+    gc_predState     gc_predSt;
+    gc_predState     gc_predUnqSt;
+
+  in the structure typedef.  These are no longer pointers, which avoids
+  the need to malloc memory for the pointers.  They are, rather, the actual
+  structure declared within the gainQuantState structure.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, gain_q.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef gain_q_h
+#define gain_q_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "gc_pred.h"
+#include "g_adapt.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 sf0_exp_gcode0;
+        Word16 sf0_frac_gcode0;
+        Word16 sf0_exp_target_en;
+        Word16 sf0_frac_target_en;
+        Word16 sf0_exp_coeff[5];
+        Word16 sf0_frac_coeff[5];
+        Word16 *gain_idx_ptr;
+
+        gc_predState     gc_predSt;
+        gc_predState     gc_predUnqSt;
+        GainAdaptState   *adaptSt;
+    } gainQuantState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 gainQuant_init(gainQuantState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to gainQuant in each call.
+       returns 0 on success
+     */
+    Word16 gainQuant_reset(gainQuantState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void gainQuant_exit(gainQuantState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void gainQuant(
+        gainQuantState *st,   /* i/o : State struct                      */
+        enum Mode mode,       /* i   : coder mode                        */
+        Word16 res[],         /* i   : LP residual,                 Q0   */
+        Word16 exc[],         /* i   : LTP excitation (unfiltered), Q0   */
+        Word16 code[],        /* i   : CB innovation (unfiltered),  Q13  */
+        /*       (unsharpened for MR475)           */
+        Word16 xn[],          /* i   : Target vector.                    */
+        Word16 xn2[],         /* i   : Target vector.                    */
+        Word16 y1[],          /* i   : Adaptive codebook.                */
+        Word16 Y2[],          /* i   : Filtered innovative vector.       */
+        Word16 g_coeff[],     /* i   : Correlations <xn y1> <y1 y1>      */
+        /*       Compute in G_pitch().             */
+        Word16 even_subframe, /* i   : even subframe indicator flag      */
+        Word16 gp_limit,      /* i   : pitch gain limit                  */
+        Word16 *sf0_gain_pit, /* o   : Pitch gain sf 0.   MR475          */
+        Word16 *sf0_gain_cod, /* o   : Code gain sf 0.    MR475          */
+        Word16 *gain_pit,     /* i/o : Pitch gain.                       */
+        Word16 *gain_cod,     /* o   : Code gain.                        */
+        /*       MR475: gain_* unquantized in even */
+        /*       subframes, quantized otherwise    */
+        Word16 **anap,        /* o   : Index of quantization             */
+        Flag   *pOverflow     /* o   : overflow indicator                */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* gain_q_h */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/gsmamr_enc.h b/media/libstagefright/codecs/amrnb/enc/src/gsmamr_enc.h
new file mode 100644
index 0000000..390a44d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/gsmamr_enc.h
@@ -0,0 +1,212 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm-amr/c/include/gsmamr_enc.h
+
+     Date: 09/26/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changing code as per review comments. These changes include
+              removing unnecessary tables and changing function descriptions.
+              The comments were changed to "slash-star" rather than double
+              slash, and some wordings of comments were corrected.
+
+ Description: Replaced GSMEncodeFrame function prototype with that of
+              AMREncode. Updated copyright year.
+
+ Description: Added #define for WMF and IF2, and updated function prototype
+              of AMREncode.
+
+ Description: Renamed WMF and IF2 to AMR_WMF and AMR_IF2, respectively. Added
+              AMR_ETS, and changed output_type to output_format in the
+              function prototype of AMREncode(). Removed function prototypes
+              for frame_header_move() and reverse_bits() since they are not
+              needed anymore.
+
+ Description: Moved WMFBytesUsed and IF2BytesUsed tables to
+              enc_output_format_tab.c.
+
+ Description: Added function prototypes for init, reset, and exit functions
+              in amrencode.c. Renamed output format #defines so that it it
+              unique to the encoder.
+
+ Description: Added comment to describe L_FRAME.
+
+ Description: Added Frame_Type_3GPP type definition.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This header contains all the necessary information needed to use the
+ GSM AMR encoder library.
+
+------------------------------------------------------------------------------
+*/
+#ifndef _GSMAMR_ENC_H_
+#define _GSMAMR_ENC_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "gsm_amr_typedefs.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ----------------------------------------------------------------------------*/
+    /* Number of 13-bit linear PCM samples per 20 ms frame */
+    /* L_FRAME = (8 kHz) * (20 msec) = 160 samples         */
+#define L_FRAME     160
+
+    /* Output format types */
+#define AMR_TX_WMF  0
+#define AMR_TX_IF2  1
+#define AMR_TX_ETS  2
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    enum Mode
+    {
+        MR475 = 0,/* 4.75 kbps */
+        MR515,    /* 5.15 kbps */
+        MR59,     /* 5.90 kbps */
+        MR67,     /* 6.70 kbps */
+        MR74,     /* 7.40 kbps */
+        MR795,    /* 7.95 kbps */
+        MR102,    /* 10.2 kbps */
+        MR122,    /* 12.2 kbps */
+        MRDTX,    /* DTX       */
+        N_MODES   /* Not Used  */
+    };
+
+    enum Frame_Type_3GPP
+    {
+        AMR_475 = 0,        /* 4.75 kbps    */
+        AMR_515,            /* 5.15 kbps    */
+        AMR_59,             /* 5.9 kbps     */
+        AMR_67,             /* 6.7 kbps     */
+        AMR_74,             /* 7.4 kbps     */
+        AMR_795,            /* 7.95 kbps    */
+        AMR_102,            /* 10.2 kbps    */
+        AMR_122,            /* 12.2 kbps    */
+        AMR_SID,            /* GSM AMR DTX  */
+        GSM_EFR_SID,        /* GSM EFR DTX  */
+        TDMA_EFR_SID,       /* TDMA EFR DTX */
+        PDC_EFR_SID,        /* PDC EFR DTX  */
+        FOR_FUTURE_USE1,    /* Unused 1     */
+        FOR_FUTURE_USE2,    /* Unused 2     */
+        FOR_FUTURE_USE3,    /* Unused 3     */
+        AMR_NO_DATA         /* No data      */
+    };
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ----------------------------------------------------------------------------*/
+    /* AMREncodeInit initializes the GSM AMR Encoder library by calling
+     * GSMInitEncode and sid_sync_init. If initialization was successful,
+     * init_status is set to zero, otherwise, it is set to -1.
+    */
+    int AMREncodeInit(
+        void **pEncStructure,
+        void **pSidSyncStructure,
+        Flag dtx_enable);
+
+    /* AMREncodeReset resets the state memory used by the Encoder and SID sync
+     * function. If reset was successful, reset_status is set to zero, otherwise,
+     * it is set to -1.
+    */
+    int AMREncodeReset(
+        void *pEncStructure,
+        void *pSidSyncStructure);
+
+    /* AMREncodeExit frees up the state memory used by the Encoder and SID
+     * synchronization function.
+    */
+    void AMREncodeExit(
+        void **pEncStructure,
+        void **pSidSyncStructure);
+
+    /*
+     * AMREncode is the entry point to the ETS Encoder library that encodes the raw
+     * data speech bits and converts the encoded bitstream into either an IF2-
+     * formatted bitstream, WMF-formatted bitstream, or ETS-formatted bitstream,
+     * depending on the the value of output_format. A zero is returned on success.
+     */
+    int AMREncode(
+        void *pEncState,
+        void *pSidSyncState,
+        enum Mode mode,
+        Word16 *pEncInput,
+        unsigned char *pEncOutput,
+        enum Frame_Type_3GPP *p3gpp_frame_type,
+        Word16 output_format
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* _GSMAMR_DEC_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/hp_max.cpp b/media/libstagefright/codecs/amrnb/enc/src/hp_max.cpp
new file mode 100644
index 0000000..d086594
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/hp_max.cpp
@@ -0,0 +1,332 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/hp_max.c
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "hp_max.h"
+#include    "basic_op.h"
+#include    "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: hp_max
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    corr[] = correlation vector (Word16)
+    scal_sig[] = scaled signal vector (Word16)
+    L_frame = length of frame to compute pitch (Word16
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_hp_max = pointer to max high-pass filtered norm. correlation (Word16)
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    cor_hp_max contains max high-pass filtered norm. correlation (Word16)
+    pOverflow -> 1 if the maximum correlation computation resulted in overflow
+
+ Returns:
+    0 (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function finds the maximum high-pass filtered correlation of scal_sig[]
+ in a given delay range.
+
+ The correlation is given by
+    corr[t] = <scal_sig[n],scal_sig[n-t]>,  t=lag_min,...,lag_max
+ The functions outputs the maximum high-pass filtered correlation after
+ normalization.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] hp_max.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 hp_max (
+    Word32 corr[],      // i   : correlation vector
+    Word16 scal_sig[],  // i   : scaled signal
+    Word16 L_frame,     // i   : length of frame to compute pitch
+    Word16 lag_max,     // i   : maximum lag
+    Word16 lag_min,     // i   : minimum lag
+    Word16 *cor_hp_max) // o   : max high-pass filtered norm. correlation
+{
+    Word16 i;
+    Word16 *p, *p1;
+    Word32 max, t0, t1;
+    Word16 max16, t016, cor_max;
+    Word16 shift, shift1, shift2;
+
+    max = MIN_32;
+    t0 = 0L;
+* The reference ETSI code uses a global flag for Overflow inside the math functions
+* saturate(). In the actual implementation a pointer to Overflow flag is passed in
+* as a parameter to the function
+
+    for (i = lag_max-1; i > lag_min; i--)
+    {
+       // high-pass filtering
+       t0 = L_sub (L_sub(L_shl(corr[-i], 1), corr[-i-1]), corr[-i+1]);
+       t0 = L_abs (t0);
+
+       if (L_sub (t0, max) >= 0)
+       {
+          max = t0;
+       }
+    }
+
+    // compute energy
+    p = scal_sig;
+    p1 = &scal_sig[0];
+    t0 = 0L;
+    for (i = 0; i < L_frame; i++, p++, p1++)
+    {
+       t0 = L_mac (t0, *p, *p1);
+    }
+
+    p = scal_sig;
+    p1 = &scal_sig[-1];
+    t1 = 0L;
+    for (i = 0; i < L_frame; i++, p++, p1++)
+    {
+       t1 = L_mac (t1, *p, *p1);
+    }
+
+    // high-pass filtering
+    t0 = L_sub(L_shl(t0, 1), L_shl(t1, 1));
+    t0 = L_abs (t0);
+
+    // max/t0
+    shift1 = sub(norm_l(max), 1);
+    max16  = extract_h(L_shl(max, shift1));
+    shift2 = norm_l(t0);
+    t016 =  extract_h(L_shl(t0, shift2));
+
+    if (t016 != 0)
+    {
+       cor_max = div_s(max16, t016);
+    }
+    else
+    {
+       cor_max = 0;
+    }
+
+    shift = sub(shift1, shift2);
+
+    if (shift >= 0)
+    {
+       *cor_hp_max = shr(cor_max, shift); // Q15
+    }
+    else
+    {
+       *cor_hp_max = shl(cor_max, negate(shift)); // Q15
+    }
+
+    return 0;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+Word16 hp_max(
+    Word32 corr[],      /* i   : correlation vector.                      */
+    Word16 scal_sig[],  /* i   : scaled signal.                           */
+    Word16 L_frame,     /* i   : length of frame to compute pitch         */
+    Word16 lag_max,     /* i   : maximum lag                              */
+    Word16 lag_min,     /* i   : minimum lag                              */
+    Word16 *cor_hp_max, /* o   : max high-pass filtered norm. correlation */
+    Flag   *pOverflow   /* i/o : overflow Flag                            */
+)
+{
+    Word16 i;
+    Word16 *p, *p1;
+    Word32 max, t0, t1;
+    Word16 max16, t016, cor_max;
+    Word16 shift, shift1, shift2;
+    Word32 L_temp;
+
+    max = MIN_32;
+    t0 = 0L;
+
+    for (i = lag_max - 1; i > lag_min; i--)
+    {
+        /* high-pass filtering */
+        t0 = L_shl(corr[-i], 1, pOverflow);
+        L_temp = L_sub(t0, corr[-i-1], pOverflow);
+        t0 = L_sub(L_temp, corr[-i+1], pOverflow);
+        t0 = L_abs(t0);
+
+        if (t0 >= max)
+        {
+            max = t0;
+        }
+    }
+
+    /* compute energy */
+    p = scal_sig;
+    p1 = &scal_sig[0];
+    t0 = 0L;
+    for (i = 0; i < L_frame; i++, p++, p1++)
+    {
+        t0 = L_mac(t0, *p, *p1, pOverflow);
+    }
+
+    p = scal_sig;
+    p1 = &scal_sig[-1];
+    t1 = 0L;
+    for (i = 0; i < L_frame; i++, p++, p1++)
+    {
+        t1 = L_mac(t1, *p, *p1, pOverflow);
+    }
+
+    /* high-pass filtering */
+    L_temp = L_shl(t0, 1, pOverflow);
+    t1 = L_shl(t1, 1, pOverflow);
+    t0 = L_sub(L_temp, t1, pOverflow);
+    t0 = L_abs(t0);
+
+    /* max/t0 */
+    /*  shift1 = sub(norm_l(max), 1);
+        max16  = extract_h(L_shl(max, shift1));
+        shift2 = norm_l(t0);
+        t016 =  extract_h(L_shl(t0, shift2));   */
+
+    t016 = norm_l(max);
+    shift1 = sub(t016, 1, pOverflow);
+
+    L_temp = L_shl(max, shift1, pOverflow);
+    max16  = (Word16)(L_temp >> 16);
+
+    shift2 = norm_l(t0);
+    L_temp = L_shl(t0, shift2, pOverflow);
+    t016 = (Word16)(L_temp >> 16);
+
+    if (t016 != 0)
+    {
+        cor_max = div_s(max16, t016);
+    }
+    else
+    {
+        cor_max = 0;
+    }
+
+    shift = sub(shift1, shift2, pOverflow);
+
+    if (shift >= 0)
+    {
+        *cor_hp_max = shr(cor_max, shift, pOverflow); /* Q15 */
+    }
+    else
+    {
+        *cor_hp_max = shl(cor_max, negate(shift), pOverflow); /* Q15 */
+    }
+
+    return 0;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/hp_max.h b/media/libstagefright/codecs/amrnb/enc/src/hp_max.h
new file mode 100644
index 0000000..b668924
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/hp_max.h
@@ -0,0 +1,116 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/hp_max.h
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : hp_max.h
+       Purpose          : Find the maximum correlation of scal_sig[] in a given
+                          delay range.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef HP_MAX_H
+#define HP_MAX_H  "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 hp_max(
+        Word32 corr[],      /* i   : correlation vector.                      */
+        Word16 scal_sig[],  /* i   : scaled signal.                           */
+        Word16 L_frame,     /* i   : length of frame to compute pitch         */
+        Word16 lag_max,     /* i   : maximum lag                              */
+        Word16 lag_min,     /* i   : minimum lag                              */
+        Word16 *cor_hp_max, /* o   : max high-pass filtered norm. correlation */
+        Flag   *pOverflow   /* i/o : overflow Flag                            */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _HP_MAX_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36.cpp b/media/libstagefright/codecs/amrnb/enc/src/inter_36.cpp
new file mode 100644
index 0000000..87766a9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/inter_36.cpp
@@ -0,0 +1,250 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/inter_36.c
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation
+              4. Unrolled loops to speed up processing, use decrement loops
+              5. Eliminated call to round by proper initialization
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Using intrinsics from fxp_arithmetic.h .
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "inter_36.h"
+#include "cnst.h"
+#include "inter_36_tab.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define UP_SAMP_MAX  6
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: inter_36
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pX    = pointer to input vector of type Word16
+    frac  = fraction  (-2..2 for 3*, -3..3 for 6*)  of type Word16
+    flag3 = if set, upsampling rate = 3 (6 otherwise) of type Word16
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      File             : inter_36.c
+      Purpose          : Interpolating the normalized correlation
+                       : with 1/3 or 1/6 resolution.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ inter_36.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    Word16 i, k;
+    Word16 *x1, *x2;
+    const Word16 *c1, *c2;
+    Word32 s;
+
+    if (flag3 != 0)
+    {
+      frac = shl (frac, 1);   // inter_3[k] = inter_6[2*k] -> k' = 2*k
+    }
+
+    if (frac < 0)
+    {
+        frac = add (frac, UP_SAMP_MAX);
+        x--;
+    }
+
+    x1 = &x[0];
+    x2 = &x[1];
+    c1 = &inter_6[frac];
+    c2 = &inter_6[sub (UP_SAMP_MAX, frac)];
+
+    s = 0;
+    for (i = 0, k = 0; i < L_INTER_SRCH; i++, k += UP_SAMP_MAX)
+    {
+        s = L_mac (s, x1[-i], c1[k]);
+        s = L_mac (s, x2[i], c2[k]);
+    }
+
+    return pv_round (s);
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 Interpol_3or6(   /* o : interpolated value                        */
+    Word16 *pX,         /* i : input vector                              */
+    Word16 frac,        /* i : fraction  (-2..2 for 3*, -3..3 for 6*)    */
+    Word16 flag3,       /* i : if set, upsampling rate = 3 (6 otherwise) */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 k;
+    Word16 *pX1;
+    Word16 *pX2;
+    const Word16 *pC1;
+    const Word16 *pC2;
+    Word32 s;
+    Word16 temp1;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    if (flag3 != 0)
+    {
+        frac <<= 1;
+        /* inter_3[k] = inter_6[2*k] -> k' = 2*k */
+    }
+
+    if (frac < 0)
+    {
+        frac += UP_SAMP_MAX;
+        pX--;
+    }
+
+    pX1   = &pX[0];
+    pX2   = &pX[1];
+    pC1   = &inter_6[frac];
+    temp1 = UP_SAMP_MAX - frac;
+    pC2   = &inter_6[temp1];
+
+    s = 0x04000;
+    k = 0;
+
+    for (i = (L_INTER_SRCH >> 1); i != 0; i--)
+    {
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (pX1--), (Word32) pC1[k], s);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (pX2++), (Word32) pC2[k], s);
+        k += UP_SAMP_MAX;
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (pX1--), (Word32) pC1[k], s);
+        s = amrnb_fxp_mac_16_by_16bb((Word32) * (pX2++), (Word32) pC2[k], s);
+        k <<= 1;
+    }
+
+    return((Word16)(s >> 15));
+}
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36.h b/media/libstagefright/codecs/amrnb/enc/src/inter_36.h
new file mode 100644
index 0000000..f35a5c5
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/inter_36.h
@@ -0,0 +1,117 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/inter_36.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : inter_36.h
+      Purpose          : Interpolating the normalized correlation
+                       : with 1/3 or 1/6 resolution.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _INTER_36_H_
+#define _INTER_36_H_
+#define inter_36_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 Interpol_3or6(   /* (o)  : interpolated value                        */
+        Word16 *x,          /* (i)  : input vector                              */
+        Word16 frac,        /* (i)  : fraction  (-2..2 for 3*, -3..3 for 6*)    */
+        Word16 flag3,        /* (i)  : if set, upsampling rate = 3 (6 otherwise) */
+        Flag   *pOverflow
+    );
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _INTER_36_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.cpp b/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.cpp
new file mode 100644
index 0000000..27f33e9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.cpp
@@ -0,0 +1,212 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Pathname: .audio/gsm-amr/c/src/inter_36_tab.c
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed tables from static const to just const.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition. Removed corresponding header file from Include
+              section.
+
+ Description: Put "extern" back.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    None
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      File             : inter_36.tab
+      Purpose          : Tables for interpolating the normalized correlation
+                         with 1/3 or 1/6 resolution.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+#include    "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define UP_SAMP_MAX  6
+#define FIR_SIZE     (UP_SAMP_MAX*L_INTER_SRCH+1)
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    /* 1/6 resolution interpolation filter  (-3 dB at 3600 Hz) */
+    /* Note: The IS641 (7.4) 1/3 resolution filter is simply a subsampled
+             version of the 1/6 resolution filter, i.e. it uses
+             every second coefficient:
+
+             inter_3[k] = inter_6[2*k], 0 <= k <= 3*L_INTER_SRCH
+     */
+
+    extern const Word16 inter_6[FIR_SIZE] =
+    {
+        29519,
+        28316, 24906, 19838, 13896, 7945, 2755,
+        -1127, -3459, -4304, -3969, -2899, -1561,
+        -336, 534, 970, 1023, 823, 516,
+        220, 0, -131, -194, -215, 0
+    };
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL FUNCTION REFERENCES
+    ; Declare functions defined elsewhere and referenced in this module
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.h b/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.h
new file mode 100644
index 0000000..21ade69
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/inter_36_tab.h
@@ -0,0 +1,113 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Pathname: .audio/gsm-amr/c/include/inter_36_tab.h
+
+     Date: 02/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a table BytesUsed.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef INTER_36_TAB_H
+#define INTER_36_TAB_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 inter_6[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_comp.cpp b/media/libstagefright/codecs/amrnb/enc/src/l_comp.cpp
new file mode 100644
index 0000000..64be4dd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/l_comp.cpp
@@ -0,0 +1,162 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    hi = 16 bit signed integer (Word16) whose value falls in
+         the range : 0x8000 <= hi <= 0x7fff.
+    lo = 16 bit signed integer (Word16) whose value falls in
+         the range : 0x8000 <= lo <= 0x7fff.
+
+ Outputs:
+    pOverflow = 1 if overflow happens in a math function called by this function.
+    L_out = 32-bit result of (hi<<16 + lo<<1).
+
+ Returns:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+        None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function composes a 32 bit integer from two 16 bit double precision
+ format (DPF) numbers hi and lo by the following operation:
+ 1. Deposit hi into the 16 MS bits of the 32 bit output L_out.
+ 2. Shift lo left by 1.
+ 3. Add results from 1 and 2 with saturation to return the 32 bit result
+    L_out.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] oper_32b.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "l_comp.h"
+#include "basic_op.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Word32 L_Comp(Word16 hi, Word16 lo, Flag *pOverflow)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Word32 L_32;
+    Word32 temp32;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    L_32 = L_deposit_h(hi);
+
+    temp32 = L_mac(L_32, lo, 1, pOverflow);
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+
+    return (temp32);       /* = hi<<16 + lo<<1 */
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_extract.cpp b/media/libstagefright/codecs/amrnb/enc/src/l_extract.cpp
new file mode 100644
index 0000000..6add299
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/l_extract.cpp
@@ -0,0 +1,174 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+
+
+
+
+ Filename: /audio/gsm_amr/c/src/l_extract.c
+
+     Date: 09/07/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Changed function interface to pass in a
+              pointer to overflow flag into the function instead of using a
+              global flag. Changed names of function parameters for clarity.
+              Removed inclusion of unwanted header files.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: L_extract
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_var = 32 bit signed integer (Word32) whose value falls
+           in the range : 0x8000 0000 <= L_32 <= 0x7fff ffff.
+
+    pL_var_hi =  pointer to the most significant word of L_var (Word16).
+
+    pL_var_lo =  pointer to the least significant word of L_var shifted
+              to the left by 1 (Word16).
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the 32 bit add operation resulted in overflow
+    pL_var_hi -> MS word of L_32.
+    pL_var_lo -> LS word of L_32 shifted left by 1.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function extracts two 16-bit double precision format (DPF) numbers
+ from a 32-bit integer. The MS word of L_var will be stored in the location
+ pointed to by pL_var_hi and the shifted LS word of L_var will be stored in
+ the location pointed to by pL_var_lo.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] L_extract() function in oper_32b.c,  UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void L_Extract(Word32 L_var,
+               Word16 *pL_var_hi,
+               Word16 *pL_var_lo,
+               Flag   *pOverflow)
+{
+
+    Word32  temp;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    temp = (L_var >> 16);
+
+    *(pL_var_hi) = (Word16) temp;
+    *(pL_var_lo) = (Word16)((L_var >> 1) - (temp << 15));
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/l_negate.cpp b/media/libstagefright/codecs/amrnb/enc/src/l_negate.cpp
new file mode 100644
index 0000000..588abbb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/l_negate.cpp
@@ -0,0 +1,166 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_var1 = 32 bit long signed integer (Word32) whose value falls
+             in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    L_var1 = 32-bit negation of input
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function negates the 32 bit variable, L_var1, with saturation; saturate
+ in the case where input is -2147483648 (0x8000 0000).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 L_negate (Word32 L_var1)
+{
+    Word32 L_var_out;
+
+    L_var_out = (L_var1 == MIN_32) ? MAX_32 : -L_var1;
+#if (WMOPS)
+    multiCounter[currCounter].L_negate++;
+#endif
+    return (L_var_out);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+Word32 L_negate(register Word32 L_var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    L_var1 = (L_var1 == MIN_32) ? MAX_32 : -L_var1;
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (L_var1);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind.cpp b/media/libstagefright/codecs/amrnb/enc/src/lag_wind.cpp
new file mode 100644
index 0000000..0b2d2a1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lag_wind.cpp
@@ -0,0 +1,195 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/lag_wind.c
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated l_extract() function call
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "lag_wind.h"
+#include "lag_wind_tab.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lag_wind
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    m = LPC order of type Word16
+    r_h[] = pointer to autocorrelations (msb) of type Word16
+    r_l[] = pointer to autocorrelations (lsb) of type Word16
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      File             : lag_wind.c
+      Purpose          : Lag windowing of autocorrelations.
+
+    FUNCTION:  Lag_window()
+
+    PURPOSE:  Lag windowing of autocorrelations.
+
+    DESCRIPTION:
+          r[i] = r[i]*lag_wind[i],   i=1,...,10
+
+      r[i] and lag_wind[i] are in special double precision format.
+      See "oper_32b.c" for the format.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lag_wind.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    Word16 i;
+    Word32 x;
+
+    for (i = 1; i <= m; i++)
+    {
+        x = Mpy_32 (r_h[i], r_l[i], lag_h[i - 1], lag_l[i - 1], pOverflow);
+        L_Extract (x, &r_h[i], &r_l[i], pOverflow);
+    }
+    return;
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void Lag_window(
+    Word16 m,           /* (i)     : LPC order                        */
+    Word16 r_h[],       /* (i/o)   : Autocorrelations  (msb)          */
+    Word16 r_l[],       /* (i/o)   : Autocorrelations  (lsb)          */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word32 x;
+    const Word16 *p_lag_h = &lag_h[0];
+    const Word16 *p_lag_l = &lag_l[0];
+    Word16 *p_r_h = &r_h[1];
+    Word16 *p_r_l = &r_l[1];
+
+    for (i = m; i != 0 ; i--)
+    {
+        x = Mpy_32(*(p_r_h), *(p_r_l), *(p_lag_h++), *(p_lag_l++), pOverflow);
+        *(p_r_h) = (Word16)(x >> 16);
+        *(p_r_l++) = (x >> 1) - (*(p_r_h++) << 15);
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind.h b/media/libstagefright/codecs/amrnb/enc/src/lag_wind.h
new file mode 100644
index 0000000..4928ac4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lag_wind.h
@@ -0,0 +1,117 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/lag_wind.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : lag_wind.h
+      Purpose          : Lag windowing of autocorrelations.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _LAG_WIND_H_
+#define _LAG_WIND_H_
+#define lag_wind_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    void Lag_window(
+        Word16 m,          /* (i)    : LPC order                                */
+        Word16 r_h[],      /* (i/o)  : Autocorrelations  (msb)                  */
+        Word16 r_l[],      /* (i/o)  : Autocorrelations  (lsb)                  */
+        Flag   *pOverflow
+    );
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _LAG_WIND_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.cpp b/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.cpp
new file mode 100644
index 0000000..53889bb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.cpp
@@ -0,0 +1,232 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Pathname: .audio/gsm-amr/c/src/lag_wind_tab.c
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition. Removed corresponding header file from Include
+              section.
+
+ Description: Put "extern" back.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    None
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      File             : lag_wind.tab
+      Purpose          : Table of lag_window for autocorrelation.
+
+ *-----------------------------------------------------*
+ | Table of lag_window for autocorrelation.            |
+ |                                                     |
+ | noise floor = 1.0001   = (0.9999  on r[1] ..r[10])  |
+ | Bandwitdh expansion = 60 Hz                         |
+ |                                                     |
+ |                                                     |
+ | lag_wind[0] =  1.00000000    (not stored)           |
+ | lag_wind[1] =  0.99879038                           |
+ | lag_wind[2] =  0.99546897                           |
+ | lag_wind[3] =  0.98995781                           |
+ | lag_wind[4] =  0.98229337                           |
+ | lag_wind[5] =  0.97252619                           |
+ | lag_wind[6] =  0.96072036                           |
+ | lag_wind[7] =  0.94695264                           |
+ | lag_wind[8] =  0.93131179                           |
+ | lag_wind[9] =  0.91389757                           |
+ | lag_wind[10]=  0.89481968                           |
+ -------------------------------------------------------
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE: [stack count for this module] + [variable to represent
+          stack usage for each subroutine called]
+
+     where: [stack usage variable] = stack usage for [subroutine
+         name] (see [filename].ext)
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES: [cycle count equation for this module] + [variable
+           used to represent cycle count for each subroutine
+           called]
+
+     where: [cycle count variable] = cycle count for [subroutine
+        name] (see [filename].ext)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    extern const Word16 lag_h[10] =
+    {
+        32728,
+        32619,
+        32438,
+        32187,
+        31867,
+        31480,
+        31029,
+        30517,
+        29946,
+        29321
+    };
+
+    extern const Word16 lag_l[10] =
+    {
+        11904,
+        17280,
+        30720,
+        25856,
+        24192,
+        28992,
+        24384,
+        7360,
+        19520,
+        14784
+    };
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL FUNCTION REFERENCES
+    ; Declare functions defined elsewhere and referenced in this module
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.h b/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.h
new file mode 100644
index 0000000..c210932
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lag_wind_tab.h
@@ -0,0 +1,112 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Pathname: .audio/gsm-amr/c/include/lag_wind_tab.h
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares tables used by lag_wind.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LAG_WIND_TAB_H
+#define LAG_WIND_TAB_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 lag_h[];
+    extern const Word16 lag_l[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/levinson.cpp b/media/libstagefright/codecs/amrnb/enc/src/levinson.cpp
new file mode 100644
index 0000000..001897b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/levinson.cpp
@@ -0,0 +1,824 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/levinson.c
+ Funtions: Levinson_init
+           Levinson_reset
+           Levinson_exit
+           Levinson
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the function the implements the Levinson-Durbin algorithm
+ using double-precision arithmetic. This file also includes functions to
+ initialize, allocate, and deallocate memory used by the Levinson function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+#include <string.h>
+
+#include "levinson.h"
+#include "basicop_malloc.h"
+#include "basic_op.h"
+#include "div_32.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Levinson_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to an array of pointers to structures of type
+            LevinsonState
+
+ Outputs:
+    pointer pointed to by state points to the newly allocated memory to
+      be used by Levinson function
+
+ Returns:
+    return_value = 0, if initialization was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates and initializes the state memory used by the
+ Levinson function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ levinson.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Levinson_init (LevinsonState **state)
+{
+  LevinsonState* s;
+
+  if (state == (LevinsonState **) NULL){
+      //fprint(stderr, "Levinson_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (LevinsonState *) malloc(sizeof(LevinsonState))) == NULL){
+      //fprint(stderr, "Levinson_init: can not malloc state structure\n");
+      return -1;
+  }
+
+  Levinson_reset(s);
+  *state = s;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Levinson_init(LevinsonState **state)
+{
+    LevinsonState* s;
+
+    if (state == (LevinsonState **) NULL)
+    {
+        /*  fprint(stderr, "Levinson_init: invalid parameter\n");  */
+        return(-1);
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (LevinsonState *) malloc(sizeof(LevinsonState))) == NULL)
+    {
+        /*  fprint(stderr, "Levinson_init:
+                            can not malloc state structure\n");  */
+        return(-1);
+    }
+
+    Levinson_reset(s);
+    *state = s;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Levinson_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to structures of type LevinsonState
+
+ Outputs:
+    old_A field of structure pointed to by state is initialized to 4096
+      (first location) and the rest to zeros
+
+ Returns:
+    return_value = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the state memory used by the Levinson function to
+ zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ levinson.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Levinson_reset (LevinsonState *state)
+{
+  Word16 i;
+
+  if (state == (LevinsonState *) NULL){
+      fprint(stderr, "Levinson_reset: invalid parameter\n");
+      return -1;
+  }
+
+  state->old_A[0] = 4096;
+  for(i = 1; i < M + 1; i++)
+      state->old_A[i] = 0;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Levinson_reset(LevinsonState *state)
+{
+    Word16 i;
+
+    if (state == (LevinsonState *) NULL)
+    {
+        /*  fprint(stderr, "Levinson_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    state->old_A[0] = 4096;
+    for (i = 1; i < M + 1; i++)
+    {
+        state->old_A[i] = 0;
+    }
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Levinson_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to an array of pointers to structures of type
+            LevinsonState
+
+ Outputs:
+    pointer pointed to by state is set to the NULL address
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function deallocates the state memory used by the Levinson function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ levinson.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Levinson_exit (LevinsonState **state)
+{
+  if (state == NULL || *state == NULL)
+      return;
+
+  // deallocate memory
+  free(*state);
+  *state = NULL;
+
+  return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void Levinson_exit(LevinsonState **state)
+{
+    if (state == NULL || *state == NULL)
+    {
+        return;
+    }
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Levinson
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type LevinsonState
+    Rh = vector containing most significant byte of
+         autocorrelation values (Word16)
+    Rl = vector containing least significant byte of
+         autocorrelation values (Word16)
+    A = vector of LPC coefficients (10th order) (Word16)
+    rc = vector containing first four reflection coefficients (Word16)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    A contains the newly calculated LPC coefficients
+    rc contains the newly calculated reflection coefficients
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function implements the Levinson-Durbin algorithm using double-
+ precision arithmetic. This is used to compute the Linear Predictive (LP)
+ filter parameters from the speech autocorrelation values.
+
+ The algorithm implemented is as follows:
+    A[0] = 1
+    K    = -R[1]/R[0]
+    A[1] = K
+    Alpha = R[0] * (1-K**2]
+
+    FOR  i = 2 to M
+
+        S =  SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i]
+        K = -S / Alpha
+
+        FOR j = 1 to  i-1
+            An[j] = A[j] + K*A[i-j]  where   An[i] = new A[i]
+        ENDFOR
+
+        An[i]=K
+        Alpha=Alpha * (1-K**2)
+
+    END
+
+ where:
+    R[i] = autocorrelations
+    A[i] = filter coefficients
+    K = reflection coefficient
+    Alpha = prediction gain
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ levinson.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Levinson (
+    LevinsonState *st,
+    Word16 Rh[],       // i : Rh[m+1] Vector of autocorrelations (msb)
+    Word16 Rl[],       // i : Rl[m+1] Vector of autocorrelations (lsb)
+    Word16 A[],        // o : A[m]    LPC coefficients  (m = 10)
+    Word16 rc[]        // o : rc[4]   First 4 reflection coefficients
+)
+{
+    Word16 i, j;
+    Word16 hi, lo;
+    Word16 Kh, Kl;                // reflexion coefficient; hi and lo
+    Word16 alp_h, alp_l, alp_exp; // Prediction gain; hi lo and exponent
+    Word16 Ah[M + 1], Al[M + 1];  // LPC coef. in double prec.
+    Word16 Anh[M + 1], Anl[M + 1];// LPC coef.for next iteration in double
+                                     prec.
+    Word32 t0, t1, t2;            // temporary variable
+
+    // K = A[1] = -R[1] / R[0]
+
+    t1 = L_Comp (Rh[1], Rl[1]);
+    t2 = L_abs (t1);                    // abs R[1]
+    t0 = Div_32 (t2, Rh[0], Rl[0]);     // R[1]/R[0]
+    if (t1 > 0)
+       t0 = L_negate (t0);             // -R[1]/R[0]
+    L_Extract (t0, &Kh, &Kl);           // K in DPF
+
+    rc[0] = pv_round (t0);
+
+    t0 = L_shr (t0, 4);                 // A[1] in
+    L_Extract (t0, &Ah[1], &Al[1]);     // A[1] in DPF
+
+    //  Alpha = R[0] * (1-K**2)
+
+    t0 = Mpy_32 (Kh, Kl, Kh, Kl);       // K*K
+    t0 = L_abs (t0);                    // Some case <0 !!
+    t0 = L_sub ((Word32) 0x7fffffffL, t0); // 1 - K*K
+    L_Extract (t0, &hi, &lo);           // DPF format
+    t0 = Mpy_32 (Rh[0], Rl[0], hi, lo); // Alpha in
+
+    // Normalize Alpha
+
+    alp_exp = norm_l (t0);
+    t0 = L_shl (t0, alp_exp);
+    L_Extract (t0, &alp_h, &alp_l);     // DPF format
+
+     *--------------------------------------*
+     * ITERATIONS  I=2 to M                 *
+     *--------------------------------------*
+
+    for (i = 2; i <= M; i++)
+    {
+       // t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i]
+
+       t0 = 0;
+       for (j = 1; j < i; j++)
+       {
+          t0 = L_add (t0, Mpy_32 (Rh[j], Rl[j], Ah[i - j], Al[i - j]));
+       }
+       t0 = L_shl (t0, 4);
+
+       t1 = L_Comp (Rh[i], Rl[i]);
+       t0 = L_add (t0, t1);            // add R[i]
+
+       // K = -t0 / Alpha
+
+       t1 = L_abs (t0);
+       t2 = Div_32 (t1, alp_h, alp_l); // abs(t0)/Alpha
+       if (t0 > 0)
+          t2 = L_negate (t2);         // K =-t0/Alpha
+       t2 = L_shl (t2, alp_exp);       // denormalize; compare to Alpha
+       L_Extract (t2, &Kh, &Kl);       // K in DPF
+
+       if (sub (i, 5) < 0)
+       {
+          rc[i - 1] = pv_round (t2);
+       }
+       // Test for unstable filter. If unstable keep old A(z)
+
+       if (sub (abs_s (Kh), 32750) > 0)
+       {
+          for (j = 0; j <= M; j++)
+          {
+             A[j] = st->old_A[j];
+          }
+
+          for (j = 0; j < 4; j++)
+          {
+             rc[j] = 0;
+          }
+
+          return 0;
+       }
+        *------------------------------------------*
+        *  Compute new LPC coeff. -> An[i]         *
+        *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *
+        *  An[i]= K                                *
+        *------------------------------------------*
+
+       for (j = 1; j < i; j++)
+       {
+          t0 = Mpy_32 (Kh, Kl, Ah[i - j], Al[i - j]);
+          t0 = L_add(t0, L_Comp(Ah[j], Al[j]));
+          L_Extract (t0, &Anh[j], &Anl[j]);
+       }
+       t2 = L_shr (t2, 4);
+       L_Extract (t2, &Anh[i], &Anl[i]);
+
+       //  Alpha = Alpha * (1-K**2)
+
+       t0 = Mpy_32 (Kh, Kl, Kh, Kl);           // K*K
+       t0 = L_abs (t0);                        // Some case <0 !!
+       t0 = L_sub ((Word32) 0x7fffffffL, t0);  // 1 - K*K
+       L_Extract (t0, &hi, &lo);               // DPF format
+       t0 = Mpy_32 (alp_h, alp_l, hi, lo);
+
+       // Normalize Alpha
+
+       j = norm_l (t0);
+       t0 = L_shl (t0, j);
+       L_Extract (t0, &alp_h, &alp_l);         // DPF format
+       alp_exp = add (alp_exp, j);             // Add normalization to
+                                                  alp_exp
+
+       // A[j] = An[j]
+
+       for (j = 1; j <= i; j++)
+       {
+          Ah[j] = Anh[j];
+          Al[j] = Anl[j];
+       }
+    }
+
+    A[0] = 4096;
+    for (i = 1; i <= M; i++)
+    {
+       t0 = L_Comp (Ah[i], Al[i]);
+       st->old_A[i] = A[i] = pv_round (L_shl (t0, 1));
+    }
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Levinson(
+    LevinsonState *st,
+    Word16 Rh[],       /* i : Rh[m+1] Vector of autocorrelations (msb) */
+    Word16 Rl[],       /* i : Rl[m+1] Vector of autocorrelations (lsb) */
+    Word16 A[],        /* o : A[m]    LPC coefficients  (m = 10)       */
+    Word16 rc[],       /* o : rc[4]   First 4 reflection coefficients  */
+    Flag   *pOverflow
+)
+{
+    register Word16 i;
+    register Word16 j;
+    Word16 hi;
+    Word16 lo;
+    Word16 Kh;                    /* reflexion coefficient; hi and lo   */
+    Word16 Kl;
+    Word16 alp_h;                 /* Prediction gain; hi lo and exponent*/
+    Word16 alp_l;
+    Word16 alp_exp;
+    Word16 Ah[M + 1];             /* LPC coef. in double prec.          */
+    Word16 Al[M + 1];
+    Word16 Anh[M + 1];            /* LPC coef.for next iteration in     */
+    Word16 Anl[M + 1];            /* double prec.                       */
+    register Word32 t0;           /* temporary variable                 */
+    register Word32 t1;           /* temporary variable                 */
+    register Word32 t2;           /* temporary variable                 */
+
+    Word16 *p_Rh;
+    Word16 *p_Rl;
+    Word16 *p_Ah;
+    Word16 *p_Al;
+    Word16 *p_Anh;
+    Word16 *p_Anl;
+    Word16 *p_A;
+
+    /* K = A[1] = -R[1] / R[0] */
+    t1 = ((Word32) * (Rh + 1)) << 16;
+    t1 += *(Rl + 1) << 1;
+
+    t2 = L_abs(t1);         /* abs R[1] - required by Div_32 */
+    t0 = Div_32(t2, *Rh, *Rl, pOverflow);  /* R[1]/R[0]        */
+
+    if (t1 > 0)
+    {
+        t0 = L_negate(t0);  /* -R[1]/R[0]       */
+    }
+
+    /* K in DPF         */
+    Kh = (Word16)(t0 >> 16);
+    Kl = (Word16)((t0 >> 1) - ((Word32)(Kh) << 15));
+
+    *rc = pv_round(t0, pOverflow);
+
+    t0 = t0 >> 4;
+
+    /* A[1] in DPF      */
+    *(Ah + 1) = (Word16)(t0 >> 16);
+
+    *(Al + 1) = (Word16)((t0 >> 1) - ((Word32)(*(Ah + 1)) << 15));
+
+    /*  Alpha = R[0] * (1-K**2) */
+    t0 = Mpy_32(Kh, Kl, Kh, Kl, pOverflow);         /* K*K              */
+    t0 = L_abs(t0);                                 /* Some case <0 !!  */
+    t0 = 0x7fffffffL - t0;                          /* 1 - K*K          */
+
+    /* DPF format       */
+    hi = (Word16)(t0 >> 16);
+    lo = (Word16)((t0 >> 1) - ((Word32)(hi) << 15));
+
+    t0 = Mpy_32(*Rh, *Rl, hi, lo, pOverflow);      /* Alpha in         */
+
+    /* Normalize Alpha */
+
+    alp_exp = norm_l(t0);
+    t0 = t0 << alp_exp;
+
+    /* DPF format       */
+    alp_h = (Word16)(t0 >> 16);
+    alp_l = (Word16)((t0 >> 1) - ((Word32)(alp_h) << 15));
+
+    /*--------------------------------------*
+    * ITERATIONS  I=2 to M                 *
+    *--------------------------------------*/
+
+    for (i = 2; i <= M; i++)
+    {
+        /* t0 = SUM ( R[j]*A[i-j] ,j=1,i-1 ) +  R[i] */
+
+        t0 = 0;
+        p_Rh = &Rh[1];
+        p_Rl = &Rl[1];
+        p_Ah = &Ah[i-1];
+        p_Al = &Al[i-1];
+        for (j = 1; j < i; j++)
+        {
+            t0 += (((Word32) * (p_Rh)* *(p_Al--)) >> 15);
+            t0 += (((Word32) * (p_Rl++)* *(p_Ah)) >> 15);
+            t0 += ((Word32) * (p_Rh++)* *(p_Ah--));
+        }
+
+        t0 = t0 << 5;
+
+        t1 = ((Word32) * (Rh + i) << 16) + ((Word32)(*(Rl + i)) << 1);
+        t0 += t1;
+
+        /* K = -t0 / Alpha */
+
+        t1 = L_abs(t0);
+        t2 = Div_32(t1, alp_h, alp_l, pOverflow);  /* abs(t0)/Alpha        */
+
+        if (t0 > 0)
+        {
+            t2 = L_negate(t2);          /* K =-t0/Alpha     */
+        }
+
+        t2 = L_shl(t2, alp_exp, pOverflow);  /* denormalize; compare to Alpha */
+        Kh = (Word16)(t2 >> 16);
+        Kl = (Word16)((t2 >> 1) - ((Word32)(Kh) << 15));
+
+        if (i < 5)
+        {
+            *(rc + i - 1) = (Word16)((t2 + 0x00008000L) >> 16);
+        }
+        /* Test for unstable filter. If unstable keep old A(z) */
+        if ((abs_s(Kh)) > 32750)
+        {
+            memcpy(A, &(st->old_A[0]), sizeof(Word16)*(M + 1));
+            memset(rc, 0, sizeof(Word16)*4);
+            return(0);
+        }
+        /*------------------------------------------*
+        *  Compute new LPC coeff. -> An[i]         *
+        *  An[j]= A[j] + K*A[i-j]     , j=1 to i-1 *
+        *  An[i]= K                                *
+        *------------------------------------------*/
+        p_Ah = &Ah[i-1];
+        p_Al = &Al[i-1];
+        p_Anh = &Anh[1];
+        p_Anl = &Anl[1];
+        for (j = 1; j < i; j++)
+        {
+            t0  = (((Word32)Kh* *(p_Al--)) >> 15);
+            t0 += (((Word32)Kl* *(p_Ah)) >> 15);
+            t0 += ((Word32)Kh* *(p_Ah--));
+
+            t0 += (Ah[j] << 15) + Al[j];
+
+            *(p_Anh) = (Word16)(t0 >> 15);
+            *(p_Anl++) = (Word16)(t0 - ((Word32)(*(p_Anh++)) << 15));
+        }
+
+        *(p_Anh) = (Word16)(t2 >> 20);
+        *(p_Anl) = (Word16)((t2 >> 5) - ((Word32)(*(Anh + i)) << 15));
+
+        /*  Alpha = Alpha * (1-K**2) */
+
+        t0 = Mpy_32(Kh, Kl, Kh, Kl, pOverflow);  /* K*K             */
+        t0 = L_abs(t0);                          /* Some case <0 !! */
+        t0 = 0x7fffffffL - t0;                   /* 1 - K*K          */
+
+        hi = (Word16)(t0 >> 16);
+        lo = (Word16)((t0 >> 1) - ((Word32)(hi) << 15));
+
+        t0  = (((Word32)alp_h * lo) >> 15);
+        t0 += (((Word32)alp_l * hi) >> 15);
+        t0 += ((Word32)alp_h * hi);
+
+        t0 <<= 1;
+        /* Normalize Alpha */
+
+        j = norm_l(t0);
+        t0 <<= j;
+        alp_h = (Word16)(t0 >> 16);
+        alp_l = (Word16)((t0 >> 1) - ((Word32)(alp_h) << 15));
+        alp_exp += j;             /* Add normalization to alp_exp */
+
+        /* A[j] = An[j] */
+        memcpy(&Ah[1], &Anh[1], sizeof(Word16)*i);
+        memcpy(&Al[1], &Anl[1], sizeof(Word16)*i);
+    }
+
+    p_A = &A[0];
+    *(p_A++) = 4096;
+    p_Ah = &Ah[1];
+    p_Al = &Al[1];
+
+    for (i = 1; i <= M; i++)
+    {
+        t0 = ((Word32) * (p_Ah++) << 15) + *(p_Al++);
+        st->old_A[i] = *(p_A++) = (Word16)((t0 + 0x00002000) >> 14);
+    }
+
+    return(0);
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/levinson.h b/media/libstagefright/codecs/amrnb/enc/src/levinson.h
new file mode 100644
index 0000000..65ba481
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/levinson.h
@@ -0,0 +1,143 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/levinson.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+ Description: 1. Modified "int" definition by Word16
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : lag_wind.h
+      Purpose          : Lag windowing of autocorrelations.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _LEVINSON_H_
+#define _LEVINSON_H_
+#define levinson_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 old_A[M + 1];     /* Last A(z) for case of unstable filter */
+    } LevinsonState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 Levinson_init(LevinsonState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Levinson in each call.
+       returns 0 on success
+     */
+
+    Word16 Levinson_reset(LevinsonState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void Levinson_exit(LevinsonState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    Word16 Levinson(
+        LevinsonState *st,
+        Word16 Rh[],       /* i : Rh[m+1] Vector of autocorrelations (msb) */
+        Word16 Rl[],       /* i : Rl[m+1] Vector of autocorrelations (lsb) */
+        Word16 A[],        /* o : A[m]    LPC coefficients  (m = 10)       */
+        Word16 rc[],        /* o : rc[4]   First 4 reflection coefficients  */
+        Flag   *pOverflow
+    );
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _LEVINSON_H_ */
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lpc.cpp b/media/libstagefright/codecs/amrnb/enc/src/lpc.cpp
new file mode 100644
index 0000000..3c1a4bc
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lpc.cpp
@@ -0,0 +1,542 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/lpc.c
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updating includes and making code more simple as per comments.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "lpc.h"
+#include "typedef.h"
+#include "oper_32b.h"
+#include "autocorr.h"
+#include "lag_wind.h"
+#include "levinson.h"
+#include "cnst.h"
+#include "mode.h"
+#include "window_tab.h"
+#include "sub.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lpc_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer of state data of type lpcState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the state data for the LPC module.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lpc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+  lpcState* s;
+
+  if (state == (lpcState **) NULL){
+      // fprintf(stderr, "lpc_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (lpcState *) malloc(sizeof(lpcState))) == NULL){
+      // fprintf(stderr, "lpc_init: can not malloc state structure\n");
+      return -1;
+  }
+
+  s->levinsonSt = NULL;
+
+  // Init sub states
+  if (Levinson_init(&s->levinsonSt)) {
+     lpc_exit(&s);
+     return -1;
+  }
+
+
+  lpc_reset(s);
+  *state = s;
+
+  return 0;
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 lpc_init(lpcState **state)
+{
+    lpcState* s;
+
+    if (state == (lpcState **) NULL)
+    {
+        /* fprintf(stderr, "lpc_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (lpcState *) malloc(sizeof(lpcState))) == NULL)
+    {
+        /* fprintf(stderr, "lpc_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    s->levinsonSt = NULL;
+
+    /* Init sub states */
+    if (Levinson_init(&s->levinsonSt))
+    {
+        lpc_exit(&s);
+        return -1;
+    }
+
+    lpc_reset(s);
+    *state = s;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lpc_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer of state data of type lpcState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets the state data for the LPC module.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lpc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+  if (state == (lpcState *) NULL){
+      // fprintf(stderr, "lpc_reset: invalid parameter\n");
+      return -1;
+  }
+
+  Levinson_reset(state->levinsonSt);
+
+  return 0;
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 lpc_reset(lpcState *state)
+{
+
+    if (state == (lpcState *) NULL)
+    {
+        /* fprintf(stderr, "lpc_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    Levinson_reset(state->levinsonSt);
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lpc_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer of state data of type lpcState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees the state data for the LPC module.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lpc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+  if (state == NULL || *state == NULL)
+      return;
+
+  Levinson_exit(&(*state)->levinsonSt);
+
+  // deallocate memory
+  free(*state);
+  *state = NULL;
+
+  return;
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void lpc_exit(lpcState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    Levinson_exit(&(*state)->levinsonSt);
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lpc
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to state data of type lpcState
+    mode  = coder mode of type enum Mode
+    x[]   = pointer to input signal (Q15) of type Word16
+    x_12k2[] = pointer to input signal (EFR) (Q15) of type Word16
+    pOverflow = pointer to overflow indicator of type Flag
+
+ Outputs:
+    a[]   = pointer to predictor coefficients (Q12) of type Word16
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function executes the LPC functionality for GSM AMR.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lpc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+   Word16 rc[4];                  // First 4 reflection coefficients Q15
+   Word16 rLow[MP1], rHigh[MP1];  // Autocorrelations low and hi
+                                  // No fixed Q value but normalized
+                                  // so that overflow is avoided
+
+   if ( sub ((Word16)mode, (Word16)MR122) == 0)
+   {
+       // Autocorrelations
+       Autocorr(x_12k2, M, rHigh, rLow, window_160_80);
+       // Lag windowing
+       Lag_window(M, rHigh, rLow);
+       // Levinson Durbin
+       Levinson(st->levinsonSt, rHigh, rLow, &a[MP1], rc);
+
+       // Autocorrelations
+       Autocorr(x_12k2, M, rHigh, rLow, window_232_8);
+       // Lag windowing
+       Lag_window(M, rHigh, rLow);
+       // Levinson Durbin
+       Levinson(st->levinsonSt, rHigh, rLow, &a[MP1 * 3], rc);
+   }
+   else
+   {
+       // Autocorrelations
+       Autocorr(x, M, rHigh, rLow, window_200_40);
+       // Lag windowing
+       Lag_window(M, rHigh, rLow);
+       // Levinson Durbin
+       Levinson(st->levinsonSt, rHigh, rLow, &a[MP1 * 3], rc);
+   }
+
+   return 0;
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void lpc(
+    lpcState *st,     /* i/o: State struct                */
+    enum Mode mode,   /* i  : coder mode                  */
+    Word16 x[],       /* i  : Input signal           Q15  */
+    Word16 x_12k2[],  /* i  : Input signal (EFR)     Q15  */
+    Word16 a[],       /* o  : predictor coefficients Q12  */
+    Flag   *pOverflow
+)
+{
+    Word16 rc[4];                  /* First 4 reflection coefficients Q15 */
+    Word16 rLow[MP1], rHigh[MP1];  /* Autocorrelations low and hi      */
+    /* No fixed Q value but normalized  */
+    /* so that overflow is avoided      */
+
+    if (mode == MR122)
+    {
+        /* Autocorrelations */
+        Autocorr(x_12k2, M, rHigh, rLow, window_160_80, pOverflow);
+        /* Lag windowing    */
+        Lag_window(M, rHigh, rLow, pOverflow);
+        /* Levinson Durbin  */
+        Levinson(st->levinsonSt, rHigh, rLow, &a[MP1], rc, pOverflow);
+
+        /* Autocorrelations */
+        Autocorr(x_12k2, M, rHigh, rLow, window_232_8, pOverflow);
+        /* Lag windowing    */
+        Lag_window(M, rHigh, rLow, pOverflow);
+        /* Levinson Durbin  */
+        Levinson(st->levinsonSt, rHigh, rLow, &a[MP1 * 3], rc, pOverflow);
+    }
+    else
+    {
+        /* Autocorrelations */
+        Autocorr(x, M, rHigh, rLow, window_200_40, pOverflow);
+        /* Lag windowing    */
+        Lag_window(M, rHigh, rLow, pOverflow);
+        /* Levinson Durbin  */
+        Levinson(st->levinsonSt, rHigh, rLow, &a[MP1 * 3], rc, pOverflow);
+    }
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/lpc.h b/media/libstagefright/codecs/amrnb/enc/src/lpc.h
new file mode 100644
index 0000000..705a1d4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/lpc.h
@@ -0,0 +1,147 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/lpc.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : lpc.h
+      Purpose          : 2 LP analyses centered at 2nd and 4th subframe
+                         for mode 12.2. For all other modes a
+                         LP analysis centered at 4th subframe is
+                         performed.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _LPC_H_
+#define _LPC_H_
+#define lpc_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "levinson.h"
+#include "mode.h"
+
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        LevinsonState *levinsonSt;
+    } lpcState;
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 lpc_init(lpcState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to lpc in each call.
+       returns 0 on success
+     */
+
+    Word16 lpc_reset(lpcState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void lpc_exit(lpcState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void lpc(
+        lpcState *st,     /* i/o: State struct                */
+        enum Mode mode,   /* i  : coder mode                  */
+        Word16 x[],       /* i  : Input signal           Q15  */
+        Word16 x_12k2[],  /* i  : Input signal (EFR)     Q15  */
+        Word16 a[],       /* o  : predictor coefficients Q12  */
+        Flag   *pOverflow
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _LPC_H_ */
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.cpp b/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.cpp
new file mode 100644
index 0000000..7d034e0
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.cpp
@@ -0,0 +1,246 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/ol_ltp.c
+ Funtions: ol_ltp
+
+     Date: 04/18/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Adding pOverflow to the functions to remove global variables.
+              These changes are needed for the EPOC releases. Cleaned up code.
+              Updated template.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "ol_ltp.h"
+#include "cnst.h"
+#include "pitch_ol.h"
+#include "p_ol_wgh.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ol_ltp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to pitchOLWghtState structure
+    vadSt = pointer to a vadState structure
+    mode = coder mode (Mode)
+    wsp = pointer to buffer of signal used to compute the Open loop pitch
+    T_op = pointer to open loop pitch lag
+    old_lags = pointer to history with old stored Cl lags (Word16)
+    ol_gain_flg = pointer to OL gain flag (Word16)
+    idx = 16 bit value specifies the frame index
+    dtx = Data of type 'Flag' used for dtx. Use dtx=1, do not use dtx=0
+    pOverflow = pointer to Overflow indicator (Flag)
+
+ Outputs:
+    pOverflow -> 1 if processing this funvction results in satuaration
+
+ Returns:
+    Zero
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the open loop pitch lag.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ol_ltp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ol_ltp(
+    pitchOLWghtState *st, // i/o : State struct
+    vadState *vadSt,      // i/o : VAD state struct
+    enum Mode mode,       // i   : coder mode
+    Word16 wsp[],         // i   : signal used to compute the OL pitch, Q0
+                          //       uses signal[-pit_max] to signal[-1]
+    Word16 *T_op,         // o   : open loop pitch lag,                 Q0
+    Word16 old_lags[],    // i   : history with old stored Cl lags
+    Word16 ol_gain_flg[], // i   : OL gain flag
+    Word16 idx,           // i   : index
+    Flag dtx              // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+{
+   if (sub ((Word16)mode, (Word16)MR102) != 0 )
+   {
+      ol_gain_flg[0] = 0;
+      ol_gain_flg[1] = 0;
+   }
+
+   if (sub ((Word16)mode, (Word16)MR475) == 0 || sub ((Word16)mode, (Word16)MR515) == 0 )
+   {
+      *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN, PIT_MAX, L_FRAME, idx, dtx);
+   }
+   else
+   {
+      if ( sub ((Word16)mode, (Word16)MR795) <= 0 )
+      {
+         *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN, PIT_MAX, L_FRAME_BY2,
+                          idx, dtx);
+      }
+      else if ( sub ((Word16)mode, (Word16)MR102) == 0 )
+      {
+         *T_op = Pitch_ol_wgh(st, vadSt, wsp, PIT_MIN, PIT_MAX, L_FRAME_BY2,
+                              old_lags, ol_gain_flg, idx, dtx);
+      }
+      else
+      {
+         *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN_MR122, PIT_MAX,
+                          L_FRAME_BY2, idx, dtx);
+      }
+   }
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void ol_ltp(
+    pitchOLWghtState *st, /* i/o : State struct                            */
+    vadState *vadSt,      /* i/o : VAD state struct                        */
+    enum Mode mode,       /* i   : coder mode                              */
+    Word16 wsp[],         /* i   : signal used to compute the OL pitch, Q0 */
+    /*       uses signal[-pit_max] to signal[-1]     */
+    Word16 *T_op,         /* o   : open loop pitch lag,                 Q0 */
+    Word16 old_lags[],    /* i   : history with old stored Cl lags         */
+    Word16 ol_gain_flg[], /* i   : OL gain flag                            */
+    Word16 idx,           /* i   : index                                   */
+    Flag dtx,             /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag *pOverflow       /* i/o : overflow indicator                      */
+)
+{
+    if ((mode != MR102))
+    {
+        ol_gain_flg[0] = 0;
+        ol_gain_flg[1] = 0;
+    }
+
+    if ((mode == MR475) || (mode == MR515))
+    {
+        *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN, PIT_MAX, L_FRAME, idx, dtx,
+                         pOverflow);
+    }
+    else
+    {
+        if (mode <= MR795)
+        {
+            *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN, PIT_MAX, L_FRAME_BY2,
+                             idx, dtx, pOverflow);
+        }
+        else if (mode == MR102)
+        {
+            *T_op = Pitch_ol_wgh(st, vadSt, wsp, PIT_MIN, PIT_MAX, L_FRAME_BY2,
+                                 old_lags, ol_gain_flg, idx, dtx, pOverflow);
+        }
+        else
+        {
+            *T_op = Pitch_ol(vadSt, mode, wsp, PIT_MIN_MR122, PIT_MAX,
+                             L_FRAME_BY2, idx, dtx, pOverflow);
+        }
+    }
+
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.h b/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.h
new file mode 100644
index 0000000..f8c1481
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ol_ltp.h
@@ -0,0 +1,125 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/ol_ltp.h
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : ol_ltp.h
+       Purpose          : Compute the open loop pitch lag.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef OL_LTP_H
+#define OL_LTP_H "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "p_ol_wgh.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    void ol_ltp(
+        pitchOLWghtState *st, /* i/o : State struct                            */
+        vadState *vadSt,      /* i/o : VAD state struct                        */
+        enum Mode mode,       /* i   : coder mode                              */
+        Word16 wsp[],         /* i   : signal used to compute the OL pitch, Q0 */
+        /*       uses signal[-pit_max] to signal[-1]     */
+        Word16 *T_op,         /* o   : open loop pitch lag,                 Q0 */
+        Word16 old_lags[],    /* i   : history with old stored Cl lags         */
+        Word16 ol_gain_flg[], /* i   : OL gain flag                            */
+        Word16 idx,           /* i   : index                                   */
+        Flag dtx,             /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+        Flag *pOverflow       /* i/o : overflow Flag                           */
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _OL_LTP_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/p_ol_wgh.cpp b/media/libstagefright/codecs/amrnb/enc/src/p_ol_wgh.cpp
new file mode 100644
index 0000000..68d7345
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/p_ol_wgh.cpp
@@ -0,0 +1,989 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/p_ol_wgh.c
+ Funtions: p_ol_wgh_init
+           p_ol_wgh_reset
+           p_ol_wgh_exit
+           Lag_max
+           Pitch_ol_wgh
+
+     Date: 02/05/2002
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: t0 was not being declared as Word32.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ The modules in this file compute the open loop pitch lag with weighting.
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "p_ol_wgh.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "basic_op.h"
+#include "gmed_n.h"
+#include "inv_sqrt.h"
+#include "vad1.h"
+#include "calc_cor.h"
+#include "hp_max.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: p_ol_wgh_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs
+    state = pointer to a pointer of structure type pitchOLWghtState
+
+ Outputs:
+    None
+
+ Returns:
+    0 if the memory allocation is a success
+    -1 if the memory allocation fails
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ p_ol_wgh.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int p_ol_wgh_init (pitchOLWghtState **state)
+{
+    pitchOLWghtState* s;
+
+    if (state == (pitchOLWghtState **) NULL){
+        // fprintf(stderr, "p_ol_wgh_init: invalid parameter\n");
+        return -1;
+    }
+    *state = NULL;
+
+    // allocate memory
+    if ((s= (pitchOLWghtState *) malloc(sizeof(pitchOLWghtState))) == NULL){
+        // fprintf(stderr, "p_ol_wgh_init: can not malloc state structure\n");
+        return -1;
+    }
+
+    p_ol_wgh_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 p_ol_wgh_init(pitchOLWghtState **state)
+{
+    pitchOLWghtState* s;
+
+    if (state == (pitchOLWghtState **) NULL)
+    {
+        /* fprintf(stderr, "p_ol_wgh_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (pitchOLWghtState *) malloc(sizeof(pitchOLWghtState))) == NULL)
+    {
+        /* fprintf(stderr, "p_ol_wgh_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    p_ol_wgh_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+/*----------------------------------------------------------------------------
+; End Function: p_ol_wgh_init
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: p_ol_wgh_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs
+    st = pointer to structure type pitchOLWghtState
+
+ Outputs:
+    None
+
+ Returns:
+    0 if the memory initialization is a success
+    -1 if the memory initialization fails
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes state memory to zero
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ p_ol_wgh.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int p_ol_wgh_reset (pitchOLWghtState *st)
+{
+   if (st == (pitchOLWghtState *) NULL){
+      // fprintf(stderr, "p_ol_wgh_reset: invalid parameter\n");
+      return -1;
+   }
+
+   // Reset pitch search states
+   st->old_T0_med = 40;
+   st->ada_w = 0;
+   st->wght_flg = 0;
+
+   return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 p_ol_wgh_reset(pitchOLWghtState *st)
+{
+    if (st == (pitchOLWghtState *) NULL)
+    {
+        /* fprintf(stderr, "p_ol_wgh_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    /* Reset pitch search states */
+    st->old_T0_med = 40;
+    st->ada_w = 0;
+    st->wght_flg = 0;
+
+    return 0;
+}
+
+/*----------------------------------------------------------------------------
+; End Function: p_ol_wgh_reset
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: p_ol_wgh_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs
+    st = pointer to a pointer of structure type pitchOLWghtState
+
+ Outputs:
+    None
+
+ Returns:
+    0 if the memory initialization is a success
+    -1 if the memory initialization fails
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees the memory used for state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ p_ol_wgh.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void p_ol_wgh_exit (pitchOLWghtState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    // deallocate memory
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void p_ol_wgh_exit(pitchOLWghtState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; End Function: p_ol_wgh_exit
+----------------------------------------------------------------------------*/
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lag_max
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    corr = pointer to buffer of correlation values (Word32)
+    scal_sig = pointer to buffer of scaled signal values (Word16)
+    scal_fac = scaled signal factor (Word16)
+    scal_flag = EFR compatible scaling flag (Word16)
+    L_frame = length of frame to compute pitch (Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_max = pointer to the normalized correlation of selected lag (Word16)
+    rmax = pointer to max(<s[i]*s[j]>), (Word32)
+    r0 = pointer to the residual energy (Word32)
+    dtx  = dtx flag; equal to 1, if dtx is enabled, 0, otherwise (Flag)
+    pOverflow = Pointer to overflow (Flag)
+
+ Outputs:
+    cor_max contains the newly calculated normalized correlation of the
+      selected lag
+    rmax contains the newly calculated max(<s[i]*s[j]>)
+    r0 contains the newly calculated residual energy
+    pOverflow -> 1 if the math functions called by this routine saturate.
+
+ Returns:
+    p_max = lag of the max correlation found (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function finds the lag that has maximum correlation of scal_sig[] in a
+ given delay range.
+ The correlation is given by
+    cor[t] = <scal_sig[n],scal_sig[n-t]>,  t=lag_min,...,lag_max
+ The functions outputs the maximum correlation after normalization and the
+ corresponding lag.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ p_ol_wgh.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word16 Lag_max ( // o : lag found
+    vadState *vadSt,    // i/o : VAD state struct
+    Word32 corr[],      // i   : correlation vector.
+    Word16 scal_sig[],  // i : scaled signal.
+    Word16 L_frame,     // i : length of frame to compute pitch
+    Word16 lag_max,     // i : maximum lag
+    Word16 lag_min,     // i : minimum lag
+    Word16 old_lag,     // i : old open-loop lag
+    Word16 *cor_max,    // o : normalized correlation of selected lag
+    Word16 wght_flg,    // i : is weighting function used
+    Word16 *gain_flg,   // o : open-loop flag
+    Flag dtx            // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+{
+    Word16 i, j;
+    Word16 *p, *p1;
+    Word32 max, t0;
+    Word16 t0_h, t0_l;
+    Word16 p_max;
+    const Word16 *ww, *we;
+    Word32 t1;
+
+    ww = &corrweight[250];
+    we = &corrweight[123 + lag_max - old_lag];
+
+    max = MIN_32;
+    p_max = lag_max;
+
+    for (i = lag_max; i >= lag_min; i--)
+    {
+       t0 = corr[-i];
+
+       // Weighting of the correlation function.
+       L_Extract (corr[-i], &t0_h, &t0_l);
+       t0 = Mpy_32_16 (t0_h, t0_l, *ww);
+       ww--;
+       if (wght_flg > 0) {
+          // Weight the neighbourhood of the old lag
+          L_Extract (t0, &t0_h, &t0_l);
+          t0 = Mpy_32_16 (t0_h, t0_l, *we);
+          we--;
+       }
+
+       if (L_sub (t0, max) >= 0)
+       {
+          max = t0;
+          p_max = i;
+       }
+    }
+
+    p  = &scal_sig[0];
+    p1 = &scal_sig[-p_max];
+    t0 = 0;
+    t1 = 0;
+
+    for (j = 0; j < L_frame; j++, p++, p1++)
+    {
+       t0 = L_mac (t0, *p, *p1);
+       t1 = L_mac (t1, *p1, *p1);
+    }
+
+    if (dtx)
+    {  // no test() call since this if is only in simulation env
+#ifdef VAD2
+       vadSt->L_Rmax = L_add(vadSt->L_Rmax, t0);   // Save max correlation
+       vadSt->L_R0 =   L_add(vadSt->L_R0, t1);        // Save max energy
+#else
+       // update and detect tone
+       vad_tone_detection_update (vadSt, 0);
+       vad_tone_detection (vadSt, t0, t1);
+#endif
+    }
+
+    // gain flag is set according to the open_loop gain
+    // is t2/t1 > 0.4 ?
+    *gain_flg = pv_round(L_msu(t0, pv_round(t1), 13107));
+
+    *cor_max = 0;
+
+    return (p_max);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16 Lag_max(  /* o : lag found                               */
+    vadState *vadSt,    /* i/o : VAD state struct                      */
+    Word32 corr[],      /* i   : correlation vector.                   */
+    Word16 scal_sig[],  /* i : scaled signal.                          */
+    Word16 L_frame,     /* i : length of frame to compute pitch        */
+    Word16 lag_max,     /* i : maximum lag                             */
+    Word16 lag_min,     /* i : minimum lag                             */
+    Word16 old_lag,     /* i : old open-loop lag                       */
+    Word16 *cor_max,    /* o : normalized correlation of selected lag  */
+    Word16 wght_flg,    /* i : is weighting function used              */
+    Word16 *gain_flg,   /* o : open-loop flag                          */
+    Flag dtx,           /* i : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag   *pOverflow   /* o : overflow flag                           */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 *p;
+    Word16 *p1;
+    Word32 max;
+    Word32 t0;
+    Word16 t0_h;
+    Word16 t0_l;
+    Word16 p_max;
+    const Word16 *ww;
+    const Word16 *we;
+    Word32 t1;
+    Word16 temp;
+
+    ww = &corrweight[250];
+    we = &corrweight[123 + lag_max - old_lag];
+
+    max = MIN_32;
+    p_max = lag_max;
+
+    for (i = lag_max; i >= lag_min; i--)
+    {
+        t0 = corr[-i];
+
+        /* Weighting of the correlation function.   */
+        L_Extract(corr[-i], &t0_h, &t0_l, pOverflow);
+        t0 = Mpy_32_16(t0_h, t0_l, *ww, pOverflow);
+        ww--;
+        if (wght_flg > 0)
+        {
+            /* Weight the neighbourhood of the old lag. */
+            L_Extract(t0, &t0_h, &t0_l, pOverflow);
+            t0 = Mpy_32_16(t0_h, t0_l, *we, pOverflow);
+            we--;
+        }
+
+        /*       if (L_sub (t0, max) >= 0) */
+        if (t0 >= max)
+        {
+            max = t0;
+            p_max = i;
+        }
+    }
+    p  = &scal_sig[0];
+    p1 = &scal_sig[-p_max];
+    t0 = 0;
+    t1 = 0;
+
+    for (j = 0; j < L_frame; j++, p++, p1++)
+    {
+        t0 = L_mac(t0, *p, *p1, pOverflow);
+        t1 = L_mac(t1, *p1, *p1, pOverflow);
+    }
+
+    if (dtx)
+    {  /* no test() call since this if is only in simulation env */
+#ifdef VAD2
+        /* Save max correlation */
+        vadSt->L_Rmax = L_add(vadSt->L_Rmax, t0, pOverflow);
+        /* Save max energy */
+        vadSt->L_R0 =   L_add(vadSt->L_R0, t1, pOverflow);
+#else
+        /* update and detect tone */
+        vad_tone_detection_update(vadSt, 0, pOverflow);
+        vad_tone_detection(vadSt, t0, t1, pOverflow);
+#endif
+    }
+
+    /* gain flag is set according to the open_loop gain */
+    /* is t2/t1 > 0.4 ? */
+    temp = pv_round(t1, pOverflow);
+    t1 = L_msu(t0, temp, 13107, pOverflow);
+    *gain_flg = pv_round(t1, pOverflow);
+
+    *cor_max = 0;
+
+    return (p_max);
+}
+/*----------------------------------------------------------------------------
+; End Function: Lag_max
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_ol_wgh
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to pitchOLWghtState structure
+    vadSt = pointer to a vadState structure
+    signal = pointer to buffer of signal used to compute the open loop
+         pitch where signal[-pit_max] to signal[-1] should be known
+    pit_min = 16 bit value specifies the minimum pitch lag
+    pit_max = 16 bit value specifies the maximum pitch lag
+    L_frame = 16 bit value specifies the length of frame to compute pitch
+    old_lags = pointer to history with old stored Cl lags (Word16)
+    ol_gain_flg = pointer to OL gain flag (Word16)
+    idx = 16 bit value specifies the frame index
+    dtx = Data of type 'Flag' used for dtx. Use dtx=1, do not use dtx=0
+    pOverflow = pointer to Overflow indicator (Flag)
+ Outputs
+    st = The pitchOLWghtState may be modified
+    vadSt = The vadSt state structure may be modified.
+    pOverflow -> 1 if the math functions invoked by this routine saturate.
+
+ Returns:
+    p_max1 = 16 bit value representing the open loop pitch lag.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs an open-loop pitch search with weighting
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_ol.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Pitch_ol_wgh (     // o   : open loop pitch lag
+    pitchOLWghtState *st, // i/o : State struct
+    vadState *vadSt,      // i/o : VAD state struct/
+    Word16 signal[],      // i   : signal used to compute the open loop pitch
+                          //       signal[-pit_max] to signal[-1] should be known
+    Word16 pit_min,       // i   : minimum pitch lag
+    Word16 pit_max,       // i   : maximum pitch lag
+    Word16 L_frame,       // i   : length of frame to compute pitch
+    Word16 old_lags[],    // i   : history with old stored Cl lags
+    Word16 ol_gain_flg[], // i   : OL gain flag
+    Word16 idx,           // i   : index
+    Flag dtx              // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+{
+    Word16 i;
+    Word16 max1;
+    Word16 p_max1;
+    Word32 t0;
+#ifndef VAD2
+    Word16 corr_hp_max;
+#endif
+    Word32 corr[PIT_MAX+1], *corr_ptr;
+
+    // Scaled signal
+    Word16 scaled_signal[PIT_MAX + L_FRAME];
+    Word16 *scal_sig;
+
+    scal_sig = &scaled_signal[pit_max];
+
+    t0 = 0L;
+    for (i = -pit_max; i < L_frame; i++)
+    {
+        t0 = L_mac (t0, signal[i], signal[i]);
+    }
+    //
+    // Scaling of input signal
+    //
+    //   if Overflow        -> scal_sig[i] = signal[i]>>2
+    //   else if t0 < 1^22  -> scal_sig[i] = signal[i]<<2
+    //   else               -> scal_sig[i] = signal[i]
+
+    //
+    //  Verification for risk of overflow.
+    //
+
+    // Test for overflow
+    if (L_sub (t0, MAX_32) == 0L)
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shr (signal[i], 3);
+        }
+    }
+    else if (L_sub (t0, (Word32) 1048576L) < (Word32) 0)
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shl (signal[i], 3);
+        }
+    }
+    else
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = signal[i];
+        }
+    }
+
+    // calculate all coreelations of scal_sig, from pit_min to pit_max
+    corr_ptr = &corr[pit_max];
+    comp_corr (scal_sig, L_frame, pit_max, pit_min, corr_ptr);
+
+    p_max1 = Lag_max (vadSt, corr_ptr, scal_sig, L_frame, pit_max, pit_min,
+                      st->old_T0_med, &max1, st->wght_flg, &ol_gain_flg[idx],
+                      dtx);
+
+    if (ol_gain_flg[idx] > 0)
+    {
+       // Calculate 5-point median of previous lag
+       for (i = 4; i > 0; i--) // Shift buffer
+       {
+          old_lags[i] = old_lags[i-1];
+       }
+       old_lags[0] = p_max1;
+       st->old_T0_med = gmed_n (old_lags, 5);
+       st->ada_w = 32767; // Q15 = 1.0
+    }
+    else
+    {
+       st->old_T0_med = p_max1;
+       st->ada_w = mult(st->ada_w, 29491);      // = ada_w = ada_w * 0.9
+    }
+
+    if (sub(st->ada_w, 9830) < 0)  // ada_w - 0.3
+    {
+       st->wght_flg = 0;
+    }
+    else
+    {
+       st->wght_flg = 1;
+    }
+
+#ifndef VAD2
+    if (dtx)
+    {  // no test() call since this if is only in simulation env
+       if (sub(idx, 1) == 0)
+       {
+          // calculate max high-passed filtered correlation of all lags
+          hp_max (corr_ptr, scal_sig, L_frame, pit_max, pit_min, &corr_hp_max);
+
+          // update complex background detector
+          vad_complex_detection_update(vadSt, corr_hp_max);
+       }
+    }
+#endif
+
+    return (p_max1);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Pitch_ol_wgh(      /* o   : open loop pitch lag                            */
+    pitchOLWghtState *st, /* i/o : State struct                                   */
+    vadState *vadSt,      /* i/o : VAD state struct                               */
+    Word16 signal[],      /* i   : signal used to compute the open loop pitch     */
+    /*       signal[-pit_max] to signal[-1] should be known */
+    Word16 pit_min,       /* i   : minimum pitch lag                              */
+    Word16 pit_max,       /* i   : maximum pitch lag                              */
+    Word16 L_frame,       /* i   : length of frame to compute pitch               */
+    Word16 old_lags[],    /* i   : history with old stored Cl lags                */
+    Word16 ol_gain_flg[], /* i   : OL gain flag                                   */
+    Word16 idx,           /* i   : index                                          */
+    Flag dtx,             /* i   : dtx flag; use dtx=1, do not use dtx=0          */
+    Flag   *pOverflow     /* o   : overflow flag                                  */
+)
+{
+    Word16 i;
+    Word16 max1;
+    Word16 p_max1;
+    Word32 t0;
+#ifndef VAD2
+    Word16 corr_hp_max;
+#endif
+    Word32 corr[PIT_MAX+1], *corr_ptr;
+
+    /* Scaled signal */
+    Word16 scaled_signal[PIT_MAX + L_FRAME];
+    Word16 *scal_sig;
+
+    scal_sig = &scaled_signal[pit_max];
+
+    t0 = 0L;
+    for (i = -pit_max; i < L_frame; i++)
+    {
+        t0 = L_mac(t0, signal[i], signal[i], pOverflow);
+    }
+    /*--------------------------------------------------------*
+     * Scaling of input signal.                               *
+     *                                                        *
+     *   if Overflow        -> scal_sig[i] = signal[i]>>2     *
+     *   else if t0 < 1^22  -> scal_sig[i] = signal[i]<<2     *
+     *   else               -> scal_sig[i] = signal[i]        *
+     *--------------------------------------------------------*/
+
+    /*--------------------------------------------------------*
+     *  Verification for risk of overflow.                    *
+     *--------------------------------------------------------*/
+
+    /* Test for overflow */
+    if (L_sub(t0, MAX_32, pOverflow) == 0L)
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shr(signal[i], 3, pOverflow);
+        }
+    }
+    else if (L_sub(t0, (Word32) 1048576L, pOverflow) < (Word32) 0)
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shl(signal[i], 3, pOverflow);
+        }
+    }
+    else
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = signal[i];
+        }
+    }
+
+    /* calculate all coreelations of scal_sig, from pit_min to pit_max */
+    corr_ptr = &corr[pit_max];
+    comp_corr(scal_sig, L_frame, pit_max, pit_min, corr_ptr);
+
+    p_max1 = Lag_max(vadSt, corr_ptr, scal_sig, L_frame, pit_max, pit_min,
+                     st->old_T0_med, &max1, st->wght_flg, &ol_gain_flg[idx],
+                     dtx, pOverflow);
+
+    if (ol_gain_flg[idx] > 0)
+    {
+        /* Calculate 5-point median of previous lags */
+        for (i = 4; i > 0; i--) /* Shift buffer */
+        {
+            old_lags[i] = old_lags[i-1];
+        }
+        old_lags[0] = p_max1;
+        st->old_T0_med = gmed_n(old_lags, 5);
+        st->ada_w = 32767; /* Q15 = 1.0 */
+    }
+    else
+    {
+        st->old_T0_med = p_max1;
+        /* = ada_w = ada_w * 0.9 */
+        st->ada_w = mult(st->ada_w, 29491, pOverflow);
+    }
+
+    if (sub(st->ada_w, 9830, pOverflow) < 0)  /* ada_w - 0.3 */
+    {
+        st->wght_flg = 0;
+    }
+    else
+    {
+        st->wght_flg = 1;
+    }
+
+#ifndef VAD2
+    if (dtx)
+    {  /* no test() call since this if is only in simulation env */
+        if (sub(idx, 1, pOverflow) == 0)
+        {
+            /* calculate max high-passed filtered correlation of all lags */
+            hp_max(corr_ptr, scal_sig, L_frame, pit_max, pit_min, &corr_hp_max, pOverflow);
+
+            /* update complex background detector */
+            vad_complex_detection_update(vadSt, corr_hp_max);
+        }
+    }
+#endif
+
+    return (p_max1);
+}
+
+/*----------------------------------------------------------------------------
+; End Function: Pitch_ol_wgh
+----------------------------------------------------------------------------*/
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.cpp b/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.cpp
new file mode 100644
index 0000000..5a846fa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.cpp
@@ -0,0 +1,1609 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/pitch_fr.c
+ Functions:
+
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added pOverflow as a passed in value to searchFrac and made
+              other fixes to the code regarding simple syntax fixes. Removed
+              the include of stio.h.
+
+ Description: *lag-- decrements the pointer.  (*lag)-- decrements what is
+ pointed to.  The latter is what the coder intended, but the former is
+ the coding instruction that was used.
+
+ Description: A common problem -- a comparison != 0 was inadvertantly replaced
+ by a comparison == 0.
+
+
+ Description:  For Norm_Corr() and getRange()
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation, in some cases this by shifting before adding and
+                 in other cases by evaluating the operands
+              4. Unrolled loops to speed up processing, use decrement loops
+              5. Replaced extract_l() call with equivalent code
+              6. Modified scaling threshold and group all shifts (avoiding
+                 successive shifts)
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Removed compiler warnings.
+
+ Description:
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+      File             : pitch_fr.c
+      Purpose          : Find the pitch period with 1/3 or 1/6 subsample
+                       : resolution (closed loop).
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "pitch_fr.h"
+#include "oper_32b.h"
+#include "cnst.h"
+#include "enc_lag3.h"
+#include "enc_lag6.h"
+#include "inter_36.h"
+#include "inv_sqrt.h"
+#include "convolve.h"
+
+#include "basic_op.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+ * mode dependent parameters used in Pitch_fr()
+ * Note: order of MRxx in 'enum Mode' is important!
+ */
+static const struct
+{
+    Word16 max_frac_lag;     /* lag up to which fractional lags are used    */
+    Word16 flag3;            /* enable 1/3 instead of 1/6 fract. resolution */
+    Word16 first_frac;       /* first fractional to check                   */
+    Word16 last_frac;        /* last fractional to check                    */
+    Word16 delta_int_low;    /* integer lag below TO to start search from   */
+    Word16 delta_int_range;  /* integer range around T0                     */
+    Word16 delta_frc_low;    /* fractional below T0                         */
+    Word16 delta_frc_range;  /* fractional range around T0                  */
+    Word16 pit_min;          /* minimum pitch                               */
+} mode_dep_parm[N_MODES] =
+{
+    /* MR475 */  { 84,  1, -2,  2,  5, 10,  5,  9, PIT_MIN },
+    /* MR515 */  { 84,  1, -2,  2,  5, 10,  5,  9, PIT_MIN },
+    /* MR59  */  { 84,  1, -2,  2,  3,  6,  5,  9, PIT_MIN },
+    /* MR67  */  { 84,  1, -2,  2,  3,  6,  5,  9, PIT_MIN },
+    /* MR74  */  { 84,  1, -2,  2,  3,  6,  5,  9, PIT_MIN },
+    /* MR795 */  { 84,  1, -2,  2,  3,  6, 10, 19, PIT_MIN },
+    /* MR102 */  { 84,  1, -2,  2,  3,  6,  5,  9, PIT_MIN },
+    /* MR122 */  { 94,  0, -3,  3,  3,  6,  5,  9, PIT_MIN_MR122 }
+};
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Norm_Corr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    exc[] = pointer to buffer of type Word16
+    xn[]  = pointer to buffer of type Word16
+    h[]   = pointer to buffer of type Word16
+    L_subfr = length of sub frame (Word16)
+    t_min  = the minimum table value of type Word16
+    t_max = the maximum table value of type Word16
+    corr_norm[] = pointer to buffer of type Word16
+
+ Outputs:
+    pOverflow = 1 if the math functions called result in overflow else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  FUNCTION:   Norm_Corr()
+
+  PURPOSE: Find the normalized correlation between the target vector
+           and the filtered past excitation.
+
+  DESCRIPTION:
+     The normalized correlation is given by the correlation between the
+     target and filtered past excitation divided by the square root of
+     the energy of filtered excitation.
+                   corr[k] = <x[], y_k[]>/sqrt(y_k[],y_k[])
+     where x[] is the target vector and y_k[] is the filtered past
+     excitation at delay k.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void Norm_Corr (Word16 exc[], Word16 xn[], Word16 h[], Word16 L_subfr,
+                       Word16 t_min, Word16 t_max, Word16 corr_norm[])
+{
+    Word16 i, j, k;
+    Word16 corr_h, corr_l, norm_h, norm_l;
+    Word32 s;
+
+    // Usally dynamic allocation of (L_subfr)
+    Word16 excf[L_SUBFR];
+    Word16 scaling, h_fac, *s_excf, scaled_excf[L_SUBFR];
+
+    k = -t_min;
+
+    // compute the filtered excitation for the first delay t_min
+
+    Convolve (&exc[k], h, excf, L_subfr);
+
+    // scale "excf[]" to avoid overflow
+
+    for (j = 0; j < L_subfr; j++) {
+        scaled_excf[j] = shr (excf[j], 2);
+    }
+
+    // Compute 1/sqrt(energy of excf[])
+
+    s = 0;
+    for (j = 0; j < L_subfr; j++) {
+        s = L_mac (s, excf[j], excf[j]);
+    }
+    if (L_sub (s, 67108864L) <= 0) {            // if (s <= 2^26)
+        s_excf = excf;
+        h_fac = 15 - 12;
+        scaling = 0;
+    }
+    else {
+        // "excf[]" is divided by 2
+        s_excf = scaled_excf;
+        h_fac = 15 - 12 - 2;
+        scaling = 2;
+    }
+
+    // loop for every possible period
+
+    for (i = t_min; i <= t_max; i++) {
+        // Compute 1/sqrt(energy of excf[])
+
+        s = 0;
+        for (j = 0; j < L_subfr; j++) {
+            s = L_mac (s, s_excf[j], s_excf[j]);
+        }
+
+        s = Inv_sqrt (s);
+        L_Extract (s, &norm_h, &norm_l);
+
+        // Compute correlation between xn[] and excf[]
+
+        s = 0;
+        for (j = 0; j < L_subfr; j++) {
+            s = L_mac (s, xn[j], s_excf[j]);
+        }
+        L_Extract (s, &corr_h, &corr_l);
+
+        // Normalize correlation = correlation * (1/sqrt(energy))
+
+        s = Mpy_32 (corr_h, corr_l, norm_h, norm_l);
+
+        corr_norm[i] = extract_h (L_shl (s, 16));
+
+            // modify the filtered excitation excf[] for the next iteration
+
+        if (sub (i, t_max) != 0) {
+            k--;
+            for (j = L_subfr - 1; j > 0; j--) {
+                s = L_mult (exc[k], h[j]);
+                s = L_shl (s, h_fac);
+                s_excf[j] = add (extract_h (s), s_excf[j - 1]);
+            }
+            s_excf[0] = shr (exc[k], scaling);
+        }
+    }
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void Norm_Corr(Word16 exc[],
+                      Word16 xn[],
+                      Word16 h[],
+                      Word16 L_subfr,
+                      Word16 t_min,
+                      Word16 t_max,
+                      Word16 corr_norm[],
+                      Flag *pOverflow)
+{
+    Word16 i;
+    Word16 j;
+    Word16 k;
+    Word16 corr_h;
+    Word16 corr_l;
+    Word16 norm_h;
+    Word16 norm_l;
+    Word32 s;
+    Word32 s2;
+    Word16 excf[L_SUBFR];
+    Word16 scaling;
+    Word16 h_fac;
+    Word16 *s_excf;
+    Word16 scaled_excf[L_SUBFR];
+    Word16 *p_s_excf;
+    Word16 *p_excf;
+    Word16  temp;
+    Word16 *p_x;
+    Word16 *p_h;
+
+    k = -t_min;
+
+    /* compute the filtered excitation for the first delay t_min */
+
+    Convolve(&exc[k], h, excf, L_subfr);
+
+    /* scale "excf[]" to avoid overflow */
+    s = 0;
+    p_s_excf = scaled_excf;
+    p_excf   = excf;
+
+    for (j = (L_subfr >> 1); j != 0; j--)
+    {
+        temp = *(p_excf++);
+        *(p_s_excf++) = temp >> 2;
+        s += (Word32) temp * temp;
+        temp = *(p_excf++);
+        *(p_s_excf++) = temp >> 2;
+        s += (Word32) temp * temp;
+    }
+
+
+    if (s <= (67108864L >> 1))
+    {
+        s_excf = excf;
+        h_fac = 12;
+        scaling = 0;
+    }
+    else
+    {
+        /* "excf[]" is divided by 2 */
+        s_excf = scaled_excf;
+        h_fac = 14;
+        scaling = 2;
+    }
+
+    /* loop for every possible period */
+
+    for (i = t_min; i <= t_max; i++)
+    {
+        /* Compute 1/sqrt(energy of excf[]) */
+
+        s   = s2 = 0;
+        p_x      = xn;
+        p_s_excf = s_excf;
+        j        = L_subfr >> 1;
+
+        while (j--)
+        {
+            s  += (Word32) * (p_x++) * *(p_s_excf);
+            s2 += ((Word32)(*(p_s_excf)) * (*(p_s_excf)));
+            p_s_excf++;
+            s  += (Word32) * (p_x++) * *(p_s_excf);
+            s2 += ((Word32)(*(p_s_excf)) * (*(p_s_excf)));
+            p_s_excf++;
+        }
+
+        s2     = s2 << 1;
+        s2     = Inv_sqrt(s2, pOverflow);
+        norm_h = (Word16)(s2 >> 16);
+        norm_l = (Word16)((s2 >> 1) - (norm_h << 15));
+        corr_h = (Word16)(s >> 15);
+        corr_l = (Word16)((s) - (corr_h << 15));
+
+        /* Normalize correlation = correlation * (1/sqrt(energy)) */
+
+        s = Mpy_32(corr_h, corr_l, norm_h, norm_l, pOverflow);
+
+        corr_norm[i] = (Word16) s ;
+
+        /* modify the filtered excitation excf[] for the next iteration */
+        if (i != t_max)
+        {
+            k--;
+            temp = exc[k];
+            p_s_excf = &s_excf[L_subfr - 1];
+            p_h = &h[L_subfr - 1];
+
+            p_excf = &s_excf[L_subfr - 2];
+            for (j = (L_subfr - 1) >> 1; j != 0; j--)
+            {
+                s = ((Word32) temp * *(p_h--)) >> h_fac;
+                *(p_s_excf--) = (Word16) s  + *(p_excf--);
+                s = ((Word32) temp * *(p_h--)) >> h_fac;
+                *(p_s_excf--) = (Word16) s  + *(p_excf--);
+            }
+
+            s = ((Word32) temp * *(p_h)) >> h_fac;
+            *(p_s_excf--) = (Word16) s  + *(p_excf);
+
+            *(p_s_excf) = temp >> scaling;
+        }
+
+    }
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: searchFrac
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lag = pointer to integer pitch of type Word16
+    frac = pointer to starting point of search fractional pitch of type Word16
+    last_frac = endpoint of search  of type Word16
+    corr[] = pointer to normalized correlation of type Word16
+    flag3 = subsample resolution (3: =1 / 6: =0) of type Word16
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   FUNCTION:   searchFrac()
+
+   PURPOSE: Find fractional pitch
+
+   DESCRIPTION:
+      The function interpolates the normalized correlation at the
+      fractional positions around lag T0. The position at which the
+      interpolation function reaches its maximum is the fractional pitch.
+      Starting point of the search is frac, end point is last_frac.
+      frac is overwritten with the fractional pitch.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void searchFrac (
+    Word16 *lag,       // i/o : integer pitch
+    Word16 *frac,      // i/o : start point of search -
+                               fractional pitch
+    Word16 last_frac,  // i   : endpoint of search
+    Word16 corr[],     // i   : normalized correlation
+    Word16 flag3       // i   : subsample resolution
+                                (3: =1 / 6: =0)
+)
+{
+    Word16 i;
+    Word16 max;
+    Word16 corr_int;
+
+    // Test the fractions around T0 and choose the one which maximizes
+    // the interpolated normalized correlation.
+
+    max = Interpol_3or6 (&corr[*lag], *frac, flag3); // function result
+
+    for (i = add (*frac, 1); i <= last_frac; i++) {
+        corr_int = Interpol_3or6 (&corr[*lag], i, flag3);
+        if (sub (corr_int, max) > 0) {
+            max = corr_int;
+            *frac = i;
+        }
+    }
+
+    if (flag3 == 0) {
+        // Limit the fraction value in the interval [-2,-1,0,1,2,3]
+
+        if (sub (*frac, -3) == 0) {
+            *frac = 3;
+            *lag = sub (*lag, 1);
+        }
+    }
+    else {
+        // limit the fraction value between -1 and 1
+
+        if (sub (*frac, -2) == 0) {
+            *frac = 1;
+            *lag = sub (*lag, 1);
+        }
+        if (sub (*frac, 2) == 0) {
+            *frac = -1;
+            *lag = add (*lag, 1);
+        }
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void searchFrac(
+    Word16 *lag,       /* i/o : integer pitch           */
+    Word16 *frac,      /* i/o : start point of search -
+                                fractional pitch        */
+    Word16 last_frac,  /* i   : endpoint of search      */
+    Word16 corr[],     /* i   : normalized correlation  */
+    Word16 flag3,      /* i   : subsample resolution
+                                (3: =1 / 6: =0)         */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 max;
+    Word16 corr_int;
+
+    /* Test the fractions around T0 and choose the one which maximizes   */
+    /* the interpolated normalized correlation.                          */
+
+    max = Interpol_3or6(&corr[*lag], *frac, flag3, pOverflow);
+    /* function result */
+
+    for (i = *frac + 1; i <= last_frac; i++)
+    {
+        corr_int = Interpol_3or6(&corr[*lag], i, flag3, pOverflow);
+        if (corr_int > max)
+        {
+            max = corr_int;
+            *frac = i;
+        }
+    }
+
+    if (flag3 == 0)
+    {
+        /* Limit the fraction value in the interval [-2,-1,0,1,2,3] */
+
+        if (*frac == -3)
+        {
+            *frac = 3;
+            (*lag)--;
+        }
+    }
+    else
+    {
+        /* limit the fraction value between -1 and 1 */
+
+        if (*frac == -2)
+        {
+            *frac = 1;
+            (*lag)--;
+        }
+        if (*frac == 2)
+        {
+            *frac = -1;
+            (*lag)++;
+        }
+    }
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: getRange
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    T0 = integer pitch of type Word16
+    delta_low = search start offset of type Word16
+    delta_range = search range of type Word16
+    pitmin = minimum pitch of type Word16
+    pitmax = maximum pitch of type Word16
+    t0_min = search range minimum of type Word16
+    t0_max = search range maximum of type Word16
+
+ Outputs:
+    pOverflow = 1 if the math functions called result in overflow else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   FUNCTION:   getRange()
+
+   PURPOSE: Sets range around open-loop pitch or integer pitch of last subframe
+
+   DESCRIPTION:
+      Takes integer pitch T0 and calculates a range around it with
+        t0_min = T0-delta_low  and t0_max = (T0-delta_low) + delta_range
+      t0_min and t0_max are bounded by pitmin and pitmax
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void getRange (
+    Word16 T0,           // i : integer pitch
+    Word16 delta_low,    // i : search start offset
+    Word16 delta_range,  // i : search range
+    Word16 pitmin,       // i : minimum pitch
+    Word16 pitmax,       // i : maximum pitch
+    Word16 *t0_min,      // o : search range minimum
+    Word16 *t0_max)      // o : search range maximum
+{
+    *t0_min = sub(T0, delta_low);
+    if (sub(*t0_min, pitmin) < 0) {
+        *t0_min = pitmin;
+    }
+    *t0_max = add(*t0_min, delta_range);
+    if (sub(*t0_max, pitmax) > 0) {
+        *t0_max = pitmax;
+        *t0_min = sub(*t0_max, delta_range);
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+static void getRange(
+    Word16 T0,           /* i : integer pitch          */
+    Word16 delta_low,    /* i : search start offset    */
+    Word16 delta_range,  /* i : search range           */
+    Word16 pitmin,       /* i : minimum pitch          */
+    Word16 pitmax,       /* i : maximum pitch          */
+    Word16 *t0_min,      /* o : search range minimum   */
+    Word16 *t0_max,      /* o : search range maximum   */
+    Flag   *pOverflow)
+{
+
+    Word16 temp;
+    OSCL_UNUSED_ARG(pOverflow);
+
+    temp = *t0_min;
+    temp = T0 - delta_low;
+    if (temp < pitmin)
+    {
+        temp = pitmin;
+    }
+    *t0_min = temp;
+
+    temp +=  delta_range;
+    if (temp > pitmax)
+    {
+        temp = pitmax;
+        *t0_min = pitmax - delta_range;
+    }
+    *t0_max = temp;
+
+}
+
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_fr_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer of structure type Pitch_fr_State.
+
+ Outputs:
+    None
+
+ Returns:
+    Returns a zero if successful and -1 if not successful.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   Pitch_fr_init
+  Purpose:    Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Pitch_fr_init (Pitch_frState **state)
+{
+    Pitch_frState* s;
+
+    if (state == (Pitch_frState **) NULL){
+        // fprintf(stderr, "Pitch_fr_init: invalid parameter\n");
+        return -1;
+    }
+    *state = NULL;
+
+    // allocate memory
+    if ((s= (Pitch_frState *) malloc(sizeof(Pitch_frState))) == NULL){
+        // fprintf(stderr, "Pitch_fr_init: can not malloc state structure\n");
+        return -1;
+    }
+
+    Pitch_fr_reset(s);
+    *state = s;
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 Pitch_fr_init(Pitch_frState **state)
+{
+    Pitch_frState* s;
+
+    if (state == (Pitch_frState **) NULL)
+    {
+        /* fprintf(stderr, "Pitch_fr_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (Pitch_frState *) malloc(sizeof(Pitch_frState))) == NULL)
+    {
+        /* fprintf(stderr, "Pitch_fr_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    Pitch_fr_reset(s);
+    *state = s;
+
+    return 0;
+}
+
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_fr_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer of structure type Pitch_fr_State.
+
+ Outputs:
+    None
+
+ Returns:
+    Returns a zero if successful and -1 if not successful.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   Pitch_fr_reset
+  Purpose:    Initializes state memory to zero
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Pitch_fr_reset (Pitch_frState *state)
+{
+
+    if (state == (Pitch_frState *) NULL){
+        // fprintf(stderr, "Pitch_fr_reset: invalid parameter\n");
+        return -1;
+    }
+
+    state->T0_prev_subframe = 0;
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 Pitch_fr_reset(Pitch_frState *state)
+{
+
+    if (state == (Pitch_frState *) NULL)
+    {
+        /* fprintf(stderr, "Pitch_fr_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    state->T0_prev_subframe = 0;
+
+    return 0;
+}
+
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_fr_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer of structure type Pitch_fr_State.
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   Pitch_fr_exit
+  Purpose:    The memory for state is freed.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Pitch_fr_exit (Pitch_frState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    // deallocate memory
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void Pitch_fr_exit(Pitch_frState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_fr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to stat structure of type Pitch_frState
+    mode = codec mode of type enum Mode
+    T_op[] = pointer to open loop pitch lags of type Word16
+    exc[] = pointer to excitation buffer of type Word16
+    xn[] = pointer to target vector of type Word16
+    h[] = pointer to impulse response of synthesis and weighting filters
+          of type Word16
+    L_subfr = length of subframe of type Word16
+    i_subfr = subframe offset of type Word16
+
+ Outputs:
+    pit_frac = pointer to pitch period (fractional) of type Word16
+    resu3 = pointer to subsample resolution of type Word16
+    ana_index = pointer to index of encoding of type Word16
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   FUNCTION:   Pitch_fr()
+
+   PURPOSE: Find the pitch period with 1/3 or 1/6 subsample resolution
+            (closed loop).
+
+   DESCRIPTION:
+         - find the normalized correlation between the target and filtered
+           past excitation in the search range.
+         - select the delay with maximum normalized correlation.
+         - interpolate the normalized correlation at fractions -3/6 to 3/6
+           with step 1/6 around the chosen delay.
+         - The fraction which gives the maximum interpolated value is chosen.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_fr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Pitch_fr (        // o   : pitch period (integer)
+    Pitch_frState *st,   // i/o : State struct
+    enum Mode mode,      // i   : codec mode
+    Word16 T_op[],       // i   : open loop pitch lags
+    Word16 exc[],        // i   : excitation buffer                      Q0
+    Word16 xn[],         // i   : target vector                          Q0
+    Word16 h[],          // i   : impulse response of synthesis and
+                                  weighting filters                     Q12
+    Word16 L_subfr,      // i   : Length of subframe
+    Word16 i_subfr,      // i   : subframe offset
+    Word16 *pit_frac,    // o   : pitch period (fractional)
+    Word16 *resu3,       // o   : subsample resolution 1/3 (=1) or 1/6 (=0)
+    Word16 *ana_index    // o   : index of encoding
+)
+{
+    Word16 i;
+    Word16 t_min, t_max;
+    Word16 t0_min, t0_max;
+    Word16 max, lag, frac;
+    Word16 tmp_lag;
+    Word16 *corr;
+    Word16 corr_v[40];    // Total length = t0_max-t0_min+1+2*L_INTER_SRCH
+
+    Word16 max_frac_lag;
+    Word16 flag3, flag4;
+    Word16 last_frac;
+    Word16 delta_int_low, delta_int_range;
+    Word16 delta_frc_low, delta_frc_range;
+    Word16 pit_min;
+    Word16 frame_offset;
+    Word16 delta_search;
+
+    //-----------------------------------------------------------------------
+     //                      set mode specific variables
+     //----------------------------------------------------------------------
+
+    max_frac_lag    = mode_dep_parm[mode].max_frac_lag;
+    flag3           = mode_dep_parm[mode].flag3;
+    frac            = mode_dep_parm[mode].first_frac;
+    last_frac       = mode_dep_parm[mode].last_frac;
+    delta_int_low   = mode_dep_parm[mode].delta_int_low;
+    delta_int_range = mode_dep_parm[mode].delta_int_range;
+
+    delta_frc_low   = mode_dep_parm[mode].delta_frc_low;
+    delta_frc_range = mode_dep_parm[mode].delta_frc_range;
+    pit_min         = mode_dep_parm[mode].pit_min;
+
+    //-----------------------------------------------------------------------
+    //                 decide upon full or differential search
+    //-----------------------------------------------------------------------
+
+    delta_search = 1;
+
+    if ((i_subfr == 0) || (sub(i_subfr,L_FRAME_BY2) == 0)) {
+
+        // Subframe 1 and 3
+
+        if (((sub((Word16)mode, (Word16)MR475) != 0) && (sub((Word16)mode,
+            (Word16)MR515) != 0)) ||
+            (sub(i_subfr,L_FRAME_BY2) != 0)) {
+
+            // set t0_min, t0_max for full search
+            // this is *not* done for mode MR475, MR515 in subframe 3
+
+            delta_search = 0; // no differential search
+
+            // calculate index into T_op which contains the open-loop
+            // pitch estimations for the 2 big subframes
+
+            frame_offset = 1;
+            if (i_subfr == 0)
+                frame_offset = 0;
+
+            // get T_op from the corresponding half frame and
+            // set t0_min, t0_max
+
+            getRange (T_op[frame_offset], delta_int_low, delta_int_range,
+                      pit_min, PIT_MAX, &t0_min, &t0_max);
+        }
+        else {
+
+            // mode MR475, MR515 and 3. Subframe: delta search as well
+            getRange (st->T0_prev_subframe, delta_frc_low, delta_frc_range,
+                      pit_min, PIT_MAX, &t0_min, &t0_max);
+        }
+    }
+    else {
+
+        // for Subframe 2 and 4
+        // get range around T0 of previous subframe for delta search
+
+        getRange (st->T0_prev_subframe, delta_frc_low, delta_frc_range,
+                  pit_min, PIT_MAX, &t0_min, &t0_max);
+    }
+
+    //-----------------------------------------------------------------------
+                Find interval to compute normalized correlation
+     -----------------------------------------------------------------------
+
+    t_min = sub (t0_min, L_INTER_SRCH);
+    t_max = add (t0_max, L_INTER_SRCH);
+
+    corr = &corr_v[-t_min];
+
+    //-----------------------------------------------------------------------
+      Compute normalized correlation between target and filtered excitation
+     -----------------------------------------------------------------------
+
+    Norm_Corr (exc, xn, h, L_subfr, t_min, t_max, corr);
+
+    //-----------------------------------------------------------------------
+                                Find integer pitch
+     -----------------------------------------------------------------------
+
+    max = corr[t0_min];
+    lag = t0_min;
+
+    for (i = t0_min + 1; i <= t0_max; i++) {
+        if (sub (corr[i], max) >= 0) {
+            max = corr[i];
+            lag = i;
+        }
+    }
+
+    //-----------------------------------------------------------------------
+                             Find fractional pitch
+     -----------------------------------------------------------------------
+    if ((delta_search == 0) && (sub (lag, max_frac_lag) > 0)) {
+
+        // full search and integer pitch greater than max_frac_lag
+        // fractional search is not needed, set fractional to zero
+
+        frac = 0;
+    }
+    else {
+
+        // if differential search AND mode MR475 OR MR515 OR MR59 OR MR67
+        // then search fractional with 4 bits resolution
+
+       if ((delta_search != 0) &&
+           ((sub ((Word16)mode, (Word16)MR475) == 0) ||
+            (sub ((Word16)mode, (Word16)MR515) == 0) ||
+            (sub ((Word16)mode, (Word16)MR59) == 0) ||
+            (sub ((Word16)mode, (Word16)MR67) == 0))) {
+
+          // modify frac or last_frac according to position of last
+          // integer pitch: either search around integer pitch,
+          // or only on left or right side
+
+          tmp_lag = st->T0_prev_subframe;
+          if ( sub( sub(tmp_lag, t0_min), 5) > 0)
+             tmp_lag = add (t0_min, 5);
+          if ( sub( sub(t0_max, tmp_lag), 4) > 0)
+               tmp_lag = sub (t0_max, 4);
+
+          if ((sub (lag, tmp_lag) == 0) ||
+              (sub (lag, sub(tmp_lag, 1)) == 0)) {
+
+             // normal search in fractions around T0
+
+             searchFrac (&lag, &frac, last_frac, corr, flag3);
+
+          }
+          else if (sub (lag, sub (tmp_lag, 2)) == 0) {
+             // limit search around T0 to the right side
+             frac = 0;
+             searchFrac (&lag, &frac, last_frac, corr, flag3);
+          }
+          else if (sub (lag, add(tmp_lag, 1)) == 0) {
+             // limit search around T0 to the left side
+             last_frac = 0;
+             searchFrac (&lag, &frac, last_frac, corr, flag3);
+          }
+          else {
+             // no fractional search
+             frac = 0;
+            }
+       }
+       else
+          // test the fractions around T0
+          searchFrac (&lag, &frac, last_frac, corr, flag3);
+    }
+
+    //-----------------------------------------------------------------------
+     //                           encode pitch
+     //-----------------------------------------------------------------------
+
+    if (flag3 != 0) {
+       // flag4 indicates encoding with 4 bit resolution;
+       // this is needed for mode MR475, MR515 and MR59
+
+       flag4 = 0;
+       if ( (sub ((Word16)mode, (Word16)MR475) == 0) ||
+            (sub ((Word16)mode, (Word16)MR515) == 0) ||
+            (sub ((Word16)mode, (Word16)MR59) == 0) ||
+            (sub ((Word16)mode, (Word16)MR67) == 0) ) {
+          flag4 = 1;
+       }
+
+       // encode with 1/3 subsample resolution
+
+       *ana_index = Enc_lag3(lag, frac, st->T0_prev_subframe,
+                             t0_min, t0_max, delta_search, flag4);
+       // function result
+
+    }
+    else
+    {
+       // encode with 1/6 subsample resolution
+
+       *ana_index = Enc_lag6(lag, frac, t0_min, delta_search);
+       // function result
+    }
+
+     //-----------------------------------------------------------------------
+     //                          update state variables
+     //-----------------------------------------------------------------------
+
+    st->T0_prev_subframe = lag;
+
+     //-----------------------------------------------------------------------
+     //                      update output variables
+     //-----------------------------------------------------------------------
+
+    *resu3    = flag3;
+
+    *pit_frac = frac;
+
+    return (lag);
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 Pitch_fr(         /* o   : pitch period (integer)                    */
+    Pitch_frState *st,   /* i/o : State struct                              */
+    enum Mode mode,      /* i   : codec mode                                */
+    Word16 T_op[],       /* i   : open loop pitch lags                      */
+    Word16 exc[],        /* i   : excitation buffer                      Q0 */
+    Word16 xn[],         /* i   : target vector                          Q0 */
+    Word16 h[],          /* i   : impulse response of synthesis and
+                                  weighting filters                     Q12 */
+    Word16 L_subfr,      /* i   : Length of subframe                        */
+    Word16 i_subfr,      /* i   : subframe offset                           */
+    Word16 *pit_frac,    /* o   : pitch period (fractional)                 */
+    Word16 *resu3,       /* o   : subsample resolution 1/3 (=1) or 1/6 (=0) */
+    Word16 *ana_index,   /* o   : index of encoding                         */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 t_min;
+    Word16 t_max;
+    Word16 t0_min = 0;
+    Word16 t0_max;
+    Word16 max;
+    Word16 lag;
+    Word16 frac;
+    Word16 tmp_lag;
+    Word16 *corr;
+    Word16 corr_v[40];    /* Total length = t0_max-t0_min+1+2*L_INTER_SRCH */
+
+    Word16 max_frac_lag;
+    Word16 flag3;
+    Word16 flag4;
+    Word16 last_frac;
+    Word16 delta_int_low;
+    Word16 delta_int_range;
+    Word16 delta_frc_low;
+    Word16 delta_frc_range;
+    Word16 pit_min;
+    Word16 frame_offset;
+    Word16 delta_search;
+
+    /*-----------------------------------------------------------------------*
+     *                      set mode specific variables                      *
+     *-----------------------------------------------------------------------*/
+
+    max_frac_lag    = mode_dep_parm[mode].max_frac_lag;
+    flag3           = mode_dep_parm[mode].flag3;
+    frac            = mode_dep_parm[mode].first_frac;
+    last_frac       = mode_dep_parm[mode].last_frac;
+    delta_int_low   = mode_dep_parm[mode].delta_int_low;
+    delta_int_range = mode_dep_parm[mode].delta_int_range;
+
+    delta_frc_low   = mode_dep_parm[mode].delta_frc_low;
+    delta_frc_range = mode_dep_parm[mode].delta_frc_range;
+    pit_min         = mode_dep_parm[mode].pit_min;
+
+    /*-----------------------------------------------------------------------*
+     *                 decide upon full or differential search               *
+     *-----------------------------------------------------------------------*/
+
+    delta_search = 1;
+
+    if ((i_subfr == 0) || (i_subfr == L_FRAME_BY2))
+    {
+
+        /* Subframe 1 and 3 */
+
+        if (((mode != MR475) && (mode != MR515)) || (i_subfr != L_FRAME_BY2))
+        {
+
+            /* set t0_min, t0_max for full search */
+            /* this is *not* done for mode MR475, MR515 in subframe 3 */
+
+            delta_search = 0; /* no differential search */
+
+            /* calculate index into T_op which contains the open-loop */
+            /* pitch estimations for the 2 big subframes */
+
+            frame_offset = 1;
+            if (i_subfr == 0)
+                frame_offset = 0;
+
+            /* get T_op from the corresponding half frame and */
+            /* set t0_min, t0_max */
+
+            getRange(T_op[frame_offset], delta_int_low, delta_int_range,
+                     pit_min, PIT_MAX, &t0_min, &t0_max, pOverflow);
+        }
+        else
+        {
+
+            /* mode MR475, MR515 and 3. Subframe: delta search as well */
+            getRange(st->T0_prev_subframe, delta_frc_low, delta_frc_range,
+                     pit_min, PIT_MAX, &t0_min, &t0_max, pOverflow);
+        }
+    }
+    else
+    {
+
+        /* for Subframe 2 and 4 */
+        /* get range around T0 of previous subframe for delta search */
+
+        getRange(st->T0_prev_subframe, delta_frc_low, delta_frc_range,
+                 pit_min, PIT_MAX, &t0_min, &t0_max, pOverflow);
+    }
+
+    /*-----------------------------------------------------------------------*
+     *           Find interval to compute normalized correlation             *
+     *-----------------------------------------------------------------------*/
+
+    t_min = sub(t0_min, L_INTER_SRCH, pOverflow);
+    t_max = add(t0_max, L_INTER_SRCH, pOverflow);
+
+    corr = &corr_v[-t_min];
+
+    /*-----------------------------------------------------------------------*
+     * Compute normalized correlation between target and filtered excitation *
+     *-----------------------------------------------------------------------*/
+
+    Norm_Corr(exc, xn, h, L_subfr, t_min, t_max, corr, pOverflow);
+
+    /*-----------------------------------------------------------------------*
+     *                           Find integer pitch                          *
+     *-----------------------------------------------------------------------*/
+
+    max = corr[t0_min];
+    lag = t0_min;
+
+    for (i = t0_min + 1; i <= t0_max; i++)
+    {
+        if (corr[i] >= max)
+        {
+            max = corr[i];
+            lag = i;
+        }
+    }
+
+    /*-----------------------------------------------------------------------*
+     *                        Find fractional pitch                          *
+     *-----------------------------------------------------------------------*/
+    if ((delta_search == 0) && (lag > max_frac_lag))
+    {
+
+        /* full search and integer pitch greater than max_frac_lag */
+        /* fractional search is not needed, set fractional to zero */
+
+        frac = 0;
+    }
+    else
+    {
+
+        /* if differential search AND mode MR475 OR MR515 OR MR59 OR MR67   */
+        /* then search fractional with 4 bits resolution           */
+
+        if ((delta_search != 0) &&
+                ((mode == MR475) || (mode == MR515) ||
+                 (mode == MR59) || (mode == MR67)))
+        {
+
+            /* modify frac or last_frac according to position of last */
+            /* integer pitch: either search around integer pitch, */
+            /* or only on left or right side */
+
+            tmp_lag = st->T0_prev_subframe;
+            if (sub(sub(tmp_lag, t0_min, pOverflow), 5, pOverflow) > 0)
+                tmp_lag = add(t0_min, 5, pOverflow);
+            if (sub(sub(t0_max, tmp_lag, pOverflow), 4, pOverflow) > 0)
+                tmp_lag = sub(t0_max, 4, pOverflow);
+
+            if ((lag == tmp_lag) || (lag == (tmp_lag - 1)))
+            {
+
+                /* normal search in fractions around T0 */
+
+                searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow);
+
+            }
+            else if (lag == (tmp_lag - 2))
+            {
+                /* limit search around T0 to the right side */
+                frac = 0;
+                searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow);
+            }
+            else if (lag == (tmp_lag + 1))
+            {
+                /* limit search around T0 to the left side */
+                last_frac = 0;
+                searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow);
+            }
+            else
+            {
+                /* no fractional search */
+                frac = 0;
+            }
+        }
+        else
+            /* test the fractions around T0 */
+            searchFrac(&lag, &frac, last_frac, corr, flag3, pOverflow);
+    }
+
+    /*-----------------------------------------------------------------------*
+     *                           encode pitch                                *
+     *-----------------------------------------------------------------------*/
+
+    if (flag3 != 0)
+    {
+        /* flag4 indicates encoding with 4 bit resolution;         */
+        /* this is needed for mode MR475, MR515 and MR59           */
+
+        flag4 = 0;
+        if ((mode == MR475) || (mode == MR515) ||
+                (mode == MR59) || (mode == MR67))
+        {
+            flag4 = 1;
+        }
+
+        /* encode with 1/3 subsample resolution */
+
+        *ana_index = Enc_lag3(lag, frac, st->T0_prev_subframe,
+                              t0_min, t0_max, delta_search, flag4, pOverflow);
+        /* function result */
+
+    }
+    else
+    {
+        /* encode with 1/6 subsample resolution */
+
+        *ana_index = Enc_lag6(lag, frac, t0_min, delta_search, pOverflow);
+        /* function result */
+    }
+
+    /*-----------------------------------------------------------------------*
+     *                          update state variables                       *
+     *-----------------------------------------------------------------------*/
+
+    st->T0_prev_subframe = lag;
+
+    /*-----------------------------------------------------------------------*
+     *                      update output variables                          *
+     *-----------------------------------------------------------------------*/
+
+    *resu3    = flag3;
+
+    *pit_frac = frac;
+
+    return (lag);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.h b/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.h
new file mode 100644
index 0000000..5e87cc9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pitch_fr.h
@@ -0,0 +1,148 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/pitch_fr.h
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : pitch_fr.h
+      Purpose          : Find the pitch period with 1/3 or 1/6 subsample
+                       : resolution (closed loop).
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _PITCH_FR_H_
+#define _PITCH_FR_H_
+#define pitch_fr_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 T0_prev_subframe;   /* integer pitch lag of previous sub-frame */
+    } Pitch_frState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    Word16 Pitch_fr_init(Pitch_frState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Pitch_fr in each call.
+       returns 0 on success
+     */
+
+    Word16 Pitch_fr_reset(Pitch_frState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void Pitch_fr_exit(Pitch_frState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    Word16 Pitch_fr(         /* o   : pitch period (integer)                    */
+        Pitch_frState *st,   /* i/o : State struct                              */
+        enum Mode mode,      /* i   : codec mode                                */
+        Word16 T_op[],       /* i   : open loop pitch lags                      */
+        Word16 exc[],        /* i   : excitation buffer                         */
+        Word16 xn[],         /* i   : target vector                             */
+        Word16 h[],          /* i   : impulse response of synthesis and
+                                  weighting filters                         */
+        Word16 L_subfr,      /* i   : Length of subframe                        */
+        Word16 i_subfr,      /* i   : subframe offset                           */
+        Word16 *pit_frac,    /* o   : pitch period (fractional)                 */
+        Word16 *resu3,       /* o   : subsample resolution 1/3 (=1) or 1/6 (=0) */
+        Word16 *ana_index,   /* o   : index of encoding                         */
+        Flag   *pOverflow
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _PITCH_FR_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.cpp b/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.cpp
new file mode 100644
index 0000000..d3a2ec0
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.cpp
@@ -0,0 +1,1213 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/pitch_ol.c
+ Funtions: Pitch_ol
+           Lag_max
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ The modules in this file compute the open loop pitch lag.
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "pitch_ol.h"
+#include "typedef.h"
+#include "basicop_malloc.h"
+#include "cnst.h"
+#include "inv_sqrt.h"
+#include "vad.h"
+#include "calc_cor.h"
+#include "hp_max.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define THRESHOLD 27853
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lag_max
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS (If VAD2 is defined)
+
+ Inputs
+    corr = pointer to buffer of correlation values (Word32)
+    scal_sig = pointer to buffer of scaled signal values (Word16)
+    scal_fac = scaled signal factor (Word16)
+    scal_flag = EFR compatible scaling flag (Word16)
+    L_frame = length of frame to compute pitch (Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_max = pointer to the normalized correlation of selected lag (Word16)
+    rmax = pointer to max(<s[i]*s[j]>), (Word32)
+    r0 = pointer to the residual energy (Word32)
+    dtx  = dtx flag; equal to 1, if dtx is enabled, 0, otherwise (Flag)
+
+ Outputs:
+    cor_max contains the newly calculated normalized correlation of the
+      selected lag
+    rmax contains the newly calculated max(<s[i]*s[j]>)
+    r0 contains the newly calculated residual energy
+
+ Returns:
+    p_max = lag of the max correlation found (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS (If VAD2 is not defined)
+
+ Inputs
+    vadSt = pointer to a vadState structure
+    corr = pointer to buffer of correlation values (Word32)
+    scal_sig = pointer to buffer of scaled signal values (Word16)
+    scal_fac = scaled signal factor (Word16)
+    scal_flag = EFR compatible scaling flag (Word16)
+    L_frame = length of frame to compute pitch (Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_max = pointer to the normalized correlation of selected lag (Word16)
+    dtx  = dtx flag; equal to 1, if dtx is enabled, 0, otherwise (Flag)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    cor_max contains the newly calculated normalized correlation of the
+      selected lag
+    vadSt contains the updated VAD state parameters
+    pOverflow -> 1 if the math operations called by this routine saturate
+
+ Returns:
+    p_max = lag of the max correlation found (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Find the lag that has maximum correlation of scal_sig in a given delay range.
+ The correlation is given by:
+
+         cor[t] = <scal_sig[n],scal_sig[n-t]>,  t=lag_min,...,lag_max
+
+ The function returns the maximum correlation after normalization and the
+ corresponding lag.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_ol.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+#ifdef VAD2
+static Word16 Lag_max ( // o   : lag found
+    Word32 corr[],      // i   : correlation vector.
+    Word16 scal_sig[],  // i   : scaled signal.
+    Word16 scal_fac,    // i   : scaled signal factor.
+    Word16 scal_flag,   // i   : if 1 use EFR compatible scaling
+    Word16 L_frame,     // i   : length of frame to compute pitch
+    Word16 lag_max,     // i   : maximum lag
+    Word16 lag_min,     // i   : minimum lag
+    Word16 *cor_max,    // o   : normalized correlation of selected lag
+    Word32 *rmax,       // o   : max(<s[i]*s[j]>)
+    Word32 *r0,         // o   : residual energy
+    Flag dtx            // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+#else
+static Word16 Lag_max ( // o   : lag found
+    vadState *vadSt,    // i/o : VAD state struct
+    Word32 corr[],      // i   : correlation vector.
+    Word16 scal_sig[],  // i   : scaled signal.
+    Word16 scal_fac,    // i   : scaled signal factor.
+    Word16 scal_flag,   // i   : if 1 use EFR compatible scaling
+    Word16 L_frame,     // i   : length of frame to compute pitch
+    Word16 lag_max,     // i   : maximum lag
+    Word16 lag_min,     // i   : minimum lag
+    Word16 *cor_max,    // o   : normalized correlation of selected lag
+    Flag dtx            // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+#endif
+{
+    Word16 i, j;
+    Word16 *p;
+    Word32 max, t0;
+    Word16 max_h, max_l, ener_h, ener_l;
+    Word16 p_max = 0; // initialization only needed to keep gcc silent
+
+    max = MIN_32;
+    p_max = lag_max;
+
+    for (i = lag_max, j = (PIT_MAX-lag_max-1); i >= lag_min; i--, j--)
+    {
+       if (L_sub (corr[-i], max) >= 0)
+       {
+          max = corr[-i];
+          p_max = i;
+       }
+    }
+
+    // compute energy
+
+    t0 = 0;
+    p = &scal_sig[-p_max];
+    for (i = 0; i < L_frame; i++, p++)
+    {
+        t0 = L_mac (t0, *p, *p);
+    }
+    // 1/sqrt(energy)
+
+    if (dtx)
+    {  // no test() call since this if is only in simulation env
+#ifdef VAD2
+       *rmax = max;
+       *r0 = t0;
+#else
+       // check tone
+       vad_tone_detection (vadSt, max, t0);
+#endif
+    }
+
+    t0 = Inv_sqrt (t0);
+
+    if (scal_flag)
+    {
+       t0 = L_shl (t0, 1);
+    }
+
+    // max = max/sqrt(energy)
+
+    L_Extract (max, &max_h, &max_l);
+    L_Extract (t0, &ener_h, &ener_l);
+
+    t0 = Mpy_32 (max_h, max_l, ener_h, ener_l);
+
+    if (scal_flag)
+    {
+      t0 = L_shr (t0, scal_fac);
+      *cor_max = extract_h (L_shl (t0, 15)); // divide by 2
+    }
+    else
+    {
+      *cor_max = extract_l(t0);
+    }
+
+    return (p_max);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+#ifdef VAD2
+static Word16 Lag_max(  /* o   : lag found                               */
+    Word32 corr[],      /* i   : correlation vector.                     */
+    Word16 scal_sig[],  /* i   : scaled signal.                          */
+    Word16 scal_fac,    /* i   : scaled signal factor.                   */
+    Word16 scal_flag,   /* i   : if 1 use EFR compatible scaling         */
+    Word16 L_frame,     /* i   : length of frame to compute pitch        */
+    Word16 lag_max,     /* i   : maximum lag                             */
+    Word16 lag_min,     /* i   : minimum lag                             */
+    Word16 *cor_max,    /* o   : normalized correlation of selected lag  */
+    Word32 *rmax,       /* o   : max(<s[i]*s[j]>)                        */
+    Word32 *r0,         /* o   : residual energy                         */
+    Flag dtx,           /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag *pOverflow     /* i/o : overflow Flag                           */
+)
+#else
+static Word16 Lag_max(  /* o   : lag found                               */
+    vadState *vadSt,    /* i/o : VAD state struct                        */
+    Word32 corr[],      /* i   : correlation vector.                     */
+    Word16 scal_sig[],  /* i   : scaled signal.                          */
+    Word16 scal_fac,    /* i   : scaled signal factor.                   */
+    Word16 scal_flag,   /* i   : if 1 use EFR compatible scaling         */
+    Word16 L_frame,     /* i   : length of frame to compute pitch        */
+    Word16 lag_max,     /* i   : maximum lag                             */
+    Word16 lag_min,     /* i   : minimum lag                             */
+    Word16 *cor_max,    /* o   : normalized correlation of selected lag  */
+    Flag dtx,           /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag *pOverflow     /* i/o : overflow Flag                           */
+)
+#endif
+{
+    register Word16 i;
+    Word16 *p;
+    Word32 max;
+    Word32 t0;
+    Word16 max_h;
+    Word16 max_l;
+    Word16 ener_h;
+    Word16 ener_l;
+    Word16 p_max = 0; /* initialization only needed to keep gcc silent */
+    Word32 L_temp;
+    Word32 L_temp_2;
+    Word32 L_temp_3;
+    Word32  *p_corr = &corr[-lag_max];
+
+    max = MIN_32;
+    p_max = lag_max;
+
+    for (i = lag_max; i >= lag_min; i--)
+    {
+        /* The negative array index is equivalent to a negative */
+        /* address offset, i.e., corr[-i] == *(corr - i)        */
+        if (*(p_corr++) >= max)
+        {
+            p_corr--;
+            max = *(p_corr++);
+            p_max = i;
+        }
+    }
+
+    /* compute energy */
+
+    t0 = 0;
+
+    /* The negative array index is equivalent to a negative          */
+    /* address offset, i.e., scal_sig[-p_max] == *(scal_sig - p_max) */
+    p = &scal_sig[-p_max];
+    for (i = (L_frame >> 2); i != 0; i--)
+    {
+        t0 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p), t0);
+        p++;
+        t0 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p), t0);
+        p++;
+        t0 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p), t0);
+        p++;
+        t0 = amrnb_fxp_mac_16_by_16bb((Word32) * (p), (Word32) * (p), t0);
+        p++;
+    }
+
+    t0 <<= 1;
+    /* 1/sqrt(energy) */
+
+    if (dtx)
+    {  /* no test() call since this if is only in simulation env */
+        /* check tone */
+#ifdef VAD2
+        *rmax = max;
+        *r0 = t0;
+#else
+        /* check tone */
+        vad_tone_detection(vadSt, max, t0, pOverflow);
+#endif
+    }
+
+    t0 = Inv_sqrt(t0, pOverflow);
+
+    if (scal_flag)
+    {
+        if (t0 > (Word32) 0x3fffffffL)
+        {
+            t0 = MAX_32;
+        }
+        else
+        {
+            t0 = t0 << 1;
+        }
+    }
+
+    /* max = max/sqrt(energy)  */
+    /* The following code is an inlined version of */
+    /* L_Extract (max, &max_h, &max_l), i.e.       */
+    /*                                             */
+    /* *max_h = extract_h (max);                   */
+    max_h = (Word16)(max >> 16);
+
+    /* L_temp_2 = L_shr(max,1), which is used in      */
+    /* the calculation of *max_l (see next operation) */
+    L_temp_2 = max >> 1;
+
+    /* *max_l = extract_l (L_msu (L_shr (max, 1), *max_h, 16384)); */
+    L_temp_3 = (Word32)(max_h << 15);
+
+    L_temp = L_temp_2 - L_temp_3;
+
+    max_l = (Word16)L_temp;
+
+    /* The following code is an inlined version of */
+    /* L_Extract (t0, &ener_h, &ener_l), i.e.      */
+    /*                                             */
+    /* *ener_h = extract_h (t0);                   */
+    ener_h = (Word16)(t0 >> 16);
+
+    /* L_temp_2 = L_shr(t0,1), which is used in        */
+    /* the calculation of *ener_l (see next operation) */
+
+    L_temp_2 = t0 >> 1;
+
+    L_temp_3 = (Word32)(ener_h << 15);
+
+    L_temp = L_temp_2 - L_temp_3;
+
+    ener_l = (Word16)L_temp;
+
+    t0 = Mpy_32(max_h, max_l, ener_h, ener_l, pOverflow);
+
+    if (scal_flag)
+    {
+        t0 = L_shr(t0, scal_fac, pOverflow);
+
+        if (t0 > (Word32) 0X0000FFFFL)
+        {
+            *cor_max = MAX_16;
+        }
+        else if (t0 < (Word32) 0xFFFF0000L)
+        {
+            *cor_max = MIN_16;
+        }
+        else
+        {
+            *cor_max = (Word16)(t0 >> 1);
+        }
+    }
+    else
+    {
+        *cor_max = (Word16)t0;
+    }
+
+    return (p_max);
+}
+
+/*----------------------------------------------------------------------------
+; End Function: Lag_max
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lag_max_wrapper
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs
+    corr = pointer to buffer of correlation values (Word32)
+    scal_sig = pointer to buffer of scaled signal values (Word16)
+    scal_fac = scaled signal factor (Word16)
+    scal_flag = EFR compatible scaling flag (Word16)
+    L_frame = length of frame to compute pitch (Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_max = pointer to the normalized correlation of selected lag (Word16)
+    rmax = pointer to max(<s[i]*s[j]>), (Word32)
+    r0 = pointer to the residual energy (Word32)
+    dtx  = dtx flag; equal to 1, if dtx is enabled, 0, otherwise (Flag)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    cor_max contains the newly calculated normalized correlation of the
+      selected lag
+    rmax contains the newly calculated max(<s[i]*s[j]>)
+    r0 contains the newly calculated residual energy
+    pOverflow -> 1 if the math operations called by this routine saturate
+
+ Returns:
+    p_max = lag of the max correlation found (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS (If VAD2 is not defined)
+
+ Inputs
+    vadSt = pointer to a vadState structure
+    corr = pointer to buffer of correlation values (Word32)
+    scal_sig = pointer to buffer of scaled signal values (Word16)
+    scal_fac = scaled signal factor (Word16)
+    scal_flag = EFR compatible scaling flag (Word16)
+    L_frame = length of frame to compute pitch (Word16)
+    lag_max = maximum lag (Word16)
+    lag_min = minimum lag (Word16)
+    cor_max = pointer to the normalized correlation of selected lag (Word16)
+    dtx  = dtx flag; equal to 1, if dtx is enabled, 0, otherwise (Flag)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    cor_max contains the newly calculated normalized correlation of the
+      selected lag
+    vadSt contains the updated VAD state parameters
+    pOverflow -> 1 if the math operations called by this routine saturate
+
+ Returns:
+    p_max = lag of the max correlation found (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function provides external access to the local function Lag_max.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_ol.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+#ifdef VAD2
+ CALL Lag_max(corr = corr
+          scal_sig = scal_sig
+          scal_fac = scal_fac
+          scal_flag = scal_flag
+          L_frame = L_frame
+          lag_max = lag_max
+          lag_min = lag_min
+          cor_max = cor_max
+          rmax = rmax
+          r0 = r0
+          dtx = dtx
+          pOverflow = pOverflow)
+   MODIFYING(nothing)
+   RETURNING(temp)
+
+#else
+ CALL Lag_max(vadSt = vadSt
+          corr = corr
+          scal_sig = scal_sig
+          scal_fac = scal_fac
+          scal_flag = scal_flag
+          L_frame = L_frame
+          lag_max = lag_max
+          lag_min = lag_min
+          cor_max = cor_max
+          dtx = dtx
+          pOverflow = pOverflow)
+   MODIFYING(nothing)
+   RETURNING(temp)
+
+#endif
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+#ifdef VAD2
+Word16 Lag_max_wrapper(  /* o   : lag found                          */
+    Word32 corr[],      /* i   : correlation vector.                     */
+    Word16 scal_sig[],  /* i   : scaled signal.                          */
+    Word16 scal_fac,    /* i   : scaled signal factor.                   */
+    Word16 scal_flag,   /* i   : if 1 use EFR compatible scaling         */
+    Word16 L_frame,     /* i   : length of frame to compute pitch        */
+    Word16 lag_max,     /* i   : maximum lag                             */
+    Word16 lag_min,     /* i   : minimum lag                             */
+    Word16 *cor_max,    /* o   : normalized correlation of selected lag  */
+    Word32 *rmax,       /* o   : max(<s[i]*s[j]>)                        */
+    Word32 *r0,         /* o   : residual energy                         */
+    Flag dtx,           /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag *pOverflow     /* i/o : overflow Flag                           */
+)
+{
+    Word16 temp;
+
+    temp = Lag_max(corr, scal_sig, scal_fac, scal_flag, L_frame, lag_max,
+                   lag_min, cor_max, rmax, r0, dtx, pOverflow);
+
+    return(temp);
+}
+
+#else
+Word16 Lag_max_wrapper(  /* o   : lag found                          */
+    vadState *vadSt,    /* i/o : VAD state struct                        */
+    Word32 corr[],      /* i   : correlation vector.                     */
+    Word16 scal_sig[],  /* i   : scaled signal.                          */
+    Word16 scal_fac,    /* i   : scaled signal factor.                   */
+    Word16 scal_flag,   /* i   : if 1 use EFR compatible scaling         */
+    Word16 L_frame,     /* i   : length of frame to compute pitch        */
+    Word16 lag_max,     /* i   : maximum lag                             */
+    Word16 lag_min,     /* i   : minimum lag                             */
+    Word16 *cor_max,    /* o   : normalized correlation of selected lag  */
+    Flag dtx,           /* i   : dtx flag; use dtx=1, do not use dtx=0   */
+    Flag *pOverflow     /* i/o : overflow Flag                           */
+)
+{
+    Word16 temp;
+
+    temp = Lag_max(vadSt, corr, scal_sig, scal_fac, scal_flag, L_frame,
+                   lag_max, lag_min, cor_max, dtx, pOverflow);
+
+    return(temp);
+}
+
+#endif
+
+/*----------------------------------------------------------------------------
+; End Function: Lag_max_wrapper
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pitch_ol
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    vadSt = pointer to a vadState structure
+    mode =  data of type enum Mode specifies the mode.
+    signal = pointer to buffer of signal used to compute the open loop
+         pitch
+    where signal[-pit_max] to signal[-1] should be known
+    pit_min = 16 bit value specifies the minimum pitch lag
+    pit_max = 16 bit value specifies the maximum pitch lag
+    L_frame = 16 bit value specifies the length of frame to compute pitch
+    idx = 16 bit value specifies the frame index
+    dtx = Data of type 'Flag' used for dtx. Use dtx=1, do not use dtx=0
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs
+    vadSt = The vadSt state structure may be modified.
+    pOverflow -> 1 if the math operations called by this routine saturate
+
+ Returns:
+    p_max1 = 16 bit value representing the open loop pitch lag.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the open loop pitch lag based on the perceptually
+ weighted speech signal. This is done in the following steps:
+       - find three maxima of the correlation <sw[n],sw[n-T]>,
+         dividing the search range into three parts:
+              pit_min ... 2*pit_min-1
+            2*pit_min ... 4*pit_min-1
+            4*pit_min ...   pit_max
+       - divide each maximum by <sw[n-t], sw[n-t]> where t is the delay at
+         that maximum correlation.
+       - select the delay of maximum normalized correlation (among the
+         three candidates) while favoring the lower delay ranges.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pitch_ol.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Pitch_ol (      // o   : open loop pitch lag
+    vadState *vadSt,   // i/o : VAD state struct
+    enum Mode mode,    // i   : coder mode
+    Word16 signal[],   // i   : signal used to compute the open loop pitch
+                       //    signal[-pit_max] to signal[-1] should be known
+    Word16 pit_min,    // i   : minimum pitch lag
+    Word16 pit_max,    // i   : maximum pitch lag
+    Word16 L_frame,    // i   : length of frame to compute pitch
+    Word16 idx,        // i   : frame index
+    Flag dtx           // i   : dtx flag; use dtx=1, do not use dtx=0
+    )
+{
+    Word16 i, j;
+    Word16 max1, max2, max3;
+    Word16 p_max1, p_max2, p_max3;
+    Word16 scal_flag = 0;
+    Word32 t0;
+#ifdef VAD2
+    Word32  r01, r02, r03;
+    Word32  rmax1, rmax2, rmax3;
+#else
+    Word16 corr_hp_max;
+#endif
+    Word32 corr[PIT_MAX+1], *corr_ptr;
+
+    // Scaled signal
+
+    Word16 scaled_signal[L_FRAME + PIT_MAX];
+    Word16 *scal_sig, scal_fac;
+
+#ifndef VAD2
+    if (dtx)
+    {  // no test() call since this if is only in simulation env
+       // update tone detection
+       if ((sub(mode, MR475) == 0) || (sub(mode, MR515) == 0))
+       {
+          vad_tone_detection_update (vadSt, 1);
+       }
+       else
+       {
+          vad_tone_detection_update (vadSt, 0);
+       }
+    }
+#endif
+
+    scal_sig = &scaled_signal[pit_max];
+
+    t0 = 0L;
+    for (i = -pit_max; i < L_frame; i++)
+    {
+        t0 = L_mac (t0, signal[i], signal[i]);
+    }
+
+     *--------------------------------------------------------*
+     * Scaling of input signal.                               *
+     *                                                        *
+     *   if Overflow        -> scal_sig[i] = signal[i]>>3     *
+     *   else if t0 < 1^20  -> scal_sig[i] = signal[i]<<3     *
+     *   else               -> scal_sig[i] = signal[i]        *
+     *--------------------------------------------------------*
+
+     *--------------------------------------------------------*
+     *  Verification for risk of overflow.                    *
+     *--------------------------------------------------------*
+
+    if (L_sub (t0, MAX_32) == 0L)               // Test for overflow
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shr (signal[i], 3);
+        }
+        scal_fac = 3;
+    }
+    else if (L_sub (t0, (Word32) 1048576L) < (Word32) 0)
+        // if (t0 < 2^20)
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = shl (signal[i], 3);
+        }
+        scal_fac = -3;
+    }
+    else
+    {
+        for (i = -pit_max; i < L_frame; i++)
+        {
+            scal_sig[i] = signal[i];
+        }
+        scal_fac = 0;
+    }
+
+    // calculate all coreelations of scal_sig, from pit_min to pit_max
+    corr_ptr = &corr[pit_max];
+    comp_corr (scal_sig, L_frame, pit_max, pit_min, corr_ptr);
+
+     *--------------------------------------------------------------------*
+     *  The pitch lag search is divided in three sections.                *
+     *  Each section cannot have a pitch multiple.                        *
+     *  We find a maximum for each section.                               *
+     *  We compare the maximum of each section by favoring small lags.    *
+     *                                                                    *
+     *  First section:  lag delay = pit_max     downto 4*pit_min          *
+     *  Second section: lag delay = 4*pit_min-1 downto 2*pit_min          *
+     *  Third section:  lag delay = 2*pit_min-1 downto pit_min            *
+     *--------------------------------------------------------------------*
+
+    // mode dependent scaling in Lag_max
+    if (sub(mode, MR122) == 0)
+    {
+       scal_flag = 1;
+    }
+    else
+    {
+       scal_flag = 0;
+    }
+
+#ifdef VAD2
+    j = shl (pit_min, 2);
+    p_max1 = Lag_max (corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      pit_max, j, &max1, &rmax1, &r01, dtx);
+
+    i = sub (j, 1);
+    j = shl (pit_min, 1);
+    p_max2 = Lag_max (corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      i, j, &max2, &rmax2, &r02, dtx);
+
+    i = sub (j, 1);
+    p_max3 = Lag_max (corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      i, pit_min, &max3, &rmax3, &r03, dtx);
+#else
+    j = shl (pit_min, 2);
+    p_max1 = Lag_max (vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      pit_max, j, &max1, dtx);
+
+    i = sub (j, 1);
+    j = shl (pit_min, 1);
+    p_max2 = Lag_max (vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      i, j, &max2, dtx);
+
+    i = sub (j, 1);
+    p_max3 = Lag_max (vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                      i, pit_min, &max3, dtx);
+
+    if (dtx)
+    {  // no test() call since this if is only in simulation env
+       if (sub(idx, 1) == 0)
+       {
+          // calculate max high-passed filtered correlation of all lags
+          hp_max (corr_ptr, scal_sig, L_frame, pit_max, pit_min, &corr_hp_max);
+
+          // update complex background detector
+          vad_complex_detection_update(vadSt, corr_hp_max);
+       }
+    }
+#endif
+
+     *--------------------------------------------------------------------*
+     * Compare the 3 sections maximum, and favor small lag.               *
+     *--------------------------------------------------------------------*
+
+    if (sub (mult (max1, THRESHOLD), max2) < 0)
+    {
+        max1 = max2;
+        p_max1 = p_max2;
+#ifdef VAD2
+        if (dtx)
+        {
+            rmax1 = rmax2;
+            r01 = r02;
+#endif
+    }
+    if (sub (mult (max1, THRESHOLD), max3) < 0)
+    {
+        p_max1 = p_max3;
+#ifdef VAD2
+        if (dtx)
+        {
+            rmax1 = rmax3;
+            r01 = r03;
+        }
+#endif
+    }
+
+#ifdef VAD2
+    if (dtx)
+    {
+        vadSt->L_Rmax = L_add(vadSt->L_Rmax, rmax1);   // Save max correlation
+        vadSt->L_R0 =   L_add(vadSt->L_R0, r01);        // Save max energy
+    }
+#endif
+
+    return (p_max1);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Pitch_ol(       /* o   : open loop pitch lag                         */
+    vadState *vadSt,   /* i/o : VAD state struct                            */
+    enum Mode mode,    /* i   : coder mode                                  */
+    Word16 signal[],   /* i   : signal used to compute the open loop pitch  */
+    /*    signal[-pit_max] to signal[-1] should be known */
+    Word16 pit_min,    /* i   : minimum pitch lag                           */
+    Word16 pit_max,    /* i   : maximum pitch lag                           */
+    Word16 L_frame,    /* i   : length of frame to compute pitch            */
+    Word16 idx,        /* i   : frame index                                 */
+    Flag dtx,          /* i   : dtx flag; use dtx=1, do not use dtx=0       */
+    Flag *pOverflow    /* i/o : overflow Flag                               */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 max1;
+    Word16 max2;
+    Word16 max3;
+    Word16 p_max1;
+    Word16 p_max2;
+    Word16 p_max3;
+    Word16 scal_flag = 0;
+    Word32 t0;
+
+#ifdef VAD2
+    Word32 r01;
+    Word32 r02;
+    Word32 r03;
+    Word32 rmax1;
+    Word32 rmax2;
+    Word32 rmax3;
+#else
+    Word16 corr_hp_max;
+#endif
+    Word32 corr[PIT_MAX+1];
+    Word32 *corr_ptr;
+
+    /* Scaled signal */
+
+    Word16 scaled_signal[L_FRAME + PIT_MAX];
+    Word16 *scal_sig;
+    Word16 *p_signal;
+    Word16 scal_fac;
+    Word32 L_temp;
+
+#ifndef VAD2
+    if (dtx)
+    {   /* no test() call since this if is only in simulation env */
+        /* update tone detection */
+        if ((mode == MR475) || (mode == MR515))
+        {
+            vad_tone_detection_update(vadSt, 1, pOverflow);
+        }
+        else
+        {
+            vad_tone_detection_update(vadSt, 0, pOverflow);
+        }
+    }
+#endif
+
+
+    t0 = 0L;
+    p_signal = &signal[-pit_max];
+
+    for (i = -pit_max; i < L_frame; i++)
+    {
+        t0 += (((Word32) * (p_signal)) * *(p_signal)) << 1;
+        p_signal++;
+        if (t0 < 0)
+        {
+            t0 = MAX_32;
+            break;
+        }
+
+    }
+
+    /*--------------------------------------------------------*
+     * Scaling of input signal.                               *
+     *                                                        *
+     *   if Overflow        -> scal_sig[i] = signal[i]>>3     *
+     *   else if t0 < 1^20  -> scal_sig[i] = signal[i]<<3     *
+     *   else               -> scal_sig[i] = signal[i]        *
+     *--------------------------------------------------------*/
+
+    /*--------------------------------------------------------*
+     *  Verification for risk of overflow.                    *
+     *--------------------------------------------------------*/
+
+    scal_sig = &scaled_signal[0];
+    p_signal = &signal[-pit_max];
+
+    if (t0 == MAX_32)     /* Test for overflow */
+    {
+
+        for (i = (pit_max + L_frame) >> 1; i != 0; i--)
+        {
+            *(scal_sig++) = (Word16)(((Word32) * (p_signal++) >> 3));
+            *(scal_sig++) = (Word16)(((Word32) * (p_signal++) >> 3));
+        }
+
+        if ((pit_max + L_frame) & 1)
+        {
+            *(scal_sig) = (Word16)(((Word32) * (p_signal) >> 3));
+        }
+
+        scal_fac = 3;
+    }
+    else if (t0 < (Word32)1048576L)
+        /* if (t0 < 2^20) */
+    {
+        for (i = (pit_max + L_frame) >> 1; i != 0; i--)
+        {
+            *(scal_sig++) = (Word16)(((Word32) * (p_signal++) << 3));
+            *(scal_sig++) = (Word16)(((Word32) * (p_signal++) << 3));
+        }
+
+        if ((pit_max + L_frame) & 1)
+        {
+            *(scal_sig) = (Word16)(((Word32) * (p_signal) << 3));
+        }
+        scal_fac = -3;
+    }
+    else
+    {
+
+        memcpy(scal_sig, p_signal, (L_frame + pit_max)*sizeof(*signal));
+        scal_fac = 0;
+    }
+
+    /* calculate all coreelations of scal_sig, from pit_min to pit_max */
+    corr_ptr = &corr[pit_max];
+
+    scal_sig = &scaled_signal[pit_max];
+
+    comp_corr(scal_sig, L_frame, pit_max, pit_min, corr_ptr);
+
+    /*--------------------------------------------------------------------*
+     *  The pitch lag search is divided in three sections.                *
+     *  Each section cannot have a pitch multiple.                        *
+     *  We find a maximum for each section.                               *
+     *  We compare the maximum of each section by favoring small lags.    *
+     *                                                                    *
+     *  First section:  lag delay = pit_max     downto 4*pit_min          *
+     *  Second section: lag delay = 4*pit_min-1 downto 2*pit_min          *
+     *  Third section:  lag delay = 2*pit_min-1 downto pit_min            *
+     *--------------------------------------------------------------------*/
+
+    /* mode dependent scaling in Lag_max */
+
+    if (mode == MR122)
+    {
+        scal_flag = 1;
+    }
+    else
+    {
+        scal_flag = 0;
+    }
+
+#ifdef VAD2
+    L_temp = ((Word32)pit_min) << 2;
+    if (L_temp != (Word32)((Word16) L_temp))
+    {
+        *pOverflow = 1;
+        j = (pit_min > 0) ? MAX_16 : MIN_16;
+    }
+    else
+    {
+        j = (Word16)L_temp;
+    }
+
+    p_max1 = Lag_max(corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     pit_max, j, &max1, &rmax1, &r01, dtx, pOverflow);
+
+    i = j - 1;
+
+    j = pit_min << 1;
+
+    p_max2 = Lag_max(corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     i, j, &max2, &rmax2, &r02, dtx, pOverflow);
+
+    i = j - 1;
+
+    p_max3 = Lag_max(corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     i, pit_min, &max3, &rmax3, &r03, dtx, pOverflow);
+
+#else
+    L_temp = ((Word32)pit_min) << 2;
+    if (L_temp != (Word32)((Word16) L_temp))
+    {
+        *pOverflow = 1;
+        j = (pit_min > 0) ? MAX_16 : MIN_16;
+    }
+    else
+    {
+        j = (Word16)L_temp;
+    }
+
+    p_max1 = Lag_max(vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     pit_max, j, &max1, dtx, pOverflow);
+
+    i = j - 1;
+
+
+    j = pit_min << 1;
+
+
+    p_max2 = Lag_max(vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     i, j, &max2, dtx, pOverflow);
+
+    i = j - 1;
+    p_max3 = Lag_max(vadSt, corr_ptr, scal_sig, scal_fac, scal_flag, L_frame,
+                     i, pit_min, &max3, dtx, pOverflow);
+
+    if (dtx)
+    {  /* no test() call since this if is only in simulation env */
+
+        if (idx == 1)
+        {
+            /* calculate max high-passed filtered correlation of all lags */
+            hp_max(corr_ptr, scal_sig, L_frame, pit_max, pit_min, &corr_hp_max,
+                   pOverflow);
+
+            /* update complex background detector */
+            vad_complex_detection_update(vadSt, corr_hp_max);
+        }
+    }
+#endif
+
+    /*--------------------------------------------------------------------*
+     * Compare the 3 sections maximum, and favor small lag.               *
+     *--------------------------------------------------------------------*/
+
+    i =  mult(max1, THRESHOLD, pOverflow);
+
+    if (i < max2)
+    {
+        max1 = max2;
+        p_max1 = p_max2;
+
+#ifdef VAD2
+        if (dtx)
+        {
+            rmax1 = rmax2;
+            r01 = r02;
+        }
+#endif
+    }
+
+    i =  mult(max1, THRESHOLD, pOverflow);
+
+    if (i < max3)
+    {
+        p_max1 = p_max3;
+
+#ifdef VAD2
+        if (dtx)
+        {
+            rmax1 = rmax3;
+            r01 = r03;
+        }
+#endif
+    }
+
+#ifdef VAD2
+    if (dtx)
+    {
+        /* Save max correlation */
+        vadSt->L_Rmax = L_add(vadSt->L_Rmax, rmax1, pOverflow);
+        /* Save max energy */
+        vadSt->L_R0 =   L_add(vadSt->L_R0, r01, pOverflow);
+    }
+#endif
+
+    return (p_max1);
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.h b/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.h
new file mode 100644
index 0000000..df7f307
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pitch_ol.h
@@ -0,0 +1,122 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/pitch_ol.h
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : pitch_ol.h
+       Purpose          : Compute the open loop pitch lag.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PITCH_OL_H
+#define PITCH_OL_H "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "vad.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 Pitch_ol(       /* o   : open loop pitch lag                         */
+        vadState *vadSt,   /* i/o : VAD state struct                            */
+        enum Mode mode,    /* i   : coder mode                                  */
+        Word16 signal[],   /* i   : signal used to compute the open loop pitch  */
+        /*    signal[-pit_max] to signal[-1] should be known */
+        Word16 pit_min,    /* i   : minimum pitch lag                           */
+        Word16 pit_max,    /* i   : maximum pitch lag                           */
+        Word16 L_frame,    /* i   : length of frame to compute pitch            */
+        Word16 idx,        /* i   : frame index                                 */
+        Flag dtx,          /* i   : dtx flag; use dtx=1, do not use dtx=0       */
+        Flag *pOverflow    /* i/o : overflow Flag                               */
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PITCH_OL_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_big.cpp b/media/libstagefright/codecs/amrnb/enc/src/pre_big.cpp
new file mode 100644
index 0000000..02544cf
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pre_big.cpp
@@ -0,0 +1,210 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/pre_big.c
+ Functions:
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Big subframe (2 subframes) preprocessing
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pre_big.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "syn_filt.h"
+#include "weight_a.h"
+#include "residu.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: pre_big
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode = enum Mode -- coder mode
+    gamma1 = array of type const Word16 -- spectral exp. factor 1
+    gamma1_12k2 = array of type const Word16 -- spectral exp. factor 1 for EFR
+    gamma2 = array of type const Word16 -- spectral exp. factor 2
+    A_t = array of type Word16 -- A(z) unquantized, for 4 subframes, Q12
+    frameOffset = Word16 -- Start position in speech vector,   Q0
+    speech[] = array of type Word16 -- speech,                            Q0
+
+ Outputs:
+    mem_w = array of type Word16 -- synthesis filter memory state,     Q0
+    wsp   = array of type Word16 -- weighted speech                    Q0
+    pOverflow = pointer of type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pre_big.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void pre_big(
+    enum Mode mode,            /* i  : coder mode                             */
+    const Word16 gamma1[],     /* i  : spectral exp. factor 1                 */
+    const Word16 gamma1_12k2[],/* i  : spectral exp. factor 1 for EFR         */
+    const Word16 gamma2[],     /* i  : spectral exp. factor 2                 */
+    Word16 A_t[],              /* i  : A(z) unquantized, for 4 subframes, Q12 */
+    Word16 frameOffset,        /* i  : Start position in speech vector,   Q0  */
+    Word16 speech[],           /* i  : speech,                            Q0  */
+    Word16 mem_w[],            /* i/o: synthesis filter memory state,     Q0  */
+    Word16 wsp[],              /* o  : weighted speech                    Q0  */
+    Flag   *pOverflow          /* o  : overflow indicator                     */
+)
+{
+    Word16 Ap1[MP1];            /* A(z) with spectral expansion         */
+    Word16 Ap2[MP1];            /* A(z) with spectral expansion         */
+    const Word16 *g1;           /* Pointer to correct gammma1 vector    */
+    Word16 aOffset;
+    Word16 i;
+
+    if (mode <= MR795)
+    {
+        g1 = gamma1;
+    }
+    else
+    {
+        g1 = gamma1_12k2;
+    }
+
+    if (frameOffset > 0)
+    {
+        aOffset = 2 * MP1;
+    }
+    else
+    {
+        aOffset = 0;
+    }
+
+    /* process two subframes (which form the "big" subframe) */
+    for (i = 0; i < 2; i++)
+    {
+        Weight_Ai(&A_t[aOffset], g1, Ap1);
+        Weight_Ai(&A_t[aOffset], gamma2, Ap2);
+        Residu(Ap1, &speech[frameOffset], &wsp[frameOffset], L_SUBFR);
+
+        Syn_filt(Ap2, &wsp[frameOffset], &wsp[frameOffset], L_SUBFR, mem_w, 1);
+
+        aOffset = add(aOffset, MP1, pOverflow);
+
+        frameOffset = add(frameOffset, L_SUBFR, pOverflow);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_big.h b/media/libstagefright/codecs/amrnb/enc/src/pre_big.h
new file mode 100644
index 0000000..6b47bfe
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pre_big.h
@@ -0,0 +1,131 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/pre_big.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, pre_big.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef pre_big_h
+#define pre_big_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void pre_big(
+        enum Mode mode,            /* i  : coder mode                             */
+        const Word16 gamma1[],     /* i  : spectral exp. factor 1                 */
+        const Word16 gamma1_12k2[],/* i  : spectral exp. factor 1 for EFR         */
+        const Word16 gamma2[],     /* i  : spectral exp. factor 2                 */
+        Word16 A_t[],              /* i  : A(z) unquantized, for 4 subframes, Q12 */
+        Word16 frameOffset,        /* i  : Start position in speech vector,   Q0  */
+        Word16 speech[],           /* i  : speech,                            Q0  */
+        Word16 mem_w[],            /* i/o: synthesis filter memory state,     Q0  */
+        Word16 wsp[],              /* o  : weighted speech                    Q0  */
+        Flag   *pOverflow          /* o  : overflow indicator                     */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_proc.cpp b/media/libstagefright/codecs/amrnb/enc/src/pre_proc.cpp
new file mode 100644
index 0000000..fdc2440
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pre_proc.cpp
@@ -0,0 +1,589 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/pre_proc.c
+ Funtions: Pre_Process_init
+           Pre_Process_reset
+           Pre_Process_exit
+           Pre_Process
+
+     Date: 05/17/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put the file into our template structure.
+
+ Description: First pass optimization.
+
+ Description: Made changes based on comments from review meeting.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Removed basic_op.h from the Include section. It is not used.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Fixed typecasting issue with TI C compiler.
+              2. Modified FOR loop to count down.
+              3. Cosmetic changes to the code to make address post-increment
+                 clearer.
+              4. Removed unnecessary typecasting in the multiply-accumulate
+                 portion of FOR loop body.
+              5. Removed "static" in table definitions.
+              6. Updated copyright year.
+
+ Description:  For Pre_Process()
+              1. Replaced variables (containing filter coefficients) with
+                 constants, to avoid extra register swaping.
+              2. Changed to decrement loop
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These modules handle the preprocessing of input speech.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "pre_proc.h"
+#include "typedef.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pre_Process_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to an array of pointer to structures of type
+        Pre_ProcessState
+
+ Outputs:
+    Structure pointed to by the pointer pointed to by state is
+      initialized to its reset value
+    state points to the allocated memory
+
+ Returns:
+    return_value = 0 if memory was successfully initialized,
+                   otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Allocates state memory and initializes state memory.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pre_proc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Pre_Process_init (Pre_ProcessState **state)
+{
+  Pre_ProcessState* s;
+
+  if (state == (Pre_ProcessState **) NULL){
+      fprintf(stderr, "Pre_Process_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (Pre_ProcessState *) malloc(sizeof(Pre_ProcessState))) == NULL){
+      fprintf(stderr, "Pre_Process_init: can not malloc state structure\n");
+      return -1;
+  }
+
+  Pre_Process_reset(s);
+  *state = s;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Pre_Process_init(Pre_ProcessState **state)
+{
+    Pre_ProcessState* s;
+
+    if (state == (Pre_ProcessState **) NULL)
+    {
+        /*  fprintf(stderr, "Pre_Process_init: invalid parameter\n");  */
+        return(-1);
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (Pre_ProcessState *) malloc(sizeof(Pre_ProcessState))) == NULL)
+    {
+        /*  fprintf(stderr, "Pre_Process_init:
+            can not malloc state structure\n");  */
+        return(-1);
+    }
+
+    Pre_Process_reset(s);
+    *state = s;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pre_Process_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to structure of type Pre_ProcessState
+
+ Outputs:
+    Structure pointed to by state is initialized to zero.
+
+ Returns:
+    return_value = 0 if memory was successfully reset,
+                   otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Initializes state memory to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pre_proc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Pre_Process_reset (Pre_ProcessState *state)
+{
+  if (state == (Pre_ProcessState *) NULL){
+      fprintf(stderr, "Pre_Process_reset: invalid parameter\n");
+      return -1;
+  }
+
+  state->y2_hi = 0;
+  state->y2_lo = 0;
+  state->y1_hi = 0;
+  state->y1_lo = 0;
+  state->x0 = 0;
+  state->x1 = 0;
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Pre_Process_reset(Pre_ProcessState *state)
+{
+    if (state == (Pre_ProcessState *) NULL)
+    {
+        /*  fprintf(stderr, "Pre_Process_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    state->y2_hi = 0;
+    state->y2_lo = 0;
+    state->y1_hi = 0;
+    state->y1_lo = 0;
+    state->x0 = 0;
+    state->x1 = 0;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pre_Process_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = a pointer to an array of pointers to structures of
+        type Pre_ProcessState
+
+ Outputs:
+    state points to a NULL address
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ The memory used for state memory is freed.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pre_proc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Pre_Process_exit (Pre_ProcessState **state)
+{
+  if (state == NULL || *state == NULL)
+      return;
+
+  // deallocate memory
+  free(*state);
+  *state = NULL;
+
+  return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void Pre_Process_exit(Pre_ProcessState **state)
+{
+    if (state == NULL || *state == NULL)
+    {
+        return;
+    }
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pre_Process
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = a pointer to a structure of type Pre_ProcessState
+    signal = input/output signal (Word16)
+    lg = length of signal (Word16)
+
+ Outputs:
+    st points to the updated structure
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    a = points to a buffer of filter coefficients
+    b = points to a buffer of filter coefficients
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module performs the preprocessing of the input speech.
+ The signal is passed through a 2nd order high pass filtering with cut off
+ frequency at 80 Hz. The input is divided by two in the filtering process.
+
+    y[i] = b[0]*x[i]/2 + b[1]*x[i-1]/2 + b[2]*x[i-2]/2
+                     + a[1]*y[i-1] + a[2]*y[i-2];
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pre_proc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Pre_Process (
+    Pre_ProcessState *st,
+    Word16 signal[], // input/output signal
+    Word16 lg)       // lenght of signal
+{
+    Word16 i, x2;
+    Word32 L_tmp;
+
+    for (i = 0; i < lg; i++)
+    {
+        x2 = st->x1;
+        st->x1 = st->x0;
+        st->x0 = signal[i];
+
+        //  y[i] = b[0]*x[i]/2 + b[1]*x[i-1]/2 + b140[2]*x[i-2]/2
+        //                     + a[1]*y[i-1] + a[2] * y[i-2];
+
+        L_tmp = Mpy_32_16 (st->y1_hi, st->y1_lo, a[1]);
+        L_tmp = L_add (L_tmp, Mpy_32_16 (st->y2_hi, st->y2_lo, a[2]));
+        L_tmp = L_mac (L_tmp, st->x0, b[0]);
+        L_tmp = L_mac (L_tmp, st->x1, b[1]);
+        L_tmp = L_mac (L_tmp, x2, b[2]);
+        L_tmp = L_shl (L_tmp, 3);
+        signal[i] = pv_round (L_tmp);
+
+        st->y2_hi = st->y1_hi;
+        st->y2_lo = st->y1_lo;
+        L_Extract (L_tmp, &st->y1_hi, &st->y1_lo);
+    }
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+/*
+    filter coefficients (fc = 80 Hz, coeff. b[] is divided by 2)
+    const Word16 b[3] = {1899, -3798, 1899};
+    const Word16 a[3] = {4096, 7807, -3733};
+
+*/
+
+void Pre_Process(
+    Pre_ProcessState *st,
+    Word16 signal[], /* input/output signal */
+    Word16 lg)       /* length of signal    */
+{
+    register Word16 i;
+    Word16 x_n_2;
+    Word16 x_n_1;
+    Word32 L_tmp;
+    Word16 *p_signal = signal;
+
+    x_n_2 = st->x1;
+    x_n_1 = st->x0;
+
+    for (i = lg; i != 0; i--)
+    {
+
+
+        /*  y[i] = b[0]*x[i]/2 + b[1]*x[i-1]/2 + b140[2]*x[i-2]/2  */
+        /*                     + a[1]*y[i-1] + a[2] * y[i-2];      */
+
+        L_tmp     = ((Word32) st->y1_hi) * 7807;
+        L_tmp    += (Word32)(((Word32) st->y1_lo * 7807) >> 15);
+
+        L_tmp    += ((Word32) st->y2_hi) * (-3733);
+        st->y2_hi =  st->y1_hi;
+        L_tmp    += (Word32)(((Word32) st->y2_lo * (-3733)) >> 15);
+        st->y2_lo =  st->y1_lo;
+
+        L_tmp    += ((Word32) x_n_2) * 1899;
+        x_n_2     =  x_n_1;
+        L_tmp    += ((Word32) x_n_1) * (-3798);
+        x_n_1     = *(p_signal);
+        L_tmp    += ((Word32) x_n_1) * 1899;
+
+
+        *(p_signal++) = (Word16)((L_tmp + 0x0000800L) >> 12);
+
+        st->y1_hi = (Word16)(L_tmp >> 12);
+        st->y1_lo = (Word16)((L_tmp << 3) - ((Word32)(st->y1_hi) << 15));
+
+    }
+
+    st->x1 = x_n_2;
+    st->x0 = x_n_1;
+
+    return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/pre_proc.h b/media/libstagefright/codecs/amrnb/enc/src/pre_proc.h
new file mode 100644
index 0000000..abe676f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/pre_proc.h
@@ -0,0 +1,114 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+********************************************************************************
+*
+*      GSM AMR-NB speech codec   R98   Version 7.5.0   March 2, 2001
+*                                R99   Version 3.2.0
+*                                REL-4 Version 4.0.0
+*
+********************************************************************************
+*
+*      File             : pre_proc.h
+*      Purpose          : Preprocessing of input speech.
+*
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+********************************************************************************
+*/
+#ifndef pre_proc_h
+#define pre_proc_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         LOCAL VARIABLES AND TABLES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+    typedef struct
+    {
+        Word16 y2_hi;
+        Word16 y2_lo;
+        Word16 y1_hi;
+        Word16 y1_lo;
+        Word16 x0;
+        Word16 x1;
+    } Pre_ProcessState;
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+
+    Word16 Pre_Process_init(Pre_ProcessState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Pre_Process in each call.
+       returns 0 on success
+     */
+
+    Word16 Pre_Process_reset(Pre_ProcessState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void Pre_Process_exit(Pre_ProcessState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void Pre_Process(
+        Pre_ProcessState *st,
+        Word16 signal[],   /* Input/output signal                               */
+        Word16 lg          /* Lenght of signal                                  */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/prm2bits.cpp b/media/libstagefright/codecs/amrnb/enc/src/prm2bits.cpp
new file mode 100644
index 0000000..9088f7d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/prm2bits.cpp
@@ -0,0 +1,310 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+
+
+
+
+ Filename: /audio/gsm_amr/c/src/prm2bits.c
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Improved the code as per review comments.
+
+ Description:  For Int2bin() and Prm2bits()
+              1. Eliminated unused include file typedef.h.
+              2. Replaced array addressing by pointers
+              3. Changed to decrement loops
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "prm2bits.h"
+#include "mode.h"
+#include "bitno_tab.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+#define MASK      0x0001
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Int2bin
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    value = value to be converted to binary of type Word16
+    no_of_bits = number of bits associated with value of type Word16
+
+ Outputs:
+    bitstream = pointer to address where bits are written of type Word16
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  FUNCTION:  Int2bin
+
+  PURPOSE:  convert integer to binary and write the bits to the array
+            bitstream[]. The most significant bits are written first.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ prm2bits.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void Int2bin (
+    Word16 value,       // input : value to be converted to binary
+    Word16 no_of_bits,  // input : number of bits associated with value
+    Word16 *bitstream   // output: address where bits are written
+)
+{
+    Word16 *pt_bitstream, i, bit;
+
+    pt_bitstream = &bitstream[no_of_bits];
+
+    for (i = 0; i < no_of_bits; i++)
+    {
+        bit = value & MASK;
+        if (bit == 0)
+        {
+            *--pt_bitstream = BIT_0;
+        }
+        else
+        {
+            *--pt_bitstream = BIT_1;
+        }
+        value = shr (value, 1);
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+static void Int2bin(
+    Word16 value,       /* input : value to be converted to binary      */
+    Word16 no_of_bits,  /* input : number of bits associated with value */
+    Word16 *bitstream   /* output: address where bits are written       */
+)
+{
+    Word16 *pt_bitstream;
+    Word16 i;
+
+    pt_bitstream = &bitstream[no_of_bits-1];
+
+    for (i = no_of_bits; i != 0; i--)
+    {
+        *(pt_bitstream--) = value & MASK;
+        value >>= 1;
+    }
+
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: prm2bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode  = AMR mode of type enum Mode
+    prm[] = pointer to analysis parameters of type Word16
+
+ Outputs:
+    bits[] = pointer to serial bits of type Word16
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  FUNCTION:    Prm2bits
+
+  PURPOSE:     converts the encoder parameter vector into a vector of serial
+               bits.
+
+  DESCRIPTION: depending on the mode, different numbers of parameters
+               (with differing numbers of bits) are processed. Details
+               are found in bitno.tab
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ prm2bits.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Prm2bits (
+    enum Mode mode,    // i : AMR mode
+    Word16 prm[],      // i : analysis parameters (size <= MAX_PRM_SIZE)
+    Word16 bits[]      // o : serial bits         (size <= MAX_SERIAL_SIZE)
+)
+{
+   Word16 i;
+
+   for (i = 0; i < prmno[mode]; i++)
+   {
+       Int2bin (prm[i], bitno[mode][i], bits);
+       bits += bitno[mode][i];
+       add(0,0);       // account for above pointer update
+   }
+
+   return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void Prm2bits(
+    enum Mode mode,    /* i : AMR mode                                      */
+    Word16 prm[],      /* i : analysis parameters (size <= MAX_PRM_SIZE)    */
+    Word16 bits[]      /* o : serial bits         (size <= MAX_SERIAL_SIZE) */
+)
+{
+    Word16 i;
+    const Word16 *p_mode;
+    Word16 *p_prm;
+
+    p_mode = &bitno[mode][0];
+    p_prm  = &prm[0];
+
+    for (i = prmno[mode]; i != 0; i--)
+    {
+        Int2bin(*(p_prm++), *(p_mode), bits);
+        bits += *(p_mode++);
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/prm2bits.h b/media/libstagefright/codecs/amrnb/enc/src/prm2bits.h
new file mode 100644
index 0000000..8ad11a8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/prm2bits.h
@@ -0,0 +1,81 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+********************************************************************************
+*
+*      GSM AMR-NB speech codec   R98   Version 7.5.0   March 2, 2001
+*                                R99   Version 3.2.0
+*                                REL-4 Version 4.0.0
+*
+********************************************************************************
+*
+*      File             : prm2bits.h
+*      Purpose          : Converts the encoder parameter vector into a
+*                       : vector of serial bits.
+*
+********************************************************************************
+*/
+#ifndef prm2bits_h
+#define prm2bits_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+#include "mode.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Prm2bits(
+        enum Mode mode,    /* i : AMR mode */
+        Word16 prm[],      /* input : analysis parameters                       */
+        Word16 bits[]      /* output: serial bits                               */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.cpp b/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.cpp
new file mode 100644
index 0000000..c58b687
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.cpp
@@ -0,0 +1,293 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/q_gain_c.c
+ Functions: q_gain_code
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:
+ (1) Removed optimization -- mult(i, 3, pOverflow) is NOT the same as adding
+     i to itself 3 times.  The reason is because the mult function does a
+     right shift by 15, which will obliterate smaller numbers.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Eliminated math operations that unnecessary checked for
+                 saturation by evaluating the operands
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Scalar quantization of the innovative codebook gain.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "q_gain_c.h"
+#include "mode.h"
+#include "oper_32b.h"
+#include "basic_op.h"
+#include "log2.h"
+#include "pow2.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define NB_QUA_CODE 32
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 qua_gain_code[NB_QUA_CODE*3];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: q_gain_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode -- enum Mode -- AMR mode
+    exp_gcode0 -- Word16 -- predicted CB gain (exponent),  Q0
+    frac_gcode0 -- Word16 -- predicted CB gain (fraction),  Q15
+    gain -- Pointer to Word16 -- quantized fixed codebook gain, Q1
+
+ Outputs:
+    gain -- Pointer to Word16 -- quantized fixed codebook gain, Q1
+
+    qua_ener_MR122 -- Pointer to Word16 -- quantized energy error, Q10
+                                           (for MR122 MA predictor update)
+
+    qua_ener -- Pointer to Word16 -- quantized energy error,        Q10
+                                     (for other MA predictor update)
+
+    pOverflow -- Pointer to Flag -- overflow indicator
+ Returns:
+    quantization index -- Word16 -- Q0
+
+ Global Variables Used:
+    qua_gain_code[]
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Scalar quantization of the innovative codebook gain.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_gain_c.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 q_gain_code(         /* o  : quantization index,            Q0  */
+    enum Mode mode,         /* i  : AMR mode                           */
+    Word16 exp_gcode0,      /* i  : predicted CB gain (exponent),  Q0  */
+    Word16 frac_gcode0,     /* i  : predicted CB gain (fraction),  Q15 */
+    Word16 *gain,           /* i/o: quantized fixed codebook gain, Q1  */
+    Word16 *qua_ener_MR122, /* o  : quantized energy error,        Q10 */
+    /*      (for MR122 MA predictor update)    */
+    Word16 *qua_ener,       /* o  : quantized energy error,        Q10 */
+    /*      (for other MA predictor update)    */
+    Flag   *pOverflow
+)
+{
+    const Word16 *p;
+    Word16 i;
+    Word16 index;
+    Word16 gcode0;
+    Word16 err;
+    Word16 err_min;
+    Word16 g_q0;
+    Word16 temp;
+
+    if (mode == MR122)
+    {
+        g_q0 = *gain >> 1; /* Q1 -> Q0 */
+    }
+    else
+    {
+        g_q0 = *gain;
+    }
+
+    /*-------------------------------------------------------------------*
+     *  predicted codebook gain                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *  gc0     = Pow2(int(d)+frac(d))                                   *
+     *          = 2^exp + 2^frac                                         *
+     *                                                                   *
+     *-------------------------------------------------------------------*/
+
+    gcode0 = (Word16) Pow2(exp_gcode0, frac_gcode0, pOverflow);  /* predicted gain */
+
+    if (mode == MR122)
+    {
+        gcode0 = shl(gcode0, 4, pOverflow);
+    }
+    else
+    {
+        gcode0 = shl(gcode0, 5, pOverflow);
+    }
+
+    /*-------------------------------------------------------------------*
+     *                   Search for best quantizer                        *
+     *-------------------------------------------------------------------*/
+
+    p = &qua_gain_code[0];
+    err_min = ((Word32)gcode0 * *(p++)) >> 15;
+    err_min =  g_q0 - err_min;
+    if (err_min < 0)
+    {
+        err_min = -err_min;
+    }
+
+    p += 2;                                  /* skip quantized energy errors */
+    index = 0;
+
+    for (i = 1; i < NB_QUA_CODE; i++)
+    {
+        err = ((Word32)gcode0 * *(p++)) >> 15;
+        err =  g_q0 - err;
+
+        if (err < 0)
+        {
+            err = -err;
+        }
+
+        p += 2;                              /* skip quantized energy error */
+
+        if (err < err_min)
+        {
+            err_min = err;
+            index = i;
+        }
+    }
+
+    temp = index + (index << 1);
+
+    p = &qua_gain_code[temp];
+
+    temp  = (gcode0 * *(p++)) >> 15;
+    if (mode == MR122)
+    {
+        *gain =  temp << 1;
+    }
+    else
+    {
+        *gain = temp;
+    }
+
+    /* quantized error energies (for MA predictor update) */
+    *qua_ener_MR122 = *p++;
+    *qua_ener = *p;
+
+    return index;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.h b/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.h
new file mode 100644
index 0000000..621143d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/q_gain_c.h
@@ -0,0 +1,136 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/q_gain.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, q_gain.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef q_gain_c_h
+#define q_gain_c_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "gc_pred.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*--------------------------------------------------------------------------*
+     * Function q_gain_code()                                                   *
+     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                  *
+     * Scalar quantization of the innovative codebook gain.                     *
+     *                                                                          *
+     * gc_pred() is used for MA prediction of the innovation energy             *
+     *--------------------------------------------------------------------------*/
+    Word16 q_gain_code(         /* o  : quantization index,            Q0  */
+        enum Mode mode,         /* i  : AMR mode                           */
+        Word16 exp_gcode0,      /* i  : predicted CB gain (exponent),  Q0  */
+        Word16 frac_gcode0,     /* i  : predicted CB gain (fraction),  Q15 */
+        Word16 *gain,           /* i/o: quantized fixed codebook gain, Q1  */
+        Word16 *qua_ener_MR122, /* o  : quantized energy error,        Q10 */
+        /*      (for MR122 MA predictor update)    */
+        Word16 *qua_ener,       /* o  : quantized energy error,        Q10 */
+        /*      (for other MA predictor update)    */
+        Flag   *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* q_gain_c_h */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.cpp b/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.cpp
new file mode 100644
index 0000000..c1aff6b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.cpp
@@ -0,0 +1,267 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/q_gain_p.c
+ Functions: q_gain_pitch
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "q_gain_p.h"
+#include "typedef.h"
+#include "oper_32b.h"
+#include "cnst.h"
+#include "basic_op.h"
+
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define NB_QUA_PITCH 16
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 qua_gain_pitch[NB_QUA_PITCH];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: q_gain_pitch
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode -- enum Mode -- AMR mode
+    gp_limit -- Word16 -- pitch gain limit
+    gain -- Pointer to Word16 -- Pitch gain (unquant/quant),              Q14
+
+ Outputs:
+    gain -- Pointer to Word16 -- Pitch gain (unquant/quant),              Q14
+
+    gain_cand -- Array of type Word16 -- pitch gain candidates (3),
+                                         MR795 only, Q14
+
+    gain_cind -- Array of type Word16 -- pitch gain cand. indices (3),
+                                         MR795 only, Q0
+
+    pOverflow -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    Word16 -- index of quantization
+
+ Global Variables Used:
+    qua_gain_pitch
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_gain_p.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 q_gain_pitch(    /* Return index of quantization                      */
+    enum Mode mode,     /* i  : AMR mode                                     */
+    Word16 gp_limit,    /* i  : pitch gain limit                             */
+    Word16 *gain,       /* i/o: Pitch gain (unquant/quant),              Q14 */
+    Word16 gain_cand[], /* o  : pitch gain candidates (3),   MR795 only, Q14 */
+    Word16 gain_cind[], /* o  : pitch gain cand. indices (3),MR795 only, Q0  */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 index;
+    Word16 err;
+    Word16 err_min;
+
+    err_min = sub(*gain, qua_gain_pitch[0], pOverflow);
+    err_min = abs_s(err_min);
+
+    index = 0;
+
+    for (i = 1; i < NB_QUA_PITCH; i++)
+    {
+        if (qua_gain_pitch[i] <= gp_limit)
+        {
+            err = sub(*gain, qua_gain_pitch[i], pOverflow);
+            err = abs_s(err);
+
+            if (err < err_min)
+            {
+                err_min = err;
+                index = i;
+            }
+        }
+    }
+
+    if (mode == MR795)
+    {
+        /* in MR795 mode, compute three gain_pit candidates around the index
+         * found in the quantization loop: the index found and the two direct
+         * neighbours, except for the extreme cases (i=0 or i=NB_QUA_PITCH-1),
+         * where the direct neighbour and the neighbour to that is used.
+         */
+        Word16 ii;
+
+        if (index == 0)
+        {
+            ii = index;
+        }
+        else
+        {
+            if (index == (NB_QUA_PITCH - 1) ||
+                    (qua_gain_pitch[index+1] > gp_limit))
+            {
+                ii = index - 2;
+            }
+            else
+            {
+                ii = index - 1;
+            }
+        }
+
+        /* store candidate indices and values */
+        for (i = 0; i < 3; i++)
+        {
+            gain_cind[i] = ii;
+            gain_cand[i] = qua_gain_pitch[ii];
+
+            ii = add(ii, 1, pOverflow);
+        }
+
+        *gain = qua_gain_pitch[index];
+    }
+    else
+    {
+        /* in MR122 mode, just return the index and gain pitch found.
+         * If bitexactness is required, mask away the two LSBs (because
+         * in the original EFR, gain_pit was scaled Q12)
+         */
+        if (mode == MR122)
+        {
+            /* clear 2 LSBits */
+            *gain = qua_gain_pitch[index] & 0xFFFC;
+        }
+        else
+        {
+            *gain = qua_gain_pitch[index];
+        }
+    }
+    return index;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.h b/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.h
new file mode 100644
index 0000000..233ccb0
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/q_gain_p.h
@@ -0,0 +1,124 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/q_gain_p.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, q_gain_p.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef q_gain_p_h
+#define q_gain_p_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 q_gain_pitch(    /* Return index of quantization                      */
+        enum Mode mode,     /* i  : AMR mode                                     */
+        Word16 gp_limit,    /* i  : pitch gain limit                             */
+        Word16 *gain,       /* i/o: Pitch gain (unquant/quant),              Q14 */
+        Word16 gain_cand[], /* o  : pitch gain candidates (3),   MR795 only, Q14 */
+        Word16 gain_cind[], /* o  : pitch gain cand. indices (3),MR795 only, Q0  */
+        Flag   *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* q_gain_p_h */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp b/media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp
new file mode 100644
index 0000000..f8da589
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/qgain475.cpp
@@ -0,0 +1,1445 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/qgain475.c
+ Funtions: MR475_quant_store_results
+           MR475_update_unq_pred
+           MR475_gain_quant
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These modules handle the quantization of pitch and codebook gains for MR475.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "qgain475.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "mode.h"
+#include "cnst.h"
+#include "pow2.h"
+#include "log2.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define MR475_VQ_SIZE 256
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* The table contains the following data:
+ *
+ *    g_pitch(0)        (Q14) // for sub-
+ *    g_fac(0)          (Q12) // frame 0 and 2
+ *    g_pitch(1)        (Q14) // for sub-
+ *    g_fac(2)          (Q12) // frame 1 and 3
+ *
+ */
+static const Word16 table_gain_MR475[MR475_VQ_SIZE*4] =
+{
+    /*g_pit(0), g_fac(0),      g_pit(1), g_fac(1) */
+    812,          128,           542,      140,
+    2873,         1135,          2266,     3402,
+    2067,          563,         12677,      647,
+    4132,         1798,          5601,     5285,
+    7689,          374,          3735,      441,
+    10912,         2638,         11807,     2494,
+    20490,          797,          5218,      675,
+    6724,         8354,          5282,     1696,
+    1488,          428,          5882,      452,
+    5332,         4072,          3583,     1268,
+    2469,          901,         15894,     1005,
+    14982,         3271,         10331,     4858,
+    3635,         2021,          2596,      835,
+    12360,         4892,         12206,     1704,
+    13432,         1604,          9118,     2341,
+    3968,         1538,          5479,     9936,
+    3795,          417,          1359,      414,
+    3640,         1569,          7995,     3541,
+    11405,          645,          8552,      635,
+    4056,         1377,         16608,     6124,
+    11420,          700,          2007,      607,
+    12415,         1578,         11119,     4654,
+    13680,         1708,         11990,     1229,
+    7996,         7297,         13231,     5715,
+    2428,         1159,          2073,     1941,
+    6218,         6121,          3546,     1804,
+    8925,         1802,          8679,     1580,
+    13935,         3576,         13313,     6237,
+    6142,         1130,          5994,     1734,
+    14141,         4662,         11271,     3321,
+    12226,         1551,         13931,     3015,
+    5081,        10464,          9444,     6706,
+    1689,          683,          1436,     1306,
+    7212,         3933,          4082,     2713,
+    7793,          704,         15070,      802,
+    6299,         5212,          4337,     5357,
+    6676,          541,          6062,      626,
+    13651,         3700,         11498,     2408,
+    16156,          716,         12177,      751,
+    8065,        11489,          6314,     2256,
+    4466,          496,          7293,      523,
+    10213,         3833,          8394,     3037,
+    8403,          966,         14228,     1880,
+    8703,         5409,         16395,     4863,
+    7420,         1979,          6089,     1230,
+    9371,         4398,         14558,     3363,
+    13559,         2873,         13163,     1465,
+    5534,         1678,         13138,    14771,
+    7338,          600,          1318,      548,
+    4252,         3539,         10044,     2364,
+    10587,          622,         13088,      669,
+    14126,         3526,          5039,     9784,
+    15338,          619,          3115,      590,
+    16442,         3013,         15542,     4168,
+    15537,         1611,         15405,     1228,
+    16023,         9299,          7534,     4976,
+    1990,         1213,         11447,     1157,
+    12512,         5519,          9475,     2644,
+    7716,         2034,         13280,     2239,
+    16011,         5093,          8066,     6761,
+    10083,         1413,          5002,     2347,
+    12523,         5975,         15126,     2899,
+    18264,         2289,         15827,     2527,
+    16265,        10254,         14651,    11319,
+    1797,          337,          3115,      397,
+    3510,         2928,          4592,     2670,
+    7519,          628,         11415,      656,
+    5946,         2435,          6544,     7367,
+    8238,          829,          4000,      863,
+    10032,         2492,         16057,     3551,
+    18204,         1054,          6103,     1454,
+    5884,         7900,         18752,     3468,
+    1864,          544,          9198,      683,
+    11623,         4160,          4594,     1644,
+    3158,         1157,         15953,     2560,
+    12349,         3733,         17420,     5260,
+    6106,         2004,          2917,     1742,
+    16467,         5257,         16787,     1680,
+    17205,         1759,          4773,     3231,
+    7386,         6035,         14342,    10012,
+    4035,          442,          4194,      458,
+    9214,         2242,          7427,     4217,
+    12860,          801,         11186,      825,
+    12648,         2084,         12956,     6554,
+    9505,          996,          6629,      985,
+    10537,         2502,         15289,     5006,
+    12602,         2055,         15484,     1653,
+    16194,         6921,         14231,     5790,
+    2626,          828,          5615,     1686,
+    13663,         5778,          3668,     1554,
+    11313,         2633,          9770,     1459,
+    14003,         4733,         15897,     6291,
+    6278,         1870,          7910,     2285,
+    16978,         4571,         16576,     3849,
+    15248,         2311,         16023,     3244,
+    14459,        17808,         11847,     2763,
+    1981,         1407,          1400,      876,
+    4335,         3547,          4391,     4210,
+    5405,          680,         17461,      781,
+    6501,         5118,          8091,     7677,
+    7355,          794,          8333,     1182,
+    15041,         3160,         14928,     3039,
+    20421,          880,         14545,      852,
+    12337,        14708,          6904,     1920,
+    4225,          933,          8218,     1087,
+    10659,         4084,         10082,     4533,
+    2735,          840,         20657,     1081,
+    16711,         5966,         15873,     4578,
+    10871,         2574,          3773,     1166,
+    14519,         4044,         20699,     2627,
+    15219,         2734,         15274,     2186,
+    6257,         3226,         13125,    19480,
+    7196,          930,          2462,     1618,
+    4515,         3092,         13852,     4277,
+    10460,          833,         17339,      810,
+    16891,         2289,         15546,     8217,
+    13603,         1684,          3197,     1834,
+    15948,         2820,         15812,     5327,
+    17006,         2438,         16788,     1326,
+    15671,         8156,         11726,     8556,
+    3762,         2053,          9563,     1317,
+    13561,         6790,         12227,     1936,
+    8180,         3550,         13287,     1778,
+    16299,         6599,         16291,     7758,
+    8521,         2551,          7225,     2645,
+    18269,         7489,         16885,     2248,
+    17882,         2884,         17265,     3328,
+    9417,        20162,         11042,     8320,
+    1286,          620,          1431,      583,
+    5993,         2289,          3978,     3626,
+    5144,          752,         13409,      830,
+    5553,         2860,         11764,     5908,
+    10737,          560,          5446,      564,
+    13321,         3008,         11946,     3683,
+    19887,          798,          9825,      728,
+    13663,         8748,          7391,     3053,
+    2515,          778,          6050,      833,
+    6469,         5074,          8305,     2463,
+    6141,         1865,         15308,     1262,
+    14408,         4547,         13663,     4515,
+    3137,         2983,          2479,     1259,
+    15088,         4647,         15382,     2607,
+    14492,         2392,         12462,     2537,
+    7539,         2949,         12909,    12060,
+    5468,          684,          3141,      722,
+    5081,         1274,         12732,     4200,
+    15302,          681,          7819,      592,
+    6534,         2021,         16478,     8737,
+    13364,          882,          5397,      899,
+    14656,         2178,         14741,     4227,
+    14270,         1298,         13929,     2029,
+    15477,         7482,         15815,     4572,
+    2521,         2013,          5062,     1804,
+    5159,         6582,          7130,     3597,
+    10920,         1611,         11729,     1708,
+    16903,         3455,         16268,     6640,
+    9306,         1007,          9369,     2106,
+    19182,         5037,         12441,     4269,
+    15919,         1332,         15357,     3512,
+    11898,        14141,         16101,     6854,
+    2010,          737,          3779,      861,
+    11454,         2880,          3564,     3540,
+    9057,         1241,         12391,      896,
+    8546,         4629,         11561,     5776,
+    8129,          589,          8218,      588,
+    18728,         3755,         12973,     3149,
+    15729,          758,         16634,      754,
+    15222,        11138,         15871,     2208,
+    4673,          610,         10218,      678,
+    15257,         4146,          5729,     3327,
+    8377,         1670,         19862,     2321,
+    15450,         5511,         14054,     5481,
+    5728,         2888,          7580,     1346,
+    14384,         5325,         16236,     3950,
+    15118,         3744,         15306,     1435,
+    14597,         4070,         12301,    15696,
+    7617,         1699,          2170,      884,
+    4459,         4567,         18094,     3306,
+    12742,          815,         14926,      907,
+    15016,         4281,         15518,     8368,
+    17994,         1087,          2358,      865,
+    16281,         3787,         15679,     4596,
+    16356,         1534,         16584,     2210,
+    16833,         9697,         15929,     4513,
+    3277,         1085,          9643,     2187,
+    11973,         6068,          9199,     4462,
+    8955,         1629,         10289,     3062,
+    16481,         5155,         15466,     7066,
+    13678,         2543,          5273,     2277,
+    16746,         6213,         16655,     3408,
+    20304,         3363,         18688,     1985,
+    14172,        12867,         15154,    15703,
+    4473,         1020,          1681,      886,
+    4311,         4301,          8952,     3657,
+    5893,         1147,         11647,     1452,
+    15886,         2227,          4582,     6644,
+    6929,         1205,          6220,      799,
+    12415,         3409,         15968,     3877,
+    19859,         2109,          9689,     2141,
+    14742,         8830,         14480,     2599,
+    1817,         1238,          7771,      813,
+    19079,         4410,          5554,     2064,
+    3687,         2844,         17435,     2256,
+    16697,         4486,         16199,     5388,
+    8028,         2763,          3405,     2119,
+    17426,         5477,         13698,     2786,
+    19879,         2720,          9098,     3880,
+    18172,         4833,         17336,    12207,
+    5116,          996,          4935,      988,
+    9888,         3081,          6014,     5371,
+    15881,         1667,          8405,     1183,
+    15087,         2366,         19777,     7002,
+    11963,         1562,          7279,     1128,
+    16859,         1532,         15762,     5381,
+    14708,         2065,         20105,     2155,
+    17158,         8245,         17911,     6318,
+    5467,         1504,          4100,     2574,
+    17421,         6810,          5673,     2888,
+    16636,         3382,          8975,     1831,
+    20159,         4737,         19550,     7294,
+    6658,         2781,         11472,     3321,
+    19397,         5054,         18878,     4722,
+    16439,         2373,         20430,     4386,
+    11353,        26526,         11593,     3068,
+    2866,         1566,          5108,     1070,
+    9614,         4915,          4939,     3536,
+    7541,          878,         20717,      851,
+    6938,         4395,         16799,     7733,
+    10137,         1019,          9845,      964,
+    15494,         3955,         15459,     3430,
+    18863,          982,         20120,      963,
+    16876,        12887,         14334,     4200,
+    6599,         1220,          9222,      814,
+    16942,         5134,          5661,     4898,
+    5488,         1798,         20258,     3962,
+    17005,         6178,         17929,     5929,
+    9365,         3420,          7474,     1971,
+    19537,         5177,         19003,     3006,
+    16454,         3788,         16070,     2367,
+    8664,         2743,          9445,    26358,
+    10856,         1287,          3555,     1009,
+    5606,         3622,         19453,     5512,
+    12453,          797,         20634,      911,
+    15427,         3066,         17037,    10275,
+    18883,         2633,          3913,     1268,
+    19519,         3371,         18052,     5230,
+    19291,         1678,         19508,     3172,
+    18072,        10754,         16625,     6845,
+    3134,         2298,         10869,     2437,
+    15580,         6913,         12597,     3381,
+    11116,         3297,         16762,     2424,
+    18853,         6715,         17171,     9887,
+    12743,         2605,          8937,     3140,
+    19033,         7764,         18347,     3880,
+    20475,         3682,         19602,     3380,
+    13044,        19373,         10526,    23124
+};
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR475_quant_store_results
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pred_st = pointer to structure of type gc_predState
+    p = pointer to selected quantizer table entry (const Word16)
+    gcode0 = predicted CB gain (Word16)
+    exp_gcode0 = exponent of predicted CB gain (Word16)
+    gain_pit = pointer to Pitch gain (Word16)
+    gain_cod = pointer to Code gain (Word16)
+
+ Outputs:
+    pred_st points to the updated structure of type gc_predState
+    gain_pit points to Pitch gain
+    gain_cod points to Code gain
+    pOverflow points to overflow indicator (Flag)
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the final fixed codebook gain and the predictor
+ update values, and updates the gain predictor.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain475.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void MR475_quant_store_results(
+
+    gc_predState *pred_st, // i/o: gain predictor state struct
+    const Word16 *p,       // i  : pointer to selected quantizer table entry
+    Word16 gcode0,         // i  : predicted CB gain,     Q(14 - exp_gcode0)
+    Word16 exp_gcode0,     // i  : exponent of predicted CB gain,        Q0
+    Word16 *gain_pit,      // o  : Pitch gain,                           Q14
+    Word16 *gain_cod       // o  : Code gain,                            Q1
+)
+{
+
+    Word16 g_code, exp, frac, tmp;
+    Word32 L_tmp;
+
+    Word16 qua_ener_MR122; // o  : quantized energy error, MR122 version Q10
+    Word16 qua_ener;       // o  : quantized energy error,               Q10
+
+    // Read the quantized gains
+    *gain_pit = *p++;
+    g_code = *p++;
+
+    //------------------------------------------------------------------*
+     *  calculate final fixed codebook gain:                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
+     *                                                                  *
+     *   gc = gc0 * g                                                   *
+     *------------------------------------------------------------------
+
+    L_tmp = L_mult(g_code, gcode0);
+    L_tmp = L_shr(L_tmp, sub(10, exp_gcode0));
+    *gain_cod = extract_h(L_tmp);
+
+    //------------------------------------------------------------------*
+     *  calculate predictor update values and update gain predictor:    *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    *
+     *                                                                  *
+     *   qua_ener       = log2(g)                                       *
+     *   qua_ener_MR122 = 20*log10(g)                                   *
+     *------------------------------------------------------------------
+
+    Log2 (L_deposit_l (g_code), &exp, &frac); // Log2(x Q12) = log2(x) + 12
+    exp = sub(exp, 12);
+
+    tmp = shr_r (frac, 5);
+    qua_ener_MR122 = add (tmp, shl (exp, 10));
+
+    L_tmp = Mpy_32_16(exp, frac, 24660); // 24660 Q12 ~= 6.0206 = 20*log10(2)
+    qua_ener = pv_round (L_shl (L_tmp, 13)); // Q12 * Q0 = Q13 -> Q10
+
+    gc_pred_update(pred_st, qua_ener_MR122, qua_ener);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void MR475_quant_store_results(
+    gc_predState *pred_st, /* i/o: gain predictor state struct               */
+    const Word16 *p,       /* i  : pointer to selected quantizer table entry */
+    Word16 gcode0,         /* i  : predicted CB gain,     Q(14 - exp_gcode0) */
+    Word16 exp_gcode0,     /* i  : exponent of predicted CB gain,        Q0  */
+    Word16 *gain_pit,      /* o  : Pitch gain,                           Q14 */
+    Word16 *gain_cod,      /* o  : Code gain,                            Q1  */
+    Flag   *pOverflow      /* o  : overflow indicator                        */
+)
+{
+    Word16 g_code;
+    Word16 exp;
+    Word16 frac;
+    Word16 tmp;
+    Word32 L_tmp;
+
+    Word16 qua_ener_MR122; /* o  : quantized energy error, MR122 version Q10 */
+    Word16 qua_ener;       /* o  : quantized energy error,               Q10 */
+
+
+    /* Read the quantized gains */
+    *gain_pit = *p++;
+    g_code = *p++;
+
+    /*------------------------------------------------------------------*
+     *  calculate final fixed codebook gain:                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
+     *                                                                  *
+     *   gc = gc0 * g                                                   *
+     *------------------------------------------------------------------*/
+
+    L_tmp = ((Word32) g_code * gcode0) << 1;
+    tmp   = 10 - exp_gcode0;
+    L_tmp = L_shr(L_tmp, tmp, pOverflow);
+    *gain_cod = (Word16)(L_tmp >> 16);
+
+    /*------------------------------------------------------------------*
+     *  calculate predictor update values and update gain predictor:    *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    *
+     *                                                                  *
+     *   qua_ener       = log2(g)                                       *
+     *   qua_ener_MR122 = 20*log10(g)                                   *
+     *------------------------------------------------------------------*/
+
+    /* Log2(x Q12) = log2(x) + 12 */
+    Log2((Word32) g_code, &exp, &frac, pOverflow);
+    exp -= 12;
+
+    tmp = shr_r(frac, 5, pOverflow);
+    qua_ener_MR122 = exp << 10;
+    qua_ener_MR122 = tmp + qua_ener_MR122;
+
+    /* 24660 Q12 ~= 6.0206 = 20*log10(2) */
+    L_tmp = Mpy_32_16(exp, frac, 24660, pOverflow);
+    L_tmp = L_tmp << 13;
+
+    /* Q12 * Q0 = Q13 -> Q10 */
+    qua_ener = (Word16)((L_tmp + (Word32) 0x00008000L) >> 16);
+
+    gc_pred_update(pred_st, qua_ener_MR122, qua_ener);
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR475_update_unq_pred
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pred_st = pointer to structure of type gc_predState
+    exp_gcode0 = predicted CB gain (exponent MSW) (Word16)
+    frac_gcode0 = predicted CB gain (exponent LSW) (Word16)
+    cod_gain_exp = optimum codebook gain (exponent)(Word16)
+    cod_gain_frac = optimum codebook gain (fraction) (Word16)
+
+ Outputs:
+    pred_st points to the updated structure of type gc_predState
+    pOverflow points to overflow indicator (Flag)
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module uses the optimum codebook gain and updates the "unquantized"
+ gain predictor with the (bounded) prediction error.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain475.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void
+MR475_update_unq_pred(
+    gc_predState *pred_st, // i/o: gain predictor state struct
+    Word16 exp_gcode0,     // i  : predicted CB gain (exponent MSW),  Q0
+    Word16 frac_gcode0,    // i  : predicted CB gain (exponent LSW),  Q15
+    Word16 cod_gain_exp,   // i  : optimum codebook gain (exponent),  Q0
+    Word16 cod_gain_frac   // i  : optimum codebook gain (fraction),  Q15
+)
+{
+    Word16 tmp, exp, frac;
+    Word16 qua_ener, qua_ener_MR122;
+    Word32 L_tmp;
+
+    // calculate prediction error factor (given optimum CB gain gcu):
+    //   predErrFact = gcu / gcode0
+    //   (limit to MIN_PRED_ERR_FACT <= predErrFact <= MAX_PRED_ERR_FACT
+    //    -> limit qua_ener*)
+    //
+    // calculate prediction error (log):
+    //
+    //   qua_ener_MR122 = log2(predErrFact)
+    //   qua_ener       = 20*log10(predErrFact)
+
+    if (cod_gain_frac <= 0)
+    {
+        // if gcu <= 0 -> predErrFact = 0 < MIN_PRED_ERR_FACT
+        // -> set qua_ener(_MR122) directly
+        qua_ener = MIN_QUA_ENER;
+        qua_ener_MR122 = MIN_QUA_ENER_MR122;
+    }
+    else
+    {
+        // convert gcode0 from DPF to standard fraction/exponent format
+        // with normalized frac, i.e. 16384 <= frac <= 32767
+        // Note: exponent correction (exp=exp-14) is done after div_s
+        frac_gcode0 = extract_l (Pow2 (14, frac_gcode0));
+
+        // make sure cod_gain_frac < frac_gcode0  for div_s
+        if (sub(cod_gain_frac, frac_gcode0) >= 0)
+        {
+            cod_gain_frac = shr (cod_gain_frac, 1);
+            cod_gain_exp = add (cod_gain_exp, 1);
+        }
+
+        // predErrFact
+        //   = gcu / gcode0
+        //   = cod_gain_frac/frac_gcode0 * 2^(cod_gain_exp-(exp_gcode0-14))
+        //   = div_s (c_g_f, frac_gcode0)*2^-15 * 2^(c_g_e-exp_gcode0+14)
+        //   = div_s * 2^(cod_gain_exp-exp_gcode0 - 1)
+
+        frac = div_s (cod_gain_frac, frac_gcode0);
+        tmp = sub (sub (cod_gain_exp, exp_gcode0), 1);
+
+        Log2 (L_deposit_l (frac), &exp, &frac);
+        exp = add (exp, tmp);
+
+        // calculate prediction error (log2, Q10)
+        qua_ener_MR122 = shr_r (frac, 5);
+        qua_ener_MR122 = add (qua_ener_MR122, shl (exp, 10));
+
+        if (sub(qua_ener_MR122, MIN_QUA_ENER_MR122) < 0)
+        {
+            qua_ener = MIN_QUA_ENER;
+            qua_ener_MR122 = MIN_QUA_ENER_MR122;
+        }
+        else if (sub(qua_ener_MR122, MAX_QUA_ENER_MR122) > 0)
+        {
+            qua_ener = MAX_QUA_ENER;
+            qua_ener_MR122 = MAX_QUA_ENER_MR122;
+        }
+        else
+        {
+            // calculate prediction error (20*log10, Q10)
+            L_tmp = Mpy_32_16(exp, frac, 24660);
+            // 24660 Q12 ~= 6.0206 = 20*log10(2)
+            qua_ener = pv_round (L_shl (L_tmp, 13));
+            // Q12 * Q0 = Q13 -> Q26 -> Q10
+        }
+    }
+
+    // update MA predictor memory
+    gc_pred_update(pred_st, qua_ener_MR122, qua_ener);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void MR475_update_unq_pred(
+    gc_predState *pred_st, /* i/o: gain predictor state struct            */
+    Word16 exp_gcode0,     /* i  : predicted CB gain (exponent MSW),  Q0  */
+    Word16 frac_gcode0,    /* i  : predicted CB gain (exponent LSW),  Q15 */
+    Word16 cod_gain_exp,   /* i  : optimum codebook gain (exponent),  Q0  */
+    Word16 cod_gain_frac,  /* i  : optimum codebook gain (fraction),  Q15 */
+    Flag   *pOverflow      /* o  : overflow indicator                     */
+)
+{
+    Word16 tmp;
+    Word16 exp;
+    Word16 frac;
+    Word16 qua_ener;
+    Word16 qua_ener_MR122;
+    Word32 L_tmp;
+
+    /* calculate prediction error factor (given optimum CB gain gcu):
+     *
+     *   predErrFact = gcu / gcode0
+     *   (limit to MIN_PRED_ERR_FACT <= predErrFact <= MAX_PRED_ERR_FACT
+     *    -> limit qua_ener*)
+     *
+     * calculate prediction error (log):
+     *
+     *   qua_ener_MR122 = log2(predErrFact)
+     *   qua_ener       = 20*log10(predErrFact)
+     *
+     */
+
+    if (cod_gain_frac <= 0)
+    {
+        /* if gcu <= 0 -> predErrFact = 0 < MIN_PRED_ERR_FACT */
+        /* -> set qua_ener(_MR122) directly                   */
+        qua_ener = MIN_QUA_ENER;
+        qua_ener_MR122 = MIN_QUA_ENER_MR122;
+    }
+    else
+    {
+        /* convert gcode0 from DPF to standard fraction/exponent format */
+        /* with normalized frac, i.e. 16384 <= frac <= 32767            */
+        /* Note: exponent correction (exp=exp-14) is done after div_s   */
+        frac_gcode0 = (Word16)(Pow2(14, frac_gcode0, pOverflow));
+
+        /* make sure cod_gain_frac < frac_gcode0  for div_s */
+        if (cod_gain_frac >= frac_gcode0)
+        {
+            cod_gain_frac >>= 1;
+            cod_gain_exp += 1;
+        }
+
+        /*
+          predErrFact
+             = gcu / gcode0
+             = cod_gain_frac/frac_gcode0 * 2^(cod_gain_exp-(exp_gcode0-14))
+             = div_s (c_g_f, frac_gcode0)*2^-15 * 2^(c_g_e-exp_gcode0+14)
+             = div_s * 2^(cod_gain_exp-exp_gcode0 - 1)
+        */
+        frac = div_s(cod_gain_frac, frac_gcode0);
+        tmp = cod_gain_exp - exp_gcode0;
+        tmp -= 1;
+
+        Log2((Word32) frac, &exp, &frac, pOverflow);
+        exp += tmp;
+
+        /* calculate prediction error (log2, Q10) */
+        qua_ener_MR122 = shr_r(frac, 5, pOverflow);
+        tmp = exp << 10;
+        qua_ener_MR122 += tmp;
+
+        if (qua_ener_MR122 > MAX_QUA_ENER_MR122)
+        {
+            qua_ener = MAX_QUA_ENER;
+            qua_ener_MR122 = MAX_QUA_ENER_MR122;
+        }
+        else
+        {
+            /* calculate prediction error (20*log10, Q10) */
+            L_tmp = Mpy_32_16(exp, frac, 24660, pOverflow);
+            /* 24660 Q12 ~= 6.0206 = 20*log10(2) */
+            L_tmp =  L_shl(L_tmp, 13, pOverflow);
+            qua_ener = pv_round(L_tmp, pOverflow);
+
+            /* Q12 * Q0 = Q13 -> Q26 -> Q10     */
+        }
+    }
+
+    /* update MA predictor memory */
+    gc_pred_update(pred_st, qua_ener_MR122, qua_ener);
+
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR475_gain_quant
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pred_st = pointer to structure of type gc_predState
+    sf0_exp_gcode0 = predicted CB gain (exponent) (Word16)
+    f0_frac_gcode0 = predicted CB gain (fraction) (Word16)
+    sf0_exp_coeff = energy coeff. (exponent part) (Word16)
+    sf0_frac_coeff = energy coeff. ((fraction part) (Word16)
+    sf0_exp_target_en = exponent of target energy (Word16)
+    sf0_frac_target_en = fraction of target energy (Word16)
+    sf1_code_nosharp = innovative codebook vector  (Word16)
+    sf1_exp_gcode0 = predicted CB gain (exponent) (Word16)
+    sf1_frac_gcode0 = predicted CB gain (fraction) (Word16)
+    sf1_exp_coeff = energy coeff. (exponent part) (Word16)
+    sf1_frac_coeff = energy coeff. (fraction part) (Word16)
+    sf1_exp_target_en = exponent of target energy (Word16)
+    sf1_frac_target_en = fraction of target energy (Word16)
+    gp_limit = pitch gain limit (Word16)
+    sf0_gain_pit = pointer to Pitch gain (Word16)
+    sf0_gain_cod = pointer to Code gain (Word16)
+    sf1_gain_pit = pointer to Pitch gain (Word16)
+    sf1_gain_cod = pointer to Code gain (Word16)
+
+ Outputs:
+    pred_st points to the updated structure of type gc_predState
+    sf0_gain_pit points to Pitch gain
+    sf0_gain_cod points to Code gain
+    sf1_gain_pit points to Pitch gain
+    sf1_gain_cod points to Code gain
+
+ Returns:
+    index = index of quantization
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module provides quantization of pitch and codebook gains for two
+ subframes using the predicted codebook gain.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain475.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16
+MR475_gain_quant(              // o  : index of quantization.
+    gc_predState *pred_st,     // i/o: gain predictor state struct
+
+                               // data from subframe 0 (or 2)
+    Word16 sf0_exp_gcode0,     // i  : predicted CB gain (exponent),      Q0
+    Word16 sf0_frac_gcode0,    // i  : predicted CB gain (fraction),      Q15
+    Word16 sf0_exp_coeff[],    // i  : energy coeff. (5), exponent part,  Q0
+    Word16 sf0_frac_coeff[],   // i  : energy coeff. (5), fraction part,  Q15
+                               //      (frac_coeff and exp_coeff computed in
+                               //       calc_filt_energies())
+    Word16 sf0_exp_target_en,  // i  : exponent of target energy,         Q0
+    Word16 sf0_frac_target_en, // i  : fraction of target energy,         Q15
+
+                               // data from subframe 1 (or 3)
+    Word16 sf1_code_nosharp[], // i  : innovative codebook vector (L_SUBFR)
+                               //      (whithout pitch sharpening)
+    Word16 sf1_exp_gcode0,     // i  : predicted CB gain (exponent),      Q0
+    Word16 sf1_frac_gcode0,    // i  : predicted CB gain (fraction),      Q15
+    Word16 sf1_exp_coeff[],    // i  : energy coeff. (5), exponent part,  Q0
+    Word16 sf1_frac_coeff[],   // i  : energy coeff. (5), fraction part,  Q15
+                               //      (frac_coeff and exp_coeff computed in
+                               //       calc_filt_energies())
+    Word16 sf1_exp_target_en,  // i  : exponent of target energy,         Q0
+    Word16 sf1_frac_target_en, // i  : fraction of target energy,         Q15
+
+    Word16 gp_limit,           // i  : pitch gain limit
+
+    Word16 *sf0_gain_pit,      // o  : Pitch gain,                        Q14
+    Word16 *sf0_gain_cod,      // o  : Code gain,                         Q1
+
+    Word16 *sf1_gain_pit,      // o  : Pitch gain,                        Q14
+    Word16 *sf1_gain_cod       // o  : Code gain,                         Q1
+)
+{
+    const Word16 *p;
+    Word16 i, index = 0;
+    Word16 tmp;
+    Word16 exp;
+    Word16 sf0_gcode0, sf1_gcode0;
+    Word16 g_pitch, g2_pitch, g_code, g2_code, g_pit_cod;
+    Word16 coeff[10], coeff_lo[10], exp_max[10];  // 0..4: sf0; 5..9: sf1
+    Word32 L_tmp, dist_min;
+
+     *-------------------------------------------------------------------*
+     *  predicted codebook gain                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *  gc0     = 2^exp_gcode0 + 2^frac_gcode0                           *
+     *                                                                   *
+     *  gcode0 (Q14) = 2^14*2^frac_gcode0 = gc0 * 2^(14-exp_gcode0)      *
+     *-------------------------------------------------------------------*
+
+    sf0_gcode0 = extract_l(Pow2(14, sf0_frac_gcode0));
+    sf1_gcode0 = extract_l(Pow2(14, sf1_frac_gcode0));
+
+     * For each subframe, the error energy (sum) to be minimized consists
+     * of five terms, t[0..4].
+     *
+     *                      t[0] =    gp^2  * <y1 y1>
+     *                      t[1] = -2*gp    * <xn y1>
+     *                      t[2] =    gc^2  * <y2 y2>
+     *                      t[3] = -2*gc    * <xn y2>
+     *                      t[4] =  2*gp*gc * <y1 y2>
+     *
+
+    // sf 0
+    // determine the scaling exponent for g_code: ec = ec0 - 11
+    exp = sub(sf0_exp_gcode0, 11);
+
+    // calculate exp_max[i] = s[i]-1
+    exp_max[0] = sub(sf0_exp_coeff[0], 13);
+    exp_max[1] = sub(sf0_exp_coeff[1], 14);
+    exp_max[2] = add(sf0_exp_coeff[2], add(15, shl(exp, 1)));
+    exp_max[3] = add(sf0_exp_coeff[3], exp);
+    exp_max[4] = add(sf0_exp_coeff[4], add(1, exp));
+
+    // sf 1
+    // determine the scaling exponent for g_code: ec = ec0 - 11
+    exp = sub(sf1_exp_gcode0, 11);
+
+    // calculate exp_max[i] = s[i]-1
+    exp_max[5] = sub(sf1_exp_coeff[0], 13);
+    exp_max[6] = sub(sf1_exp_coeff[1], 14);
+    exp_max[7] = add(sf1_exp_coeff[2], add(15, shl(exp, 1)));
+    exp_max[8] = add(sf1_exp_coeff[3], exp);
+    exp_max[9] = add(sf1_exp_coeff[4], add(1, exp));
+
+     *-------------------------------------------------------------------*
+     *  Gain search equalisation:                                        *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                        *
+     *  The MSE for the two subframes is weighted differently if there   *
+     *  is a big difference in the corresponding target energies         *
+     *-------------------------------------------------------------------*
+
+    // make the target energy exponents the same by de-normalizing the
+    // fraction of the smaller one. This is necessary to be able to compare
+    // them
+
+    exp = sf0_exp_target_en - sf1_exp_target_en;
+    if (exp > 0)
+    {
+        sf1_frac_target_en = shr (sf1_frac_target_en, exp);
+    }
+    else
+    {
+        sf0_frac_target_en = shl (sf0_frac_target_en, exp);
+    }
+
+    // assume no change of exponents
+    exp = 0;
+
+    // test for target energy difference; set exp to +1 or -1 to scale
+    // up/down coefficients for sf 1
+
+    tmp = shr_r (sf1_frac_target_en, 1);   // tmp = ceil(0.5*en(sf1))
+    if (sub (tmp, sf0_frac_target_en) > 0) // tmp > en(sf0)?
+    {
+        // target_energy(sf1) > 2*target_energy(sf0)
+        //   -> scale up MSE(sf0) by 2 by adding 1 to exponents 0..4
+        exp = 1;
+    }
+    else
+    {
+        tmp = shr (add (sf0_frac_target_en, 3), 2); // tmp=ceil(0.25*en(sf0))
+        if (sub (tmp, sf1_frac_target_en) > 0)      // tmp > en(sf1)?
+        {
+            // target_energy(sf1) < 0.25*target_energy(sf0)
+            //   -> scale down MSE(sf0) by 0.5 by subtracting 1 from
+            //      coefficients 0..4
+            exp = -1;
+        }
+    }
+
+    for (i = 0; i < 5; i++)
+    {
+        exp_max[i] = add (exp_max[i], exp);
+    }
+
+     *-------------------------------------------------------------------*
+     *  Find maximum exponent:                                           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~                                           *
+     *                                                                   *
+     *  For the sum operation, all terms must have the same scaling;     *
+     *  that scaling should be low enough to prevent overflow. There-    *
+     *  fore, the maximum scale is determined and all coefficients are   *
+     *  re-scaled:                                                       *
+     *                                                                   *
+     *    exp = max(exp_max[i]) + 1;                                     *
+     *    e = exp_max[i]-exp;         e <= 0!                            *
+     *    c[i] = c[i]*2^e                                                *
+     *-------------------------------------------------------------------*
+
+    exp = exp_max[0];
+    for (i = 1; i < 10; i++)
+    {
+        if (sub(exp_max[i], exp) > 0)
+        {
+            exp = exp_max[i];
+        }
+    }
+    exp = add(exp, 1);      // To avoid overflow
+
+    p = &sf0_frac_coeff[0];
+    for (i = 0; i < 5; i++) {
+        tmp = sub(exp, exp_max[i]);
+        L_tmp = L_deposit_h(*p++);
+        L_tmp = L_shr(L_tmp, tmp);
+        L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
+    }
+    p = &sf1_frac_coeff[0];
+    for (; i < 10; i++) {
+        tmp = sub(exp, exp_max[i]);
+        L_tmp = L_deposit_h(*p++);
+        L_tmp = L_shr(L_tmp, tmp);
+        L_Extract(L_tmp, &coeff[i], &coeff_lo[i]);
+    }
+
+    //-------------------------------------------------------------------*
+     *  Codebook search:                                                 *
+     *  ~~~~~~~~~~~~~~~~                                                 *
+     *                                                                   *
+     *  For each pair (g_pitch, g_fac) in the table calculate the        *
+     *  terms t[0..4] and sum them up; the result is the mean squared    *
+     *  error for the quantized gains from the table. The index for the  *
+     *  minimum MSE is stored and finally used to retrieve the quantized *
+     *  gains                                                            *
+     *-------------------------------------------------------------------
+
+    // start with "infinite" MSE
+    dist_min = MAX_32;
+
+    p = &table_gain_MR475[0];
+
+    for (i = 0; i < MR475_VQ_SIZE; i++)
+    {
+        // subframe 0 (and 2) calculations
+        g_pitch = *p++;
+        g_code = *p++;
+
+        g_code = mult(g_code, sf0_gcode0);
+        g2_pitch = mult(g_pitch, g_pitch);
+        g2_code = mult(g_code, g_code);
+        g_pit_cod = mult(g_code, g_pitch);
+
+        L_tmp = Mpy_32_16(       coeff[0], coeff_lo[0], g2_pitch);
+        L_tmp = Mac_32_16(L_tmp, coeff[1], coeff_lo[1], g_pitch);
+        L_tmp = Mac_32_16(L_tmp, coeff[2], coeff_lo[2], g2_code);
+        L_tmp = Mac_32_16(L_tmp, coeff[3], coeff_lo[3], g_code);
+        L_tmp = Mac_32_16(L_tmp, coeff[4], coeff_lo[4], g_pit_cod);
+
+        tmp = sub (g_pitch, gp_limit);
+
+        // subframe 1 (and 3) calculations
+        g_pitch = *p++;
+        g_code = *p++;
+
+        if (tmp <= 0 && sub(g_pitch, gp_limit) <= 0)
+        {
+            g_code = mult(g_code, sf1_gcode0);
+            g2_pitch = mult(g_pitch, g_pitch);
+            g2_code = mult(g_code, g_code);
+            g_pit_cod = mult(g_code, g_pitch);
+
+            L_tmp = Mac_32_16(L_tmp, coeff[5], coeff_lo[5], g2_pitch);
+            L_tmp = Mac_32_16(L_tmp, coeff[6], coeff_lo[6], g_pitch);
+            L_tmp = Mac_32_16(L_tmp, coeff[7], coeff_lo[7], g2_code);
+            L_tmp = Mac_32_16(L_tmp, coeff[8], coeff_lo[8], g_code);
+            L_tmp = Mac_32_16(L_tmp, coeff[9], coeff_lo[9], g_pit_cod);
+
+            // store table index if MSE for this index is lower
+               than the minimum MSE seen so far
+            if (L_sub(L_tmp, dist_min) < (Word32) 0)
+            {
+                dist_min = L_tmp;
+                index = i;
+            }
+        }
+    }
+
+     *------------------------------------------------------------------*
+     *  read quantized gains and update MA predictor memories           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~           *
+     *------------------------------------------------------------------*
+
+    // for subframe 0, the pre-calculated gcode0/exp_gcode0 are the same
+    // as those calculated from the "real" predictor using quantized gains
+    tmp = shl(index, 2);
+    MR475_quant_store_results(pred_st,
+                              &table_gain_MR475[tmp],
+                              sf0_gcode0,
+                              sf0_exp_gcode0,
+                              sf0_gain_pit,
+                              sf0_gain_cod);
+
+    // calculate new predicted gain for subframe 1 (this time using
+    // the real, quantized gains)
+    gc_pred(pred_st, MR475, sf1_code_nosharp,
+            &sf1_exp_gcode0, &sf1_frac_gcode0,
+            &sf0_exp_gcode0, &sf0_gcode0); // last two args are dummy
+    sf1_gcode0 = extract_l(Pow2(14, sf1_frac_gcode0));
+
+    tmp = add (tmp, 2);
+    MR475_quant_store_results(pred_st,
+                              &table_gain_MR475[tmp],
+                              sf1_gcode0,
+                              sf1_exp_gcode0,
+                              sf1_gain_pit,
+                              sf1_gain_cod);
+
+    return index;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 MR475_gain_quant(       /* o  : index of quantization.                 */
+    gc_predState *pred_st,     /* i/o: gain predictor state struct            */
+
+    /* data from subframe 0 (or 2) */
+    Word16 sf0_exp_gcode0,     /* i  : predicted CB gain (exponent),      Q0  */
+    Word16 sf0_frac_gcode0,    /* i  : predicted CB gain (fraction),      Q15 */
+    Word16 sf0_exp_coeff[],    /* i  : energy coeff. (5), exponent part,  Q0  */
+    Word16 sf0_frac_coeff[],   /* i  : energy coeff. (5), fraction part,  Q15 */
+    /*      (frac_coeff and exp_coeff computed in  */
+    /*       calc_filt_energies())                 */
+    Word16 sf0_exp_target_en,  /* i  : exponent of target energy,         Q0  */
+    Word16 sf0_frac_target_en, /* i  : fraction of target energy,         Q15 */
+
+    /* data from subframe 1 (or 3) */
+    Word16 sf1_code_nosharp[], /* i  : innovative codebook vector (L_SUBFR)   */
+    /*      (whithout pitch sharpening)            */
+    Word16 sf1_exp_gcode0,     /* i  : predicted CB gain (exponent),      Q0  */
+    Word16 sf1_frac_gcode0,    /* i  : predicted CB gain (fraction),      Q15 */
+    Word16 sf1_exp_coeff[],    /* i  : energy coeff. (5), exponent part,  Q0  */
+    Word16 sf1_frac_coeff[],   /* i  : energy coeff. (5), fraction part,  Q15 */
+    /*      (frac_coeff and exp_coeff computed in  */
+    /*       calc_filt_energies())                 */
+    Word16 sf1_exp_target_en,  /* i  : exponent of target energy,         Q0  */
+    Word16 sf1_frac_target_en, /* i  : fraction of target energy,         Q15 */
+
+    Word16 gp_limit,           /* i  : pitch gain limit                       */
+
+    Word16 *sf0_gain_pit,      /* o  : Pitch gain,                        Q14 */
+    Word16 *sf0_gain_cod,      /* o  : Code gain,                         Q1  */
+
+    Word16 *sf1_gain_pit,      /* o  : Pitch gain,                        Q14 */
+    Word16 *sf1_gain_cod,      /* o  : Code gain,                         Q1  */
+    Flag   *pOverflow          /* o  : overflow indicator                     */
+)
+{
+    const Word16 *p;
+    Word16 i;
+    Word16 index = 0;
+    Word16 tmp;
+    Word16 exp;
+    Word16 sf0_gcode0;
+    Word16 sf1_gcode0;
+    Word16 g_pitch;
+    Word16 g2_pitch;
+    Word16 g_code;
+    Word16 g2_code;
+    Word16 g_pit_cod;
+    Word16 coeff[10];
+    Word16 coeff_lo[10];
+    Word16 exp_max[10];  /* 0..4: sf0; 5..9: sf1 */
+    Word32 L_tmp;
+    Word32 dist_min;
+
+    /*-------------------------------------------------------------------*
+     *  predicted codebook gain                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *  gc0     = 2^exp_gcode0 + 2^frac_gcode0                           *
+     *                                                                   *
+     *  gcode0 (Q14) = 2^14*2^frac_gcode0 = gc0 * 2^(14-exp_gcode0)      *
+     *-------------------------------------------------------------------*/
+
+    sf0_gcode0 = (Word16)(Pow2(14, sf0_frac_gcode0, pOverflow));
+    sf1_gcode0 = (Word16)(Pow2(14, sf1_frac_gcode0, pOverflow));
+
+    /*
+     * For each subframe, the error energy (sum) to be minimized consists
+     * of five terms, t[0..4].
+     *
+     *                      t[0] =    gp^2  * <y1 y1>
+     *                      t[1] = -2*gp    * <xn y1>
+     *                      t[2] =    gc^2  * <y2 y2>
+     *                      t[3] = -2*gc    * <xn y2>
+     *                      t[4] =  2*gp*gc * <y1 y2>
+     *
+     */
+
+    /* sf 0 */
+    /* determine the scaling exponent for g_code: ec = ec0 - 11 */
+    exp = sf0_exp_gcode0 - 11;
+
+    /* calculate exp_max[i] = s[i]-1 */
+    exp_max[0] = (sf0_exp_coeff[0] - 13);
+    exp_max[1] = (sf0_exp_coeff[1] - 14);
+    exp_max[2] = (sf0_exp_coeff[2] + (15 + (exp << 1)));
+    exp_max[3] = (sf0_exp_coeff[3] + exp);
+    exp_max[4] = (sf0_exp_coeff[4] + (1 + exp));
+
+    /* sf 1 */
+    /* determine the scaling exponent for g_code: ec = ec0 - 11 */
+    exp = sf1_exp_gcode0 - 11;
+
+    /* calculate exp_max[i] = s[i]-1 */
+    exp_max[5] = (sf1_exp_coeff[0] - 13);
+    exp_max[6] = (sf1_exp_coeff[1] - 14);
+    exp_max[7] = (sf1_exp_coeff[2] + (15 + (exp << 1)));
+    exp_max[8] = (sf1_exp_coeff[3] + exp);
+    exp_max[9] = (sf1_exp_coeff[4] + (1 + exp));
+
+    /*-------------------------------------------------------------------*
+     *  Gain search equalisation:                                        *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~                                        *
+     *  The MSE for the two subframes is weighted differently if there   *
+     *  is a big difference in the corresponding target energies         *
+     *-------------------------------------------------------------------*/
+
+    /* make the target energy exponents the same by de-normalizing the
+       fraction of the smaller one. This is necessary to be able to compare
+       them
+     */
+    exp = sf0_exp_target_en - sf1_exp_target_en;
+    if (exp > 0)
+    {
+        sf1_frac_target_en >>= exp;
+    }
+    else
+    {
+        sf0_frac_target_en >>= (-exp);
+    }
+
+    /* assume no change of exponents */
+    exp = 0;
+
+    /* test for target energy difference; set exp to +1 or -1 to scale
+     * up/down coefficients for sf 1
+     */
+    tmp = shr_r(sf1_frac_target_en, 1, pOverflow);  /* tmp = ceil(0.5*en(sf1)) */
+
+    if (tmp > sf0_frac_target_en)          /* tmp > en(sf0)? */
+    {
+        /*
+         * target_energy(sf1) > 2*target_energy(sf0)
+         *   -> scale up MSE(sf0) by 2 by adding 1 to exponents 0..4
+         */
+        exp = 1;
+    }
+    else
+    {
+        tmp = ((sf0_frac_target_en + 3) >> 2); /* tmp=ceil(0.25*en(sf0)) */
+
+        if (tmp > sf1_frac_target_en)      /* tmp > en(sf1)? */
+        {
+            /*
+             * target_energy(sf1) < 0.25*target_energy(sf0)
+             *   -> scale down MSE(sf0) by 0.5 by subtracting 1 from
+             *      coefficients 0..4
+             */
+            exp = -1;
+        }
+    }
+
+    for (i = 0; i < 5; i++)
+    {
+        exp_max[i] += exp;
+    }
+
+    /*-------------------------------------------------------------------*
+     *  Find maximum exponent:                                           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~                                           *
+     *                                                                   *
+     *  For the sum operation, all terms must have the same scaling;     *
+     *  that scaling should be low enough to prevent overflow. There-    *
+     *  fore, the maximum scale is determined and all coefficients are   *
+     *  re-scaled:                                                       *
+     *                                                                   *
+     *    exp = max(exp_max[i]) + 1;                                     *
+     *    e = exp_max[i]-exp;         e <= 0!                            *
+     *    c[i] = c[i]*2^e                                                *
+     *-------------------------------------------------------------------*/
+
+    exp = exp_max[0];
+    for (i = 9; i > 0; i--)
+    {
+        if (exp_max[i] > exp)
+        {
+            exp = exp_max[i];
+        }
+    }
+    exp++;      /* To avoid overflow */
+
+    p = &sf0_frac_coeff[0];
+    for (i = 0; i < 5; i++)
+    {
+        tmp = (exp - exp_max[i]);
+        L_tmp = ((Word32)(*p++) << 16);
+        L_tmp = L_shr(L_tmp, tmp, pOverflow);
+        coeff[i] = (Word16)(L_tmp >> 16);
+        coeff_lo[i] = (Word16)((L_tmp >> 1) - ((L_tmp >> 16) << 15));
+    }
+    p = &sf1_frac_coeff[0];
+    for (; i < 10; i++)
+    {
+        tmp = exp - exp_max[i];
+        L_tmp = ((Word32)(*p++) << 16);
+        L_tmp = L_shr(L_tmp, tmp, pOverflow);
+        coeff[i] = (Word16)(L_tmp >> 16);
+        coeff_lo[i] = (Word16)((L_tmp >> 1) - ((L_tmp >> 16) << 15));
+    }
+
+
+    /*-------------------------------------------------------------------*
+     *  Codebook search:                                                 *
+     *  ~~~~~~~~~~~~~~~~                                                 *
+     *                                                                   *
+     *  For each pair (g_pitch, g_fac) in the table calculate the        *
+     *  terms t[0..4] and sum them up; the result is the mean squared    *
+     *  error for the quantized gains from the table. The index for the  *
+     *  minimum MSE is stored and finally used to retrieve the quantized *
+     *  gains                                                            *
+     *-------------------------------------------------------------------*/
+
+    /* start with "infinite" MSE */
+    dist_min = MAX_32;
+
+    p = &table_gain_MR475[0];
+
+    for (i = 0; i < MR475_VQ_SIZE; i++)
+    {
+        /* subframe 0 (and 2) calculations */
+        g_pitch = *p++;
+        g_code = *p++;
+
+        /* Need to be there OKA */
+        g_code    = (Word16)(((Word32) g_code * sf0_gcode0) >> 15);
+        g2_pitch  = (Word16)(((Word32) g_pitch * g_pitch) >> 15);
+        g2_code   = (Word16)(((Word32) g_code * g_code) >> 15);
+        g_pit_cod = (Word16)(((Word32) g_code * g_pitch) >> 15);
+
+
+        L_tmp = Mpy_32_16(coeff[0], coeff_lo[0], g2_pitch, pOverflow) +
+                Mpy_32_16(coeff[1], coeff_lo[1], g_pitch, pOverflow) +
+                Mpy_32_16(coeff[2], coeff_lo[2], g2_code, pOverflow) +
+                Mpy_32_16(coeff[3], coeff_lo[3], g_code, pOverflow) +
+                Mpy_32_16(coeff[4], coeff_lo[4], g_pit_cod, pOverflow);
+
+        tmp = (g_pitch - gp_limit);
+
+        /* subframe 1 (and 3) calculations */
+        g_pitch = *p++;
+        g_code = *p++;
+
+        if ((tmp <= 0) && (g_pitch <= gp_limit))
+        {
+            g_code = (Word16)(((Word32) g_code * sf1_gcode0) >> 15);
+            g2_pitch  = (Word16)(((Word32) g_pitch * g_pitch) >> 15);
+            g2_code   = (Word16)(((Word32) g_code * g_code) >> 15);
+            g_pit_cod = (Word16)(((Word32) g_code * g_pitch) >> 15);
+
+            L_tmp += (Mpy_32_16(coeff[5], coeff_lo[5], g2_pitch, pOverflow) +
+                      Mpy_32_16(coeff[6], coeff_lo[6], g_pitch, pOverflow) +
+                      Mpy_32_16(coeff[7], coeff_lo[7], g2_code, pOverflow) +
+                      Mpy_32_16(coeff[8], coeff_lo[8], g_code, pOverflow) +
+                      Mpy_32_16(coeff[9], coeff_lo[9], g_pit_cod, pOverflow));
+
+            /* store table index if MSE for this index is lower
+               than the minimum MSE seen so far */
+            if (L_tmp < dist_min)
+            {
+                dist_min = L_tmp;
+                index = i;
+            }
+        }
+    }
+
+    /*------------------------------------------------------------------*
+     *  read quantized gains and update MA predictor memories           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~           *
+     *------------------------------------------------------------------*/
+
+    /* for subframe 0, the pre-calculated gcode0/exp_gcode0 are the same
+       as those calculated from the "real" predictor using quantized gains */
+    tmp = index << 2;
+    MR475_quant_store_results(pred_st,
+                              &table_gain_MR475[tmp],
+                              sf0_gcode0,
+                              sf0_exp_gcode0,
+                              sf0_gain_pit,
+                              sf0_gain_cod,
+                              pOverflow);
+
+    /* calculate new predicted gain for subframe 1 (this time using
+       the real, quantized gains)                                   */
+    gc_pred(pred_st, MR475, sf1_code_nosharp,
+            &sf1_exp_gcode0, &sf1_frac_gcode0,
+            &sf0_exp_gcode0, &sf0_gcode0, /* dummy args */
+            pOverflow);
+
+    sf1_gcode0 = (Word16)(Pow2(14, sf1_frac_gcode0, pOverflow));
+
+    tmp += 2;
+    MR475_quant_store_results(
+        pred_st,
+        &table_gain_MR475[tmp],
+        sf1_gcode0,
+        sf1_exp_gcode0,
+        sf1_gain_pit,
+        sf1_gain_cod,
+        pOverflow);
+
+    return(index);
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain475.h b/media/libstagefright/codecs/amrnb/enc/src/qgain475.h
new file mode 100644
index 0000000..3f1f03f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/qgain475.h
@@ -0,0 +1,180 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm-amr/c/include/qgain475.h
+
+     Date: 01/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template and copied #defines from qgain475.c file.
+
+ Description: Changed to include pOverflow as a function parameter for all
+ functions in qgain475.c
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the defines and function prototypes used in the
+ quantization of pitch and codebook gains for MR475.
+
+------------------------------------------------------------------------------
+*/
+#ifndef _QGAIN475_H_
+#define _QGAIN475_H_
+#define qgain475_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "gc_pred.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+    /* minimum allowed gain code prediction error: 102.887/4096 = 0.0251189 */
+#define MIN_QUA_ENER         ( -5443) /* Q10 <->    log2 (0.0251189) */
+#define MIN_QUA_ENER_MR122   (-32768) /* Q10 <-> 20*log10(0.0251189) */
+
+    /* minimum allowed gain code prediction error: 32000/4096 = 7.8125 */
+#define MAX_QUA_ENER         (  3037) /* Q10 <->    log2 (7.8125)    */
+#define MAX_QUA_ENER_MR122   ( 18284) /* Q10 <-> 20*log10(7.8125)    */
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*************************************************************************
+     *
+     * FUNCTION:  MR475_update_unq_pred()
+     *
+     * PURPOSE:   use optimum codebook gain and update "unquantized"
+     *            gain predictor with the (bounded) prediction error
+     *
+     *************************************************************************/
+    void
+    MR475_update_unq_pred(
+        gc_predState *pred_st, /* i/o: gain predictor state struct            */
+        Word16 exp_gcode0,     /* i  : predicted CB gain (exponent),      Q0  */
+        Word16 frac_gcode0,    /* i  : predicted CB gain (fraction),      Q15 */
+        Word16 cod_gain_exp,   /* i  : optimum codebook gain (exponent),  Q0  */
+        Word16 cod_gain_frac,  /* i  : optimum codebook gain (fraction),  Q15 */
+        Flag   *pOverflow      /* o  : overflow indicator                     */
+    );
+
+    /*************************************************************************
+     *
+     * FUNCTION:  MR475_gain_quant()
+     *
+     * PURPOSE: Quantization of pitch and codebook gains for two subframes
+     *          (using predicted codebook gain)
+     *
+     *************************************************************************/
+
+    Word16
+    MR475_gain_quant(              /* o  : index of quantization.                 */
+        gc_predState *pred_st,     /* i/o: gain predictor state struct            */
+
+        /* data from subframe 0 (or 2) */
+        Word16 sf0_exp_gcode0,     /* i  : predicted CB gain (exponent),      Q0  */
+        Word16 sf0_frac_gcode0,    /* i  : predicted CB gain (fraction),      Q15 */
+        Word16 sf0_exp_coeff[],    /* i  : energy coeff. (5), exponent part,  Q0  */
+        Word16 sf0_frac_coeff[],   /* i  : energy coeff. (5), fraction part,  Q15 */
+        /*      (frac_coeff and exp_coeff computed in  */
+        /*       calc_filt_energies())                 */
+        Word16 sf0_exp_target_en,  /* i  : exponent of target energy,         Q0  */
+        Word16 sf0_frac_target_en, /* i  : fraction of target energy,         Q15 */
+
+        /* data from subframe 1 (or 3) */
+        Word16 sf1_code_nosharp[], /* i  : innovative codebook vector (L_SUBFR)   */
+        /*      (whithout pitch sharpening)            */
+        Word16 sf1_exp_gcode0,     /* i  : predicted CB gain (exponent),      Q0  */
+        Word16 sf1_frac_gcode0,    /* i  : predicted CB gain (fraction),      Q15 */
+        Word16 sf1_exp_coeff[],    /* i  : energy coeff. (5), exponent part,  Q0  */
+        Word16 sf1_frac_coeff[],   /* i  : energy coeff. (5), fraction part,  Q15 */
+        /*      (frac_coeff and exp_coeff computed in  */
+        /*       calc_filt_energies())                 */
+        Word16 sf1_exp_target_en,  /* i  : exponent of target energy,         Q0  */
+        Word16 sf1_frac_target_en, /* i  : fraction of target energy,         Q15 */
+
+        Word16 gp_limit,           /* i  : pitch gain limit                       */
+
+        Word16 *sf0_gain_pit,      /* o  : Pitch gain,                        Q14 */
+        Word16 *sf0_gain_cod,      /* o  : Code gain,                         Q1  */
+
+        Word16 *sf1_gain_pit,      /* o  : Pitch gain,                        Q14 */
+        Word16 *sf1_gain_cod,      /* o  : Code gain,                         Q1  */
+        Flag   *pOverflow          /* o  : overflow indicator                     */
+    );
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _QGAIN475_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain795.cpp b/media/libstagefright/codecs/amrnb/enc/src/qgain795.cpp
new file mode 100644
index 0000000..d09fbe3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/qgain795.cpp
@@ -0,0 +1,904 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/qgain795.c
+ Functions: MR795_gain_code_quant3
+            MR795_gain_code_quant_mod
+            MR795_gain_quant
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:
+ (1) Removed optimization -- mult(i, 3, pOverflow) is NOT the same as adding
+     i to itself 3 times.  The reason is because the mult function does a
+     right shift by 15, which will obliterate smaller numbers.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "qgain795.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "log2.h"
+#include "pow2.h"
+#include "sqrt_l.h"
+#include "g_adapt.h"
+#include "calc_en.h"
+#include "q_gain_p.h"
+
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+#define NB_QUA_CODE 32
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 qua_gain_code[NB_QUA_CODE*3];
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR795_gain_code_quant3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    exp_gcode0     -- Word16       -- predicted CB gain (exponent), Q0
+    gcode0         -- Word16       -- predicted CB gain (norm.)
+    g_pitch_cand[] -- Word16 array -- Pitch gain candidates (3),    Q14
+    g_pitch_cind[] -- Word16 array -- Pitch gain cand. indices (3), Q0
+    frac_coeff[]   -- Word16 array -- coefficients (5),             Q15
+    exp_coeff[]    -- Word16 array -- energy coefficients (5),      Q0
+                                      coefficients from calc_filt_ener()
+
+ Outputs:
+    gain_pit       -- Pointer to Word16 -- Pitch gain,                     Q14
+    gain_pit_ind   -- Pointer to Word16 -- Pitch gain index,               Q0
+    gain_cod       -- Pointer to Word16 -- Code gain,                      Q1
+    gain_cod_ind   -- Pointer to Word16 -- Code gain index,                Q0
+    qua_ener_MR122 -- Pointer to Word16 -- quantized energy error,         Q10
+                                          (for MR122 MA predictor update)
+
+    qua_ener -- Pointer to Word16 -- quantized energy error,       Q10
+                                     (for other MA predictor update)
+
+    pOverflow -- Pointer to Flag --  overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: Pre-quantization of codebook gains, given three possible
+          LTP gains (using predicted codebook gain)
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain795.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static void
+MR795_gain_code_quant3(
+    Word16 exp_gcode0,        /* i  : predicted CB gain (exponent), Q0  */
+    Word16 gcode0,            /* i  : predicted CB gain (norm.),    Q14 */
+    Word16 g_pitch_cand[],    /* i  : Pitch gain candidates (3),    Q14 */
+    Word16 g_pitch_cind[],    /* i  : Pitch gain cand. indices (3), Q0  */
+    Word16 frac_coeff[],      /* i  : coefficients (5),             Q15 */
+    Word16 exp_coeff[],       /* i  : energy coefficients (5),      Q0  */
+    /*      coefficients from calc_filt_ener()*/
+    Word16 *gain_pit,         /* o  : Pitch gain,                   Q14 */
+    Word16 *gain_pit_ind,     /* o  : Pitch gain index,             Q0  */
+    Word16 *gain_cod,         /* o  : Code gain,                    Q1  */
+    Word16 *gain_cod_ind,     /* o  : Code gain index,              Q0  */
+    Word16 *qua_ener_MR122,   /* o  : quantized energy error,       Q10 */
+    /*      (for MR122 MA predictor update)   */
+    Word16 *qua_ener,         /* o  : quantized energy error,       Q10 */
+    /*      (for other MA predictor update)   */
+    Flag   *pOverflow         /* o  : overflow indicator                */
+)
+{
+    const Word16 *p;
+    Word16 i;
+    Word16 j;
+    Word16 cod_ind;
+    Word16 pit_ind;
+    Word16 e_max;
+    Word16 exp_code;
+    Word16 g_pitch;
+    Word16 g2_pitch;
+    Word16 g_code;
+    Word16 g2_code_h;
+    Word16 g2_code_l;
+    Word16 g_pit_cod_h;
+    Word16 g_pit_cod_l;
+    Word16 coeff[5];
+    Word16 coeff_lo[5];
+    Word16 exp_max[5];
+    Word32 L_tmp;
+    Word32 L_tmp0;
+    Word32 dist_min;
+
+    /*
+     * The error energy (sum) to be minimized consists of five terms, t[0..4].
+     *
+     *                      t[0] =    gp^2  * <y1 y1>
+     *                      t[1] = -2*gp    * <xn y1>
+     *                      t[2] =    gc^2  * <y2 y2>
+     *                      t[3] = -2*gc    * <xn y2>
+     *                      t[4] =  2*gp*gc * <y1 y2>
+     *
+     */
+
+    /* determine the scaling exponent for g_code: ec = ec0 - 10 */
+    exp_code = sub(exp_gcode0, 10, pOverflow);
+
+    /* calculate exp_max[i] = s[i]-1 */
+    exp_max[0] = sub(exp_coeff[0], 13, pOverflow);
+    exp_max[1] = sub(exp_coeff[1], 14, pOverflow);
+    exp_max[2] = add(exp_coeff[2], add(15, shl(exp_code, 1, pOverflow), pOverflow), pOverflow);
+    exp_max[3] = add(exp_coeff[3], exp_code, pOverflow);
+    exp_max[4] = add(exp_coeff[4], add(exp_code, 1, pOverflow), pOverflow);
+
+
+    /*-------------------------------------------------------------------*
+     *  Find maximum exponent:                                           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~                                           *
+     *                                                                   *
+     *  For the sum operation, all terms must have the same scaling;     *
+     *  that scaling should be low enough to prevent overflow. There-    *
+     *  fore, the maximum scale is determined and all coefficients are   *
+     *  re-scaled:                                                       *
+     *                                                                   *
+     *    e_max = max(exp_max[i]) + 1;                                   *
+     *    e = exp_max[i]-e_max;         e <= 0!                          *
+     *    c[i] = c[i]*2^e                                                *
+     *-------------------------------------------------------------------*/
+
+    e_max = exp_max[0];
+    for (i = 1; i < 5; i++)     /* implemented flattened */
+    {
+        if (exp_max[i] > e_max)
+        {
+            e_max = exp_max[i];
+        }
+    }
+
+    e_max = add(e_max, 1, pOverflow);      /* To avoid overflow */
+
+    for (i = 0; i < 5; i++)
+    {
+        j = sub(e_max, exp_max[i], pOverflow);
+        L_tmp = L_deposit_h(frac_coeff[i]);
+        L_tmp = L_shr(L_tmp, j, pOverflow);
+        L_Extract(L_tmp, &coeff[i], &coeff_lo[i], pOverflow);
+    }
+
+
+    /*-------------------------------------------------------------------*
+     *  Codebook search:                                                 *
+     *  ~~~~~~~~~~~~~~~~                                                 *
+     *                                                                   *
+     *  For each of the candiates LTP gains in g_pitch_cand[], the terms *
+     *  t[0..4] are calculated from the values in the table (and the     *
+     *  pitch gain candidate) and summed up; the result is the mean      *
+     *  squared error for the LPT/CB gain pair. The index for the mini-  *
+     *  mum MSE is stored and finally used to retrieve the quantized CB  *
+     *  gain                                                             *
+     *-------------------------------------------------------------------*/
+
+    /* start with "infinite" MSE */
+    dist_min = MAX_32;
+    cod_ind = 0;
+    pit_ind = 0;
+
+    /* loop through LTP gain candidates */
+    for (j = 0; j < 3; j++)
+    {
+        /* pre-calculate terms only dependent on pitch gain */
+        g_pitch = g_pitch_cand[j];
+        g2_pitch = mult(g_pitch, g_pitch, pOverflow);
+        L_tmp0 = Mpy_32_16(coeff[0], coeff_lo[0], g2_pitch, pOverflow);
+        L_tmp0 = Mac_32_16(L_tmp0, coeff[1], coeff_lo[1], g_pitch, pOverflow);
+
+        p = &qua_gain_code[0];
+        for (i = 0; i < NB_QUA_CODE; i++)
+        {
+            g_code = *p++;                   /* this is g_fac        Q11 */
+            p++;                             /* skip log2(g_fac)         */
+            p++;                             /* skip 20*log10(g_fac)     */
+
+            g_code = mult(g_code, gcode0, pOverflow);
+
+            L_tmp = L_mult(g_code, g_code, pOverflow);
+            L_Extract(L_tmp, &g2_code_h, &g2_code_l, pOverflow);
+
+            L_tmp = L_mult(g_code, g_pitch, pOverflow);
+            L_Extract(L_tmp, &g_pit_cod_h, &g_pit_cod_l, pOverflow);
+
+            L_tmp = Mac_32(L_tmp0, coeff[2], coeff_lo[2],
+                           g2_code_h, g2_code_l, pOverflow);
+            L_tmp = Mac_32_16(L_tmp, coeff[3], coeff_lo[3],
+                              g_code, pOverflow);
+            L_tmp = Mac_32(L_tmp, coeff[4], coeff_lo[4],
+                           g_pit_cod_h, g_pit_cod_l, pOverflow);
+
+            /* store table index if MSE for this index is lower
+               than the minimum MSE seen so far; also store the
+               pitch gain for this (so far) lowest MSE          */
+            if (L_tmp < dist_min)
+            {
+                dist_min = L_tmp;
+                cod_ind = i;
+                pit_ind = j;
+            }
+        }
+    }
+
+    /*------------------------------------------------------------------*
+     *  read quantized gains and new values for MA predictor memories   *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   *
+     *------------------------------------------------------------------*/
+
+    /* Read the quantized gains */
+    p = &qua_gain_code[
+            add(add(cod_ind, cod_ind, pOverflow), cod_ind, pOverflow)];
+
+    g_code = *p++;
+    *qua_ener_MR122 = *p++;
+    *qua_ener = *p;
+
+    /*------------------------------------------------------------------*
+     *  calculate final fixed codebook gain:                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
+     *                                                                  *
+     *   gc = gc0 * g                                                   *
+     *------------------------------------------------------------------*/
+
+    L_tmp = L_mult(g_code, gcode0, pOverflow);
+    L_tmp = L_shr(L_tmp, sub(9, exp_gcode0, pOverflow), pOverflow);
+    *gain_cod = extract_h(L_tmp);
+    *gain_cod_ind = cod_ind;
+    *gain_pit = g_pitch_cand[pit_ind];
+    *gain_pit_ind = g_pitch_cind[pit_ind];
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR795_gain_code_quant_mod
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    gain_pit     -- Word16 -- pitch gain,                                   Q14
+    exp_gcode0   -- Word16 -- predicted CB gain (exponent),                 Q0
+    gcode0       -- Word16 -- predicted CB gain (norm.),                    Q14
+    frac_en[]    -- Word16 array -- energy coefficients (4), fraction part, Q15
+    exp_en[]     -- Word16 array -- energy coefficients (4), exponent part, Q0
+    alpha        -- Word16 -- gain adaptor factor (>0),                     Q15
+
+    gain_cod_unq -- Word16 -- Code gain (unquantized)
+                              (scaling: Q10 - exp_gcode0)
+
+    gain_cod     -- Pointer to Word16 -- Code gain (pre-/quantized),        Q1
+
+ Outputs:
+    qua_ener_MR122 -- Pointer to Word16 -- quantized energy error,       Q10
+                                           (for MR122 MA predictor update)
+    qua_ener       -- Pointer to Word16 -- quantized energy error,       Q10
+                                           (for other MA predictor update)
+    pOverflow      -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    index of quantization (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: Modified quantization of the MR795 codebook gain
+
+ Uses pre-computed energy coefficients in frac_en[]/exp_en[]
+
+       frac_en[0]*2^exp_en[0] = <res res>   // LP residual energy
+       frac_en[1]*2^exp_en[1] = <exc exc>   // LTP residual energy
+       frac_en[2]*2^exp_en[2] = <exc code>  // LTP/CB innovation dot product
+       frac_en[3]*2^exp_en[3] = <code code> // CB innovation energy
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain795.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16
+MR795_gain_code_quant_mod(  /* o  : index of quantization.            */
+    Word16 gain_pit,        /* i  : pitch gain,                   Q14 */
+    Word16 exp_gcode0,      /* i  : predicted CB gain (exponent), Q0  */
+    Word16 gcode0,          /* i  : predicted CB gain (norm.),    Q14 */
+    Word16 frac_en[],       /* i  : energy coefficients (4),
+                                    fraction part,                Q15 */
+    Word16 exp_en[],        /* i  : energy coefficients (4),
+                                    eponent part,                 Q0  */
+    Word16 alpha,           /* i  : gain adaptor factor (>0),     Q15 */
+    Word16 gain_cod_unq,    /* i  : Code gain (unquantized)           */
+    /*      (scaling: Q10 - exp_gcode0)       */
+    Word16 *gain_cod,       /* i/o: Code gain (pre-/quantized),   Q1  */
+    Word16 *qua_ener_MR122, /* o  : quantized energy error,       Q10 */
+    /*      (for MR122 MA predictor update)   */
+    Word16 *qua_ener,       /* o  : quantized energy error,       Q10 */
+    /*      (for other MA predictor update)   */
+    Flag   *pOverflow       /* o  : overflow indicator                */
+)
+{
+    const Word16 *p;
+    Word16 i;
+    Word16 index;
+    Word16 tmp;
+    Word16 one_alpha;
+    Word16 exp;
+    Word16 e_max;
+
+    Word16 g2_pitch;
+    Word16 g_code;
+    Word16 g2_code_h;
+    Word16 g2_code_l;
+    Word16 d2_code_h;
+    Word16 d2_code_l;
+    Word16 coeff[5];
+    Word16 coeff_lo[5];
+    Word16 exp_coeff[5];
+    Word32 L_tmp;
+    Word32 L_t0;
+    Word32 L_t1;
+    Word32 dist_min;
+    Word16 gain_code;
+
+    /*
+      Steps in calculation of the error criterion (dist):
+      ---------------------------------------------------
+
+      underlined = constant; alp = FLP value of alpha, alpha = FIP
+      ----------
+
+
+        ExEn = gp^2 * LtpEn + 2.0*gp*gc[i] * XC + gc[i]^2 * InnEn;
+               ------------   ------         --             -----
+
+        aExEn= alp * ExEn
+             = alp*gp^2*LtpEn + 2.0*alp*gp*XC* gc[i] + alp*InnEn* gc[i]^2
+               --------------   -------------          ---------
+
+             =         t[1]   +              t[2]    +          t[3]
+
+        dist = d1 + d2;
+
+          d1 = (1.0 - alp) * InnEn * (gcu - gc[i])^2 = t[4]
+               -------------------    ---
+
+          d2 =        alp  * (ResEn - 2.0 * sqrt(ResEn*ExEn) + ExEn);
+                      ---     -----   ---        -----
+
+             =        alp  * (sqrt(ExEn) - sqrt(ResEn))^2
+                      ---                  -----------
+
+             =               (sqrt(aExEn) - sqrt(alp*ResEn))^2
+                                            ---------------
+
+             =               (sqrt(aExEn) -       t[0]     )^2
+                                                  ----
+
+     */
+
+    /*
+     * calculate scalings of the constant terms
+     */
+    gain_code = shl(*gain_cod, sub(10, exp_gcode0, pOverflow), pOverflow);   /* Q1  -> Q11 (-ec0) */
+    g2_pitch = mult(gain_pit, gain_pit, pOverflow);               /* Q14 -> Q13        */
+    /* 0 < alpha <= 0.5 => 0.5 <= 1-alpha < 1, i.e one_alpha is normalized  */
+    one_alpha = add(sub(32767, alpha, pOverflow), 1, pOverflow);   /* 32768 - alpha */
+
+
+    /*  alpha <= 0.5 -> mult. by 2 to keep precision; compensate in exponent */
+    L_t1 = L_mult(alpha, frac_en[1], pOverflow);
+    L_t1 = L_shl(L_t1, 1, pOverflow);
+    tmp = extract_h(L_t1);
+
+    /* directly store in 32 bit variable because no further mult. required */
+    L_t1 = L_mult(tmp, g2_pitch, pOverflow);
+    exp_coeff[1] = sub(exp_en[1], 15, pOverflow);
+
+
+    tmp = extract_h(L_shl(L_mult(alpha, frac_en[2], pOverflow), 1, pOverflow));
+    coeff[2] = mult(tmp, gain_pit, pOverflow);
+    exp = sub(exp_gcode0, 10, pOverflow);
+    exp_coeff[2] = add(exp_en[2], exp, pOverflow);
+
+
+    /* alpha <= 0.5 -> mult. by 2 to keep precision; compensate in exponent */
+    coeff[3] = extract_h(L_shl(L_mult(alpha, frac_en[3], pOverflow), 1, pOverflow));
+    exp = sub(shl(exp_gcode0, 1, pOverflow), 7, pOverflow);
+    exp_coeff[3] = add(exp_en[3], exp, pOverflow);
+
+
+    coeff[4] = mult(one_alpha, frac_en[3], pOverflow);
+    exp_coeff[4] = add(exp_coeff[3], 1, pOverflow);
+
+
+    L_tmp = L_mult(alpha, frac_en[0], pOverflow);
+    /* sqrt_l returns normalized value and 2*exponent
+       -> result = val >> (exp/2)
+       exp_coeff holds 2*exponent for c[0]            */
+    /* directly store in 32 bit variable because no further mult. required */
+    L_t0 = sqrt_l_exp(L_tmp, &exp, pOverflow);  /* normalization included in sqrt_l_exp */
+    exp = add(exp, 47, pOverflow);
+    exp_coeff[0] = sub(exp_en[0], exp, pOverflow);
+
+    /*
+     * Determine the maximum exponent occuring in the distance calculation
+     * and adjust all fractions accordingly (including a safety margin)
+     *
+     */
+
+    /* find max(e[1..4],e[0]+31) */
+    e_max = add(exp_coeff[0], 31, pOverflow);
+    for (i = 1; i <= 4; i++)
+    {
+        if (exp_coeff[i] > e_max)
+        {
+            e_max = exp_coeff[i];
+        }
+    }
+
+    /* scale c[1]         (requires no further multiplication) */
+    tmp = sub(e_max, exp_coeff[1], pOverflow);
+    L_t1 = L_shr(L_t1, tmp, pOverflow);
+
+    /* scale c[2..4] (used in Mpy_32_16 in the quantizer loop) */
+    for (i = 2; i <= 4; i++)
+    {
+        tmp = sub(e_max, exp_coeff[i], pOverflow);
+        L_tmp = L_deposit_h(coeff[i]);
+        L_tmp = L_shr(L_tmp, tmp, pOverflow);
+        L_Extract(L_tmp, &coeff[i], &coeff_lo[i], pOverflow);
+    }
+
+    /* scale c[0]         (requires no further multiplication) */
+    exp = sub(e_max, 31, pOverflow);              /* new exponent */
+    tmp = sub(exp, exp_coeff[0], pOverflow);
+    L_t0 = L_shr(L_t0, shr(tmp, 1, pOverflow), pOverflow);
+    /* perform correction by 1/sqrt(2) if exponent difference is odd */
+    if ((tmp & 0x1) != 0)
+    {
+        L_Extract(L_t0, &coeff[0], &coeff_lo[0], pOverflow);
+        L_t0 = Mpy_32_16(coeff[0], coeff_lo[0],
+                         23170, pOverflow);                    /* 23170 Q15 = 1/sqrt(2)*/
+    }
+
+    /* search the quantizer table for the lowest value
+       of the search criterion                           */
+    dist_min = MAX_32;
+    index = 0;
+    p = &qua_gain_code[0];
+
+    for (i = 0; i < NB_QUA_CODE; i++)
+    {
+        g_code = *p++;                   /* this is g_fac (Q11)  */
+        p++;                             /* skip log2(g_fac)     */
+        p++;                             /* skip 20*log10(g_fac) */
+        g_code = mult(g_code, gcode0, pOverflow);
+
+        /* only continue if    gc[i]            < 2.0*gc
+           which is equiv. to  g_code (Q10-ec0) < gain_code (Q11-ec0) */
+
+        if (g_code >= gain_code)
+        {
+            break;
+        }
+
+        L_tmp = L_mult(g_code, g_code, pOverflow);
+        L_Extract(L_tmp, &g2_code_h, &g2_code_l, pOverflow);
+
+        tmp = sub(g_code, gain_cod_unq, pOverflow);
+        L_tmp = L_mult(tmp, tmp, pOverflow);
+        L_Extract(L_tmp, &d2_code_h, &d2_code_l, pOverflow);
+
+        /* t2, t3, t4 */
+        L_tmp = Mac_32_16(L_t1, coeff[2], coeff_lo[2], g_code, pOverflow);
+        L_tmp = Mac_32(L_tmp,    coeff[3], coeff_lo[3], g2_code_h, g2_code_l, pOverflow);
+
+        L_tmp = sqrt_l_exp(L_tmp, &exp, pOverflow);
+        L_tmp = L_shr(L_tmp, shr(exp, 1, pOverflow), pOverflow);
+
+        /* d2 */
+        tmp = pv_round(L_sub(L_tmp, L_t0, pOverflow), pOverflow);
+        L_tmp = L_mult(tmp, tmp, pOverflow);
+
+        /* dist */
+        L_tmp = Mac_32(L_tmp, coeff[4], coeff_lo[4], d2_code_h, d2_code_l, pOverflow);
+
+        /* store table index if distance measure for this
+            index is lower than the minimum seen so far   */
+        if (L_tmp < dist_min)
+        {
+            dist_min = L_tmp;
+            index = i;
+        }
+    }
+
+    /*------------------------------------------------------------------*
+     *  read quantized gains and new values for MA predictor memories   *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   *
+     *------------------------------------------------------------------*/
+
+    /* Read the quantized gains */
+    p = &qua_gain_code[add(add(index, index, pOverflow), index, pOverflow)];
+    g_code = *p++;
+    *qua_ener_MR122 = *p++;
+    *qua_ener = *p;
+
+    /*------------------------------------------------------------------*
+     *  calculate final fixed codebook gain:                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
+     *                                                                  *
+     *   gc = gc0 * g                                                   *
+     *------------------------------------------------------------------*/
+
+    L_tmp = L_mult(g_code, gcode0, pOverflow);
+    L_tmp = L_shr(L_tmp, sub(9, exp_gcode0, pOverflow), pOverflow);
+    *gain_cod = extract_h(L_tmp);
+
+    return index;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: MR795_gain_quant
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+MR795_gain_quant(
+
+
+ Inputs:
+    adapt_st      -- Pointer to GainAdaptState -- gain adapter state structure
+    res           -- Word16 array -- LP residual,                  Q0
+    exc           -- Word16 array -- LTP excitation (unfiltered),  Q0
+    code          -- Word16 array -- CB innovation (unfiltered),   Q13
+    frac_coeff    -- Word16 array -- coefficients (5),             Q15
+    exp_coeff     -- Word16 array -- energy coefficients (5),      Q0
+                                    coefficients from calc_filt_ener()
+    exp_code_en   -- Word16 -- innovation energy (exponent), Q0
+    frac_code_en  -- Word16 -- innovation energy (fraction), Q15
+    exp_gcode0    -- Word16 -- predicted CB gain (exponent), Q0
+    frac_gcode0   -- Word16 -- predicted CB gain (fraction), Q15
+    L_subfr       -- Word16 -- Subframe length
+    cod_gain_frac -- Word16 -- opt. codebook gain (fraction),Q15
+    cod_gain_exp  -- Word16 -- opt. codebook gain (exponent), Q0
+    gp_limit      -- Word16 -- pitch gain limit
+    gain_pit      -- Pointer to Word16 -- Pitch gain,              Q14
+
+ Output
+    adapt_st       -- Pointer to GainAdaptState -- gain adapter state structure
+    gain_pit       -- Pointer to Word16 -- Pitch gain,              Q14
+
+    gain_pit       -- Pointer to Word16 -- Pitch gain,                   Q14
+    gain_cod       -- Pointer to Word16 -- Code gain,                    Q1
+    qua_ener_MR122 -- Pointer to Word16 -- quantized energy error,       Q10
+                                           (for MR122 MA predictor update)
+
+    qua_ener       -- Pointer to Word16 -- quantized energy error,       Q10
+                                           (for other MA predictor update)
+
+    anap           -- Double Pointer to Word16 -- Index of quantization
+                                           (first gain pitch, then code pitch)
+
+    pOverflow      -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ pitch and codebook quantization for MR795
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qgain795.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void
+MR795_gain_quant(
+    GainAdaptState *adapt_st, /* i/o: gain adapter state structure       */
+    Word16 res[],             /* i  : LP residual,                  Q0   */
+    Word16 exc[],             /* i  : LTP excitation (unfiltered),  Q0   */
+    Word16 code[],            /* i  : CB innovation (unfiltered),   Q13  */
+    Word16 frac_coeff[],      /* i  : coefficients (5),             Q15  */
+    Word16 exp_coeff[],       /* i  : energy coefficients (5),      Q0   */
+    /*      coefficients from calc_filt_ener() */
+    Word16 exp_code_en,       /* i  : innovation energy (exponent), Q0   */
+    Word16 frac_code_en,      /* i  : innovation energy (fraction), Q15  */
+    Word16 exp_gcode0,        /* i  : predicted CB gain (exponent), Q0   */
+    Word16 frac_gcode0,       /* i  : predicted CB gain (fraction), Q15  */
+    Word16 L_subfr,           /* i  : Subframe length                    */
+    Word16 cod_gain_frac,     /* i  : opt. codebook gain (fraction),Q15  */
+    Word16 cod_gain_exp,      /* i  : opt. codebook gain (exponent), Q0  */
+    Word16 gp_limit,          /* i  : pitch gain limit                   */
+    Word16 *gain_pit,         /* i/o: Pitch gain,                   Q14  */
+    Word16 *gain_cod,         /* o  : Code gain,                    Q1   */
+    Word16 *qua_ener_MR122,   /* o  : quantized energy error,       Q10  */
+    /*      (for MR122 MA predictor update)    */
+    Word16 *qua_ener,         /* o  : quantized energy error,       Q10  */
+    /*      (for other MA predictor update)    */
+    Word16 **anap,            /* o  : Index of quantization              */
+    /*      (first gain pitch, then code pitch)*/
+    Flag   *pOverflow         /* o  : overflow indicator                */
+)
+{
+    Word16 frac_en[4];
+    Word16 exp_en[4];
+    Word16 ltpg, alpha, gcode0;
+    Word16 g_pitch_cand[3];      /* pitch gain candidates   Q14 */
+    Word16 g_pitch_cind[3];      /* pitch gain indices      Q0  */
+    Word16 gain_pit_index;
+    Word16 gain_cod_index;
+    Word16 exp;
+    Word16 gain_cod_unq;         /* code gain (unq.) Q(10-exp_gcode0)  */
+
+
+    /* get list of candidate quantized pitch gain values
+     * and corresponding quantization indices
+     */
+    gain_pit_index = q_gain_pitch(MR795, gp_limit, gain_pit,
+                                  g_pitch_cand, g_pitch_cind, pOverflow);
+
+    /*-------------------------------------------------------------------*
+     *  predicted codebook gain                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *  gc0     = 2^exp_gcode0 + 2^frac_gcode0                           *
+     *                                                                   *
+     *  gcode0 (Q14) = 2^14*2^frac_gcode0 = gc0 * 2^(14-exp_gcode0)      *
+     *-------------------------------------------------------------------*/
+    gcode0 = (Word16)(Pow2(14, frac_gcode0, pOverflow));           /* Q14 */
+
+    /* pre-quantization of codebook gain
+     * (using three pitch gain candidates);
+     * result: best guess of pitch gain and code gain
+     */
+    MR795_gain_code_quant3(
+        exp_gcode0, gcode0, g_pitch_cand, g_pitch_cind,
+        frac_coeff, exp_coeff,
+        gain_pit, &gain_pit_index, gain_cod, &gain_cod_index,
+        qua_ener_MR122, qua_ener, pOverflow);
+
+    /* calculation of energy coefficients and LTP coding gain */
+    calc_unfilt_energies(res, exc, code, *gain_pit, L_subfr,
+                         frac_en, exp_en, &ltpg, pOverflow);
+
+    /* run gain adaptor, calculate alpha factor to balance LTP/CB gain
+     * (this includes the gain adaptor update)
+     * Note: ltpg = 0 if frac_en[0] == 0, so the update is OK in that case
+     */
+    gain_adapt(adapt_st, ltpg, *gain_cod, &alpha, pOverflow);
+
+    /* if this is a very low energy signal (threshold: see
+     * calc_unfilt_energies) or alpha <= 0 then don't run the modified quantizer
+     */
+    if (frac_en[0] != 0 && alpha > 0)
+    {
+        /* innovation energy <cod cod> was already computed in gc_pred() */
+        /* (this overwrites the LtpResEn which is no longer needed)      */
+        frac_en[3] = frac_code_en;
+        exp_en[3] = exp_code_en;
+
+        /* store optimum codebook gain in Q(10-exp_gcode0) */
+        exp = add(sub(cod_gain_exp, exp_gcode0, pOverflow), 10, pOverflow);
+        gain_cod_unq = shl(cod_gain_frac, exp, pOverflow);
+
+        /* run quantization with modified criterion */
+        gain_cod_index = MR795_gain_code_quant_mod(
+                             *gain_pit, exp_gcode0, gcode0,
+                             frac_en, exp_en, alpha, gain_cod_unq,
+                             gain_cod, qua_ener_MR122, qua_ener, pOverflow); /* function result */
+    }
+
+    *(*anap)++ = gain_pit_index;
+    *(*anap)++ = gain_cod_index;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qgain795.h b/media/libstagefright/codecs/amrnb/enc/src/qgain795.h
new file mode 100644
index 0000000..b739dad
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/qgain795.h
@@ -0,0 +1,143 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/qgain795.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, qgain795.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef qgain795_h
+#define qgain795_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "g_adapt.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void
+    MR795_gain_quant(
+        GainAdaptState *adapt_st, /* i/o: gain adapter state structure       */
+        Word16 res[],             /* i  : LP residual,                  Q0   */
+        Word16 exc[],             /* i  : LTP excitation (unfiltered),  Q0   */
+        Word16 code[],            /* i  : CB innovation (unfiltered),   Q13  */
+        Word16 frac_coeff[],      /* i  : coefficients (5),             Q15  */
+        Word16 exp_coeff[],       /* i  : energy coefficients (5),      Q0   */
+        /*      coefficients from calc_filt_ener() */
+        Word16 exp_code_en,       /* i  : innovation energy (exponent), Q0   */
+        Word16 frac_code_en,      /* i  : innovation energy (fraction), Q15  */
+        Word16 exp_gcode0,        /* i  : predicted CB gain (exponent), Q0   */
+        Word16 frac_gcode0,       /* i  : predicted CB gain (fraction), Q15  */
+        Word16 L_subfr,           /* i  : Subframe length                    */
+        Word16 cod_gain_frac,     /* i  : opt. codebook gain (fraction),Q15  */
+        Word16 cod_gain_exp,      /* i  : opt. codebook gain (exponent), Q0  */
+        Word16 gp_limit,          /* i  : pitch gain limit                   */
+        Word16 *gain_pit,         /* i/o: Pitch gain (unquant/quant),   Q14  */
+        Word16 *gain_cod,         /* o  : Code gain,                    Q1   */
+        Word16 *qua_ener_MR122,   /* o  : quantized energy error,       Q10  */
+        /*      (for MR122 MA predictor update)    */
+        Word16 *qua_ener,         /* o  : quantized energy error,       Q10  */
+        /*      (for other MA predictor update)    */
+        Word16 **anap,            /* o  : Index of quantization              */
+        /*      (first gain pitch, then code pitch)*/
+        Flag   *pOverflow         /* o  : overflow indicator                 */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* qgain795_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/qua_gain.cpp b/media/libstagefright/codecs/amrnb/enc/src/qua_gain.cpp
new file mode 100644
index 0000000..740abcb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/qua_gain.cpp
@@ -0,0 +1,400 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/qua_gain.c
+ Functions:
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Changed include files to lowercase.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Quantization of pitch and codebook gains.
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "qua_gain.h"
+#include "typedef.h"
+#include "basic_op.h"
+
+#include "mode.h"
+#include "cnst.h"
+#include "pow2.h"
+#include "gc_pred.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 table_gain_lowrates[];
+    extern const Word16 table_gain_highrates[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+ Inputs:
+    mode -- enum Mode -- AMR mode
+    Word16 exp_gcode0  -- Word16 -- predicted CB gain (exponent),       Q0
+    Word16 frac_gcode0 -- Word16 -- predicted CB gain (fraction),      Q15
+    Word16 frac_coeff -- Word16 Array -- energy coeff. (5), fraction part, Q15
+    Word16 exp_coeff  -- Word16 Array -- energy coeff. (5), exponent part,  Q0
+                                    (frac_coeff and exp_coeff computed in
+                                    calc_filt_energies())
+
+    Word16 gp_limit -- Word16 --  pitch gain limit
+
+ Outputs:
+    Word16 *gain_pit -- Pointer to Word16 -- Pitch gain,               Q14
+    Word16 *gain_cod -- Pointer to Word16 -- Code gain,                Q1
+    Word16 *qua_ener_MR122 -- Pointer to Word16 -- quantized energy error,  Q10
+                                                (for MR122 MA predictor update)
+    Word16 *qua_ener -- Pointer to Word16 -- quantized energy error,        Q10
+                                                (for other MA predictor update)
+    Flag   *pOverflow -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    Word16 -- index of quantization.
+
+ Global Variables Used:
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Quantization of pitch and codebook gains.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ qua_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+
+Word16
+Qua_gain(                   /* o  : index of quantization.                 */
+    enum Mode mode,         /* i  : AMR mode                               */
+    Word16 exp_gcode0,      /* i  : predicted CB gain (exponent),      Q0  */
+    Word16 frac_gcode0,     /* i  : predicted CB gain (fraction),      Q15 */
+    Word16 frac_coeff[],    /* i  : energy coeff. (5), fraction part,  Q15 */
+    Word16 exp_coeff[],     /* i  : energy coeff. (5), exponent part,  Q0  */
+    /*      (frac_coeff and exp_coeff computed in  */
+    /*       calc_filt_energies())                 */
+    Word16 gp_limit,        /* i  : pitch gain limit                       */
+    Word16 *gain_pit,       /* o  : Pitch gain,                        Q14 */
+    Word16 *gain_cod,       /* o  : Code gain,                         Q1  */
+    Word16 *qua_ener_MR122, /* o  : quantized energy error,            Q10 */
+    /*      (for MR122 MA predictor update)        */
+    Word16 *qua_ener,       /* o  : quantized energy error,            Q10 */
+    /*      (for other MA predictor update)        */
+    Flag   *pOverflow       /* o  : overflow indicator                     */
+)
+{
+    const Word16 *p;
+    Word16 i;
+    Word16 j;
+    Word16 index = 0;
+    Word16 gcode0;
+    Word16 e_max;
+    Word16 temp;
+    Word16 exp_code;
+    Word16 g_pitch;
+    Word16 g2_pitch;
+    Word16 g_code;
+    Word16 g2_code;
+    Word16 g_pit_cod;
+    Word16 coeff[5];
+    Word16 coeff_lo[5];
+    Word16 exp_max[5];
+    Word32 L_tmp;
+    Word32 L_tmp2;
+    Word32 dist_min;
+    const Word16 *table_gain;
+    Word16 table_len;
+
+    if (mode == MR102 || mode == MR74 || mode == MR67)
+    {
+        table_len = VQ_SIZE_HIGHRATES;
+        table_gain = table_gain_highrates;
+    }
+    else
+    {
+        table_len = VQ_SIZE_LOWRATES;
+        table_gain = table_gain_lowrates;
+    }
+
+    /*-------------------------------------------------------------------*
+     *  predicted codebook gain                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *  gc0     = 2^exp_gcode0 + 2^frac_gcode0                           *
+     *                                                                   *
+     *  gcode0 (Q14) = 2^14*2^frac_gcode0 = gc0 * 2^(14-exp_gcode0)      *
+     *-------------------------------------------------------------------*/
+
+    gcode0 = (Word16)(Pow2(14, frac_gcode0, pOverflow));
+
+    /*-------------------------------------------------------------------*
+     *  Scaling considerations:                                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+     *-------------------------------------------------------------------*/
+
+    /*
+     * The error energy (sum) to be minimized consists of five terms, t[0..4].
+     *
+     *                      t[0] =    gp^2  * <y1 y1>
+     *                      t[1] = -2*gp    * <xn y1>
+     *                      t[2] =    gc^2  * <y2 y2>
+     *                      t[3] = -2*gc    * <xn y2>
+     *                      t[4] =  2*gp*gc * <y1 y2>
+     *
+     */
+
+    /* determine the scaling exponent for g_code: ec = ec0 - 11 */
+    exp_code = sub(exp_gcode0, 11, pOverflow);
+
+    /* calculate exp_max[i] = s[i]-1 */
+    exp_max[0] = sub(exp_coeff[0], 13, pOverflow);
+    exp_max[1] = sub(exp_coeff[1], 14, pOverflow);
+
+    temp = shl(exp_code, 1, pOverflow);
+    temp = add(15, temp, pOverflow);
+    exp_max[2] = add(exp_coeff[2], temp, pOverflow);
+
+    exp_max[3] = add(exp_coeff[3], exp_code, pOverflow);
+
+    temp = add(1, exp_code, pOverflow);
+    exp_max[4] = add(exp_coeff[4], temp, pOverflow);
+
+
+    /*-------------------------------------------------------------------*
+     *  Find maximum exponent:                                           *
+     *  ~~~~~~~~~~~~~~~~~~~~~~                                           *
+     *                                                                   *
+     *  For the sum operation, all terms must have the same scaling;     *
+     *  that scaling should be low enough to prevent overflow. There-    *
+     *  fore, the maximum scale is determined and all coefficients are   *
+     *  re-scaled:                                                       *
+     *                                                                   *
+     *    e_max = max(exp_max[i]) + 1;                                   *
+     *    e = exp_max[i]-e_max;         e <= 0!                          *
+     *    c[i] = c[i]*2^e                                                *
+     *-------------------------------------------------------------------*/
+
+    e_max = exp_max[0];
+    for (i = 1; i < 5; i++)
+    {
+        if (exp_max[i] > e_max)
+        {
+            e_max = exp_max[i];
+        }
+    }
+
+    e_max = add(e_max, 1, pOverflow);      /* To avoid overflow */
+
+    for (i = 0; i < 5; i++)
+    {
+        j = sub(e_max, exp_max[i], pOverflow);
+        L_tmp = L_deposit_h(frac_coeff[i]);
+        L_tmp = L_shr(L_tmp, j, pOverflow);
+        L_Extract(L_tmp, &coeff[i], &coeff_lo[i], pOverflow);
+    }
+
+
+    /*-------------------------------------------------------------------*
+     *  Codebook search:                                                 *
+     *  ~~~~~~~~~~~~~~~~                                                 *
+     *                                                                   *
+     *  For each pair (g_pitch, g_fac) in the table calculate the        *
+     *  terms t[0..4] and sum them up; the result is the mean squared    *
+     *  error for the quantized gains from the table. The index for the  *
+     *  minimum MSE is stored and finally used to retrieve the quantized *
+     *  gains                                                            *
+     *-------------------------------------------------------------------*/
+
+    /* start with "infinite" MSE */
+    dist_min = MAX_32;
+
+    p = &table_gain[0];
+
+    for (i = 0; i < table_len; i++)
+    {
+        g_pitch = *p++;
+        g_code = *p++;                   /* this is g_fac        */
+        p++;                             /* skip log2(g_fac)     */
+        p++;                             /* skip 20*log10(g_fac) */
+
+        if (g_pitch <= gp_limit)
+        {
+            g_code = mult(g_code, gcode0, pOverflow);
+            g2_pitch = mult(g_pitch, g_pitch, pOverflow);
+            g2_code = mult(g_code, g_code, pOverflow);
+            g_pit_cod = mult(g_code, g_pitch, pOverflow);
+
+            L_tmp = Mpy_32_16(coeff[0], coeff_lo[0], g2_pitch, pOverflow);
+            L_tmp2 = Mpy_32_16(coeff[1], coeff_lo[1], g_pitch, pOverflow);
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+
+            L_tmp2 = Mpy_32_16(coeff[2], coeff_lo[2], g2_code, pOverflow);
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+
+            L_tmp2 =  Mpy_32_16(coeff[3], coeff_lo[3], g_code, pOverflow);
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+
+            L_tmp2 = Mpy_32_16(coeff[4], coeff_lo[4], g_pit_cod, pOverflow);
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+
+            /* store table index if MSE for this index is lower
+               than the minimum MSE seen so far */
+            if (L_tmp < dist_min)
+            {
+                dist_min = L_tmp;
+                index = i;
+            }
+        }
+    }
+
+    /*------------------------------------------------------------------*
+     *  read quantized gains and new values for MA predictor memories   *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   *
+     *------------------------------------------------------------------*/
+
+    /* Read the quantized gains */
+    p = &table_gain[shl(index, 2, pOverflow)];
+    *gain_pit = *p++;
+    g_code = *p++;
+    *qua_ener_MR122 = *p++;
+    *qua_ener = *p;
+
+    /*------------------------------------------------------------------*
+     *  calculate final fixed codebook gain:                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                            *
+     *                                                                  *
+     *   gc = gc0 * g                                                   *
+     *------------------------------------------------------------------*/
+
+    L_tmp = L_mult(g_code, gcode0, pOverflow);
+    temp  = sub(10, exp_gcode0, pOverflow);
+    L_tmp = L_shr(L_tmp, temp, pOverflow);
+
+    *gain_cod = extract_h(L_tmp);
+
+    return index;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.cpp b/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.cpp
new file mode 100644
index 0000000..352b611
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.cpp
@@ -0,0 +1,990 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/s10_8pf.c
+ Funtions: search_10and8i40
+
+     Date: 04/18/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Adding pOverflow to the functions to remove global variables.
+              These changes are needed for the EPOC releases. Cleaned up code.
+              Updated template.
+
+ Description: Changed temp to temp32. When temp was only 16 bits it was not
+              holding the 32 bit value returned from the functions. Some
+              variables were also being declared as Word16 rather than Word32
+              as they were suposed to be.
+
+ Description: Changed copyright year. Removed all calls to math functions by
+              inlining them, and removed all unnecessary files in the Include
+              section.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Removed all #defines.
+              2. Used a pointer to &codvec[0] instead of array indexing.
+              3. Removed multiple data casting in the code.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers, this by taking
+                 advantage of the fact that the autocrrelation  matrix is
+                 a toeplitz matrix, so r[i][j] = r[j][i], then a single
+                 pointer can be used to address a matrix. The use of this
+                 is not uniform along the function (due to compiler limitations:
+                 handling so many variables in this file) so the use
+                 of this is pointer optimizations is limited to places
+                 where the ARM compiler provides the lesses numer of cycles
+              3. Eliminated use of intermediate variables to accelerate
+                 comparisons (like in the nested loops)
+              4. Introduced array temp1[], to pre-calculate the elements
+                 used in the nested loops, in this way the calculation is
+                 not repeated in every loop iteration. This is done for
+                 loops i3-i5-i7 and i9
+              5. Use array Index[] to store indexes i1:i9, and then use memcpy
+                 to update indexes.
+              6. Eliminated shifts by modifying the way number are rounded,
+                 this does not have any effect in ARM processors but may help
+                 other compilers
+
+ Description:
+              1. When storing indexes, added memcpy() to support the rates
+                 that use this function: 12.2 (already done) and 10.2 (missing).
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "s10_8pf.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: search_10and8i40
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    nbPulse = nbPulses to find (Word16)
+    step = step size (Word16)
+    nbTracks = nbTracks (Word16)
+    dn[] = correlation between target and h[] (Word16)
+    rr[][] = matrix of autocorrelation (Word16)
+    ipos[] = starting position of each pulse (Word16)
+    pos_max[] = Position of maximum dn[] (Word16)
+    codvec[] = Algebraic codebook vector (Word16)
+    pOverflow = pointer to Overflow flag (Flag)
+
+ Outputs:
+    codvec[] = Algebraic codebook vector (Word16)
+    pOverflow -> 1 if processing this funvction results in satuaration
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function searches for the best codevector; It determines the positions
+ of the 10/8 pulses in the 40-sample frame.
+
+    search_10and8i40 (10,5,5,dn, rr, ipos, pos_max, codvec);   for GSMEFR
+    search_10and8i40 (8, 4,4,dn, rr, ipos, pos_max, codvec);   for 10.2
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ s10_8pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void search_10and8i40 (
+    Word16 nbPulse,      // i : nbpulses to find
+    Word16 step,         // i :  stepsize
+    Word16 nbTracks,     // i :  nbTracks
+    Word16 dn[],         // i : correlation between target and h[]
+    Word16 rr[][L_CODE], // i : matrix of autocorrelation
+    Word16 ipos[],       // i : starting position for each pulse
+    Word16 pos_max[],    // i : position of maximum of dn[]
+    Word16 codvec[]      // o : algebraic codebook vector
+)
+{
+   Word16 i0, i1, i2, i3, i4, i5, i6, i7, i8, i9;
+   Word16 i, j, k, pos, ia, ib;
+   Word16 psk, ps, ps0, ps1, ps2, sq, sq2;
+   Word16 alpk, alp, alp_16;
+   Word16 rrv[L_CODE];
+   Word32 s, alp0, alp1, alp2;
+   Word16 gsmefrFlag;
+
+
+   if (sub(nbPulse, 10) == 0)
+   {
+      gsmefrFlag=1;
+   }
+   else
+   {
+      gsmefrFlag=0;
+   }
+
+   // fix i0 on maximum of correlation position
+   i0 = pos_max[ipos[0]];
+
+   //
+   // i1 loop:                                                         *
+   //
+
+   // Default value
+
+   psk = -1;
+   alpk = 1;
+   for (i = 0; i < nbPulse; i++)
+   {
+      codvec[i] = i;
+   }
+
+   for (i = 1; i < nbTracks; i++)
+   {
+      i1 = pos_max[ipos[1]];
+      ps0 = add (dn[i0], dn[i1]);
+      alp0 = L_mult (rr[i0][i0], _1_16);
+      alp0 = L_mac (alp0, rr[i1][i1], _1_16);
+      alp0 = L_mac (alp0, rr[i0][i1], _1_8);
+
+      //
+      // i2 and i3 loop
+      //
+
+      for (i3 = ipos[3]; i3 < L_CODE; i3 += step)
+      {
+         s = L_mult (rr[i3][i3], _1_8);       // index incr= step+L_CODE
+         s = L_mac (s, rr[i0][i3], _1_4);     // index increment = step
+         s = L_mac (s, rr[i1][i3], _1_4);     // index increment = step
+         rrv[i3] = pv_round (s);
+      }
+
+      // Default value
+      sq = -1;
+      alp = 1;
+      ps = 0;
+      ia = ipos[2];
+      ib = ipos[3];
+
+      for (i2 = ipos[2]; i2 < L_CODE; i2 += step)
+      {
+         // index increment = step
+         ps1 = add (ps0, dn[i2]);
+
+         // index incr= step+L_CODE
+         alp1 = L_mac (alp0, rr[i2][i2], _1_16);
+
+         // index increment = step
+         alp1 = L_mac (alp1, rr[i0][i2], _1_8);
+
+         // index increment = step
+         alp1 = L_mac (alp1, rr[i1][i2], _1_8);
+
+         for (i3 = ipos[3]; i3 < L_CODE; i3 += step)
+         {
+            // index increment = step
+            ps2 = add (ps1, dn[i3]);
+
+            // index increment = step
+            alp2 = L_mac (alp1, rrv[i3], _1_2);
+
+            // index increment = step
+            alp2 = L_mac (alp2, rr[i2][i3], _1_8);
+
+            sq2 = mult (ps2, ps2);
+
+            alp_16 = pv_round (alp2);
+
+            s = L_msu (L_mult (alp, sq2), sq, alp_16);
+
+            if (s > 0)
+            {
+               sq = sq2;
+               ps = ps2;
+               alp = alp_16;
+               ia = i2;
+               ib = i3;
+            }
+         }
+      }
+      i2 = ia;
+      i3 = ib;
+
+        //
+        // i4 and i5 loop:
+        //
+
+        ps0 = ps;
+        alp0 = L_mult (alp, _1_2);
+
+        for (i5 = ipos[5]; i5 < L_CODE; i5 += step)
+        {
+            s = L_mult (rr[i5][i5], _1_8);
+            s = L_mac (s, rr[i0][i5], _1_4);
+            s = L_mac (s, rr[i1][i5], _1_4);
+            s = L_mac (s, rr[i2][i5], _1_4);
+            s = L_mac (s, rr[i3][i5], _1_4);
+            rrv[i5] = pv_round (s);
+        }
+
+        // Default value
+        sq = -1;
+        alp = 1;
+        ps = 0;
+        ia = ipos[4];
+        ib = ipos[5];
+
+        for (i4 = ipos[4]; i4 < L_CODE; i4 += step)
+        {
+            ps1 = add (ps0, dn[i4]);
+
+            alp1 = L_mac (alp0, rr[i4][i4], _1_32);
+            alp1 = L_mac (alp1, rr[i0][i4], _1_16);
+            alp1 = L_mac (alp1, rr[i1][i4], _1_16);
+            alp1 = L_mac (alp1, rr[i2][i4], _1_16);
+            alp1 = L_mac (alp1, rr[i3][i4], _1_16);
+
+            for (i5 = ipos[5]; i5 < L_CODE; i5 += step)
+            {
+                ps2 = add (ps1, dn[i5]);
+
+                alp2 = L_mac (alp1, rrv[i5], _1_4);
+                alp2 = L_mac (alp2, rr[i4][i5], _1_16);
+
+                sq2 = mult (ps2, ps2);
+
+                alp_16 = pv_round (alp2);
+
+                s = L_msu (L_mult (alp, sq2), sq, alp_16);
+
+                if (s > 0)
+                {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = alp_16;
+                    ia = i4;
+                    ib = i5;
+                }
+            }
+        }
+        i4 = ia;
+        i5 = ib;
+
+        //
+        // i6 and i7 loop:
+        //
+
+        ps0 = ps;
+        alp0 = L_mult (alp, _1_2);
+
+        for (i7 = ipos[7]; i7 < L_CODE; i7 += step)
+        {
+            s = L_mult (rr[i7][i7], _1_16);
+            s = L_mac (s, rr[i0][i7], _1_8);
+            s = L_mac (s, rr[i1][i7], _1_8);
+            s = L_mac (s, rr[i2][i7], _1_8);
+            s = L_mac (s, rr[i3][i7], _1_8);
+            s = L_mac (s, rr[i4][i7], _1_8);
+            s = L_mac (s, rr[i5][i7], _1_8);
+            rrv[i7] = pv_round (s);
+        }
+
+        // Default value
+        sq = -1;
+        alp = 1;
+        ps = 0;
+        ia = ipos[6];
+        ib = ipos[7];
+
+        for (i6 = ipos[6]; i6 < L_CODE; i6 += step)
+        {
+            ps1 = add (ps0, dn[i6]);
+
+            alp1 = L_mac (alp0, rr[i6][i6], _1_64);
+            alp1 = L_mac (alp1, rr[i0][i6], _1_32);
+            alp1 = L_mac (alp1, rr[i1][i6], _1_32);
+            alp1 = L_mac (alp1, rr[i2][i6], _1_32);
+            alp1 = L_mac (alp1, rr[i3][i6], _1_32);
+            alp1 = L_mac (alp1, rr[i4][i6], _1_32);
+            alp1 = L_mac (alp1, rr[i5][i6], _1_32);
+
+            for (i7 = ipos[7]; i7 < L_CODE; i7 += step)
+            {
+                ps2 = add (ps1, dn[i7]);
+
+                alp2 = L_mac (alp1, rrv[i7], _1_4);
+                alp2 = L_mac (alp2, rr[i6][i7], _1_32);
+
+                sq2 = mult (ps2, ps2);
+
+                alp_16 = pv_round (alp2);
+
+                s = L_msu (L_mult (alp, sq2), sq, alp_16);
+
+                if (s > 0)
+                {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = alp_16;
+                    ia = i6;
+                    ib = i7;
+                }
+            }
+        }
+        i6 = ia;
+        i7 = ib;
+
+        // now finished searching a set of 8 pulses
+
+        if(gsmefrFlag != 0){
+           // go on with the two last pulses for GSMEFR
+           //
+           // i8 and i9 loop:
+           //
+
+           ps0 = ps;
+           alp0 = L_mult (alp, _1_2);
+
+           for (i9 = ipos[9]; i9 < L_CODE; i9 += step)
+           {
+              s = L_mult (rr[i9][i9], _1_16);
+              s = L_mac (s, rr[i0][i9], _1_8);
+              s = L_mac (s, rr[i1][i9], _1_8);
+              s = L_mac (s, rr[i2][i9], _1_8);
+              s = L_mac (s, rr[i3][i9], _1_8);
+              s = L_mac (s, rr[i4][i9], _1_8);
+              s = L_mac (s, rr[i5][i9], _1_8);
+              s = L_mac (s, rr[i6][i9], _1_8);
+              s = L_mac (s, rr[i7][i9], _1_8);
+              rrv[i9] = pv_round (s);
+           }
+
+           // Default value
+           sq = -1;
+           alp = 1;
+           ps = 0;
+           ia = ipos[8];
+           ib = ipos[9];
+
+           for (i8 = ipos[8]; i8 < L_CODE; i8 += step)
+           {
+              ps1 = add (ps0, dn[i8]);
+
+              alp1 = L_mac (alp0, rr[i8][i8], _1_128);
+              alp1 = L_mac (alp1, rr[i0][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i1][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i2][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i3][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i4][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i5][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i6][i8], _1_64);
+              alp1 = L_mac (alp1, rr[i7][i8], _1_64);
+
+              for (i9 = ipos[9]; i9 < L_CODE; i9 += step)
+              {
+                 ps2 = add (ps1, dn[i9]);
+
+                 alp2 = L_mac (alp1, rrv[i9], _1_8);
+                 alp2 = L_mac (alp2, rr[i8][i9], _1_64);
+
+                 sq2 = mult (ps2, ps2);
+
+                 alp_16 = pv_round (alp2);
+
+                 s = L_msu (L_mult (alp, sq2), sq, alp_16);
+
+                 if (s > 0)
+                 {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = alp_16;
+                    ia = i8;
+                    ib = i9;
+                 }
+              }
+           }
+        } // end  gsmefrFlag
+
+        //
+        // test and memorise if this combination is better than the last one/
+        //
+
+        s = L_msu (L_mult (alpk, sq), psk, alp);
+
+        if (s > 0)
+        {
+            psk = sq;
+            alpk = alp;
+            codvec[0] = i0;
+            codvec[1] = i1;
+            codvec[2] = i2;
+            codvec[3] = i3;
+            codvec[4] = i4;
+            codvec[5] = i5;
+            codvec[6] = i6;
+            codvec[7] = i7;
+
+            if (gsmefrFlag != 0)
+            {
+               codvec[8] = ia;
+               codvec[9] = ib;
+            }
+        }
+
+        //
+        // Cyclic permutation of i1,i2,i3,i4,i5,i6,i7,(i8 and i9)/
+        //
+
+        pos = ipos[1];
+        for (j = 1, k = 2; k < nbPulse; j++, k++)
+        {
+            ipos[j] = ipos[k];
+        }
+        ipos[sub(nbPulse,1)] = pos;
+   } // end 1..nbTracks  loop
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void search_10and8i40(
+    Word16 nbPulse,      /* i : nbpulses to find                       */
+    Word16 step,         /* i : stepsize                               */
+    Word16 nbTracks,     /* i : nbTracks                               */
+    Word16 dn[],         /* i : correlation between target and h[]     */
+    Word16 rr[][L_CODE], /* i : matrix of autocorrelation              */
+    Word16 ipos[],       /* i : starting position for each pulse       */
+    Word16 pos_max[],    /* i : position of maximum of dn[]            */
+    Word16 codvec[],     /* o : algebraic codebook vector              */
+    Flag   *pOverflow    /* i/o : overflow flag                        */
+)
+{
+    Word16 i0, i1, i2, i3, i4, i5, i6, i7, i9;
+    Word16 i, j, k/*, m*/;
+    Word16 pos, ia, ib;
+    Word16 psk;
+    Word16 sq, sq2;
+    Word16 alpk, alp, alp_16;
+    Word32 s;
+    Word32 alp0, alp1, alp2;
+    Word16 gsmefrFlag;
+    Word16 *p_codvec = codvec;
+    Word16  *p_temp2;
+
+    Word16  temp1[2*L_CODE];
+    Word16  *p_temp1;
+    Word16  ps2;
+    Word16  ps1;
+    Word16  ps;
+    Word16 ps0;
+
+    Word16  index[10];
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    if (nbPulse == 10)
+    {
+        gsmefrFlag = 1;
+    }
+    else
+    {
+        gsmefrFlag = 0;
+    }
+
+    /* fix i0 on maximum of correlation position */
+    i0 = pos_max[ipos[0]];
+    index[0] = i0;
+    /*------------------------------------------------------------------*
+    * i1 loop:                                                         *
+    *------------------------------------------------------------------*/
+
+    /* Default value */
+    psk = -1;
+    alpk = 1;
+    for (i = 0; i < nbPulse; i++)
+    {
+        *(p_codvec++) = i;
+    }
+
+    for (i = 1; i < nbTracks; i++)
+    {
+        i1 = pos_max[ipos[1]];
+        index[1] = i1;
+
+        /* ps0 = add (dn[i0], dn[i1], pOverflow);*/
+        ps0 = (Word16)((Word32) dn[i0] + dn[i1]);
+
+        /* alp0 = L_mult (rr[i0][i0], _1_16, pOverflow); */
+        alp0 = (Word32) rr[i0][i0] << 12;
+
+        /* alp0 = L_mac (alp0, rr[i1][i1], _1_16, pOverflow); */
+        alp0 += (Word32) rr[i1][i1] << 12;
+
+        /* alp0 = L_mac (alp0, rr[i0][i1], _1_8, pOverflow); */
+        alp0 += (Word32) rr[i0][i1] << 13;
+        alp0 += 0x00008000L;
+
+        /*----------------------------------------------------------------*
+        * i2 and i3 loop:                                                *
+        *----------------------------------------------------------------*/
+
+        p_temp1 = temp1;
+        for (i3 = ipos[3]; i3 < L_CODE; i3 += step)
+        {
+            p_temp2 = &rr[i3][0];
+            s  = (Word32) * (p_temp2 + i3) >> 1;
+            s += (Word32) * (p_temp2 + i0);
+            s += (Word32) * (p_temp2 + i1);
+            *(p_temp1++) = ps0 + dn[i3];
+            *(p_temp1++) = (Word16)((s + 2) >> 2);
+        }
+
+        /* Default value */
+        sq = -1;
+        alp = 1;
+        ps = 0;
+        ia = ipos[2];
+        ib = ipos[3];
+
+        s = (alp0 >> 12);
+
+        for (j = ipos[2]; j < L_CODE; j += step)
+        {
+            /* index increment = step  */
+            p_temp2 = &rr[j][0];
+
+            alp1 = (s + (Word32) * (p_temp2 + j)) >> 1;
+
+            alp1 += (Word32) * (p_temp2 + i0);
+
+            alp1 += (Word32) * (p_temp2 + i1);
+
+            p_temp1 = temp1;
+            ps1 = dn[j];
+
+
+            for (i3 = ipos[3]; i3 < L_CODE; i3 += step)
+            {
+                /* index increment = step */
+                ps2 = ps1 + *(p_temp1++);
+
+                sq2 = (Word16)(((Word32) ps2 * ps2) >> 15);
+
+                alp2 = (alp1 + p_temp2[i3]) >> 2;
+                alp2 = (alp2 + *(p_temp1++)) >> 1;  /*  alp2 is always > 0  */
+                if (((Word32) sq2 * alp) > ((Word32) sq * alp2))
+                {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = (Word16)alp2;
+                    ia = j;
+                    ib = i3;
+                }
+            }
+
+        }
+        i2 = ia;
+        i3 = ib;
+        index[2] = ia;
+        index[3] = ib;
+
+        /*----------------------------------------------------------------*
+        * i4 and i5 loop:                                                *
+        *----------------------------------------------------------------*/
+
+        alp0 = ((Word32) alp << 15) + 0x00008000L;
+        p_temp1 = temp1;
+
+        for (i5 = ipos[5]; i5 < L_CODE; i5 += step)
+        {
+            p_temp2 = &rr[i5][0];
+            s = (Word32) * (p_temp2 + i5) >> 1;
+            s += (Word32) * (p_temp2 + i0);
+            s += (Word32) * (p_temp2 + i1);
+            s += (Word32) * (p_temp2 + i2);
+            s += (Word32) * (p_temp2 + i3);
+
+            *(p_temp1++) = ps + dn[i5];
+            *(p_temp1++) = (Word16)((s + 2) >> 2);
+        }
+
+        /* Default value */
+        sq = -1;
+        alp = 1;
+        ps = 0;
+        ia = ipos[4];
+        ib = ipos[5];
+
+        for (j = ipos[4]; j < L_CODE; j += step)
+        {
+            /* ps1 = add (ps0, dn[i4], pOverflow); */
+            p_temp2 = &rr[j][0];
+
+            /* alp1 = L_mac (alp0, rr[i4][i4], _1_32, pOverflow); */
+            alp1 = alp0 + ((Word32) * (p_temp2 + j) << 11);
+
+            /* alp1 = L_mac (alp1, rr[i0][i4], _1_16, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i0) << 12;
+
+            /* alp1 = L_mac (alp1, rr[i1][i4], _1_16, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i1) << 12;
+
+            /* alp1 = L_mac (alp1, rr[i2][i4], _1_16, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i2) << 12;
+
+            /* alp1 = L_mac (alp1, rr[i3][i4], _1_16, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i3) << 12;
+
+            p_temp1 = temp1;
+            ps1 =  dn[j];
+
+            for (i5 = ipos[5]; i5 < L_CODE; i5 += step)
+            {
+                ps2 = ps1 + *(p_temp1++);
+
+                alp2 = alp1 + ((Word32) * (p_temp2 + i5) << 12);
+
+                alp_16 = (Word16)((alp2 + ((Word32) * (p_temp1++) << 14)) >> 16);
+                sq2 = (Word16)(((Word32) ps2 * ps2) >> 15);
+
+                if (((Word32) sq2 * alp) > ((Word32) sq * alp_16))
+                {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = alp_16;
+                    ia = j;
+                    ib = i5;
+                }
+
+            }
+        }
+        i4 = ia;
+        i5 = ib;
+        index[4] = ia;
+        index[5] = ib;
+
+        /*----------------------------------------------------------------*
+        * i6 and i7 loop:                                                *
+        *----------------------------------------------------------------*/
+
+        alp0 = ((Word32) alp << 15) + 0x00008000L;
+
+        p_temp1 = temp1;
+
+        for (i7 = ipos[7]; i7 < L_CODE; i7 += step)
+        {
+            s = (Word32) rr[i7][i7] >> 1;
+            s += (Word32) rr[i0][i7];
+            s += (Word32) rr[i1][i7];
+            s += (Word32) rr[i2][i7];
+            s += (Word32) rr[i3][i7];
+            s += (Word32) rr[i4][i7];
+            s += (Word32) rr[i5][i7];
+            *(p_temp1++) = ps + dn[i7];
+            *(p_temp1++) = (Word16)((s + 4) >> 3);
+        }
+
+
+        /* Default value */
+        sq = -1;
+        alp = 1;
+        ps = 0;
+        ia = ipos[6];
+        ib = ipos[7];
+
+        for (j = ipos[6]; j < L_CODE; j += step)
+        {
+            /* ps1 = add (ps0, dn[i6], pOverflow); */
+
+            p_temp2 = (Word16 *) & rr[j];
+
+            /* alp1 = L_mac (alp0, rr[i6][i6], _1_64, pOverflow); */
+            alp1 = alp0 + ((Word32) * (p_temp2 + j) << 10);
+
+            /* alp1 = L_mac (alp1, rr[i0][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i0) << 11;
+
+
+            /* alp1 = L_mac (alp1, rr[i1][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i1) << 11;
+
+            /* alp1 = L_mac (alp1, rr[i2][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i2) << 11;
+
+            /* alp1 = L_mac (alp1, rr[i3][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i3) << 11;
+
+            /* alp1 = L_mac (alp1, rr[i4][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i4) << 11;
+
+            /* alp1 = L_mac (alp1, rr[i5][i6], _1_32, pOverflow); */
+            alp1 += (Word32) * (p_temp2 + i5) << 11;
+
+            p_temp1 = temp1;
+            ps1 = dn[j];
+
+            for (i7 = ipos[7]; i7 < L_CODE; i7 += step)
+            {
+                ps2 = ps1 + *(p_temp1++);
+
+                alp2 = alp1 + ((Word32) * (p_temp2 + i7) << 11);
+
+                alp_16 = (Word16)((alp2 + ((Word32) * (p_temp1++) << 14)) >> 16);
+
+                sq2 = (Word16)(((Word32) ps2 * ps2) >> 15);
+
+                if (((Word32) sq2 * alp) > ((Word32) sq * alp_16))
+                {
+                    sq = sq2;
+                    ps = ps2;
+                    alp = alp_16;
+                    ia = j;
+                    ib = i7;
+                }
+            }
+        }
+
+        i6 = ia;
+        i7 = ib;
+        index[6] = ia;
+        index[7] = ib;
+
+        /* now finished searching a set of 8 pulses */
+
+        if (gsmefrFlag != 0)
+        {
+            /* go on with the two last pulses for GSMEFR                      */
+            /*----------------------------------------------------------------*
+            * i8 and i9 loop:                                                *
+            *----------------------------------------------------------------*/
+
+            alp0 = ((Word32) alp << 15) + 0x00008000L;
+
+            p_temp1 = temp1;
+
+            for (i9 = ipos[9]; i9 < L_CODE; i9 += step)
+            {
+                s = (Word32) rr[i9][i9] >> 1;
+                s += (Word32) rr[i0][i9];
+                s += (Word32) rr[i1][i9];
+                s += (Word32) rr[i2][i9];
+                s += (Word32) rr[i3][i9];
+                s += (Word32) rr[i4][i9];
+                s += (Word32) rr[i5][i9];
+                s += (Word32) rr[i6][i9];
+                s += (Word32) rr[i7][i9];
+
+                *(p_temp1++) = ps + dn[i9];
+                *(p_temp1++) = (Word16)((s + 4) >> 3);
+            }
+
+            /* Default value */
+            sq = -1;
+            alp = 1;
+            ps = 0;
+            ia = ipos[8];
+            ib = ipos[9];
+
+            for (j = ipos[8]; j < L_CODE; j += step)
+            {
+                /* ps1 = add (ps0, dn[i8], pOverflow); */
+                p_temp2 = &rr[j][0];
+
+                /* alp1 = L_mac (alp0, rr[i8][i8], _1_128, pOverflow); */
+                alp1 = alp0 + ((Word32) * (p_temp2 + j) << 9);
+
+                /* alp1 = L_mac (alp1, rr[i0][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i0][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i1][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i1][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i2][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i2][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i3][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i3][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i4][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i4][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i5][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i5][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i6][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i6][j] << 10;
+
+                /* alp1 = L_mac (alp1, rr[i7][i8], _1_64, pOverflow); */
+                alp1 += (Word32) rr[i7][j] << 10;
+
+                p_temp1 = temp1;
+                ps1 = dn[j];
+
+                for (i9 = ipos[9]; i9 < L_CODE; i9 += step)
+                {
+                    /* ps2 = add (ps1, dn[i9], pOverflow); */
+                    ps2 = ps1 + *(p_temp1++);
+
+                    /* sq2 = mult (ps2, ps2, pOverflow); */
+                    sq2 = (Word16)(((Word32) ps2 * ps2) >> 15);
+
+                    /* alp2 = L_mac (alp1, rrv[i9], _1_8, pOverflow); */
+                    alp2 = alp1 + ((Word32) * (p_temp2 + i9) << 10) ;
+
+                    /* alp2 = L_mac (alp2, rr[i8][i9], _1_64, pOverflow); */
+                    alp_16 = (Word16)((alp2 + ((Word32) * (p_temp1++) << 13)) >> 16);
+
+                    if (((Word32) sq2 * alp) > ((Word32) sq * alp_16))
+                    {
+                        sq = sq2;
+                        ps = ps2;
+                        alp = alp_16;
+                        ia = j;
+                        ib = i9;
+                    }
+                }
+            }
+
+            index[8] = ia;
+            index[9] = ib;
+
+        }/* end  gsmefrFlag */
+
+        /*----------------------------------------------------------------  *
+         * test and memorise if this combination is better than the last one.*
+         *----------------------------------------------------------------*/
+
+        if (((Word32) alpk * sq) > ((Word32) psk * alp))
+        {
+            psk = sq;
+            alpk = alp;
+
+            if (gsmefrFlag != 0)
+            {
+                memcpy(codvec, index, (2*NB_TRACK)*sizeof(*index));
+            }
+            else
+            {
+                memcpy(codvec, index, (2*NB_TRACK_MR102)*sizeof(*index));
+            }
+
+        }
+        /*----------------------------------------------------------------*
+        * Cyclic permutation of i1,i2,i3,i4,i5,i6,i7,(i8 and i9).          *
+        *----------------------------------------------------------------*/
+
+        pos = ipos[1];
+        for (j = 1, k = 2; k < nbPulse; j++, k++)
+        {
+            ipos[j] = ipos[k];
+        }
+        ipos[nbPulse-1] = pos;
+    } /* end 1..nbTracks  loop*/
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.h b/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.h
new file mode 100644
index 0000000..7591f5f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/s10_8pf.h
@@ -0,0 +1,128 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/s10_8pf.h
+
+
+
+
+     Date: 08/11/2000
+
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Changed function prototype; pointer to  overflow flag is passed
+              in as a parameter. Updated template
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the s10_8pf module.
+------------------------------------------------------------------------------
+*/
+
+#ifndef S10_8PF_H
+#define S10_8PF_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basicop_malloc.h"
+#include    "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void search_10and8i40(
+        Word16 nbPulse,       /* i : nbpulses to find                       */
+        Word16 step,          /* i :  stepsize                              */
+        Word16 nbTracks,      /* i :  nbTracks                              */
+        Word16 dn[],          /* i : correlation between target and h[]     */
+        Word16 rr[][L_CODE],  /* i : matrix of autocorrelation              */
+        Word16 ipos[],        /* i : starting position for each pulse       */
+        Word16 pos_max[],     /* i : position of maximum of dn[]            */
+        Word16 codvec[],      /* o : algebraic codebook vector              */
+        Flag   *pOverflow     /* i/o : Overflow flag                        */
+    );
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _S10_8PF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/set_sign.cpp b/media/libstagefright/codecs/amrnb/enc/src/set_sign.cpp
new file mode 100644
index 0000000..dedf91a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/set_sign.cpp
@@ -0,0 +1,609 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/set_sign.c
+ Funtions: set_sign
+           set_sign12k2
+
+     Date: 05/26/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Placed into PV template and optimized.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header files of the math functions
+              used in the file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Modified certain FOR loops to count down.
+              2. Modified code for further optimization.
+
+ Description: Modified FOR loops in set_sign12k2 to count up. The FOR loops
+              affected are the loop that calculates the starting position of
+              each incoming pulse, and the loop that calculates the position
+              of the max correlation. Updated copyright year.
+
+ Description: Passing in pointer to overflow flag for EPOC compatibility.
+
+ Description:  For set_sign12k2()
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation, this by evaluating the operands
+              4. Replaced loop counter with decrement loops
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This module contains the functions set_sign and set_sign12k2.
+ These functions are used to build a sign vector according
+ to the values in the input arrays.  These functions also
+ find the position in the input codes of the maximum correlation
+ and the starting position for each pulse.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "set_sign.h"
+#include "basic_op.h"
+#include "inv_sqrt.h"
+#include "cnst.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: set_sign
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    dn = buffer of correlation values (Word16)
+    sign = buffer containing sign of dn elements (Word16)
+    dn2 = buffer containing the maximum of correlation in each track.(Word16)
+    n = number of maximum correlations in dn2 (Word16)
+
+ Returns:
+    None
+
+ Outputs:
+    dn buffer is modified to contain the absolute value of its input
+    sign buffer is modified to contain the sign information for the
+      values in dn buffer
+    dn2 buffer is modified to denote the location of the maximum
+      correlation for each track.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+ This function builds sign vector according to dn buffer It also finds
+ the position of maximum of correlation in each track and the starting
+ position for each pulse.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ set_sign.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void set_sign(Word16 dn[],    i/o : correlation between target and h[]
+              Word16 sign[],  o   : sign of dn[]
+              Word16 dn2[],   o   : maximum of correlation in each track.
+              Word16 n        i   : # of maximum correlations in dn2[]
+)
+{
+   Word16 i, j, k;
+   Word16 val, min;
+   Word16 pos = 0;    //initialization only needed to keep gcc silent
+
+   // set sign according to dn[]
+
+   for (i = 0; i < L_CODE; i++) {
+      val = dn[i];
+
+      if (val >= 0) {
+         sign[i] = 32767;
+      } else {
+         sign[i] = -32767;
+         val = negate(val);
+      }
+      dn[i] = val;     // modify dn[] according to the fixed sign
+      dn2[i] = val;
+   }
+
+   // keep 8-n maximum positions/8 of each track and store it in dn2[]
+
+   for (i = 0; i < NB_TRACK; i++)
+   {
+      for (k = 0; k < (8-n); k++)
+      {
+         min = 0x7fff;
+         for (j = i; j < L_CODE; j += STEP)
+         {
+            if (dn2[j] >= 0)
+            {
+               val = sub(dn2[j], min);
+
+               if (val < 0)
+               {
+                  min = dn2[j];
+                  pos = j;
+               }
+            }
+         }
+         dn2[pos] = -1;
+      }
+   }
+
+   return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void set_sign(Word16 dn[],   /* i/o : correlation between target and h[]    */
+              Word16 sign[], /* o   : sign of dn[]                          */
+              Word16 dn2[],  /* o   : maximum of correlation in each track. */
+              Word16 n       /* i   : # of maximum correlations in dn2[]    */
+             )
+{
+    register Word16 i, j, k;
+    Word16 val, min;
+    Word16 pos = 0; /* initialization only needed to keep gcc silent */
+
+    /* set sign according to dn[] */
+    for (i = L_CODE - 1; i >= 0; i--)
+    {
+        val = dn[i];
+
+        if (val >= 0)
+        {
+            sign[i] = 32767;
+        }
+        else
+        {
+            sign[i] = -32767;
+            val = negate(val);
+            dn[i] = val;     /* modify dn[] according to the fixed sign */
+        }
+
+        dn2[i] = val;
+    }
+
+    /* keep 8-n maximum positions/8 of each track and store it in dn2[] */
+
+    for (i = 0; i < NB_TRACK; i++)
+    {
+        for (k = 0; k < (8 - n); k++)
+        {
+            min = 0x7fff;
+            for (j = i; j < L_CODE; j += STEP)
+            {
+                if (dn2[j] >= 0)
+                {
+                    if (dn2[j] < min)
+                    {
+                        min = dn2[j];
+                        pos = j;
+                    }
+                }
+            }
+            dn2[pos] = -1;
+        }
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: set_sign12k2()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    dn = buffer of correlation values (Word16)
+    cn = buffer of residual after long term prediction (Word16)
+    sign = sign of correlation buffer elements (Word16)
+    pos_max = buffer containing position of maximum correlation (Word16)
+    nb_track = number of tracks (Word16)
+    ipos = buffer containing the starting position for each pulse (Word16)
+    step = step size in the tracks (Word16)
+    pOverflow = pointer to Overflow flag (Flag)
+
+ Outputs:
+    sign buffer contains the sign of correlation values
+    dn buffer contains the sign-adjusted correlation values
+    pos_max buffer contains the maximum correlation position
+    ipos buffer contains the starting position of each pulse
+    pOverflow -> 1 if the math operations called by this function result in
+    saturation
+
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function builds the sign vector according to dn and cn, and modifies
+ dn to include the sign information (dn[i]=sign[i]*dn[i]). It also finds
+ the position of maximum of correlation in each track and the starting
+ position for each pulse.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ set_sign.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void set_sign12k2 (
+    Word16 dn[],       //i/o : correlation between target and h[]
+    Word16 cn[],       //i   : residual after long term prediction
+    Word16 sign[],     //o   : sign of d[n]
+    Word16 pos_max[],  //o   : position of maximum correlation
+    Word16 nb_track,   //i   : number of tracks tracks
+    Word16 ipos[],     //o   : starting position for each pulse
+    Word16 step        //i   : the step size in the tracks
+)
+{
+    Word16 i, j;
+    Word16 val, cor, k_cn, k_dn, max, max_of_all;
+    Word16 pos = 0;      // initialization only needed to keep gcc silent
+    Word16 en[L_CODE];                  // correlation vector
+    Word32 s;
+
+    // The reference ETSI code uses a global flag for Overflow. However in the
+    // actual implementation a pointer to the overflow flag is passed in. This
+    // pointer is passed into the basic math functions called by this routine.
+
+    // calculate energy for normalization of cn[] and dn[]
+
+    s = 256;
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = L_mac (s, cn[i], cn[i]);
+    }
+    s = Inv_sqrt (s);
+    k_cn = extract_h (L_shl (s, 5));
+
+    s = 256;
+    for (i = 0; i < L_CODE; i++)
+    {
+        s = L_mac (s, dn[i], dn[i]);
+    }
+    s = Inv_sqrt (s);
+    k_dn = extract_h (L_shl (s, 5));
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        val = dn[i];
+        cor = pv_round (L_shl (L_mac (L_mult (k_cn, cn[i]), k_dn, val), 10));
+
+        if (cor >= 0)
+        {
+            sign[i] = 32767;                      // sign = +1
+        }
+        else
+        {
+            sign[i] = -32767;                     // sign = -1
+            cor = negate (cor);
+            val = negate (val);
+        }
+        // modify dn[] according to the fixed sign
+        dn[i] = val;
+        en[i] = cor;
+    }
+
+    max_of_all = -1;
+    for (i = 0; i < nb_track; i++)
+    {
+        max = -1;
+
+        for (j = i; j < L_CODE; j += step)
+        {
+            cor = en[j];
+            val = sub (cor, max);
+
+            if (val > 0)
+            {
+                max = cor;
+                pos = j;
+            }
+        }
+        // store maximum correlation position
+        pos_max[i] = pos;
+        val = sub (max, max_of_all);
+
+        if (val > 0)
+        {
+            max_of_all = max;
+            // starting position for i0
+            ipos[0] = i;
+        }
+    }
+
+    //
+    //     Set starting position of each pulse.
+    //
+
+    pos = ipos[0];
+    ipos[nb_track] = pos;
+
+    for (i = 1; i < nb_track; i++)
+    {
+        pos = add (pos, 1);
+
+        if (sub (pos, nb_track) >= 0)
+        {
+           pos = 0;
+        }
+        ipos[i] = pos;
+        ipos[add(i, nb_track)] = pos;
+    }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void set_sign12k2(
+    Word16 dn[],        /* i/o : correlation between target and h[]         */
+    Word16 cn[],        /* i   : residual after long term prediction        */
+    Word16 sign[],      /* o   : sign of d[n]                               */
+    Word16 pos_max[],   /* o   : position of maximum correlation            */
+    Word16 nb_track,    /* i   : number of tracks tracks                    */
+    Word16 ipos[],      /* o   : starting position for each pulse           */
+    Word16 step,        /* i   : the step size in the tracks                */
+    Flag   *pOverflow   /* i/o: overflow flag                               */
+)
+{
+    Word16 i, j;
+    Word16 val;
+    Word16 cor;
+    Word16 k_cn;
+    Word16 k_dn;
+    Word16 max;
+    Word16 max_of_all;
+    Word16 pos = 0; /* initialization only needed to keep gcc silent */
+    Word16 en[L_CODE];                  /* correlation vector */
+    Word32 s;
+    Word32 t;
+    Word32 L_temp;
+    Word16 *p_cn;
+    Word16 *p_dn;
+    Word16 *p_sign;
+    Word16 *p_en;
+
+    /* calculate energy for normalization of cn[] and dn[] */
+
+    s = 256;
+    t = 256;
+    p_cn = cn;
+    p_dn = dn;      /* crosscorrelation values do not have strong peaks, so
+                       scaling applied in cor_h_x (sf=2) guaranteed that the
+                       mac of the energy for this vector will not overflow */
+
+    for (i = L_CODE; i != 0; i--)
+    {
+        val = *(p_cn++);
+        s = L_mac(s, val, val, pOverflow);
+        val = *(p_dn++);
+        t += ((Word32) val * val) << 1;
+    }
+    s = Inv_sqrt(s, pOverflow);
+    k_cn = (Word16)((L_shl(s, 5, pOverflow)) >> 16);
+
+    t = Inv_sqrt(t, pOverflow);
+    k_dn = (Word16)(t >> 11);
+
+    p_cn   = &cn[L_CODE-1];
+    p_sign = &sign[L_CODE-1];
+    p_en   = &en[L_CODE-1];
+
+    for (i = L_CODE - 1; i >= 0; i--)
+    {
+        L_temp = ((Word32)k_cn * *(p_cn--)) << 1;
+        val = dn[i];
+        s = L_mac(L_temp, k_dn, val, pOverflow);
+        L_temp = L_shl(s, 10, pOverflow);
+        cor = pv_round(L_temp, pOverflow);
+
+        if (cor >= 0)
+        {
+            *(p_sign--) = 32767;                      /* sign = +1 */
+        }
+        else
+        {
+            *(p_sign--) = -32767;                     /* sign = -1 */
+            cor = - (cor);
+
+            /* modify dn[] according to the fixed sign */
+            dn[i] = - val;
+        }
+
+        *(p_en--) = cor;
+    }
+
+    max_of_all = -1;
+    for (i = 0; i < nb_track; i++)
+    {
+        max = -1;
+
+        for (j = i; j < L_CODE; j += step)
+        {
+            cor = en[j];
+            if (cor > max)
+            {
+                max = cor;
+                pos = j;
+            }
+        }
+        /* store maximum correlation position */
+        pos_max[i] = pos;
+        if (max > max_of_all)
+        {
+            max_of_all = max;
+            /* starting position for i0 */
+            ipos[0] = i;
+        }
+    }
+
+    /*----------------------------------------------------------------*
+     *     Set starting position of each pulse.                       *
+     *----------------------------------------------------------------*/
+
+    pos = ipos[0];
+    ipos[nb_track] = pos;
+
+    for (i = 1; i < nb_track; i++)
+    {
+        pos++;
+
+        if (pos >= nb_track)
+        {
+            pos = 0;
+        }
+        ipos[ i] = pos;
+        ipos[ i + nb_track] = pos;
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/set_sign.h b/media/libstagefright/codecs/amrnb/enc/src/set_sign.h
new file mode 100644
index 0000000..7b0185a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/set_sign.h
@@ -0,0 +1,127 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/set_sign.h
+
+     Date: 08/11/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Changed function prototype for set_sign12k2(); pointer to
+                overflow flag is passed in as a parameter.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the set_sign() and set_sign12k2() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef SET_SIGN_H
+#define SET_SIGN_H "@(#)$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basicop_malloc.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void set_sign(Word16 dn[],   /* i/o : correlation between target and h[]    */
+    Word16 sign[], /* o   : sign of dn[]                          */
+    Word16 dn2[],  /* o   : maximum of correlation in each track. */
+    Word16 n       /* i   : # of maximum correlations in dn2[]    */
+                 );
+
+    void set_sign12k2(
+        Word16 dn[],        /* i/o : correlation between target and h[]         */
+        Word16 cn[],        /* i   : residual after long term prediction        */
+        Word16 sign[],      /* o   : sign of d[n]                               */
+        Word16 pos_max[],   /* o   : position of maximum correlation            */
+        Word16 nb_track,    /* i   : number of tracks tracks                    */
+        Word16 ipos[],      /* o   : starting position for each pulse           */
+        Word16 step,        /* i   : the step size in the tracks                */
+        Flag   *pOverflow   /* i/o : overflow flag                              */
+    );
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _SET_SIGN_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sid_sync.cpp b/media/libstagefright/codecs/amrnb/enc/src/sid_sync.cpp
new file mode 100644
index 0000000..3e744f6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/sid_sync.cpp
@@ -0,0 +1,544 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm-amr/c/src/sid_sync.c
+ Functions: sid_sync_init
+            sid_sync_reset
+            sid_sync_exit
+            sid_sync_set_handover_debt
+            sid_sync
+
+     Date: 03/13/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed type definition of state pointer to 'void' for
+              sid_sync_init, sid_sync_reset, sid_sync_exit, and sid_sync.
+              Updated to PV coding template.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that initialize, reset, exit, and perform
+ SID synchronization.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "typedef.h"
+#include "basic_op.h"
+#include "mode.h"
+#include "sid_sync.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; [Define module specific macros here]
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; [Include all pre-processor statements here. Include conditional
+; compile variables also.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sid_sync_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer containing a pointer to the state structure used for
+            SID synchronization (void)
+
+ Outputs:
+    None
+
+ Returns:
+    return_value = status of sid_sync_reset function; -1, if state is pointing
+                   to a NULL address (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initialize one instance of the sid_sync module. It stores
+ the pointer to state struct in *st. This pointer has to be passed to sid_sync
+ in each call. This function returns 0 on success, otherwise, -1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sid_sync.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 sid_sync_init(void **state)
+{
+    sid_syncState* s;
+
+    if (state == NULL)
+    {
+        /* fprintf(stderr, "sid_sync_init:invalid state parameter\n"); */
+        return -1;
+    }
+
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (sid_syncState *)
+             malloc(sizeof(sid_syncState))) == NULL)
+    {
+        /* fprintf(stderr,
+                "sid_sync_init: "
+                "can not malloc state structure\n"); */
+        return -1;
+    }
+    s->sid_update_rate = 8;
+
+    *state = (void *)s;
+
+    return(sid_sync_reset(s));
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sid_sync_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to the state structure used for SID synchronization (void)
+
+ Outputs:
+    None
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs a reset of the sid_sync module by setting the state
+ memory to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sid_sync.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+Word16 sid_sync_reset(void *st)
+{
+    sid_syncState *state = (sid_syncState *) st;
+
+    state->sid_update_counter = 3;
+    state->sid_handover_debt = 0;
+    state->prev_ft = TX_SPEECH_GOOD;
+
+    return 0;
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sid_sync_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer containing a pointer to the state structure used for
+            SID synchronization (void)
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees up the state structure used by sid_sync function. It
+ stores NULL in *state.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sid_sync.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void sid_sync_exit(void **state)
+{
+    sid_syncState **st = (sid_syncState **) state;
+
+    if (st == NULL || *st == NULL)
+    {
+        return;
+    }
+
+    /* deallocate memory */
+    free(*st);
+    *st = NULL;
+
+    return;
+
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sid_sync_set_handover_debt
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to the state structure used for SID synchronization
+         (sid_syncState)
+    debtFrames = number of handover debt frames (Word16)
+
+ Outputs:
+    st->sid_handover_debt is set to debtFrames
+
+ Returns:
+    return_value = 0
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function updates the handover debt to debtFrames. Extra SID_UPD are
+ scheduled to update remote decoder CNI states, right after an handover.
+ This is primarily for use on MS UL side.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sid_sync.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void sid_sync_set_handover_debt(sid_syncState *st,
+                                Word16 debtFrames)
+{
+    /* debtFrames >= 0 */
+    st->sid_handover_debt = debtFrames;
+    return;
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sid_sync
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to the state structure used for SID synchronization
+            (sid_syncState)
+    mode = codec mode (enum Mode)
+    tx_frame_type = pointer to TX frame type store (enum TXFrameType)
+
+ Outputs:
+    tx_frame_type contains the new TX frame type
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs SID frame synchronization to ensure that the mode
+ only switches to a neighbouring mode.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sid_sync.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+void sid_sync(void *state,
+              enum Mode mode,
+              enum TXFrameType *tx_frame_type)
+{
+
+    sid_syncState *st = (sid_syncState *) state;
+
+    if (mode == MRDTX)
+    {
+
+        st->sid_update_counter--;
+
+        if (st->prev_ft == TX_SPEECH_GOOD)
+        {
+            *tx_frame_type = TX_SID_FIRST;
+            st->sid_update_counter = 3;
+        }
+        else
+        {
+            /* TX_SID_UPDATE or TX_NO_DATA */
+            if ((st->sid_handover_debt > 0) &&
+                    (st->sid_update_counter > 2))
+            {
+                /* ensure extra updates are  properly delayed after
+                   a possible SID_FIRST */
+                *tx_frame_type = TX_SID_UPDATE;
+                st->sid_handover_debt--;
+            }
+            else
+            {
+                if (st->sid_update_counter == 0)
+                {
+                    *tx_frame_type = TX_SID_UPDATE;
+                    st->sid_update_counter = st->sid_update_rate;
+                }
+                else
+                {
+                    *tx_frame_type = TX_NO_DATA;
+                }
+            }
+        }
+    }
+    else
+    {
+        st->sid_update_counter = st->sid_update_rate ;
+        *tx_frame_type = TX_SPEECH_GOOD;
+    }
+    st->prev_ft = *tx_frame_type;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sid_sync.h b/media/libstagefright/codecs/amrnb/enc/src/sid_sync.h
new file mode 100644
index 0000000..c3cb1cf
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/sid_sync.h
@@ -0,0 +1,147 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm-amr/c/include/sid_sync.h
+
+     Date: 03/13/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added PV coding template sections to 3GPP version 3.2.0.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the type definition and function prototypes used by the
+ SID synchronization functions.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _SID_SYNC_H_
+#define _SID_SYNC_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "frame.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+#define sid_sync_h "$Id $"
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 sid_update_rate;  /* Send SID Update every sid_update_rate frame */
+        Word16 sid_update_counter; /* Number of frames since last SID          */
+        Word16 sid_handover_debt;  /* Number of extra SID_UPD frames to schedule*/
+        enum TXFrameType prev_ft;
+    } sid_syncState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /* initialize one instance of the sid_sync module
+       Stores pointer to state struct in *st. This pointer has to
+       be passed to sid_sync in each call.
+       returns 0 on success
+     */
+    Word16 sid_sync_init(void **st);
+
+    /* reset of sid_sync module (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    Word16 sid_sync_reset(void *st);
+
+    /* de-initialize sid_sync module (i.e. free status struct)
+       stores NULL in *st
+     */
+    void sid_sync_exit(void **st);
+
+    /*  update handover debt
+        debtFrames extra SID_UPD are scheduled .
+        to update remote decoder CNI states, right after an handover.
+        (primarily for use on MS UL side )
+    */
+    void sid_sync_set_handover_debt(sid_syncState *st,  /* i/o: sid_sync state  */
+                                    Word16 debtFrames);
+
+    /* To ensure that the mode only switches to a neighbouring mode */
+    void sid_sync(void *st ,
+                  enum Mode mode,
+                  enum TXFrameType *tx_frame_type);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _SID_SYNC_H_ */
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sp_enc.cpp b/media/libstagefright/codecs/amrnb/enc/src/sp_enc.cpp
new file mode 100644
index 0000000..77ae9de
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/sp_enc.cpp
@@ -0,0 +1,754 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/sp_enc.c
+ Funtions: GSMInitEncode
+           Speech_Encode_Frame_reset
+           GSMEncodeFrameExit
+           Speech_Encode_Frame_First
+           GSMEncodeFrame
+
+     Date: 02/07/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Cleaned up INCLUDES. removed inclusion of basic_op.h and count.h.
+
+
+ Description: Revert back to Speech_Encode_Frame_reset() and
+              Speech_Encode_Frame_First
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These functions comprise the pre filtering and encoding of one speech frame.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "sp_enc.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "set_zero.h"
+#include "pre_proc.h"
+#include "prm2bits.h"
+#include "mode.h"
+#include "cod_amr.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: GSMInitEncode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+ Inputs:
+    state = pointer to an array of pointers to structures of type
+            Speech_Decode_FrameState
+    dtx = flag to turn off or turn on DTX (Flag)
+    id = pointer to an array whose contents are of type char
+
+ Outputs:
+    pre_state field of the structure pointed to by the pointer pointed to
+      by state is set to NULL
+    cod_amr_state field of the structure pointed to by the pointer pointed to
+      by state is set to NULL
+    dtx field of the structure pointed to by the pointer pointed to by state
+      is set to the input dtx
+
+ Returns:
+    return_value = set to zero, if initialization was successful; -1,
+                   otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates memory for filter structure and initializes state
+ memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+ Note: Original function name of Speech_Encode_Frame_init was changed to
+       GSMInitEncode in the Code section.
+
+int Speech_Encode_Frame_init (void **state_data,
+                   Flag   dtx,
+                   char  *id)
+{
+  Speech_Encode_FrameState* s;
+
+  if (state_data == NULL){
+      fprintf(stderr, "Speech_Encode_Frame_init: invalid parameter\n");
+      return -1;
+  }
+  *state_data = NULL;
+
+  // allocate memory
+  if ((s= (Speech_Encode_FrameState *) malloc(sizeof(Speech_Encode_FrameState))) == NULL){
+      fprintf(stderr, "Speech_Encode_Frame_init: can not malloc state "
+                      "structure\n");
+      return -1;
+  }
+
+  s->complexityCounter = getCounterId(id);
+
+  s->pre_state = NULL;
+  s->cod_amr_state = NULL;
+  s->dtx = dtx;
+
+  if (Pre_Process_init(&s->pre_state) ||
+      cod_amr_init(&s->cod_amr_state, s->dtx)) {
+      GSMEncodeFrameExit(&s);
+      return -1;
+  }
+
+  Speech_Encode_Frame_reset(s);
+  *state_data = (void *)s;
+
+  return 0;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 GSMInitEncode(void **state_data,
+                     Flag   dtx,
+                     Word8  *id)
+{
+    Speech_Encode_FrameState* s;
+
+    OSCL_UNUSED_ARG(id);
+
+    if (state_data == NULL)
+    {
+        /*  fprintf(stderr, "Speech_Encode_Frame_init: invalid parameter\n");  */
+        return -1;
+    }
+    *state_data = NULL;
+
+    /* allocate memory */
+    if ((s = (Speech_Encode_FrameState *) malloc(sizeof(Speech_Encode_FrameState))) == NULL)
+    {
+        /*  fprintf(stderr, "Speech_Encode_Frame_init: can not malloc state "
+                        "structure\n");  */
+        return -1;
+    }
+
+    s->pre_state = NULL;
+    s->cod_amr_state = NULL;
+    s->dtx = dtx;
+
+    if (Pre_Process_init(&s->pre_state) ||
+            cod_amr_init(&s->cod_amr_state, s->dtx))
+    {
+        Speech_Encode_FrameState** temp = &s;
+        GSMEncodeFrameExit((void**)temp);
+        return -1;
+    }
+
+    Speech_Encode_Frame_reset(s);
+    *state_data = (void *)s;
+
+    return 0;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Speech_Encode_Frame_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to structures of type Speech_Decode_FrameState
+
+ Outputs:
+    None
+
+ Returns:
+    return_value = set to zero if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Speech_Encode_Frame_reset (void *state_data)
+{
+
+  Speech_Encode_FrameState *state =
+     (Speech_Encode_FrameState *) state_data;
+
+  if (state_data == NULL){
+        fprintf(stderr, "Speech_Encode_Frame_reset
+                           : invalid parameter\n");
+      return -1;
+  }
+
+  Pre_Process_reset(state->pre_state);
+  cod_amr_reset(state->cod_amr_state);
+
+  setCounter(state->complexityCounter);
+  Init_WMOPS_counter();
+  setCounter(0); // set counter to global counter
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 Speech_Encode_Frame_reset(void *state_data)
+{
+
+    Speech_Encode_FrameState *state =
+        (Speech_Encode_FrameState *) state_data;
+
+    if (state_data == NULL)
+    {
+        /*  fprintf(stderr, "Speech_Encode_Frame_reset
+                             : invalid parameter\n");  */
+        return -1;
+    }
+
+    Pre_Process_reset(state->pre_state);
+    cod_amr_reset(state->cod_amr_state);
+
+    return 0;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: GSMEncodeFrameExit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer to a structure of type cod_amrState
+
+ Outputs:
+    state points to a NULL address
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees the memory used for state memory.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: Original function name of Speech_Encode_Frame_exit was changed to
+       GSMEncodeFrameExit in the Code section.
+
+void Speech_Encode_Frame_exit (void **state_data)
+{
+
+    Speech_Encode_FrameState **state =
+        (Speech_Encode_FrameState **) state_data;
+
+  if (state == NULL || *state == NULL)
+      return;
+
+  Pre_Process_exit(&(*state)->pre_state);
+  cod_amr_exit(&(*state)->cod_amr_state);
+
+  setCounter((*state)->complexityCounter);
+  WMOPS_output(0);
+  setCounter(0); // set counter to global counter
+
+  // deallocate memory
+  free(*state);
+  *state = NULL;
+
+  return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void GSMEncodeFrameExit(void **state_data)
+{
+
+    Speech_Encode_FrameState **state =
+        (Speech_Encode_FrameState **) state_data;
+
+    if (state == NULL || *state == NULL)
+        return;
+
+    Pre_Process_exit(&(*state)->pre_state);
+    cod_amr_exit(&(*state)->cod_amr_state);
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Speech_Encode_Frame_First
+------------------------------------------------------------------------------
+
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type Speech_Encode_FrameState that contains
+            the post filter states
+    new_speech = pointer to buffer of length L_FRAME that contains
+                 the speech input (Word16)
+
+ Outputs:
+    The structure of type Speech_Encode_FrameState pointed to by st is updated.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function encodes the first frame of speech. It calls the pre-processing
+ filter and the first frame encoder.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Speech_Encode_Frame_First (
+    Speech_Encode_FrameState *st,  // i/o : post filter states
+    Word16 *new_speech)            // i   : speech input
+{
+#if !defined(NO13BIT)
+   Word16 i;
+#endif
+
+   setCounter(st->complexityCounter);
+
+#if !defined(NO13BIT)
+  // Delete the 3 LSBs (13-bit input)
+  for (i = 0; i < L_NEXT; i++)
+  {
+     new_speech[i] = new_speech[i] & 0xfff8;
+  }
+#endif
+
+  // filter + downscaling
+  Pre_Process (st->pre_state, new_speech, L_NEXT);
+
+  cod_amr_first(st->cod_amr_state, new_speech);
+
+  Init_WMOPS_counter (); // reset WMOPS counter for the new frame
+
+  return 0;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void Speech_Encode_Frame_First(
+    Speech_Encode_FrameState *st,  /* i/o : post filter states       */
+    Word16 *new_speech)            /* i   : speech input             */
+{
+#if !defined(NO13BIT)
+    Word16 i;
+#endif
+
+#if !defined(NO13BIT)
+    /* Delete the 3 LSBs (13-bit input) */
+    for (i = 0; i < L_NEXT; i++)
+    {
+        new_speech[i] = new_speech[i] & 0xfff8;
+    }
+#endif
+
+    /* filter + downscaling */
+    Pre_Process(st->pre_state, new_speech, L_NEXT);
+
+    cod_amr_first(st->cod_amr_state, new_speech);
+
+    return;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: cod_amr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state_data = a void pointer to the post filter states
+    mode = AMR mode of type enum Mode
+    new_speech = pointer to buffer of length L_FRAME that contains
+             the speech input of type Word16
+    serial = pointer to the serial bit stream of type Word16
+    usedMode = pointer to the used mode of type enum Mode
+
+ Outputs:
+    serial -> encoded serial bit stream
+    The value pointed to by usedMode is updated.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is the entry point to the GSM AMR encoder. The following
+ operations are performed to generate one encoded frame: First, the incoming
+ audio samples are passed through the pre-processing filter where they are
+ filtered and downscaled. A call is then made to the main encoder cod_amr().
+ This generates the set of encoded parameters which include the LSP, adaptive
+ codebook, and fixed codebook quantization indices (addresses and gains). The
+ generated parameters are then converted to serial bits.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_enc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+ Note: Original function name of Speech_Encode_Frame was changed to
+       GSMEncodeFrame in the Code section.
+
+int Speech_Encode_Frame (
+    void *state_data,             // i/o : post filter states
+    enum Mode mode,               // i   : speech coder mode
+    Word16 *new_speech,           // i   : speech input
+    Word16 *serial,               // o   : serial bit stream
+    enum Mode *usedMode           // o   : used speech coder mode
+    )
+{
+
+  Speech_Encode_FrameState *st =
+     (Speech_Encode_FrameState *) state_data;
+
+  Word16 prm[MAX_PRM_SIZE];   // Analysis parameters
+  Word16 syn[L_FRAME];        // Buffer for synthesis speech
+  Word16 i;
+
+  setCounter(st->complexityCounter);
+  Reset_WMOPS_counter (); // reset WMOPS counter for the new frame
+  // initialize the serial output frame to zero
+  for (i = 0; i < MAX_SERIAL_SIZE; i++)
+  {
+    serial[i] = 0;
+  }
+#if !defined(NO13BIT)
+  // Delete the 3 LSBs (13-bit input)
+  for (i = 0; i < L_FRAME; i++)
+  {
+     new_speech[i] = new_speech[i] & 0xfff8;
+
+
+  }
+#endif
+
+  // filter + downscaling
+  Pre_Process (st->pre_state, new_speech, L_FRAME);
+
+  // Call the speech encoder
+  cod_amr(st->cod_amr_state, mode, new_speech, prm, usedMode, syn);
+
+  // Parameters to serial bits
+  Prm2bits (*usedMode, prm, &serial[0]);
+
+  fwc();
+  setCounter(0); // set counter to global counter
+
+  return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void GSMEncodeFrame(
+    void *state_data,             /* i/o : post filter states          */
+    enum Mode mode,               /* i   : speech coder mode           */
+    Word16 *new_speech,           /* i   : speech input                */
+    Word16 *serial,               /* o   : serial bit stream           */
+    enum Mode *usedMode           /* o   : used speech coder mode      */
+)
+{
+
+    Speech_Encode_FrameState *st =
+        (Speech_Encode_FrameState *) state_data;
+
+    Word16 prm[MAX_PRM_SIZE];   /* Analysis parameters.                 */
+    Word16 syn[L_FRAME];        /* Buffer for synthesis speech          */
+    Word16 i;
+
+    /* initialize the serial output frame to zero */
+    for (i = 0; i < MAX_SERIAL_SIZE; i++)
+    {
+        serial[i] = 0;
+    }
+#if !defined(NO13BIT)
+    /* Delete the 3 LSBs (13-bit input) */
+    for (i = 0; i < L_FRAME; i++)
+    {
+        new_speech[i] = new_speech[i] & 0xfff8;
+    }
+#endif
+
+    /* filter + downscaling */
+    Pre_Process(st->pre_state, new_speech, L_FRAME);
+
+    /* Call the speech encoder */
+    cod_amr(st->cod_amr_state, mode, new_speech, prm, usedMode, syn);
+
+    /* Parameters to serial bits */
+    Prm2bits(*usedMode, prm, &serial[0]);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/sp_enc.h b/media/libstagefright/codecs/amrnb/enc/src/sp_enc.h
new file mode 100644
index 0000000..8eb2a9b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/sp_enc.h
@@ -0,0 +1,154 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/src/include/sp_enc.h
+
+     Date: 02/07/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Changed the function names of
+              Speech_Encode_Frame_reset and Speech_Encode_Frame_first to
+              GSMEncodeFrameReset and GSMEncodeFrameFirst respectively for
+              consistency.
+
+ Description: Reverted back to old function names Speech_Encode_Frame_reset()
+              and Speech_Encode_Frame_First()
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : sp_enc.h
+       Purpose          : Encoding of one speech frame
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef sp_enc_h
+#define sp_enc_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "pre_proc.h"
+#include "mode.h"
+#include "cod_amr.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; [Define module specific macros here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; [Include all pre-processor statements here.]
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Pre_ProcessState *pre_state;
+        cod_amrState   *cod_amr_state;
+        Flag dtx;
+    } Speech_Encode_FrameState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /* initialize one instance of the speech encoder
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Speech_Encode_Frame in each call.
+       returns 0 on success */
+    Word16 GSMInitEncode(void **state_data,
+                         Flag   dtx,
+                         Word8  *id);
+
+
+    /* reset speech encoder (i.e. set state memory to zero)
+       returns 0 on success */
+    Word16 Speech_Encode_Frame_reset(void *state_data);
+
+    /* de-initialize speech encoder (i.e. free status struct)
+       stores NULL in *s */
+    void GSMEncodeFrameExit(void **state_data);
+
+    void Speech_Encode_Frame_First(
+        Speech_Encode_FrameState *st, /* i/o : post filter states     */
+        Word16 *new_speech);          /* i   : speech input           */
+
+    void GSMEncodeFrame(
+        void *state_data,             /* i/o : encoder states         */
+        enum Mode mode,               /* i   : speech coder mode      */
+        Word16 *new_speech,           /* i   : input speech           */
+        Word16 *serial,               /* o   : serial bit stream      */
+        enum Mode *usedMode           /* o   : used speech coder mode */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _sp_enc_h_ */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spreproc.cpp b/media/libstagefright/codecs/amrnb/enc/src/spreproc.cpp
new file mode 100644
index 0000000..71d645a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/spreproc.cpp
@@ -0,0 +1,234 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/spreproc.c
+ Functions: subframePreProc
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Eliminated unnecessary use of the sub() function.
+
+ Description:
+              1. Replaced copy() and for-loop with more efficient memcpy().
+              2. Eliminated unused include file copy.h.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "spreproc.h"
+#include "typedef.h"
+#include "weight_a.h"
+#include "syn_filt.h"
+#include "residu.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: subframePreProc
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode        -- enum Mode          -- coder mode
+    gamma1      -- const Word16 array -- spectral exp. factor 1
+    gamma1_12k2 -- const Word16 array -- spectral exp. factor 1 for EFR
+    gamma2      -- const Word16 array -- spectral exp. factor 2
+    A           -- Pointer to Word16  -- A(z) unquantized for the 4 subframes
+    Aq          -- Pointer to Word16  -- A(z)   quantized for the 4 subframes
+    speech      -- Pointer to Word16  -- speech segment
+    mem_err     -- Pointer to Word16  -- pointer to error signal
+    mem_w0      -- Pointer to Word16  -- memory of weighting filter
+    zero        -- Pointer to Word16  -- pointer to zero vector
+
+ Outputs:
+    ai_zero -- Word16 array -- history of weighted synth. filter
+    exc     -- Word16 array -- long term prediction residual
+    h1      -- Word16 array -- impulse response
+    xn      -- Word16 array -- target vector for pitch search
+    res2    -- Word16 array -- long term prediction residual
+    error   -- Word16 array -- error of LPC synthesis filter
+
+ Returns:
+    Zero
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ spreproc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void subframePreProc(
+    enum Mode mode,            /* i  : coder mode                            */
+    const Word16 gamma1[],     /* i  : spectral exp. factor 1                */
+    const Word16 gamma1_12k2[],/* i  : spectral exp. factor 1 for EFR        */
+    const Word16 gamma2[],     /* i  : spectral exp. factor 2                */
+    Word16 *A,                 /* i  : A(z) unquantized for the 4 subframes  */
+    Word16 *Aq,                /* i  : A(z)   quantized for the 4 subframes  */
+    Word16 *speech,            /* i  : speech segment                        */
+    Word16 *mem_err,           /* i  : pointer to error signal               */
+    Word16 *mem_w0,            /* i  : memory of weighting filter            */
+    Word16 *zero,              /* i  : pointer to zero vector                */
+    Word16 ai_zero[],          /* o  : history of weighted synth. filter     */
+    Word16 exc[],              /* o  : long term prediction residual         */
+    Word16 h1[],               /* o  : impulse response                      */
+    Word16 xn[],               /* o  : target vector for pitch search        */
+    Word16 res2[],             /* o  : long term prediction residual         */
+    Word16 error[]             /* o  : error of LPC synthesis filter         */
+)
+{
+    Word16 Ap1[MP1];              /* A(z) with spectral expansion         */
+    Word16 Ap2[MP1];              /* A(z) with spectral expansion         */
+    const Word16 *g1;             /* Pointer to correct gammma1 vector    */
+
+    /* mode specific pointer to gamma1 values */
+    if (mode == MR122 || mode == MR102)
+    {
+        g1 = gamma1_12k2;
+    }
+    else
+    {
+        g1 = gamma1;
+    }
+
+    /* Find the weighted LPC coefficients for the weighting filter. */
+    Weight_Ai(A, g1, Ap1);
+    Weight_Ai(A, gamma2, Ap2);
+
+    memcpy(ai_zero, Ap1, (M + 1)*sizeof(Word16));
+
+
+    Syn_filt(Aq, ai_zero, h1, L_SUBFR, zero, 0);
+    Syn_filt(Ap2, h1, h1, L_SUBFR, zero, 0);
+
+    /*
+     *
+     *          Find the target vector for pitch search:
+     *
+     */
+
+    /* LPC residual */
+    Residu(Aq, speech, res2, L_SUBFR);
+
+    memcpy(exc, res2, L_SUBFR*sizeof(Word16));
+
+    Syn_filt(Aq, exc, error, L_SUBFR, mem_err, 0);
+
+    Residu(Ap1, error, xn, L_SUBFR);
+
+    /* target signal xn[]*/
+    Syn_filt(Ap2, xn, xn, L_SUBFR, mem_w0, 0);
+
+    return;
+
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spreproc.h b/media/libstagefright/codecs/amrnb/enc/src/spreproc.h
new file mode 100644
index 0000000..77d35fc
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/spreproc.h
@@ -0,0 +1,135 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/spreproc.h
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, spreproc.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef spreproc_h
+#define spreproc_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "cnst.h"
+#include "mode.h"
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void subframePreProc(
+        enum Mode mode,            /* i  : coder mode                            */
+        const Word16 gamma1[],     /* i  : spectral exp. factor 1                */
+        const Word16 gamma1_12k2[],/* i  : spectral exp. factor 1 for EFR        */
+        const Word16 gamma2[],     /* i  : spectral exp. factor 2                */
+        Word16 *A,                 /* i  : A(z) unquantized for the 4 subframes  */
+        Word16 *Aq,                /* i  : A(z)   quantized for the 4 subframes  */
+        Word16 *speech,            /* i  : speech segment                        */
+        Word16 *mem_err,           /* i  : pointer to error signal               */
+        Word16 *mem_w0,            /* i  : memory of weighting filter            */
+        Word16 *zero,              /* i  : pointer to zero vector                */
+        Word16 ai_zero[],          /* o  : history of weighted synth. filter     */
+        Word16 exc[],              /* o  : long term prediction residual         */
+        Word16 h1[],               /* o  : impulse response                      */
+        Word16 xn[],               /* o  : target vector for pitch search        */
+        Word16 res2[],             /* o  : long term prediction residual         */
+        Word16 error[]             /* o  : error of LPC synthesis filter         */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* spreproc_h */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spstproc.cpp b/media/libstagefright/codecs/amrnb/enc/src/spstproc.cpp
new file mode 100644
index 0000000..b9574aa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/spstproc.cpp
@@ -0,0 +1,314 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/spstproc.c
+ Functions: subframePostProc
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation
+              4. Replaced loop counter with decrement loops
+
+ Description:  Added casting to eliminate warnings
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Subframe post processing
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "spstproc.h"
+#include "syn_filt.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: subframePostProc
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+ Inputs:
+    speech    -- Pointer to Word16 -- speech segment
+    mode      -- enum Mode         -- coder mode
+    i_subfr   -- Word16 -- Subframe nr
+    gain_pit  -- Word16 -- Pitch gain  Q14
+    gain_code -- Word16 -- Decoded innovation gain
+    Aq        -- Pointer to Word16 -- A(z) quantized for the 4 subframes
+    synth     -- Word16 Array -- Local synthesis
+    xn        -- Word16 Array -- Target vector for pitch search
+    code      -- Word16 Array -- Fixed codebook exitation
+    y1        -- Word16 Array -- Filtered adaptive exitation
+    y2        -- Word16 Array -- Filtered fixed codebook excitation
+    mem_syn   -- Pointer to Word16 -- memory of synthesis filter
+
+ Outputs:
+    mem_syn -- Pointer to Word16 -- memory of synthesis filter
+    mem_err -- Pointer to Word16 -- pointer to error signal
+    mem_w0  -- Pointer to Word16 -- memory of weighting filter
+    exc     -- Pointer to Word16 -- long term prediction residual
+    sharp   -- Pointer to Word16 -- pitch sharpening value
+    pOverflow -- Pointer to Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ spstproc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void subframePostProc(
+    Word16 *speech,   /* i   : speech segment                        */
+    enum Mode mode,   /* i   : coder mode                            */
+    Word16 i_subfr,   /* i   : Subframe nr                           */
+    Word16 gain_pit,  /* i   : Pitch gain                       Q14  */
+    Word16 gain_code, /* i   : Decoded innovation gain               */
+    Word16 *Aq,       /* i   : A(z) quantized for the 4 subframes    */
+    Word16 synth[],   /* i   : Local snthesis                        */
+    Word16 xn[],      /* i   : Target vector for pitch search        */
+    Word16 code[],    /* i   : Fixed codebook exitation              */
+    Word16 y1[],      /* i   : Filtered adaptive exitation           */
+    Word16 y2[],      /* i   : Filtered fixed codebook excitation    */
+    Word16 *mem_syn,  /* i/o : memory of synthesis filter            */
+    Word16 *mem_err,  /* o   : pointer to error signal               */
+    Word16 *mem_w0,   /* o   : memory of weighting filter            */
+    Word16 *exc,      /* o   : long term prediction residual         */
+    Word16 *sharp,    /* o   : pitch sharpening value                */
+    Flag   *pOverflow /* o   : overflow indicator                    */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 temp;
+    Word32 L_temp;
+    Word32 L_temp2;
+    Word16 tempShift;
+    Word16 kShift;
+    Word16 pitch_fac;
+    Word16 *p_exc;
+    Word16 *p_code;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    if (mode != MR122)
+    {
+        tempShift = 1;
+        kShift = 16 - 2 - 1;
+        pitch_fac = gain_pit;
+    }
+    else
+    {
+        tempShift = 2;
+        kShift = 16 - 4 - 1;
+        pitch_fac = gain_pit >> 1;
+    }
+
+    /*------------------------------------------------------------*
+     * - Update pitch sharpening "sharp" with quantized gain_pit  *
+     *------------------------------------------------------------*/
+
+    if (gain_pit < SHARPMAX)
+    {
+        *sharp = gain_pit;
+    }
+    else
+    {
+        *sharp = SHARPMAX;
+    }
+
+    /*------------------------------------------------------*
+     * - Find the total excitation                          *
+     * - find synthesis speech corresponding to exc[]       *
+     * - update filters memories for finding the target     *
+     *   vector in the next subframe                        *
+     *   (update error[-m..-1] and mem_w_err[])             *
+     *------------------------------------------------------*/
+
+    p_exc  = &exc[ i_subfr];
+    p_code = &code[0];
+
+    for (i = L_SUBFR >> 1; i != 0 ; i--)
+    {
+        /* exc[i] = gain_pit*exc[i] + gain_code*code[i]; */
+
+        /*
+         *                      12k2  others
+         * ---------------------------------
+         * exc                   Q0      Q0
+         * gain_pit              Q14     Q14
+         * pitch_fac             Q13     Q14
+         *    product:           Q14     Q15
+         *
+         * code                  Q12     Q13
+         * gain_code             Q1      Q1
+         *    product            Q14     Q15
+         *    sum                Q14     Q15
+         *
+         * tempShift             2       1
+         *    sum<<tempShift     Q16     Q16
+         * result -> exc         Q0      Q0
+         */
+        L_temp     = ((Word32) * (p_exc++) * pitch_fac) << 1;
+        L_temp2    = ((Word32) * (p_exc--) * pitch_fac) << 1;
+        L_temp    += ((Word32) * (p_code++) * gain_code) << 1;
+        L_temp2   += ((Word32) * (p_code++) * gain_code) << 1;
+        L_temp   <<=  tempShift;
+        L_temp2  <<=  tempShift;
+        *(p_exc++) = (Word16)((L_temp  + 0x08000L) >> 16);
+        *(p_exc++) = (Word16)((L_temp2 + 0x08000L) >> 16);
+
+    }
+
+    Syn_filt(
+        Aq,
+        &exc[i_subfr],
+        &synth[i_subfr],
+        L_SUBFR,
+        mem_syn,
+        1);
+
+    for (i = L_SUBFR - M, j = 0; i < L_SUBFR; i++, j++)
+    {
+        mem_err[j] = speech[i_subfr + i] - synth[i_subfr + i];
+
+        /*
+         *                      12k2  others
+         * ---------------------------------
+         * y1                    Q0      Q0
+         * gain_pit              Q14     Q14
+         *    product            Q15     Q15
+         *    shifted prod.      Q16     Q16
+         * temp                  Q0      Q0
+         *
+         * y2                    Q10     Q12
+         * gain_code             Q1      Q1
+         *    product            Q12     Q14
+         * kshift                 4       2
+         *    shifted prod.      Q16     Q16
+         * k                     Q0      Q0
+         * mem_w0,xn,sum         Q0      Q0
+         */
+
+        L_temp = ((Word32)y1[i] * gain_pit);
+        temp  = (Word16)(L_temp >> 14);
+
+        L_temp = ((Word32)y2[i] * gain_code);
+        temp += (Word16)(L_temp >> kShift);
+
+        mem_w0[j] = xn[i] - temp;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/enc/src/spstproc.h b/media/libstagefright/codecs/amrnb/enc/src/spstproc.h
new file mode 100644
index 0000000..edc43e4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/spstproc.h
@@ -0,0 +1,136 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/spstproc.h
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, spstproc.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef spstproc_h
+#define spstproc_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void subframePostProc(
+        Word16 *speech,   /* i   : speech segment                        */
+        enum Mode mode,   /* i   : coder mode                            */
+        Word16 i_subfr,   /* i   : Subframe nr                           */
+        Word16 gain_pit,  /* i   : Pitch gain                       Q14  */
+        Word16 gain_code, /* i   : Decoded innovation gain               */
+        Word16 *Aq,       /* i   : A(z) quantized for the 4 subframes    */
+        Word16 synth[],   /* i   : Local snthesis                        */
+        Word16 xn[],      /* i   : Target vector for pitch search        */
+        Word16 code[],    /* i   : Fixed codebook exitation              */
+        Word16 y1[],      /* i   : Filtered adaptive exitation           */
+        Word16 y2[],      /* i   : Filtered fixed codebook excitation    */
+        Word16 *mem_syn,  /* i/o : memory of synthesis filter            */
+        Word16 *mem_err,  /* o   : pointer to error signal               */
+        Word16 *mem_w0,   /* o   : memory of weighting filter            */
+        Word16 *exc,      /* o   : long term prediction residual         */
+        Word16 *sharp,    /* o   : pitch sharpening value                */
+        Flag   *pOverflow
+    );
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* spstproc_h */
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ton_stab.cpp b/media/libstagefright/codecs/amrnb/enc/src/ton_stab.cpp
new file mode 100644
index 0000000..3c4494d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ton_stab.cpp
@@ -0,0 +1,800 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/ton_stab.c
+ Funtions:
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  For check_lsp()
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation this by evaluating the operands
+               For update_gp_clipping()
+              1. Replaced copy() with more efficient memcpy()
+              2. Replaced right shift function with right shift
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "ton_stab.h"
+#include "oper_32b.h"
+#include "cnst.h"
+#include "set_zero.h"
+#include "basic_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ton_stab_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer to structure type tonStabState.
+
+ Outputs:
+    None
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   ton_stab_init
+  Purpose:    Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+  None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ton_stab_init (tonStabState **state)
+{
+    tonStabState* s;
+
+    if (state == (tonStabState **) NULL){
+        // fprintf(stderr, "ton_stab_init: invalid parameter\n");
+        return -1;
+    }
+    *state = NULL;
+
+    // allocate memory
+    if ((s= (tonStabState *) malloc(sizeof(tonStabState))) == NULL){
+        // fprintf(stderr, "ton_stab_init: can not malloc state structure\n");
+        return -1;
+    }
+
+    ton_stab_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 ton_stab_init(tonStabState **state)
+{
+    tonStabState* s;
+
+    if (state == (tonStabState **) NULL)
+    {
+        /* fprintf(stderr, "ton_stab_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (tonStabState *) malloc(sizeof(tonStabState))) == NULL)
+    {
+        /* fprintf(stderr, "ton_stab_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    ton_stab_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ton_stab_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to pointer to structure type tonStabState.
+
+ Outputs:
+    None
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   ton_stab_reset
+  Purpose:    Initializes state memory to zero
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ton_stab_reset (tonStabState *st)
+{
+    if (st == (tonStabState *) NULL){
+        // fprintf(stderr, "ton_stab_init: invalid parameter\n");
+        return -1;
+    }
+
+    // initialize tone stabilizer state
+    st->count = 0;
+    Set_zero(st->gp, N_FRAME);    // Init Gp_Clipping
+
+    return 0;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 ton_stab_reset(tonStabState *st)
+{
+    if (st == (tonStabState *) NULL)
+    {
+        /* fprintf(stderr, "ton_stab_init: invalid parameter\n"); */
+        return -1;
+    }
+
+    /* initialize tone stabilizer state */
+    st->count = 0;
+    Set_zero(st->gp, N_FRAME);    /* Init Gp_Clipping */
+
+    return 0;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ton_stab_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer to structure type tonStabState.
+
+ Outputs:
+    None
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   ton_stab_exit
+  Purpose:    The memory used for state memory is freed
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void ton_stab_exit (tonStabState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    // deallocate memory
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void ton_stab_exit(tonStabState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: check_lsp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer to structure type tonStabState.
+    lsp   = pointer to unquantized LSPs of type Word16
+
+ Outputs:
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:  check_lsp()
+  Purpose:   Check the LSP's to detect resonances
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 check_lsp(tonStabState *st, // i/o : State struct
+                 Word16 *lsp       // i   : unquantized LSP's
+)
+{
+   Word16 i, dist, dist_min1, dist_min2, dist_th;
+
+   // Check for a resonance:
+   // Find minimum distance between lsp[i] and lsp[i+1]
+
+   dist_min1 = MAX_16;
+   for (i = 3; i < M-2; i++)
+   {
+      dist = sub(lsp[i], lsp[i+1]);
+
+      if (sub(dist, dist_min1) < 0)
+      {
+         dist_min1 = dist;
+      }
+   }
+
+   dist_min2 = MAX_16;
+   for (i = 1; i < 3; i++)
+   {
+      dist = sub(lsp[i], lsp[i+1]);
+
+      if (sub(dist, dist_min2) < 0)
+      {
+         dist_min2 = dist;
+      }
+   }
+
+   if (sub(lsp[1], 32000) > 0)
+   {
+      dist_th = 600;
+   }
+   else if (sub(lsp[1], 30500) > 0)
+   {
+      dist_th = 800;
+   }
+   else
+   {
+      dist_th = 1100;
+   }
+
+   if (sub(dist_min1, 1500) < 0 ||
+       sub(dist_min2, dist_th) < 0)
+   {
+      st->count = add(st->count, 1);
+   }
+   else
+   {
+      st->count = 0;
+   }
+
+   // Need 12 consecutive frames to set the flag
+   if (sub(st->count, 12) >= 0)
+   {
+      st->count = 12;
+      return 1;
+   }
+   else
+   {
+      return 0;
+   }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 check_lsp(tonStabState *st, /* i/o : State struct            */
+                 Word16 *lsp,      /* i   : unquantized LSP's       */
+                 Flag  *pOverflow
+                )
+{
+    Word16 i;
+    Word16 dist;
+    Word16 dist_min1;
+    Word16 dist_min2;
+    Word16 dist_th;
+    Word16 *p_lsp   = &lsp[3];
+    Word16 *p_lsp_1 = &lsp[4];
+
+    OSCL_UNUSED_ARG(pOverflow);
+    /* Check for a resonance:                             */
+    /* Find minimum distance between lsp[i] and lsp[i+1]  */
+
+    dist_min1 = MAX_16;
+    for (i = 3; i < M - 2; i++)
+    {
+        dist = *(p_lsp++) - *(p_lsp_1++);
+
+        if (dist < dist_min1)
+        {
+            dist_min1 = dist;
+        }
+    }
+
+    dist_min2 = MAX_16;
+    p_lsp   = &lsp[1];
+    p_lsp_1 = &lsp[2];
+
+    for (i = 1; i < 3; i++)
+    {
+        dist = *(p_lsp++) - *(p_lsp_1++);
+
+        if (dist < dist_min2)
+        {
+            dist_min2 = dist;
+        }
+    }
+
+    if (lsp[1] > 32000)
+    {
+        dist_th = 600;
+    }
+    else if (lsp[1] > 30500)
+    {
+        dist_th = 800;
+    }
+    else
+    {
+        dist_th = 1100;
+    }
+
+    if ((dist_min1 < 1500) || (dist_min2 < dist_th))
+    {
+        st->count++;
+    }
+    else
+    {
+        st->count = 0;
+    }
+
+    /* Need 12 consecutive frames to set the flag */
+    if (st->count >= 12)
+    {
+        st->count = 12;
+        return 1;
+    }
+    else
+    {
+        return 0;
+    }
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: check_gp_clipping
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer to structure type tonStabState.
+    g_pitch = pitch gain of type Word16
+
+ Outputs:
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:   Check_Gp_Clipping()
+  Purpose:    Verify that the sum of the last (N_FRAME+1) pitch
+              gains is under a certain threshold.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 check_gp_clipping(tonStabState *st, // i/o : State struct
+                         Word16 g_pitch    // i   : pitch gain
+)
+{
+   Word16 i, sum;
+
+   sum = shr(g_pitch, 3);          // Division by 8
+   for (i = 0; i < N_FRAME; i++)
+   {
+      sum = add(sum, st->gp[i]);
+   }
+
+   if (sub(sum, GP_CLIP) > 0)
+   {
+      return 1;
+   }
+   else
+   {
+      return 0;
+   }
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+Word16 check_gp_clipping(tonStabState *st, /* i/o : State struct            */
+                         Word16 g_pitch,   /* i   : pitch gain              */
+                         Flag   *pOverflow
+                        )
+{
+    Word16 i;
+    Word16 sum;
+
+    sum = shr(g_pitch, 3, pOverflow);        /* Division by 8 */
+    for (i = 0; i < N_FRAME; i++)
+    {
+        sum = add(sum, st->gp[i], pOverflow);
+    }
+
+    if (sum > GP_CLIP)
+    {
+        return 1;
+    }
+    else
+    {
+        return 0;
+    }
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: update_gp_clipping
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to pointer to structure type tonStabState.
+    g_pitch = pitch gain of type Word16
+
+ Outputs:
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function:  Update_Gp_Clipping()
+  Purpose:   Update past pitch gain memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ton_stab.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void update_gp_clipping(tonStabState *st, // i/o : State struct
+                        Word16 g_pitch    // i   : pitch gain
+)
+{
+   Copy(&st->gp[1], &st->gp[0], N_FRAME-1);
+   st->gp[N_FRAME-1] = shr(g_pitch, 3);
+}
+
+------------------------------------------------------------------------------
+ RESOURCES USED [optional]
+
+ When the code is written for a specific target processor the
+ the resources used should be documented below.
+
+ HEAP MEMORY USED: x bytes
+
+ STACK MEMORY USED: x bytes
+
+ CLOCK CYCLES: (cycle count equation for this function) + (variable
+                used to represent cycle count for each subroutine
+                called)
+     where: (cycle count variable) = cycle count for [subroutine
+                                     name]
+
+------------------------------------------------------------------------------
+ CAUTION [optional]
+ [State any special notes, constraints or cautions for users of this function]
+
+------------------------------------------------------------------------------
+*/
+
+void update_gp_clipping(tonStabState *st, /* i/o : State struct            */
+                        Word16 g_pitch,   /* i   : pitch gain              */
+                        Flag   *pOverflow
+                       )
+{
+    OSCL_UNUSED_ARG(pOverflow);
+    for (int i = 0; i < N_FRAME - 1; i++)
+    {
+        st->gp[i] = st->gp[i+1];
+    }
+    st->gp[N_FRAME-1] =  g_pitch >> 3;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/enc/src/ton_stab.h b/media/libstagefright/codecs/amrnb/enc/src/ton_stab.h
new file mode 100644
index 0000000..fb06e64
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/enc/src/ton_stab.h
@@ -0,0 +1,155 @@
+/* ------------------------------------------------------------------
+ * Copyright (C) 1998-2009 PacketVideo
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+ * express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************************
+Portions of this file are derived from the following 3GPP standard:
+
+    3GPP TS 26.073
+    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
+Permission to distribute, modify and use this file under the standard license
+terms listed above has been obtained from the copyright holder.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Filename: /audio/gsm_amr/c/include/ton_stab.h
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+     File             : ton_stab.h
+     Purpose          : Tone stabilization routines
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef TON_STAB_H
+#define TON_STAB_H
+#define ton_stab_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "cnst.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /* state variable */
+    typedef struct
+    {
+        /* counters */
+        Word16 count;
+        /* gain history Q11 */
+        Word16 gp[N_FRAME];
+    } tonStabState;
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 ton_stab_init(tonStabState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to ton_stab in each call.
+       returns 0 on success
+     */
+
+    Word16 ton_stab_reset(tonStabState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void ton_stab_exit(tonStabState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    Word16 check_lsp(tonStabState *st, /* i/o : State struct            */
+                     Word16 *lsp,      /* i   : unquantized LSP's       */
+                     Flag   *pOverflow
+                    );
+
+    Word16 check_gp_clipping(tonStabState *st, /* i/o : State struct          */
+                             Word16 g_pitch,   /* i   : pitch gain            */
+                             Flag  *pOverflow
+                            );
+
+    void update_gp_clipping(tonStabState *st, /* i/o : State struct            */
+                            Word16 g_pitch,   /* i   : pitch gain              */
+                            Flag  *pOverflow
+                           );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TON_STAB_H_ */
+
+
+
+
diff --git a/media/libstagefright/include/AMRNBEncoder.h b/media/libstagefright/include/AMRNBEncoder.h
new file mode 100644
index 0000000..7167c00
--- /dev/null
+++ b/media/libstagefright/include/AMRNBEncoder.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef AMR_NB_ENCODER_H_
+
+#define AMR_NB_ENCODER_H_
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+struct MediaBufferGroup;
+
+struct AMRNBEncoder : public MediaSource {
+    AMRNBEncoder(const sp<MediaSource> &source);
+
+    virtual status_t start(MetaData *params);
+    virtual status_t stop();
+
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options);
+
+protected:
+    virtual ~AMRNBEncoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    MediaBufferGroup *mBufferGroup;
+
+    void *mEncState;
+    void *mSidState;
+    int64_t mAnchorTimeUs;
+    int64_t mNumFramesOutput;
+
+    MediaBuffer *mInputBuffer;
+    int mMode;
+
+    int16_t mInputFrame[160];
+    int32_t mNumInputSamples;
+
+    AMRNBEncoder(const AMRNBEncoder &);
+    AMRNBEncoder &operator=(const AMRNBEncoder &);
+};
+
+}  // namespace android
+
+#endif  // AMR_NB_ENCODER_H_