am f31f365a: am eb5ffc23: Merge change Id8e98194 into eclair

Merge commit 'f31f365a7708c931e955670bc6213fdc8f91a87a'

* commit 'f31f365a7708c931e955670bc6213fdc8f91a87a':
  Fix issues 2333450 and 2333559:
diff --git a/cmds/stagefright/Android.mk b/cmds/stagefright/Android.mk
index 5b55252..68d8bb0 100644
--- a/cmds/stagefright/Android.mk
+++ b/cmds/stagefright/Android.mk
@@ -8,7 +8,7 @@
 	stagefright.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libstagefright
+	libstagefright libmedia libutils libbinder
 
 LOCAL_C_INCLUDES:= \
 	$(JNI_H_INCLUDE) \
@@ -30,7 +30,7 @@
         record.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libstagefright
+	libstagefright liblog libutils libbinder
 
 LOCAL_C_INCLUDES:= \
 	$(JNI_H_INCLUDE) \
@@ -43,4 +43,26 @@
 
 include $(BUILD_EXECUTABLE)
 
+################################################################################
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=         \
+        SineSource.cpp    \
+        audioloop.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libstagefright liblog libutils libbinder
+
+LOCAL_C_INCLUDES:= \
+	$(JNI_H_INCLUDE) \
+	frameworks/base/media/libstagefright \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
+
+LOCAL_CFLAGS += -Wno-multichar
+
+LOCAL_MODULE:= audioloop
+
+include $(BUILD_EXECUTABLE)
+
 endif
diff --git a/cmds/stagefright/SineSource.cpp b/cmds/stagefright/SineSource.cpp
index e5a6ccb..021f636 100644
--- a/cmds/stagefright/SineSource.cpp
+++ b/cmds/stagefright/SineSource.cpp
@@ -52,6 +52,7 @@
     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
     meta->setInt32(kKeyChannelCount, mNumChannels);
     meta->setInt32(kKeySampleRate, mSampleRate);
+    meta->setInt32(kKeyMaxInputSize, kBufferSize);
 
     return meta;
 }
@@ -86,8 +87,8 @@
         x += k;
     }
 
-    buffer->meta_data()->setInt32(kKeyTimeUnits, mPhase);
-    buffer->meta_data()->setInt32(kKeyTimeScale, mSampleRate);
+    buffer->meta_data()->setInt64(
+            kKeyTime, ((int64_t)mPhase * 1000000) / mSampleRate);
 
     mPhase += numFramesPerBuffer;
 
diff --git a/cmds/stagefright/audioloop.cpp b/cmds/stagefright/audioloop.cpp
new file mode 100644
index 0000000..3788e73
--- /dev/null
+++ b/cmds/stagefright/audioloop.cpp
@@ -0,0 +1,81 @@
+#include "SineSource.h"
+
+#include <binder/ProcessState.h>
+#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/OMXCodec.h>
+
+using namespace android;
+
+int main() {
+    // We only have an AMR-WB encoder on sholes...
+    static bool outputWBAMR = false;
+    static const int32_t kSampleRate = outputWBAMR ? 16000 : 8000;
+    static const int32_t kNumChannels = 1;
+
+    android::ProcessState::self()->startThreadPool();
+
+    OMXClient client;
+    CHECK_EQ(client.connect(), OK);
+
+    sp<MediaSource> source = new SineSource(kSampleRate, kNumChannels);
+
+    sp<MetaData> meta = new MetaData;
+
+    meta->setCString(
+            kKeyMIMEType,
+            outputWBAMR ? MEDIA_MIMETYPE_AUDIO_AMR_WB
+                        : MEDIA_MIMETYPE_AUDIO_AMR_NB);
+
+    meta->setInt32(kKeyChannelCount, kNumChannels);
+    meta->setInt32(kKeySampleRate, kSampleRate);
+
+    int32_t maxInputSize;
+    if (source->getFormat()->findInt32(kKeyMaxInputSize, &maxInputSize)) {
+        meta->setInt32(kKeyMaxInputSize, maxInputSize);
+    }
+
+    sp<MediaSource> encoder = OMXCodec::Create(
+            client.interface(),
+            meta, true /* createEncoder */,
+            source);
+
+    sp<MediaSource> decoder = OMXCodec::Create(
+            client.interface(),
+            meta, false /* createEncoder */,
+            encoder);
+
+#if 1
+    AudioPlayer *player = new AudioPlayer(NULL);
+    player->setSource(decoder);
+
+    player->start();
+
+    sleep(10);
+
+    player->stop();
+
+    delete player;
+    player = NULL;
+#else
+    CHECK_EQ(decoder->start(), OK);
+
+    MediaBuffer *buffer;
+    while (decoder->read(&buffer) == OK) {
+        // do something with buffer
+
+        putchar('.');
+        fflush(stdout);
+
+        buffer->release();
+        buffer = NULL;
+    }
+
+    CHECK_EQ(decoder->stop(), OK);
+#endif
+
+    return 0;
+}
diff --git a/cmds/stagefright/record.cpp b/cmds/stagefright/record.cpp
index 323d448..2ec0b70 100644
--- a/cmds/stagefright/record.cpp
+++ b/cmds/stagefright/record.cpp
@@ -19,21 +19,23 @@
 #include <binder/ProcessState.h>
 #include <media/stagefright/AudioPlayer.h>
 #include <media/stagefright/CameraSource.h>
+#include <media/stagefright/FileSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/MPEG4Extractor.h>
+#include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MPEG4Writer.h>
-#include <media/stagefright/MmapSource.h>
 #include <media/stagefright/OMXClient.h>
 #include <media/stagefright/OMXCodec.h>
 #include <media/MediaPlayerInterface.h>
 
 using namespace android;
 
-#if 0
+#if 1
 class DummySource : public MediaSource {
+    static const int32_t kFramerate = 24;  // fps
+
 public:
     DummySource(int width, int height)
         : mWidth(width),
@@ -52,6 +54,7 @@
     }
 
     virtual status_t start(MetaData *params) {
+        mNumFramesOutput = 0;
         return OK;
     }
 
@@ -61,6 +64,12 @@
 
     virtual status_t read(
             MediaBuffer **buffer, const MediaSource::ReadOptions *options) {
+        if (mNumFramesOutput == kFramerate * 10) {
+            // Stop returning data after 10 secs.
+            return ERROR_END_OF_STREAM;
+        }
+
+        // printf("DummySource::read\n");
         status_t err = mGroup.acquire_buffer(buffer);
         if (err != OK) {
             return err;
@@ -69,7 +78,13 @@
         char x = (char)((double)rand() / RAND_MAX * 255);
         memset((*buffer)->data(), x, mSize);
         (*buffer)->set_range(0, mSize);
+        (*buffer)->meta_data()->clear();
+        (*buffer)->meta_data()->setInt64(
+                kKeyTime, (mNumFramesOutput * 1000000) / kFramerate);
+        ++mNumFramesOutput;
 
+        // printf("DummySource::read - returning buffer\n");
+        // LOGI("DummySource::read - returning buffer");
         return OK;
     }
 
@@ -80,6 +95,7 @@
     MediaBufferGroup mGroup;
     int mWidth, mHeight;
     size_t mSize;
+    int64_t mNumFramesOutput;;
 
     DummySource(const DummySource &);
     DummySource &operator=(const DummySource &);
@@ -88,8 +104,8 @@
 sp<MediaSource> createSource(const char *filename) {
     sp<MediaSource> source;
 
-    sp<MPEG4Extractor> extractor =
-        new MPEG4Extractor(new MmapSource(filename));
+    sp<MediaExtractor> extractor =
+        MediaExtractor::Create(new FileSource(filename));
 
     size_t num_tracks = extractor->countTracks();
 
@@ -117,6 +133,8 @@
 int main(int argc, char **argv) {
     android::ProcessState::self()->startThreadPool();
 
+    DataSource::RegisterDefaultSniffers();
+
 #if 1
     if (argc != 2) {
         fprintf(stderr, "usage: %s filename\n", argv[0]);
@@ -126,7 +144,7 @@
     OMXClient client;
     CHECK_EQ(client.connect(), OK);
 
-#if 0
+#if 1
     sp<MediaSource> source = createSource(argv[1]);
 
     if (source == NULL) {
@@ -136,7 +154,7 @@
 
     sp<MetaData> meta = source->getFormat();
 
-    sp<OMXCodec> decoder = OMXCodec::Create(
+    sp<MediaSource> decoder = OMXCodec::Create(
             client.interface(), meta, false /* createEncoder */, source);
 
     int width, height;
@@ -144,8 +162,8 @@
     success = success && meta->findInt32(kKeyHeight, &height);
     CHECK(success);
 #else
-    int width = 320;
-    int height = 240;
+    int width = 800;
+    int height = 480;
     sp<MediaSource> decoder = new DummySource(width, height);
 #endif
 
@@ -155,23 +173,30 @@
     enc_meta->setInt32(kKeyWidth, width);
     enc_meta->setInt32(kKeyHeight, height);
 
-    sp<OMXCodec> encoder =
+    sp<MediaSource> encoder =
         OMXCodec::Create(
                 client.interface(), enc_meta, true /* createEncoder */, decoder);
 
-#if 0
+#if 1
     sp<MPEG4Writer> writer = new MPEG4Writer("/sdcard/output.mp4");
-    writer->addSource(enc_meta, encoder);
+    writer->addSource(encoder);
     writer->start();
-    sleep(20);
-    printf("stopping now.\n");
+    while (!writer->reachedEOS()) {
+        usleep(100000);
+    }
     writer->stop();
 #else
     encoder->start();
 
     MediaBuffer *buffer;
     while (encoder->read(&buffer) == OK) {
-        printf("got an output frame of size %d\n", buffer->range_length());
+        int32_t isSync;
+        if (!buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isSync)) {
+            isSync = false;
+        }
+
+        printf("got an output frame of size %d%s\n", buffer->range_length(),
+               isSync ? " (SYNC)" : "");
 
         buffer->release();
         buffer = NULL;
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index 4ffc8e4..ad6540a 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -24,15 +24,14 @@
 #include <binder/ProcessState.h>
 #include <media/IMediaPlayerService.h>
 #include <media/stagefright/CachingDataSource.h>
+#include <media/stagefright/FileSource.h>
 #include <media/stagefright/HTTPDataSource.h>
 #include <media/stagefright/JPEGSource.h>
 #include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaPlayerImpl.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/MmapSource.h>
 #include <media/stagefright/OMXClient.h>
 #include <media/stagefright/OMXCodec.h>
 
@@ -52,46 +51,55 @@
 static void playSource(OMXClient *client, const sp<MediaSource> &source) {
     sp<MetaData> meta = source->getFormat();
 
-    int32_t durationUnits;
-    int32_t timeScale;
-    CHECK(meta->findInt32(kKeyDuration, &durationUnits));
-    CHECK(meta->findInt32(kKeyTimeScale, &timeScale));
+    const char *mime;
+    CHECK(meta->findCString(kKeyMIMEType, &mime));
 
-    int64_t durationUs = ((int64_t)durationUnits * 1000000) / timeScale;
-
-    sp<OMXCodec> decoder = OMXCodec::Create(
+    sp<MediaSource> rawSource;
+    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
+        rawSource = source;
+    } else {
+        rawSource = OMXCodec::Create(
             client->interface(), meta, false /* createEncoder */, source);
 
-    if (decoder == NULL) {
-        return;
+        if (rawSource == NULL) {
+            fprintf(stderr, "Failed to instantiate decoder for '%s'.\n", mime);
+            return;
+        }
     }
 
-    decoder->start();
+    rawSource->start();
 
     if (gReproduceBug >= 3 && gReproduceBug <= 5) {
+        int64_t durationUs;
+        CHECK(meta->findInt64(kKeyDuration, &durationUs));
+
         status_t err;
         MediaBuffer *buffer;
         MediaSource::ReadOptions options;
         int64_t seekTimeUs = -1;
         for (;;) {
-            err = decoder->read(&buffer, &options);
+            err = rawSource->read(&buffer, &options);
             options.clearSeekTo();
 
             bool shouldSeek = false;
-            if (err != OK) {
+            if (err == INFO_FORMAT_CHANGED) {
+                CHECK_EQ(buffer, NULL);
+
+                printf("format changed.\n");
+                continue;
+            } else if (err != OK) {
                 printf("reached EOF.\n");
 
                 shouldSeek = true;
             } else {
-                int32_t timestampUnits;
-                CHECK(buffer->meta_data()->findInt32(kKeyTimeUnits, &timestampUnits));
-
-                int64_t timestampUs = ((int64_t)timestampUnits * 1000000) / timeScale;
+                int64_t timestampUs;
+                CHECK(buffer->meta_data()->findInt64(kKeyTime, &timestampUs));
 
                 bool failed = false;
 
                 if (seekTimeUs >= 0) {
                     int64_t diff = timestampUs - seekTimeUs;
+
                     if (diff < 0) {
                         diff = -diff;
                     }
@@ -134,7 +142,7 @@
             }
         }
 
-        decoder->stop();
+        rawSource->stop();
 
         return;
     }
@@ -151,16 +159,21 @@
         MediaBuffer *buffer;
 
         for (;;) {
-            status_t err = decoder->read(&buffer, &options);
+            status_t err = rawSource->read(&buffer, &options);
             options.clearSeekTo();
 
             if (err != OK) {
                 CHECK_EQ(buffer, NULL);
 
+                if (err == INFO_FORMAT_CHANGED) {
+                    printf("format changed.\n");
+                    continue;
+                }
+
                 break;
             }
 
-            if ((n++ % 16) == 0) {
+            if (buffer->range_length() > 0 && (n++ % 16) == 0) {
                 printf(".");
                 fflush(stdout);
             }
@@ -188,7 +201,7 @@
         options.setSeekTo(0);
     }
 
-    decoder->stop();
+    rawSource->stop();
     printf("\n");
 
     int64_t delay = getNowUs() - startTime;
@@ -332,12 +345,12 @@
         sp<IOMX> omx = service->getOMX();
         CHECK(omx.get() != NULL);
 
-        List<String8> list;
+        List<IOMX::ComponentInfo> list;
         omx->listNodes(&list);
 
-        for (List<String8>::iterator it = list.begin();
+        for (List<IOMX::ComponentInfo>::iterator it = list.begin();
              it != list.end(); ++it) {
-            printf("%s\n", (*it).string());
+            printf("%s\n", (*it).mName.string());
         }
     }
 
@@ -354,7 +367,7 @@
             dataSource = new HTTPDataSource(filename);
             dataSource = new CachingDataSource(dataSource, 64 * 1024, 10);
         } else {
-            dataSource = new MmapSource(filename);
+            dataSource = new FileSource(filename);
         }
 
         bool isJPEG = false;
diff --git a/include/media/IOMX.h b/include/media/IOMX.h
index 6f3ba1c..39bd5b1 100644
--- a/include/media/IOMX.h
+++ b/include/media/IOMX.h
@@ -42,7 +42,11 @@
     typedef void *buffer_id;
     typedef void *node_id;
 
-    virtual status_t listNodes(List<String8> *list) = 0;
+    struct ComponentInfo {
+        String8 mName;
+        List<String8> mRoles;
+    };
+    virtual status_t listNodes(List<ComponentInfo> *list) = 0;
 
     virtual status_t allocateNode(
             const char *name, const sp<IOMXObserver> &observer,
diff --git a/include/media/MediaPlayerInterface.h b/include/media/MediaPlayerInterface.h
index f723cfd..6575da6 100644
--- a/include/media/MediaPlayerInterface.h
+++ b/include/media/MediaPlayerInterface.h
@@ -133,9 +133,9 @@
         return INVALID_OPERATION;
     };
 
-protected:
     virtual void        sendEvent(int msg, int ext1=0, int ext2=0) { if (mNotify) mNotify(mCookie, msg, ext1, ext2); }
 
+protected:
     void*               mCookie;
     notify_callback_f   mNotify;
 };
diff --git a/include/media/MediaRecorderBase.h b/include/media/MediaRecorderBase.h
new file mode 100644
index 0000000..5b787a7
--- /dev/null
+++ b/include/media/MediaRecorderBase.h
@@ -0,0 +1,59 @@
+/*
+ * 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 MEDIA_RECORDER_BASE_H_
+
+#define MEDIA_RECORDER_BASE_H_
+
+#include <media/mediarecorder.h>
+
+namespace android {
+
+class ISurface;
+
+struct MediaRecorderBase {
+    MediaRecorderBase() {}
+    virtual ~MediaRecorderBase() {}
+
+    virtual status_t init() = 0;
+    virtual status_t setAudioSource(audio_source as) = 0;
+    virtual status_t setVideoSource(video_source vs) = 0;
+    virtual status_t setOutputFormat(output_format of) = 0;
+    virtual status_t setAudioEncoder(audio_encoder ae) = 0;
+    virtual status_t setVideoEncoder(video_encoder ve) = 0;
+    virtual status_t setVideoSize(int width, int height) = 0;
+    virtual status_t setVideoFrameRate(int frames_per_second) = 0;
+    virtual status_t setCamera(const sp<ICamera>& camera) = 0;
+    virtual status_t setPreviewSurface(const sp<ISurface>& surface) = 0;
+    virtual status_t setOutputFile(const char *path) = 0;
+    virtual status_t setOutputFile(int fd, int64_t offset, int64_t length) = 0;
+    virtual status_t setParameters(const String8& params) = 0;
+    virtual status_t setListener(const sp<IMediaPlayerClient>& listener) = 0;
+    virtual status_t prepare() = 0;
+    virtual status_t start() = 0;
+    virtual status_t stop() = 0;
+    virtual status_t close() = 0;
+    virtual status_t reset() = 0;
+    virtual status_t getMaxAmplitude(int *max) = 0;
+
+private:
+    MediaRecorderBase(const MediaRecorderBase &);
+    MediaRecorderBase &operator=(const MediaRecorderBase &);
+};
+
+}  // namespace android
+
+#endif  // MEDIA_RECORDER_BASE_H_
diff --git a/include/media/PVMediaRecorder.h b/include/media/PVMediaRecorder.h
index 0c71932..4f17c1a 100644
--- a/include/media/PVMediaRecorder.h
+++ b/include/media/PVMediaRecorder.h
@@ -18,8 +18,8 @@
 #ifndef ANDROID_PVMEDIARECORDER_H
 #define ANDROID_PVMEDIARECORDER_H
 
-#include <media/mediarecorder.h>
 #include <media/IMediaPlayerClient.h>
+#include <media/MediaRecorderBase.h>
 
 namespace android {
 
@@ -27,37 +27,39 @@
 class ICamera;
 class AuthorDriverWrapper;
 
-class PVMediaRecorder
-{
+class PVMediaRecorder : public MediaRecorderBase {
 public:
     PVMediaRecorder();
-    ~PVMediaRecorder();
+    virtual ~PVMediaRecorder();
 
-    status_t init();
-    status_t setAudioSource(audio_source as);
-    status_t setVideoSource(video_source vs);
-    status_t setOutputFormat(output_format of);
-    status_t setAudioEncoder(audio_encoder ae);
-    status_t setVideoEncoder(video_encoder ve);
-    status_t setVideoSize(int width, int height);
-    status_t setVideoFrameRate(int frames_per_second);
-    status_t setCamera(const sp<ICamera>& camera);
-    status_t setPreviewSurface(const sp<ISurface>& surface);
-    status_t setOutputFile(const char *path);
-    status_t setOutputFile(int fd, int64_t offset, int64_t length);
-    status_t setParameters(const String8& params);
-    status_t setListener(const sp<IMediaPlayerClient>& listener);
-    status_t prepare();
-    status_t start();
-    status_t stop();
-    status_t close();
-    status_t reset();
-    status_t getMaxAmplitude(int *max);
+    virtual status_t init();
+    virtual status_t setAudioSource(audio_source as);
+    virtual status_t setVideoSource(video_source vs);
+    virtual status_t setOutputFormat(output_format of);
+    virtual status_t setAudioEncoder(audio_encoder ae);
+    virtual status_t setVideoEncoder(video_encoder ve);
+    virtual status_t setVideoSize(int width, int height);
+    virtual status_t setVideoFrameRate(int frames_per_second);
+    virtual status_t setCamera(const sp<ICamera>& camera);
+    virtual status_t setPreviewSurface(const sp<ISurface>& surface);
+    virtual status_t setOutputFile(const char *path);
+    virtual status_t setOutputFile(int fd, int64_t offset, int64_t length);
+    virtual status_t setParameters(const String8& params);
+    virtual status_t setListener(const sp<IMediaPlayerClient>& listener);
+    virtual status_t prepare();
+    virtual status_t start();
+    virtual status_t stop();
+    virtual status_t close();
+    virtual status_t reset();
+    virtual status_t getMaxAmplitude(int *max);
 
 private:
     status_t doStop();
 
     AuthorDriverWrapper*            mAuthorDriverWrapper;
+
+    PVMediaRecorder(const PVMediaRecorder &);
+    PVMediaRecorder &operator=(const PVMediaRecorder &);
 };
 
 }; // namespace android
diff --git a/include/media/mediascanner.h b/include/media/mediascanner.h
index cd0b86e..0d397ac 100644
--- a/include/media/mediascanner.h
+++ b/include/media/mediascanner.h
@@ -28,33 +28,40 @@
 class MediaScannerClient;
 class StringArray;
 
-class MediaScanner 
-{
-public:
+struct MediaScanner {
     MediaScanner();
-    ~MediaScanner();
-    
-    typedef bool (*ExceptionCheck)(void* env);
+    virtual ~MediaScanner();
 
-    status_t processFile(const char *path, const char *mimeType, MediaScannerClient& client);
-    status_t processDirectory(const char *path, const char* extensions, 
-            MediaScannerClient& client, ExceptionCheck exceptionCheck, void* exceptionEnv);
-    void setLocale(const char* locale);
-    
+    virtual status_t processFile(
+            const char *path, const char *mimeType,
+            MediaScannerClient &client) = 0;
+
+    typedef bool (*ExceptionCheck)(void* env);
+    virtual status_t processDirectory(
+            const char *path, const char *extensions,
+            MediaScannerClient &client,
+            ExceptionCheck exceptionCheck, void *exceptionEnv);
+
+    void setLocale(const char *locale);
+
     // extracts album art as a block of data
-    char* extractAlbumArt(int fd);
-    
-    static void uninitializeForThread();
+    virtual char *extractAlbumArt(int fd) = 0;
+
+protected:
+    const char *locale() const;
 
 private:
-    status_t doProcessDirectory(char *path, int pathRemaining, const char* extensions, 
-            MediaScannerClient& client, ExceptionCheck exceptionCheck, void* exceptionEnv);
-    void initializeForThread();
-    
     // current locale (like "ja_JP"), created/destroyed with strdup()/free()
-    char* mLocale;
-};
+    char *mLocale;
 
+    status_t doProcessDirectory(
+            char *path, int pathRemaining, const char *extensions,
+            MediaScannerClient &client, ExceptionCheck exceptionCheck,
+            void *exceptionEnv);
+
+    MediaScanner(const MediaScanner &);
+    MediaScanner &operator=(const MediaScanner &);
+};
 
 class MediaScannerClient
 {
@@ -78,7 +85,7 @@
     // cached name and value strings, for native encoding support.
     StringArray*    mNames;
     StringArray*    mValues;
-    
+
     // default encoding based on MediaScanner::mLocale string
     uint32_t        mLocaleEncoding;
 };
diff --git a/include/media/stagefright/AMRExtractor.h b/include/media/stagefright/AMRExtractor.h
deleted file mode 100644
index c8710d3..0000000
--- a/include/media/stagefright/AMRExtractor.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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_EXTRACTOR_H_
-
-#define AMR_EXTRACTOR_H_
-
-#include <media/stagefright/MediaExtractor.h>
-
-namespace android {
-
-class String8;
-
-class AMRExtractor : public MediaExtractor {
-public:
-    AMRExtractor(const sp<DataSource> &source);
-
-    virtual size_t countTracks();
-    virtual sp<MediaSource> getTrack(size_t index);
-    virtual sp<MetaData> getTrackMetaData(size_t index);
-
-    static sp<MetaData> makeAMRFormat(bool isWide);
-
-protected:
-    virtual ~AMRExtractor();
-
-private:
-    sp<DataSource> mDataSource;
-    status_t mInitCheck;
-    bool mIsWide;
-
-    AMRExtractor(const AMRExtractor &);
-    AMRExtractor &operator=(const AMRExtractor &);
-};
-
-bool SniffAMR(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence);
-
-}  // namespace android
-
-#endif  // AMR_EXTRACTOR_H_
diff --git a/include/media/stagefright/AudioPlayer.h b/include/media/stagefright/AudioPlayer.h
index 960eda3..71344e6 100644
--- a/include/media/stagefright/AudioPlayer.h
+++ b/include/media/stagefright/AudioPlayer.h
@@ -30,12 +30,20 @@
 
 class AudioPlayer : public TimeSource {
 public:
+    enum {
+        REACHED_EOS,
+        SEEK_COMPLETE
+    };
+
     AudioPlayer(const sp<MediaPlayerBase::AudioSink> &audioSink);
     virtual ~AudioPlayer();
 
     // Caller retains ownership of "source".
     void setSource(const sp<MediaSource> &source);
 
+    void setListenerCallback(
+            void (*notify)(void *cookie, int what), void *cookie);
+
     // Return time in us.
     virtual int64_t getRealTimeUs();
 
@@ -76,6 +84,9 @@
 
     bool mStarted;
 
+    void (*mListenerCallback)(void *cookie, int what);
+    void *mListenerCookie;
+
     sp<MediaPlayerBase::AudioSink> mAudioSink;
 
     static void AudioCallback(int event, void *user, void *info);
diff --git a/include/media/stagefright/CachingDataSource.h b/include/media/stagefright/CachingDataSource.h
index e35e19e..b0fc4b2 100644
--- a/include/media/stagefright/CachingDataSource.h
+++ b/include/media/stagefright/CachingDataSource.h
@@ -29,9 +29,9 @@
     CachingDataSource(
             const sp<DataSource> &source, size_t pageSize, int numPages);
 
-    status_t InitCheck() const;
+    virtual status_t initCheck() const;
 
-    virtual ssize_t read_at(off_t offset, void *data, size_t size);
+    virtual ssize_t readAt(off_t offset, void *data, size_t size);
 
 protected:
     virtual ~CachingDataSource();
diff --git a/include/media/stagefright/CameraSource.h b/include/media/stagefright/CameraSource.h
index 7042e1a..ea435de 100644
--- a/include/media/stagefright/CameraSource.h
+++ b/include/media/stagefright/CameraSource.h
@@ -27,16 +27,19 @@
 namespace android {
 
 class ICamera;
-class ICameraClient;
 class IMemory;
+class ISurface;
+class Camera;
 
-class CameraSource : public MediaSource,
-                     public MediaBufferObserver {
+class CameraSource : public MediaSource {
 public:
     static CameraSource *Create();
+    static CameraSource *CreateFromICamera(const sp<ICamera> &icamera);
 
     virtual ~CameraSource();
 
+    void setPreviewSurface(const sp<ISurface> &surface);
+
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
 
@@ -45,24 +48,26 @@
     virtual status_t read(
             MediaBuffer **buffer, const ReadOptions *options = NULL);
 
-    virtual void notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2);
-    virtual void dataCallback(int32_t msgType, const sp<IMemory>& data);
-
-    virtual void signalBufferReturned(MediaBuffer *buffer);
-
 private:
-    CameraSource(const sp<ICamera> &camera, const sp<ICameraClient> &client);
+    friend class CameraSourceListener;
 
-    sp<ICamera> mCamera;
-    sp<ICameraClient> mCameraClient;
+    sp<Camera> mCamera;
+    sp<ISurface> mPreviewSurface;
 
     Mutex mLock;
     Condition mFrameAvailableCondition;
     List<sp<IMemory> > mFrames;
+    List<int64_t> mFrameTimes;
 
-    int mNumFrames;
+    int mWidth, mHeight;
+    int64_t mFirstFrameTimeUs;
+    int32_t mNumFrames;
     bool mStarted;
 
+    CameraSource(const sp<Camera> &camera);
+
+    void dataCallback(int32_t msgType, const sp<IMemory> &data);
+
     CameraSource(const CameraSource &);
     CameraSource &operator=(const CameraSource &);
 };
diff --git a/include/media/stagefright/ColorConverter.h b/include/media/stagefright/ColorConverter.h
new file mode 100644
index 0000000..1e341b9
--- /dev/null
+++ b/include/media/stagefright/ColorConverter.h
@@ -0,0 +1,67 @@
+/*
+ * 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 COLOR_CONVERTER_H_
+
+#define COLOR_CONVERTER_H_
+
+#include <sys/types.h>
+
+#include <stdint.h>
+
+#include <OMX_Video.h>
+
+namespace android {
+
+struct ColorConverter {
+    ColorConverter(OMX_COLOR_FORMATTYPE from, OMX_COLOR_FORMATTYPE to);
+    ~ColorConverter();
+
+    bool isValid() const;
+
+    void convert(
+            size_t width, size_t height,
+            const void *srcBits, size_t srcSkip,
+            void *dstBits, size_t dstSkip);
+
+private:
+    OMX_COLOR_FORMATTYPE mSrcFormat, mDstFormat;
+    uint8_t *mClip;
+
+    uint8_t *initClip();
+
+    void convertCbYCrY(
+            size_t width, size_t height,
+            const void *srcBits, size_t srcSkip,
+            void *dstBits, size_t dstSkip);
+
+    void convertYUV420Planar(
+            size_t width, size_t height,
+            const void *srcBits, size_t srcSkip,
+            void *dstBits, size_t dstSkip);
+
+    void convertQCOMYUV420SemiPlanar(
+            size_t width, size_t height,
+            const void *srcBits, size_t srcSkip,
+            void *dstBits, size_t dstSkip);
+
+    ColorConverter(const ColorConverter &);
+    ColorConverter &operator=(const ColorConverter &);
+};
+
+}  // namespace android
+
+#endif  // COLOR_CONVERTER_H_
diff --git a/include/media/stagefright/DataSource.h b/include/media/stagefright/DataSource.h
index f46f0af..b843cd9 100644
--- a/include/media/stagefright/DataSource.h
+++ b/include/media/stagefright/DataSource.h
@@ -33,7 +33,9 @@
 public:
     DataSource() {}
 
-    virtual ssize_t read_at(off_t offset, void *data, size_t size) = 0;
+    virtual status_t initCheck() const = 0;
+
+    virtual ssize_t readAt(off_t offset, void *data, size_t size) = 0;
 
     // Convenience methods:
     bool getUInt16(off_t offset, uint16_t *x);
diff --git a/include/media/stagefright/FileSource.h b/include/media/stagefright/FileSource.h
index ccbe0ef..8a215ea 100644
--- a/include/media/stagefright/FileSource.h
+++ b/include/media/stagefright/FileSource.h
@@ -29,14 +29,21 @@
 class FileSource : public DataSource {
 public:
     FileSource(const char *filename);
+    FileSource(int fd, int64_t offset, int64_t length);
+
+    virtual status_t initCheck() const;
+
+    virtual ssize_t readAt(off_t offset, void *data, size_t size);
+
+    virtual status_t getSize(off_t *size);
+
+protected:
     virtual ~FileSource();
 
-    status_t InitCheck() const;
-
-    virtual ssize_t read_at(off_t offset, void *data, size_t size);
-
 private:
     FILE *mFile;
+    int64_t mOffset;
+    int64_t mLength;
     Mutex mLock;
 
     FileSource(const FileSource &);
diff --git a/include/media/stagefright/HTTPDataSource.h b/include/media/stagefright/HTTPDataSource.h
index 0587c7c..d5dc9e6 100644
--- a/include/media/stagefright/HTTPDataSource.h
+++ b/include/media/stagefright/HTTPDataSource.h
@@ -19,28 +19,29 @@
 #define HTTP_DATASOURCE_H_
 
 #include <media/stagefright/DataSource.h>
-#include <media/stagefright/HTTPStream.h>
 
 namespace android {
 
+class HTTPStream;
+
 class HTTPDataSource : public DataSource {
 public:
     HTTPDataSource(const char *host, int port, const char *path);
     HTTPDataSource(const char *uri);
 
+    virtual status_t initCheck() const;
+
+    virtual ssize_t readAt(off_t offset, void *data, size_t size);
+
+protected:
     virtual ~HTTPDataSource();
 
-    // XXXandih
-    status_t InitCheck() const { return OK; }
-
-    virtual ssize_t read_at(off_t offset, void *data, size_t size);
-
 private:
     enum {
         kBufferSize = 64 * 1024
     };
 
-    HTTPStream mHttp;
+    HTTPStream *mHttp;
     char *mHost;
     int mPort;
     char *mPath;
@@ -49,6 +50,8 @@
     size_t mBufferLength;
     off_t mBufferOffset;
 
+    status_t mInitCheck;
+
     HTTPDataSource(const HTTPDataSource &);
     HTTPDataSource &operator=(const HTTPDataSource &);
 };
diff --git a/include/media/stagefright/HTTPStream.h b/include/media/stagefright/HTTPStream.h
deleted file mode 100644
index 72e796c..0000000
--- a/include/media/stagefright/HTTPStream.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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 HTTP_STREAM_H_
-
-#define HTTP_STREAM_H_
-
-#include <sys/types.h>
-
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/stagefright_string.h>
-#include <utils/KeyedVector.h>
-
-namespace android {
-
-class HTTPStream {
-public:
-    HTTPStream();
-    ~HTTPStream();
-
-    status_t connect(const char *server, int port = 80);
-    status_t disconnect();
-
-    status_t send(const char *data, size_t size);
-
-    // Assumes data is a '\0' terminated string.
-    status_t send(const char *data);
-
-    // Receive up to "size" bytes of data.
-    ssize_t receive(void *data, size_t size);
-
-    status_t receive_header(int *http_status);
-
-    // The header key used to retrieve the status line.
-    static const char *kStatusKey;
-
-    bool find_header_value(
-            const string &key, string *value) const;
-
-private:
-    enum State {
-        READY,
-        CONNECTED
-    };
-
-    State mState;
-    int mSocket;
-
-    KeyedVector<string, string> mHeaders;
-
-    // Receive a line of data terminated by CRLF, line will be '\0' terminated
-    // _excluding_ the termianting CRLF.
-    status_t receive_line(char *line, size_t size);
-
-    HTTPStream(const HTTPStream &);
-    HTTPStream &operator=(const HTTPStream &);
-};
-
-}  // namespace android
-
-#endif  // HTTP_STREAM_H_
diff --git a/include/media/stagefright/HardwareAPI.h b/include/media/stagefright/HardwareAPI.h
index 7e1f08d..b7daddc 100644
--- a/include/media/stagefright/HardwareAPI.h
+++ b/include/media/stagefright/HardwareAPI.h
@@ -18,6 +18,7 @@
 
 #define HARDWARE_API_H_
 
+#include <media/stagefright/OMXPluginBase.h>
 #include <media/stagefright/VideoRenderer.h>
 #include <ui/ISurface.h>
 #include <utils/RefBase.h>
@@ -31,5 +32,7 @@
         size_t displayWidth, size_t displayHeight,
         size_t decodedWidth, size_t decodedHeight);
 
+extern android::OMXPluginBase *createOMXPlugin();
+
 #endif  // HARDWARE_API_H_
 
diff --git a/include/media/stagefright/MP3Extractor.h b/include/media/stagefright/MP3Extractor.h
deleted file mode 100644
index 11ba01d..0000000
--- a/include/media/stagefright/MP3Extractor.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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 MP3_EXTRACTOR_H_
-
-#define MP3_EXTRACTOR_H_
-
-#include <media/stagefright/MediaExtractor.h>
-
-namespace android {
-
-class DataSource;
-class String8;
-
-class MP3Extractor : public MediaExtractor {
-public:
-    // Extractor assumes ownership of "source".
-    MP3Extractor(const sp<DataSource> &source);
-
-    virtual size_t countTracks();
-    virtual sp<MediaSource> getTrack(size_t index);
-    virtual sp<MetaData> getTrackMetaData(size_t index);
-
-protected:
-    virtual ~MP3Extractor();
-
-private:
-    sp<DataSource> mDataSource;
-    off_t mFirstFramePos;
-    sp<MetaData> mMeta;
-    uint32_t mFixedHeader;
-
-    MP3Extractor(const MP3Extractor &);
-    MP3Extractor &operator=(const MP3Extractor &);
-};
-
-bool SniffMP3(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence);
-
-}  // namespace android
-
-#endif  // MP3_EXTRACTOR_H_
diff --git a/include/media/stagefright/MPEG4Extractor.h b/include/media/stagefright/MPEG4Extractor.h
deleted file mode 100644
index 932e30f..0000000
--- a/include/media/stagefright/MPEG4Extractor.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 MPEG4_EXTRACTOR_H_
-
-#define MPEG4_EXTRACTOR_H_
-
-#include <media/stagefright/MediaExtractor.h>
-
-namespace android {
-
-class DataSource;
-class SampleTable;
-class String8;
-
-class MPEG4Extractor : public MediaExtractor {
-public:
-    // Extractor assumes ownership of "source".
-    MPEG4Extractor(const sp<DataSource> &source);
-
-    size_t countTracks();
-    sp<MediaSource> getTrack(size_t index);
-    sp<MetaData> getTrackMetaData(size_t index);
-
-protected:
-    virtual ~MPEG4Extractor();
-
-private:
-    struct Track {
-        Track *next;
-        sp<MetaData> meta;
-        uint32_t timescale;
-        sp<SampleTable> sampleTable;
-    };
-
-    sp<DataSource> mDataSource;
-    bool mHaveMetadata;
-
-    Track *mFirstTrack, *mLastTrack;
-
-    uint32_t mHandlerType;
-
-    status_t readMetaData();
-    status_t parseChunk(off_t *offset, int depth);
-
-    MPEG4Extractor(const MPEG4Extractor &);
-    MPEG4Extractor &operator=(const MPEG4Extractor &);
-};
-
-bool SniffMPEG4(
-        const sp<DataSource> &source, String8 *mimeType, float *confidence);
-
-}  // namespace android
-
-#endif  // MPEG4_EXTRACTOR_H_
diff --git a/include/media/stagefright/MPEG4Writer.h b/include/media/stagefright/MPEG4Writer.h
index 6b0399f..2ca04fa 100644
--- a/include/media/stagefright/MPEG4Writer.h
+++ b/include/media/stagefright/MPEG4Writer.h
@@ -33,6 +33,7 @@
 class MPEG4Writer : public RefBase {
 public:
     MPEG4Writer(const char *filename);
+    MPEG4Writer(int fd);
 
     void addSource(const sp<MediaSource> &source);
     status_t start();
@@ -65,6 +66,7 @@
     List<off_t> mBoxes;
 
     off_t addSample(MediaBuffer *buffer);
+    off_t addLengthPrefixedSample(MediaBuffer *buffer);
 
     MPEG4Writer(const MPEG4Writer &);
     MPEG4Writer &operator=(const MPEG4Writer &);
diff --git a/include/media/stagefright/MediaDefs.h b/include/media/stagefright/MediaDefs.h
index feb66e3..1efeb92 100644
--- a/include/media/stagefright/MediaDefs.h
+++ b/include/media/stagefright/MediaDefs.h
@@ -34,6 +34,7 @@
 extern const char *MEDIA_MIMETYPE_AUDIO_RAW;
 
 extern const char *MEDIA_MIMETYPE_CONTAINER_MPEG4;
+extern const char *MEDIA_MIMETYPE_CONTAINER_WAV;
 
 }  // namespace android
 
diff --git a/include/media/stagefright/MediaErrors.h b/include/media/stagefright/MediaErrors.h
index 2bb0ed6..73d0f77 100644
--- a/include/media/stagefright/MediaErrors.h
+++ b/include/media/stagefright/MediaErrors.h
@@ -36,6 +36,9 @@
     ERROR_BUFFER_TOO_SMALL  = MEDIA_ERROR_BASE - 9,
     ERROR_UNSUPPORTED       = MEDIA_ERROR_BASE - 10,
     ERROR_END_OF_STREAM     = MEDIA_ERROR_BASE - 11,
+
+    // Not technically an error.
+    INFO_FORMAT_CHANGED    = MEDIA_ERROR_BASE - 12,
 };
 
 }  // namespace android
diff --git a/include/media/stagefright/MediaExtractor.h b/include/media/stagefright/MediaExtractor.h
index 67e45bd..d56d4b3 100644
--- a/include/media/stagefright/MediaExtractor.h
+++ b/include/media/stagefright/MediaExtractor.h
@@ -31,9 +31,17 @@
     static sp<MediaExtractor> Create(
             const sp<DataSource> &source, const char *mime = NULL);
 
+    static sp<MediaExtractor> CreateFromURI(
+            const char *uri, const char *mime = NULL);
+
     virtual size_t countTracks() = 0;
     virtual sp<MediaSource> getTrack(size_t index) = 0;
-    virtual sp<MetaData> getTrackMetaData(size_t index) = 0;
+
+    enum GetTrackMetaDataFlags {
+        kIncludeExtensiveMetaData = 1
+    };
+    virtual sp<MetaData> getTrackMetaData(
+            size_t index, uint32_t flags = 0) = 0;
 
 protected:
     MediaExtractor() {}
diff --git a/include/media/stagefright/MediaPlayerImpl.h b/include/media/stagefright/MediaPlayerImpl.h
deleted file mode 100644
index 7adf836..0000000
--- a/include/media/stagefright/MediaPlayerImpl.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * 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 MEDIA_PLAYER_IMPL_H_
-
-#define MEDIA_PLAYER_IMPL_H_
-
-#include <pthread.h>
-
-#include <media/MediaPlayerInterface.h>
-#include <media/stagefright/OMXClient.h>
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-
-namespace android {
-
-class AudioPlayer;
-class IOMXRenderer;
-class ISurface;
-class MediaExtractor;
-class MediaBuffer;
-class MediaSource;
-class MemoryHeapPmem;
-class MetaData;
-class Surface;
-class TimeSource;
-
-class MediaPlayerImpl {
-public:
-    MediaPlayerImpl(const char *uri);
-
-    status_t initCheck() const;
-
-    // Assumes ownership of "fd".
-    MediaPlayerImpl(int fd, int64_t offset, int64_t length);
-
-    ~MediaPlayerImpl();
-
-    void play();
-    void pause();
-    bool isPlaying() const;
-
-    void setSurface(const sp<Surface> &surface);
-    void setISurface(const sp<ISurface> &isurface);
-
-    void setAudioSink(const sp<MediaPlayerBase::AudioSink> &audioSink);
-
-    int32_t getWidth() const { return mVideoWidth; }
-    int32_t getHeight() const { return mVideoHeight; }
-
-    int64_t getDuration();
-    int64_t getPosition();
-    status_t seekTo(int64_t time);
-
-private:
-    status_t mInitCheck;
-
-    OMXClient mClient;
-
-    sp<MediaExtractor> mExtractor;
-
-    TimeSource *mTimeSource;
-
-    sp<MediaSource> mAudioSource;
-    sp<MediaSource> mAudioDecoder;
-    AudioPlayer *mAudioPlayer;
-
-    sp<MediaSource> mVideoSource;
-    sp<MediaSource> mVideoDecoder;
-    int32_t mVideoWidth, mVideoHeight;
-    int64_t mVideoPosition;
-
-    int64_t mDuration;
-
-    bool mPlaying;
-    bool mPaused;
-
-    int64_t mTimeSourceDeltaUs;
-
-    sp<Surface> mSurface;
-    sp<ISurface> mISurface;
-    sp<IOMXRenderer> mVideoRenderer;
-
-    sp<MediaPlayerBase::AudioSink> mAudioSink;
-
-    Mutex mLock;
-    pthread_t mVideoThread;
-
-    bool mSeeking;
-    int64_t mSeekTimeUs;
-
-    void init();
-
-    static void *VideoWrapper(void *me);
-    void videoEntry();
-
-    void setAudioSource(const sp<MediaSource> &source);
-    void setVideoSource(const sp<MediaSource> &source);
-
-    MediaSource *makeShoutcastSource(const char *path);
-
-    void displayOrDiscardFrame(
-            MediaBuffer **lastBuffer, MediaBuffer *buffer, int64_t pts_us);
-
-    void populateISurface();
-    void depopulateISurface();
-    void sendFrameToISurface(MediaBuffer *buffer);
-
-    void stop();
-
-    MediaPlayerImpl(const MediaPlayerImpl &);
-    MediaPlayerImpl &operator=(const MediaPlayerImpl &);
-};
-
-}  // namespace android
-
-#endif  // MEDIA_PLAYER_IMPL_H_
diff --git a/include/media/stagefright/MediaSource.h b/include/media/stagefright/MediaSource.h
index d1fa114..96d57e7 100644
--- a/include/media/stagefright/MediaSource.h
+++ b/include/media/stagefright/MediaSource.h
@@ -51,6 +51,9 @@
     // buffer is available, an error is encountered of the end of the stream
     // is reached.
     // End of stream is signalled by a result of ERROR_END_OF_STREAM.
+    // A result of INFO_FORMAT_CHANGED indicates that the format of this
+    // MediaSource has changed mid-stream, the client can continue reading
+    // but should be prepared for buffers of the new configuration.
     virtual status_t read(
             MediaBuffer **buffer, const ReadOptions *options = NULL) = 0;
 
diff --git a/include/media/stagefright/MetaData.h b/include/media/stagefright/MetaData.h
index abb45a9..c6ac6c2 100644
--- a/include/media/stagefright/MetaData.h
+++ b/include/media/stagefright/MetaData.h
@@ -27,25 +27,27 @@
 
 namespace android {
 
+// The following keys map to int32_t data unless indicated otherwise.
 enum {
-    kKeyMIMEType          = 'mime',
+    kKeyMIMEType          = 'mime',  // cstring
     kKeyWidth             = 'widt',
     kKeyHeight            = 'heig',
     kKeyChannelCount      = '#chn',
     kKeySampleRate        = 'srte',
-    kKeyBitRate           = 'brte',
-    kKeyESDS              = 'esds',
-    kKeyAVCC              = 'avcc',
-    kKeyTimeUnits         = '#tim',
-    kKeyTimeScale         = 'scal',
+    kKeyBitRate           = 'brte',  // int32_t (bps)
+    kKeyESDS              = 'esds',  // raw data
+    kKeyAVCC              = 'avcc',  // raw data
     kKeyWantsNALFragments = 'NALf',
-    kKeyIsSyncFrame       = 'sync',
-    kKeyDuration          = 'dura',
+    kKeyIsSyncFrame       = 'sync',  // int32_t (bool)
+    kKeyIsCodecConfig     = 'conf',  // int32_t (bool)
+    kKeyTime              = 'time',  // int64_t (usecs)
+    kKeyDuration          = 'dura',  // int64_t (usecs)
     kKeyColorFormat       = 'colf',
-    kKeyPlatformPrivate   = 'priv',
-    kKeyDecoderComponent  = 'decC',
+    kKeyPlatformPrivate   = 'priv',  // pointer
+    kKeyDecoderComponent  = 'decC',  // cstring
     kKeyBufferID          = 'bfID',
     kKeyMaxInputSize      = 'inpS',
+    kKeyThumbnailTime     = 'thbT',  // int64_t (usecs)
 };
 
 enum {
@@ -62,6 +64,7 @@
         TYPE_NONE     = 'none',
         TYPE_C_STRING = 'cstr',
         TYPE_INT32    = 'in32',
+        TYPE_INT64    = 'in64',
         TYPE_FLOAT    = 'floa',
         TYPE_POINTER  = 'ptr ',
     };
@@ -71,11 +74,13 @@
 
     bool setCString(uint32_t key, const char *value);
     bool setInt32(uint32_t key, int32_t value);
+    bool setInt64(uint32_t key, int64_t value);
     bool setFloat(uint32_t key, float value);
     bool setPointer(uint32_t key, void *value);
 
     bool findCString(uint32_t key, const char **value);
     bool findInt32(uint32_t key, int32_t *value);
+    bool findInt64(uint32_t key, int64_t *value);
     bool findFloat(uint32_t key, float *value);
     bool findPointer(uint32_t key, void **value);
 
diff --git a/include/media/stagefright/MmapSource.h b/include/media/stagefright/MmapSource.h
deleted file mode 100644
index a8bd57f..0000000
--- a/include/media/stagefright/MmapSource.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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 MMAP_SOURCE_H_
-
-#define MMAP_SOURCE_H_
-
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/MediaErrors.h>
-
-namespace android {
-
-class MmapSource : public DataSource {
-public:
-    MmapSource(const char *filename);
-
-    // Assumes ownership of "fd".
-    MmapSource(int fd, int64_t offset, int64_t length);
-
-    virtual ~MmapSource();
-
-    status_t InitCheck() const;
-
-    virtual ssize_t read_at(off_t offset, void *data, size_t size);
-    virtual status_t getSize(off_t *size);
-
-private:
-    int mFd;
-    void *mBase;
-    size_t mSize;
-
-    MmapSource(const MmapSource &);
-    MmapSource &operator=(const MmapSource &);
-};
-
-}  // namespace android
-
-#endif  // MMAP_SOURCE_H_
-
diff --git a/include/media/stagefright/OMXCodec.h b/include/media/stagefright/OMXCodec.h
index 3f3dcf9..351763c 100644
--- a/include/media/stagefright/OMXCodec.h
+++ b/include/media/stagefright/OMXCodec.h
@@ -30,11 +30,15 @@
 
 struct OMXCodec : public MediaSource,
                   public MediaBufferObserver {
-    static sp<OMXCodec> Create(
+    enum CreationFlags {
+        kPreferSoftwareCodecs = 1,
+    };
+    static sp<MediaSource> Create(
             const sp<IOMX> &omx,
             const sp<MetaData> &meta, bool createEncoder,
             const sp<MediaSource> &source,
-            const char *matchComponentName = NULL);
+            const char *matchComponentName = NULL,
+            uint32_t flags = 0);
 
     static void setComponentRole(
             const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
@@ -90,7 +94,6 @@
         kRequiresFlushCompleteEmulation      = 16,
         kRequiresAllocateBufferOnOutputPorts = 32,
         kRequiresFlushBeforeShutdown         = 64,
-        kOutputDimensionsAre16Aligned        = 128,
     };
 
     struct BufferInfo {
@@ -107,7 +110,6 @@
 
     sp<IOMX> mOMX;
     IOMX::node_id mNode;
-    sp<OMXCodecObserver> mObserver;
     uint32_t mQuirks;
     bool mIsEncoder;
     char *mMIME;
@@ -125,6 +127,7 @@
     bool mInitialBufferSubmit;
     bool mSignalledEOS;
     bool mNoMoreOutputData;
+    bool mOutputPortSettingsHaveChanged;
     int64_t mSeekTimeUs;
 
     Mutex mLock;
@@ -143,8 +146,7 @@
 
     void setComponentRole();
 
-    void setAMRFormat();
-    void setAMRWBFormat();
+    void setAMRFormat(bool isWAMR);
     void setAACFormat(int32_t numChannels, int32_t sampleRate);
 
     status_t setVideoPortFormatType(
@@ -155,6 +157,9 @@
     void setVideoInputFormat(
             const char *mime, OMX_U32 width, OMX_U32 height);
 
+    status_t setupMPEG4EncoderParameters();
+    status_t setupAVCEncoderParameters();
+
     void setVideoOutputFormat(
             const char *mime, OMX_U32 width, OMX_U32 height);
 
@@ -208,6 +213,14 @@
 
     void dumpPortStatus(OMX_U32 portIndex);
 
+    static uint32_t getComponentQuirks(const char *componentName);
+
+    static void findMatchingCodecs(
+            const char *mime,
+            bool createEncoder, const char *matchComponentName,
+            uint32_t flags,
+            Vector<String8> *matchingCodecs);
+
     OMXCodec(const OMXCodec &);
     OMXCodec &operator=(const OMXCodec &);
 };
diff --git a/include/media/stagefright/OMXPluginBase.h b/include/media/stagefright/OMXPluginBase.h
new file mode 100644
index 0000000..2fd8e12
--- /dev/null
+++ b/include/media/stagefright/OMXPluginBase.h
@@ -0,0 +1,61 @@
+/*
+ * 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 OMX_PLUGIN_BASE_H_
+
+#define OMX_PLUGIN_BASE_H_
+
+#include <sys/types.h>
+
+#include <OMX_Component.h>
+
+#include <utils/String8.h>
+#include <utils/Vector.h>
+
+namespace android {
+
+struct OMXComponentBase;
+
+struct OMXPluginBase {
+    OMXPluginBase() {}
+    virtual ~OMXPluginBase() {}
+
+    virtual OMX_ERRORTYPE makeComponentInstance(
+            const char *name,
+            const OMX_CALLBACKTYPE *callbacks,
+            OMX_PTR appData,
+            OMX_COMPONENTTYPE **component) = 0;
+
+    virtual OMX_ERRORTYPE destroyComponentInstance(
+            OMX_COMPONENTTYPE *component) = 0;
+
+    virtual OMX_ERRORTYPE enumerateComponents(
+            OMX_STRING name,
+            size_t size,
+            OMX_U32 index) = 0;
+
+    virtual OMX_ERRORTYPE getRolesOfComponent(
+            const char *name,
+            Vector<String8> *roles) = 0;
+
+private:
+    OMXPluginBase(const OMXPluginBase &);
+    OMXPluginBase &operator=(const OMXPluginBase &);
+};
+
+}  // namespace android
+
+#endif  // OMX_PLUGIN_BASE_H_
diff --git a/include/media/stagefright/SampleTable.h b/include/media/stagefright/SampleTable.h
deleted file mode 100644
index 808d142..0000000
--- a/include/media/stagefright/SampleTable.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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 SAMPLE_TABLE_H_
-
-#define SAMPLE_TABLE_H_
-
-#include <sys/types.h>
-#include <stdint.h>
-
-#include <media/stagefright/MediaErrors.h>
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-
-namespace android {
-
-class DataSource;
-
-class SampleTable : public RefBase {
-public:
-    SampleTable(const sp<DataSource> &source);
-
-    // type can be 'stco' or 'co64'.
-    status_t setChunkOffsetParams(
-            uint32_t type, off_t data_offset, off_t data_size);
-
-    status_t setSampleToChunkParams(off_t data_offset, off_t data_size);
-
-    // type can be 'stsz' or 'stz2'.
-    status_t setSampleSizeParams(
-            uint32_t type, off_t data_offset, off_t data_size);
-
-    status_t setTimeToSampleParams(off_t data_offset, off_t data_size);
-
-    status_t setSyncSampleParams(off_t data_offset, off_t data_size);
-
-    ////////////////////////////////////////////////////////////////////////////
-
-    uint32_t countChunkOffsets() const;
-    status_t getChunkOffset(uint32_t chunk_index, off_t *offset);
-
-    status_t getChunkForSample(
-            uint32_t sample_index, uint32_t *chunk_index,
-            uint32_t *chunk_relative_sample_index, uint32_t *desc_index);
-
-    uint32_t countSamples() const;
-    status_t getSampleSize(uint32_t sample_index, size_t *sample_size);
-
-    status_t getSampleOffsetAndSize(
-            uint32_t sample_index, off_t *offset, size_t *size);
-
-    status_t getMaxSampleSize(size_t *size);
-
-    status_t getDecodingTime(uint32_t sample_index, uint32_t *time);
-
-    enum {
-        kSyncSample_Flag = 1
-    };
-    status_t findClosestSample(
-            uint32_t req_time, uint32_t *sample_index, uint32_t flags);
-
-    status_t findClosestSyncSample(
-            uint32_t start_sample_index, uint32_t *sample_index);
-
-protected:
-    ~SampleTable();
-
-private:
-    sp<DataSource> mDataSource;
-    Mutex mLock;
-
-    off_t mChunkOffsetOffset;
-    uint32_t mChunkOffsetType;
-    uint32_t mNumChunkOffsets;
-
-    off_t mSampleToChunkOffset;
-    uint32_t mNumSampleToChunkOffsets;
-
-    off_t mSampleSizeOffset;
-    uint32_t mSampleSizeFieldSize;
-    uint32_t mDefaultSampleSize;
-    uint32_t mNumSampleSizes;
-
-    uint32_t mTimeToSampleCount;
-    uint32_t *mTimeToSample;
-
-    off_t mSyncSampleOffset;
-    uint32_t mNumSyncSamples;
-
-    SampleTable(const SampleTable &);
-    SampleTable &operator=(const SampleTable &);
-};
-
-}  // namespace android
-
-#endif  // SAMPLE_TABLE_H_
diff --git a/include/media/stagefright/ShoutcastSource.h b/include/media/stagefright/ShoutcastSource.h
index 352857a..bc67156 100644
--- a/include/media/stagefright/ShoutcastSource.h
+++ b/include/media/stagefright/ShoutcastSource.h
@@ -31,7 +31,6 @@
 public:
     // Assumes ownership of "http".
     ShoutcastSource(HTTPStream *http);
-    virtual ~ShoutcastSource();
 
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
@@ -41,6 +40,9 @@
     virtual status_t read(
             MediaBuffer **buffer, const ReadOptions *options = NULL);
 
+protected:
+    virtual ~ShoutcastSource();
+
 private:
     HTTPStream *mHttp;
     size_t mMetaDataOffset;
diff --git a/include/media/stagefright/SoftwareRenderer.h b/include/media/stagefright/SoftwareRenderer.h
deleted file mode 100644
index 1545493..0000000
--- a/include/media/stagefright/SoftwareRenderer.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 SOFTWARE_RENDERER_H_
-
-#define SOFTWARE_RENDERER_H_
-
-#include <OMX_Video.h>
-#include <media/stagefright/VideoRenderer.h>
-#include <utils/RefBase.h>
-
-namespace android {
-
-class ISurface;
-class MemoryHeapBase;
-
-class SoftwareRenderer : public VideoRenderer {
-public:
-    SoftwareRenderer(
-            OMX_COLOR_FORMATTYPE colorFormat,
-            const sp<ISurface> &surface,
-            size_t displayWidth, size_t displayHeight,
-            size_t decodedWidth, size_t decodedHeight);
-
-    virtual ~SoftwareRenderer();
-
-    virtual void render(
-            const void *data, size_t size, void *platformPrivate);
-
-private:
-    uint8_t *initClip();
-
-    void renderCbYCrY(const void *data, size_t size);
-    void renderYUV420Planar(const void *data, size_t size);
-    void renderQCOMYUV420SemiPlanar(const void *data, size_t size);
-
-    OMX_COLOR_FORMATTYPE mColorFormat;
-    sp<ISurface> mISurface;
-    size_t mDisplayWidth, mDisplayHeight;
-    size_t mDecodedWidth, mDecodedHeight;
-    size_t mFrameSize;
-    sp<MemoryHeapBase> mMemoryHeap;
-    int mIndex;
-
-    uint8_t *mClip;
-
-    SoftwareRenderer(const SoftwareRenderer &);
-    SoftwareRenderer &operator=(const SoftwareRenderer &);
-};
-
-}  // namespace android
-
-#endif  // SOFTWARE_RENDERER_H_
diff --git a/include/media/stagefright/TimedEventQueue.h b/include/media/stagefright/TimedEventQueue.h
deleted file mode 100644
index a264421..0000000
--- a/include/media/stagefright/TimedEventQueue.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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 TIMED_EVENT_QUEUE_H_
-
-#define TIMED_EVENT_QUEUE_H_
-
-#include <pthread.h>
-
-#include <utils/List.h>
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-
-namespace android {
-
-struct TimedEventQueue {
-
-    struct Event : public RefBase {
-        Event() {}
-        virtual ~Event() {}
-
-    protected:
-        virtual void fire(TimedEventQueue *queue, int64_t now_us) = 0;
-
-    private:
-        friend class TimedEventQueue;
-
-        Event(const Event &);
-        Event &operator=(const Event &);
-    };
-
-    TimedEventQueue();
-    ~TimedEventQueue();
-
-    // Start executing the event loop.
-    void start();
-
-    // Stop executing the event loop, if flush is false, any pending
-    // events are discarded, otherwise the queue will stop (and this call
-    // return) once all pending events have been handled.
-    void stop(bool flush = false);
-
-    // Posts an event to the front of the queue (after all events that
-    // have previously been posted to the front but before timed events).
-    void postEvent(const sp<Event> &event);
-
-    void postEventToBack(const sp<Event> &event);
-
-    // It is an error to post an event with a negative delay.
-    void postEventWithDelay(const sp<Event> &event, int64_t delay_us);
-
-    // If the event is to be posted at a time that has already passed,
-    // it will fire as soon as possible.
-    void postTimedEvent(const sp<Event> &event, int64_t realtime_us);
-
-    // Returns true iff event is currently in the queue and has been
-    // successfully cancelled. In this case the event will have been
-    // removed from the queue and won't fire.
-    bool cancelEvent(const sp<Event> &event);
-
-    static int64_t getRealTimeUs();
-
-private:
-    struct QueueItem {
-        sp<Event> event;
-        int64_t realtime_us;
-    };
-
-    struct StopEvent : public TimedEventQueue::Event {
-        virtual void fire(TimedEventQueue *queue, int64_t now_us) {
-            queue->mStopped = true;
-        }
-    };
-
-    pthread_t mThread;
-    List<QueueItem> mQueue;
-    Mutex mLock;
-    Condition mQueueNotEmptyCondition;
-    Condition mQueueHeadChangedCondition;
-
-    bool mRunning;
-    bool mStopped;
-
-    static void *ThreadWrapper(void *me);
-    void threadEntry();
-
-    TimedEventQueue(const TimedEventQueue &);
-    TimedEventQueue &operator=(const TimedEventQueue &);
-};
-
-}  // namespace android
-
-#endif  // TIMED_EVENT_QUEUE_H_
diff --git a/include/media/stagefright/stagefright_string.h b/include/media/stagefright/stagefright_string.h
deleted file mode 100644
index 1ed4c86..0000000
--- a/include/media/stagefright/stagefright_string.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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 STAGEFRIGHT_STRING_H_
-
-#define STAGEFRIGHT_STRING_H_
-
-#include <utils/String8.h>
-
-namespace android {
-
-class string {
-public:
-    typedef size_t size_type;
-    static size_type npos;
-
-    string();
-    string(const char *s);
-    string(const char *s, size_t length);
-    string(const string &from, size_type start, size_type length = npos);
-
-    const char *c_str() const;
-    size_type size() const;
-
-    void clear();
-    void erase(size_type from, size_type length);
-
-    size_type find(char c) const;
-
-    bool operator<(const string &other) const;
-    bool operator==(const string &other) const;
-
-    string &operator+=(char c);
-
-private:
-    String8 mString;
-};
-
-}  // namespace android
-
-#endif  // STAGEFRIGHT_STRING_H_
diff --git a/media/libmedia/Android.mk b/media/libmedia/Android.mk
index 3c0ee1c..088ad6d 100644
--- a/media/libmedia/Android.mk
+++ b/media/libmedia/Android.mk
@@ -21,10 +21,18 @@
     ToneGenerator.cpp \
     JetPlayer.cpp \
     IOMX.cpp \
- 	IAudioPolicyService.cpp
+    IAudioPolicyService.cpp \
+    MediaScanner.cpp \
+    MediaScannerClient.cpp \
+    autodetect.cpp
+
+ifneq ($(BUILD_WITHOUT_PV),true)
+else
+LOCAL_SRC_FILES += StagefrightMediaScanner.cpp
+endif
 
 LOCAL_SHARED_LIBRARIES := \
-	libui libcutils libutils libbinder libsonivox
+	libui libcutils libutils libbinder libsonivox libicuuc
 
 LOCAL_MODULE:= libmedia
 
@@ -41,7 +49,8 @@
     $(call include-path-for, graphics corecg) \
         $(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include \
         external/speex/include \
-        external/speex/libspeex
+        external/speex/libspeex \
+        external/icu4c/common
 
 LOCAL_STATIC_LIBRARIES := libspeex
 
diff --git a/media/libmedia/IOMX.cpp b/media/libmedia/IOMX.cpp
index 88a7064..b43e48f 100644
--- a/media/libmedia/IOMX.cpp
+++ b/media/libmedia/IOMX.cpp
@@ -75,7 +75,7 @@
         : BpInterface<IOMX>(impl) {
     }
 
-    virtual status_t listNodes(List<String8> *list) {
+    virtual status_t listNodes(List<ComponentInfo> *list) {
         list->clear();
 
         Parcel data, reply;
@@ -84,9 +84,14 @@
 
         int32_t n = reply.readInt32();
         for (int32_t i = 0; i < n; ++i) {
-            String8 s = reply.readString8();
+            list->push_back(ComponentInfo());
+            ComponentInfo &info = *--list->end();
 
-            list->push_back(s);
+            info.mName = reply.readString8();
+            int32_t numRoles = reply.readInt32();
+            for (int32_t j = 0; j < numRoles; ++j) {
+                info.mRoles.push_back(reply.readString8());
+            }
         }
 
         return OK;
@@ -284,7 +289,7 @@
         data.writeInterfaceToken(IOMX::getInterfaceDescriptor());
         data.writeIntPtr((intptr_t)node);
         data.writeIntPtr((intptr_t)buffer);
-        remote()->transact(FILL_BUFFER, data, &reply, IBinder::FLAG_ONEWAY);
+        remote()->transact(FILL_BUFFER, data, &reply);
 
         return reply.readInt32();
     }
@@ -302,7 +307,7 @@
         data.writeInt32(range_length);
         data.writeInt32(flags);
         data.writeInt64(timestamp);
-        remote()->transact(EMPTY_BUFFER, data, &reply, IBinder::FLAG_ONEWAY);
+        remote()->transact(EMPTY_BUFFER, data, &reply);
 
         return reply.readInt32();
     }
@@ -368,13 +373,20 @@
         {
             CHECK_INTERFACE(IOMX, data, reply);
 
-            List<String8> list;
+            List<ComponentInfo> list;
             listNodes(&list);
 
             reply->writeInt32(list.size());
-            for (List<String8>::iterator it = list.begin();
+            for (List<ComponentInfo>::iterator it = list.begin();
                  it != list.end(); ++it) {
-                reply->writeString8(*it);
+                ComponentInfo &cur = *it;
+
+                reply->writeString8(cur.mName);
+                reply->writeInt32(cur.mRoles.size());
+                for (List<String8>::iterator role_it = cur.mRoles.begin();
+                     role_it != cur.mRoles.end(); ++role_it) {
+                    reply->writeString8(*role_it);
+                }
             }
 
             return NO_ERROR;
diff --git a/media/libmedia/MediaScanner.cpp b/media/libmedia/MediaScanner.cpp
new file mode 100644
index 0000000..f201667
--- /dev/null
+++ b/media/libmedia/MediaScanner.cpp
@@ -0,0 +1,189 @@
+/*
+ * 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 <media/mediascanner.h>
+
+#include <sys/stat.h>
+#include <dirent.h>
+
+namespace android {
+
+MediaScanner::MediaScanner()
+    : mLocale(NULL) {
+}
+
+MediaScanner::~MediaScanner() {
+    setLocale(NULL);
+}
+
+void MediaScanner::setLocale(const char *locale) {
+    if (mLocale) {
+        free(mLocale);
+        mLocale = NULL;
+    }
+    if (locale) {
+        mLocale = strdup(locale);
+    }
+}
+
+const char *MediaScanner::locale() const {
+    return mLocale;
+}
+
+status_t MediaScanner::processDirectory(
+        const char *path, const char *extensions,
+        MediaScannerClient &client,
+        ExceptionCheck exceptionCheck, void *exceptionEnv) {
+    int pathLength = strlen(path);
+    if (pathLength >= PATH_MAX) {
+        return UNKNOWN_ERROR;
+    }
+    char* pathBuffer = (char *)malloc(PATH_MAX + 1);
+    if (!pathBuffer) {
+        return UNKNOWN_ERROR;
+    }
+
+    int pathRemaining = PATH_MAX - pathLength;
+    strcpy(pathBuffer, path);
+    if (pathBuffer[pathLength - 1] != '/') {
+        pathBuffer[pathLength] = '/';
+        pathBuffer[pathLength + 1] = 0;
+        --pathRemaining;
+    }
+
+    client.setLocale(locale());
+
+    status_t result =
+        doProcessDirectory(
+                pathBuffer, pathRemaining, extensions, client,
+                exceptionCheck, exceptionEnv);
+
+    free(pathBuffer);
+
+    return result;
+}
+
+static bool fileMatchesExtension(const char* path, const char* extensions) {
+    char* extension = strrchr(path, '.');
+    if (!extension) return false;
+    ++extension;    // skip the dot
+    if (extension[0] == 0) return false;
+
+    while (extensions[0]) {
+        char* comma = strchr(extensions, ',');
+        size_t length = (comma ? comma - extensions : strlen(extensions));
+        if (length == strlen(extension) && strncasecmp(extension, extensions, length) == 0) return true;
+        extensions += length;
+        if (extensions[0] == ',') ++extensions;
+    }
+
+    return false;
+}
+
+status_t MediaScanner::doProcessDirectory(
+        char *path, int pathRemaining, const char *extensions,
+        MediaScannerClient &client, ExceptionCheck exceptionCheck,
+        void *exceptionEnv) {
+    // place to copy file or directory name
+    char* fileSpot = path + strlen(path);
+    struct dirent* entry;
+
+    // ignore directories that contain a  ".nomedia" file
+    if (pathRemaining >= 8 /* strlen(".nomedia") */ ) {
+        strcpy(fileSpot, ".nomedia");
+        if (access(path, F_OK) == 0) {
+            LOGD("found .nomedia, skipping directory\n");
+            fileSpot[0] = 0;
+            client.addNoMediaFolder(path);
+            return OK;
+        }
+
+        // restore path
+        fileSpot[0] = 0;
+    }
+
+    DIR* dir = opendir(path);
+    if (!dir) {
+        LOGD("opendir %s failed, errno: %d", path, errno);
+        return UNKNOWN_ERROR;
+    }
+
+    while ((entry = readdir(dir))) {
+        const char* name = entry->d_name;
+
+        // ignore "." and ".."
+        if (name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0))) {
+            continue;
+        }
+
+        int type = entry->d_type;
+        if (type == DT_UNKNOWN) {
+            // If the type is unknown, stat() the file instead.
+            // This is sometimes necessary when accessing NFS mounted filesystems, but
+            // could be needed in other cases well.
+            struct stat statbuf;
+            if (stat(path, &statbuf) == 0) {
+                if (S_ISREG(statbuf.st_mode)) {
+                    type = DT_REG;
+                } else if (S_ISDIR(statbuf.st_mode)) {
+                    type = DT_DIR;
+                }
+            } else {
+                LOGD("stat() failed for %s: %s", path, strerror(errno) );
+            }
+        }
+        if (type == DT_REG || type == DT_DIR) {
+            int nameLength = strlen(name);
+            bool isDirectory = (type == DT_DIR);
+
+            if (nameLength > pathRemaining || (isDirectory && nameLength + 1 > pathRemaining)) {
+                // path too long!
+                continue;
+            }
+
+            strcpy(fileSpot, name);
+            if (isDirectory) {
+                // ignore directories with a name that starts with '.'
+                // for example, the Mac ".Trashes" directory
+                if (name[0] == '.') continue;
+
+                strcat(fileSpot, "/");
+                int err = doProcessDirectory(path, pathRemaining - nameLength - 1, extensions, client, exceptionCheck, exceptionEnv);
+                if (err) {
+                    // pass exceptions up - ignore other errors
+                    if (exceptionCheck && exceptionCheck(exceptionEnv)) goto failure;
+                    LOGE("Error processing '%s' - skipping\n", path);
+                    continue;
+                }
+            } else if (fileMatchesExtension(path, extensions)) {
+                struct stat statbuf;
+                stat(path, &statbuf);
+                if (statbuf.st_size > 0) {
+                    client.scanFile(path, statbuf.st_mtime, statbuf.st_size);
+                }
+                if (exceptionCheck && exceptionCheck(exceptionEnv)) goto failure;
+            }
+        }
+    }
+
+    closedir(dir);
+    return OK;
+failure:
+    closedir(dir);
+    return -1;
+}
+
+}  // namespace android
diff --git a/media/libmedia/MediaScannerClient.cpp b/media/libmedia/MediaScannerClient.cpp
new file mode 100644
index 0000000..bd3596e
--- /dev/null
+++ b/media/libmedia/MediaScannerClient.cpp
@@ -0,0 +1,228 @@
+/*
+ * 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 <media/mediascanner.h>
+
+#include <utils/StringArray.h>
+
+#include "autodetect.h"
+#include "unicode/ucnv.h"
+#include "unicode/ustring.h"
+
+namespace android {
+
+MediaScannerClient::MediaScannerClient()
+    :   mNames(NULL),
+        mValues(NULL),
+        mLocaleEncoding(kEncodingNone)
+{
+}
+
+MediaScannerClient::~MediaScannerClient()
+{
+    delete mNames;
+    delete mValues;
+}
+
+void MediaScannerClient::setLocale(const char* locale)
+{
+    if (!locale) return;
+
+    if (!strncmp(locale, "ja", 2))
+        mLocaleEncoding = kEncodingShiftJIS;
+    else if (!strncmp(locale, "ko", 2))
+        mLocaleEncoding = kEncodingEUCKR;
+    else if (!strncmp(locale, "zh", 2)) {
+        if (!strcmp(locale, "zh_CN")) {
+            // simplified chinese for mainland China
+            mLocaleEncoding = kEncodingGBK;
+        } else {
+            // assume traditional for non-mainland Chinese locales (Taiwan, Hong Kong, Singapore)
+            mLocaleEncoding = kEncodingBig5;
+        }
+    }
+}
+
+void MediaScannerClient::beginFile()
+{
+    mNames = new StringArray;
+    mValues = new StringArray;
+}
+
+bool MediaScannerClient::addStringTag(const char* name, const char* value)
+{
+    if (mLocaleEncoding != kEncodingNone) {
+        // don't bother caching strings that are all ASCII.
+        // call handleStringTag directly instead.
+        // check to see if value (which should be utf8) has any non-ASCII characters
+        bool nonAscii = false;
+        const char* chp = value;
+        char ch;
+        while ((ch = *chp++)) {
+            if (ch & 0x80) {
+                nonAscii = true;
+                break;
+            }
+        }
+
+        if (nonAscii) {
+            // save the strings for later so they can be used for native encoding detection
+            mNames->push_back(name);
+            mValues->push_back(value);
+            return true;
+        }
+        // else fall through
+    }
+
+    // autodetection is not necessary, so no need to cache the values
+    // pass directly to the client instead
+    return handleStringTag(name, value);
+}
+
+static uint32_t possibleEncodings(const char* s)
+{
+    uint32_t result = kEncodingAll;
+    // if s contains a native encoding, then it was mistakenly encoded in utf8 as if it were latin-1
+    // so we need to reverse the latin-1 -> utf8 conversion to get the native chars back
+    uint8_t ch1, ch2;
+    uint8_t* chp = (uint8_t *)s;
+
+    while ((ch1 = *chp++)) {
+        if (ch1 & 0x80) {
+            ch2 = *chp++;
+            ch1 = ((ch1 << 6) & 0xC0) | (ch2 & 0x3F);
+            // ch1 is now the first byte of the potential native char
+
+            ch2 = *chp++;
+            if (ch2 & 0x80)
+                ch2 = ((ch2 << 6) & 0xC0) | (*chp++ & 0x3F);
+            // ch2 is now the second byte of the potential native char
+            int ch = (int)ch1 << 8 | (int)ch2;
+            result &= findPossibleEncodings(ch);
+        }
+        // else ASCII character, which could be anything
+    }
+
+    return result;
+}
+
+void MediaScannerClient::convertValues(uint32_t encoding)
+{
+    const char* enc = NULL;
+    switch (encoding) {
+        case kEncodingShiftJIS:
+            enc = "shift-jis";
+            break;
+        case kEncodingGBK:
+            enc = "gbk";
+            break;
+        case kEncodingBig5:
+            enc = "Big5";
+            break;
+        case kEncodingEUCKR:
+            enc = "EUC-KR";
+            break;
+    }
+
+    if (enc) {
+        UErrorCode status = U_ZERO_ERROR;
+
+        UConverter *conv = ucnv_open(enc, &status);
+        if (U_FAILURE(status)) {
+            LOGE("could not create UConverter for %s\n", enc);
+            return;
+        }
+        UConverter *utf8Conv = ucnv_open("UTF-8", &status);
+        if (U_FAILURE(status)) {
+            LOGE("could not create UConverter for UTF-8\n");
+            ucnv_close(conv);
+            return;
+        }
+
+        // for each value string, convert from native encoding to UTF-8
+        for (int i = 0; i < mNames->size(); i++) {
+            // first we need to untangle the utf8 and convert it back to the original bytes
+            // since we are reducing the length of the string, we can do this in place
+            uint8_t* src = (uint8_t *)mValues->getEntry(i);
+            int len = strlen((char *)src);
+            uint8_t* dest = src;
+
+            uint8_t uch;
+            while ((uch = *src++)) {
+                if (uch & 0x80)
+                    *dest++ = ((uch << 6) & 0xC0) | (*src++ & 0x3F);
+                else
+                    *dest++ = uch;
+            }
+            *dest = 0;
+
+            // now convert from native encoding to UTF-8
+            const char* source = mValues->getEntry(i);
+            int targetLength = len * 3 + 1;
+            char* buffer = new char[targetLength];
+            if (!buffer)
+                break;
+            char* target = buffer;
+
+            ucnv_convertEx(utf8Conv, conv, &target, target + targetLength,
+                    &source, (const char *)dest, NULL, NULL, NULL, NULL, TRUE, TRUE, &status);
+            if (U_FAILURE(status)) {
+                LOGE("ucnv_convertEx failed: %d\n", status);
+                mValues->setEntry(i, "???");
+            } else {
+                // zero terminate
+                *target = 0;
+                mValues->setEntry(i, buffer);
+            }
+
+            delete[] buffer;
+        }
+
+        ucnv_close(conv);
+        ucnv_close(utf8Conv);
+    }
+}
+
+void MediaScannerClient::endFile()
+{
+    if (mLocaleEncoding != kEncodingNone) {
+        int size = mNames->size();
+        uint32_t encoding = kEncodingAll;
+
+        // compute a bit mask containing all possible encodings
+        for (int i = 0; i < mNames->size(); i++)
+            encoding &= possibleEncodings(mValues->getEntry(i));
+
+        // if the locale encoding matches, then assume we have a native encoding.
+        if (encoding & mLocaleEncoding)
+            convertValues(mLocaleEncoding);
+
+        // finally, push all name/value pairs to the client
+        for (int i = 0; i < mNames->size(); i++) {
+            if (!handleStringTag(mNames->getEntry(i), mValues->getEntry(i)))
+                break;
+        }
+    }
+    // else addStringTag() has done all the work so we have nothing to do
+
+    delete mNames;
+    delete mValues;
+    mNames = NULL;
+    mValues = NULL;
+}
+
+}  // namespace android
+
diff --git a/media/libmedia/StagefrightMediaScanner.cpp b/media/libmedia/StagefrightMediaScanner.cpp
new file mode 100644
index 0000000..522ab5a
--- /dev/null
+++ b/media/libmedia/StagefrightMediaScanner.cpp
@@ -0,0 +1,39 @@
+/*
+ * 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 "StagefrightMediaScanner.h"
+
+namespace android {
+
+StagefrightMediaScanner::StagefrightMediaScanner() {}
+
+StagefrightMediaScanner::~StagefrightMediaScanner() {}
+
+status_t StagefrightMediaScanner::processFile(
+        const char *path, const char *mimeType,
+        MediaScannerClient &client) {
+    client.setLocale(locale());
+    client.beginFile();
+    client.endFile();
+
+    return OK;
+}
+
+char *StagefrightMediaScanner::extractAlbumArt(int fd) {
+    return NULL;
+}
+
+}  // namespace android
diff --git a/media/libmedia/StagefrightMediaScanner.h b/media/libmedia/StagefrightMediaScanner.h
new file mode 100644
index 0000000..108acb4
--- /dev/null
+++ b/media/libmedia/StagefrightMediaScanner.h
@@ -0,0 +1,42 @@
+/*
+ * 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 STAGEFRIGHT_MEDIA_SCANNER_H_
+
+#define STAGEFRIGHT_MEDIA_SCANNER_H_
+
+#include <media/mediascanner.h>
+
+namespace android {
+
+struct StagefrightMediaScanner : public MediaScanner {
+    StagefrightMediaScanner();
+    virtual ~StagefrightMediaScanner();
+
+    virtual status_t processFile(
+            const char *path, const char *mimeType,
+            MediaScannerClient &client);
+
+    virtual char *extractAlbumArt(int fd);
+
+private:
+    StagefrightMediaScanner(const StagefrightMediaScanner &);
+    StagefrightMediaScanner &operator=(const StagefrightMediaScanner &);
+};
+
+}  // namespace android
+
+#endif  // STAGEFRIGHT_MEDIA_SCANNER_H_
diff --git a/media/libmedia/ToneGenerator.cpp b/media/libmedia/ToneGenerator.cpp
index 60e3d71..82fe2d4 100644
--- a/media/libmedia/ToneGenerator.cpp
+++ b/media/libmedia/ToneGenerator.cpp
@@ -224,7 +224,8 @@
                       { duration: 0 , waveFreq: { 0 }, 0, 0}},
           repeatCnt: 2,
           repeatSegment: 0 },                              // TONE_CDMA_CONFIRM
-        { segments: { { duration: 0, waveFreq: { 0 }, 0, 0 }},
+        { segments: { { duration: 500, waveFreq: { 660, 1000, 0 }, 0, 0 },
+                      { duration: 0 , waveFreq: { 0 }, 0, 0}},
           repeatCnt: 0,
           repeatSegment: 0 },                              // TONE_CDMA_ANSWER
         { segments: { { duration: 300, waveFreq: { 440, 0 }, 0, 0 },
diff --git a/media/libmedia/autodetect.cpp b/media/libmedia/autodetect.cpp
new file mode 100644
index 0000000..dfcc6a0
--- /dev/null
+++ b/media/libmedia/autodetect.cpp
@@ -0,0 +1,885 @@
+/*
+ * Copyright (C) 2008 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 "autodetect.h"
+
+typedef struct CharRange {
+    uint16_t first;
+    uint16_t last;
+};
+
+#define ARRAY_SIZE(x)   (sizeof(x) / sizeof(*x))
+
+// generated from http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP932.TXT
+static const CharRange kShiftJISRanges[] = {
+    { 0x8140, 0x817E },
+    { 0x8180, 0x81AC },
+    { 0x81B8, 0x81BF },
+    { 0x81C8, 0x81CE },
+    { 0x81DA, 0x81E8 },
+    { 0x81F0, 0x81F7 },
+    { 0x81FC, 0x81FC },
+    { 0x824F, 0x8258 },
+    { 0x8260, 0x8279 },
+    { 0x8281, 0x829A },
+    { 0x829F, 0x82F1 },
+    { 0x8340, 0x837E },
+    { 0x8380, 0x8396 },
+    { 0x839F, 0x83B6 },
+    { 0x83BF, 0x83D6 },
+    { 0x8440, 0x8460 },
+    { 0x8470, 0x847E },
+    { 0x8480, 0x8491 },
+    { 0x849F, 0x84BE },
+    { 0x8740, 0x875D },
+    { 0x875F, 0x8775 },
+    { 0x877E, 0x877E },
+    { 0x8780, 0x879C },
+    { 0x889F, 0x88FC },
+    { 0x8940, 0x897E },
+    { 0x8980, 0x89FC },
+    { 0x8A40, 0x8A7E },
+    { 0x8A80, 0x8AFC },
+    { 0x8B40, 0x8B7E },
+    { 0x8B80, 0x8BFC },
+    { 0x8C40, 0x8C7E },
+    { 0x8C80, 0x8CFC },
+    { 0x8D40, 0x8D7E },
+    { 0x8D80, 0x8DFC },
+    { 0x8E40, 0x8E7E },
+    { 0x8E80, 0x8EFC },
+    { 0x8F40, 0x8F7E },
+    { 0x8F80, 0x8FFC },
+    { 0x9040, 0x907E },
+    { 0x9080, 0x90FC },
+    { 0x9140, 0x917E },
+    { 0x9180, 0x91FC },
+    { 0x9240, 0x927E },
+    { 0x9280, 0x92FC },
+    { 0x9340, 0x937E },
+    { 0x9380, 0x93FC },
+    { 0x9440, 0x947E },
+    { 0x9480, 0x94FC },
+    { 0x9540, 0x957E },
+    { 0x9580, 0x95FC },
+    { 0x9640, 0x967E },
+    { 0x9680, 0x96FC },
+    { 0x9740, 0x977E },
+    { 0x9780, 0x97FC },
+    { 0x9840, 0x9872 },
+    { 0x989F, 0x98FC },
+    { 0x9940, 0x997E },
+    { 0x9980, 0x99FC },
+    { 0x9A40, 0x9A7E },
+    { 0x9A80, 0x9AFC },
+    { 0x9B40, 0x9B7E },
+    { 0x9B80, 0x9BFC },
+    { 0x9C40, 0x9C7E },
+    { 0x9C80, 0x9CFC },
+    { 0x9D40, 0x9D7E },
+    { 0x9D80, 0x9DFC },
+    { 0x9E40, 0x9E7E },
+    { 0x9E80, 0x9EFC },
+    { 0x9F40, 0x9F7E },
+    { 0x9F80, 0x9FFC },
+    { 0xE040, 0xE07E },
+    { 0xE080, 0xE0FC },
+    { 0xE140, 0xE17E },
+    { 0xE180, 0xE1FC },
+    { 0xE240, 0xE27E },
+    { 0xE280, 0xE2FC },
+    { 0xE340, 0xE37E },
+    { 0xE380, 0xE3FC },
+    { 0xE440, 0xE47E },
+    { 0xE480, 0xE4FC },
+    { 0xE540, 0xE57E },
+    { 0xE580, 0xE5FC },
+    { 0xE640, 0xE67E },
+    { 0xE680, 0xE6FC },
+    { 0xE740, 0xE77E },
+    { 0xE780, 0xE7FC },
+    { 0xE840, 0xE87E },
+    { 0xE880, 0xE8FC },
+    { 0xE940, 0xE97E },
+    { 0xE980, 0xE9FC },
+    { 0xEA40, 0xEA7E },
+    { 0xEA80, 0xEAA4 },
+    { 0xED40, 0xED7E },
+    { 0xED80, 0xEDFC },
+    { 0xEE40, 0xEE7E },
+    { 0xEE80, 0xEEEC },
+    { 0xEEEF, 0xEEFC },
+    { 0xFA40, 0xFA7E },
+    { 0xFA80, 0xFAFC },
+    { 0xFB40, 0xFB7E },
+    { 0xFB80, 0xFBFC },
+    { 0xFC40, 0xFC4B },
+};
+
+// generated from http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP936.TXT
+static const CharRange kGBKRanges[] = {
+    { 0x8140, 0x817E },
+    { 0x8180, 0x81FE },
+    { 0x8240, 0x827E },
+    { 0x8280, 0x82FE },
+    { 0x8340, 0x837E },
+    { 0x8380, 0x83FE },
+    { 0x8440, 0x847E },
+    { 0x8480, 0x84FE },
+    { 0x8540, 0x857E },
+    { 0x8580, 0x85FE },
+    { 0x8640, 0x867E },
+    { 0x8680, 0x86FE },
+    { 0x8740, 0x877E },
+    { 0x8780, 0x87FE },
+    { 0x8840, 0x887E },
+    { 0x8880, 0x88FE },
+    { 0x8940, 0x897E },
+    { 0x8980, 0x89FE },
+    { 0x8A40, 0x8A7E },
+    { 0x8A80, 0x8AFE },
+    { 0x8B40, 0x8B7E },
+    { 0x8B80, 0x8BFE },
+    { 0x8C40, 0x8C7E },
+    { 0x8C80, 0x8CFE },
+    { 0x8D40, 0x8D7E },
+    { 0x8D80, 0x8DFE },
+    { 0x8E40, 0x8E7E },
+    { 0x8E80, 0x8EFE },
+    { 0x8F40, 0x8F7E },
+    { 0x8F80, 0x8FFE },
+    { 0x9040, 0x907E },
+    { 0x9080, 0x90FE },
+    { 0x9140, 0x917E },
+    { 0x9180, 0x91FE },
+    { 0x9240, 0x927E },
+    { 0x9280, 0x92FE },
+    { 0x9340, 0x937E },
+    { 0x9380, 0x93FE },
+    { 0x9440, 0x947E },
+    { 0x9480, 0x94FE },
+    { 0x9540, 0x957E },
+    { 0x9580, 0x95FE },
+    { 0x9640, 0x967E },
+    { 0x9680, 0x96FE },
+    { 0x9740, 0x977E },
+    { 0x9780, 0x97FE },
+    { 0x9840, 0x987E },
+    { 0x9880, 0x98FE },
+    { 0x9940, 0x997E },
+    { 0x9980, 0x99FE },
+    { 0x9A40, 0x9A7E },
+    { 0x9A80, 0x9AFE },
+    { 0x9B40, 0x9B7E },
+    { 0x9B80, 0x9BFE },
+    { 0x9C40, 0x9C7E },
+    { 0x9C80, 0x9CFE },
+    { 0x9D40, 0x9D7E },
+    { 0x9D80, 0x9DFE },
+    { 0x9E40, 0x9E7E },
+    { 0x9E80, 0x9EFE },
+    { 0x9F40, 0x9F7E },
+    { 0x9F80, 0x9FFE },
+    { 0xA040, 0xA07E },
+    { 0xA080, 0xA0FE },
+    { 0xA1A1, 0xA1FE },
+    { 0xA2A1, 0xA2AA },
+    { 0xA2B1, 0xA2E2 },
+    { 0xA2E5, 0xA2EE },
+    { 0xA2F1, 0xA2FC },
+    { 0xA3A1, 0xA3FE },
+    { 0xA4A1, 0xA4F3 },
+    { 0xA5A1, 0xA5F6 },
+    { 0xA6A1, 0xA6B8 },
+    { 0xA6C1, 0xA6D8 },
+    { 0xA6E0, 0xA6EB },
+    { 0xA6EE, 0xA6F2 },
+    { 0xA6F4, 0xA6F5 },
+    { 0xA7A1, 0xA7C1 },
+    { 0xA7D1, 0xA7F1 },
+    { 0xA840, 0xA87E },
+    { 0xA880, 0xA895 },
+    { 0xA8A1, 0xA8BB },
+    { 0xA8BD, 0xA8BE },
+    { 0xA8C0, 0xA8C0 },
+    { 0xA8C5, 0xA8E9 },
+    { 0xA940, 0xA957 },
+    { 0xA959, 0xA95A },
+    { 0xA95C, 0xA95C },
+    { 0xA960, 0xA97E },
+    { 0xA980, 0xA988 },
+    { 0xA996, 0xA996 },
+    { 0xA9A4, 0xA9EF },
+    { 0xAA40, 0xAA7E },
+    { 0xAA80, 0xAAA0 },
+    { 0xAB40, 0xAB7E },
+    { 0xAB80, 0xABA0 },
+    { 0xAC40, 0xAC7E },
+    { 0xAC80, 0xACA0 },
+    { 0xAD40, 0xAD7E },
+    { 0xAD80, 0xADA0 },
+    { 0xAE40, 0xAE7E },
+    { 0xAE80, 0xAEA0 },
+    { 0xAF40, 0xAF7E },
+    { 0xAF80, 0xAFA0 },
+    { 0xB040, 0xB07E },
+    { 0xB080, 0xB0FE },
+    { 0xB140, 0xB17E },
+    { 0xB180, 0xB1FE },
+    { 0xB240, 0xB27E },
+    { 0xB280, 0xB2FE },
+    { 0xB340, 0xB37E },
+    { 0xB380, 0xB3FE },
+    { 0xB440, 0xB47E },
+    { 0xB480, 0xB4FE },
+    { 0xB540, 0xB57E },
+    { 0xB580, 0xB5FE },
+    { 0xB640, 0xB67E },
+    { 0xB680, 0xB6FE },
+    { 0xB740, 0xB77E },
+    { 0xB780, 0xB7FE },
+    { 0xB840, 0xB87E },
+    { 0xB880, 0xB8FE },
+    { 0xB940, 0xB97E },
+    { 0xB980, 0xB9FE },
+    { 0xBA40, 0xBA7E },
+    { 0xBA80, 0xBAFE },
+    { 0xBB40, 0xBB7E },
+    { 0xBB80, 0xBBFE },
+    { 0xBC40, 0xBC7E },
+    { 0xBC80, 0xBCFE },
+    { 0xBD40, 0xBD7E },
+    { 0xBD80, 0xBDFE },
+    { 0xBE40, 0xBE7E },
+    { 0xBE80, 0xBEFE },
+    { 0xBF40, 0xBF7E },
+    { 0xBF80, 0xBFFE },
+    { 0xC040, 0xC07E },
+    { 0xC080, 0xC0FE },
+    { 0xC140, 0xC17E },
+    { 0xC180, 0xC1FE },
+    { 0xC240, 0xC27E },
+    { 0xC280, 0xC2FE },
+    { 0xC340, 0xC37E },
+    { 0xC380, 0xC3FE },
+    { 0xC440, 0xC47E },
+    { 0xC480, 0xC4FE },
+    { 0xC540, 0xC57E },
+    { 0xC580, 0xC5FE },
+    { 0xC640, 0xC67E },
+    { 0xC680, 0xC6FE },
+    { 0xC740, 0xC77E },
+    { 0xC780, 0xC7FE },
+    { 0xC840, 0xC87E },
+    { 0xC880, 0xC8FE },
+    { 0xC940, 0xC97E },
+    { 0xC980, 0xC9FE },
+    { 0xCA40, 0xCA7E },
+    { 0xCA80, 0xCAFE },
+    { 0xCB40, 0xCB7E },
+    { 0xCB80, 0xCBFE },
+    { 0xCC40, 0xCC7E },
+    { 0xCC80, 0xCCFE },
+    { 0xCD40, 0xCD7E },
+    { 0xCD80, 0xCDFE },
+    { 0xCE40, 0xCE7E },
+    { 0xCE80, 0xCEFE },
+    { 0xCF40, 0xCF7E },
+    { 0xCF80, 0xCFFE },
+    { 0xD040, 0xD07E },
+    { 0xD080, 0xD0FE },
+    { 0xD140, 0xD17E },
+    { 0xD180, 0xD1FE },
+    { 0xD240, 0xD27E },
+    { 0xD280, 0xD2FE },
+    { 0xD340, 0xD37E },
+    { 0xD380, 0xD3FE },
+    { 0xD440, 0xD47E },
+    { 0xD480, 0xD4FE },
+    { 0xD540, 0xD57E },
+    { 0xD580, 0xD5FE },
+    { 0xD640, 0xD67E },
+    { 0xD680, 0xD6FE },
+    { 0xD740, 0xD77E },
+    { 0xD780, 0xD7F9 },
+    { 0xD840, 0xD87E },
+    { 0xD880, 0xD8FE },
+    { 0xD940, 0xD97E },
+    { 0xD980, 0xD9FE },
+    { 0xDA40, 0xDA7E },
+    { 0xDA80, 0xDAFE },
+    { 0xDB40, 0xDB7E },
+    { 0xDB80, 0xDBFE },
+    { 0xDC40, 0xDC7E },
+    { 0xDC80, 0xDCFE },
+    { 0xDD40, 0xDD7E },
+    { 0xDD80, 0xDDFE },
+    { 0xDE40, 0xDE7E },
+    { 0xDE80, 0xDEFE },
+    { 0xDF40, 0xDF7E },
+    { 0xDF80, 0xDFFE },
+    { 0xE040, 0xE07E },
+    { 0xE080, 0xE0FE },
+    { 0xE140, 0xE17E },
+    { 0xE180, 0xE1FE },
+    { 0xE240, 0xE27E },
+    { 0xE280, 0xE2FE },
+    { 0xE340, 0xE37E },
+    { 0xE380, 0xE3FE },
+    { 0xE440, 0xE47E },
+    { 0xE480, 0xE4FE },
+    { 0xE540, 0xE57E },
+    { 0xE580, 0xE5FE },
+    { 0xE640, 0xE67E },
+    { 0xE680, 0xE6FE },
+    { 0xE740, 0xE77E },
+    { 0xE780, 0xE7FE },
+    { 0xE840, 0xE87E },
+    { 0xE880, 0xE8FE },
+    { 0xE940, 0xE97E },
+    { 0xE980, 0xE9FE },
+    { 0xEA40, 0xEA7E },
+    { 0xEA80, 0xEAFE },
+    { 0xEB40, 0xEB7E },
+    { 0xEB80, 0xEBFE },
+    { 0xEC40, 0xEC7E },
+    { 0xEC80, 0xECFE },
+    { 0xED40, 0xED7E },
+    { 0xED80, 0xEDFE },
+    { 0xEE40, 0xEE7E },
+    { 0xEE80, 0xEEFE },
+    { 0xEF40, 0xEF7E },
+    { 0xEF80, 0xEFFE },
+    { 0xF040, 0xF07E },
+    { 0xF080, 0xF0FE },
+    { 0xF140, 0xF17E },
+    { 0xF180, 0xF1FE },
+    { 0xF240, 0xF27E },
+    { 0xF280, 0xF2FE },
+    { 0xF340, 0xF37E },
+    { 0xF380, 0xF3FE },
+    { 0xF440, 0xF47E },
+    { 0xF480, 0xF4FE },
+    { 0xF540, 0xF57E },
+    { 0xF580, 0xF5FE },
+    { 0xF640, 0xF67E },
+    { 0xF680, 0xF6FE },
+    { 0xF740, 0xF77E },
+    { 0xF780, 0xF7FE },
+    { 0xF840, 0xF87E },
+    { 0xF880, 0xF8A0 },
+    { 0xF940, 0xF97E },
+    { 0xF980, 0xF9A0 },
+    { 0xFA40, 0xFA7E },
+    { 0xFA80, 0xFAA0 },
+    { 0xFB40, 0xFB7E },
+    { 0xFB80, 0xFBA0 },
+    { 0xFC40, 0xFC7E },
+    { 0xFC80, 0xFCA0 },
+    { 0xFD40, 0xFD7E },
+    { 0xFD80, 0xFDA0 },
+    { 0xFE40, 0xFE4F },
+};
+
+// generated from http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP949.TXT
+static const CharRange kEUCKRRanges[] = {
+    { 0x8141, 0x815A },
+    { 0x8161, 0x817A },
+    { 0x8181, 0x81FE },
+    { 0x8241, 0x825A },
+    { 0x8261, 0x827A },
+    { 0x8281, 0x82FE },
+    { 0x8341, 0x835A },
+    { 0x8361, 0x837A },
+    { 0x8381, 0x83FE },
+    { 0x8441, 0x845A },
+    { 0x8461, 0x847A },
+    { 0x8481, 0x84FE },
+    { 0x8541, 0x855A },
+    { 0x8561, 0x857A },
+    { 0x8581, 0x85FE },
+    { 0x8641, 0x865A },
+    { 0x8661, 0x867A },
+    { 0x8681, 0x86FE },
+    { 0x8741, 0x875A },
+    { 0x8761, 0x877A },
+    { 0x8781, 0x87FE },
+    { 0x8841, 0x885A },
+    { 0x8861, 0x887A },
+    { 0x8881, 0x88FE },
+    { 0x8941, 0x895A },
+    { 0x8961, 0x897A },
+    { 0x8981, 0x89FE },
+    { 0x8A41, 0x8A5A },
+    { 0x8A61, 0x8A7A },
+    { 0x8A81, 0x8AFE },
+    { 0x8B41, 0x8B5A },
+    { 0x8B61, 0x8B7A },
+    { 0x8B81, 0x8BFE },
+    { 0x8C41, 0x8C5A },
+    { 0x8C61, 0x8C7A },
+    { 0x8C81, 0x8CFE },
+    { 0x8D41, 0x8D5A },
+    { 0x8D61, 0x8D7A },
+    { 0x8D81, 0x8DFE },
+    { 0x8E41, 0x8E5A },
+    { 0x8E61, 0x8E7A },
+    { 0x8E81, 0x8EFE },
+    { 0x8F41, 0x8F5A },
+    { 0x8F61, 0x8F7A },
+    { 0x8F81, 0x8FFE },
+    { 0x9041, 0x905A },
+    { 0x9061, 0x907A },
+    { 0x9081, 0x90FE },
+    { 0x9141, 0x915A },
+    { 0x9161, 0x917A },
+    { 0x9181, 0x91FE },
+    { 0x9241, 0x925A },
+    { 0x9261, 0x927A },
+    { 0x9281, 0x92FE },
+    { 0x9341, 0x935A },
+    { 0x9361, 0x937A },
+    { 0x9381, 0x93FE },
+    { 0x9441, 0x945A },
+    { 0x9461, 0x947A },
+    { 0x9481, 0x94FE },
+    { 0x9541, 0x955A },
+    { 0x9561, 0x957A },
+    { 0x9581, 0x95FE },
+    { 0x9641, 0x965A },
+    { 0x9661, 0x967A },
+    { 0x9681, 0x96FE },
+    { 0x9741, 0x975A },
+    { 0x9761, 0x977A },
+    { 0x9781, 0x97FE },
+    { 0x9841, 0x985A },
+    { 0x9861, 0x987A },
+    { 0x9881, 0x98FE },
+    { 0x9941, 0x995A },
+    { 0x9961, 0x997A },
+    { 0x9981, 0x99FE },
+    { 0x9A41, 0x9A5A },
+    { 0x9A61, 0x9A7A },
+    { 0x9A81, 0x9AFE },
+    { 0x9B41, 0x9B5A },
+    { 0x9B61, 0x9B7A },
+    { 0x9B81, 0x9BFE },
+    { 0x9C41, 0x9C5A },
+    { 0x9C61, 0x9C7A },
+    { 0x9C81, 0x9CFE },
+    { 0x9D41, 0x9D5A },
+    { 0x9D61, 0x9D7A },
+    { 0x9D81, 0x9DFE },
+    { 0x9E41, 0x9E5A },
+    { 0x9E61, 0x9E7A },
+    { 0x9E81, 0x9EFE },
+    { 0x9F41, 0x9F5A },
+    { 0x9F61, 0x9F7A },
+    { 0x9F81, 0x9FFE },
+    { 0xA041, 0xA05A },
+    { 0xA061, 0xA07A },
+    { 0xA081, 0xA0FE },
+    { 0xA141, 0xA15A },
+    { 0xA161, 0xA17A },
+    { 0xA181, 0xA1FE },
+    { 0xA241, 0xA25A },
+    { 0xA261, 0xA27A },
+    { 0xA281, 0xA2E7 },
+    { 0xA341, 0xA35A },
+    { 0xA361, 0xA37A },
+    { 0xA381, 0xA3FE },
+    { 0xA441, 0xA45A },
+    { 0xA461, 0xA47A },
+    { 0xA481, 0xA4FE },
+    { 0xA541, 0xA55A },
+    { 0xA561, 0xA57A },
+    { 0xA581, 0xA5AA },
+    { 0xA5B0, 0xA5B9 },
+    { 0xA5C1, 0xA5D8 },
+    { 0xA5E1, 0xA5F8 },
+    { 0xA641, 0xA65A },
+    { 0xA661, 0xA67A },
+    { 0xA681, 0xA6E4 },
+    { 0xA741, 0xA75A },
+    { 0xA761, 0xA77A },
+    { 0xA781, 0xA7EF },
+    { 0xA841, 0xA85A },
+    { 0xA861, 0xA87A },
+    { 0xA881, 0xA8A4 },
+    { 0xA8A6, 0xA8A6 },
+    { 0xA8A8, 0xA8AF },
+    { 0xA8B1, 0xA8FE },
+    { 0xA941, 0xA95A },
+    { 0xA961, 0xA97A },
+    { 0xA981, 0xA9FE },
+    { 0xAA41, 0xAA5A },
+    { 0xAA61, 0xAA7A },
+    { 0xAA81, 0xAAF3 },
+    { 0xAB41, 0xAB5A },
+    { 0xAB61, 0xAB7A },
+    { 0xAB81, 0xABF6 },
+    { 0xAC41, 0xAC5A },
+    { 0xAC61, 0xAC7A },
+    { 0xAC81, 0xACC1 },
+    { 0xACD1, 0xACF1 },
+    { 0xAD41, 0xAD5A },
+    { 0xAD61, 0xAD7A },
+    { 0xAD81, 0xADA0 },
+    { 0xAE41, 0xAE5A },
+    { 0xAE61, 0xAE7A },
+    { 0xAE81, 0xAEA0 },
+    { 0xAF41, 0xAF5A },
+    { 0xAF61, 0xAF7A },
+    { 0xAF81, 0xAFA0 },
+    { 0xB041, 0xB05A },
+    { 0xB061, 0xB07A },
+    { 0xB081, 0xB0FE },
+    { 0xB141, 0xB15A },
+    { 0xB161, 0xB17A },
+    { 0xB181, 0xB1FE },
+    { 0xB241, 0xB25A },
+    { 0xB261, 0xB27A },
+    { 0xB281, 0xB2FE },
+    { 0xB341, 0xB35A },
+    { 0xB361, 0xB37A },
+    { 0xB381, 0xB3FE },
+    { 0xB441, 0xB45A },
+    { 0xB461, 0xB47A },
+    { 0xB481, 0xB4FE },
+    { 0xB541, 0xB55A },
+    { 0xB561, 0xB57A },
+    { 0xB581, 0xB5FE },
+    { 0xB641, 0xB65A },
+    { 0xB661, 0xB67A },
+    { 0xB681, 0xB6FE },
+    { 0xB741, 0xB75A },
+    { 0xB761, 0xB77A },
+    { 0xB781, 0xB7FE },
+    { 0xB841, 0xB85A },
+    { 0xB861, 0xB87A },
+    { 0xB881, 0xB8FE },
+    { 0xB941, 0xB95A },
+    { 0xB961, 0xB97A },
+    { 0xB981, 0xB9FE },
+    { 0xBA41, 0xBA5A },
+    { 0xBA61, 0xBA7A },
+    { 0xBA81, 0xBAFE },
+    { 0xBB41, 0xBB5A },
+    { 0xBB61, 0xBB7A },
+    { 0xBB81, 0xBBFE },
+    { 0xBC41, 0xBC5A },
+    { 0xBC61, 0xBC7A },
+    { 0xBC81, 0xBCFE },
+    { 0xBD41, 0xBD5A },
+    { 0xBD61, 0xBD7A },
+    { 0xBD81, 0xBDFE },
+    { 0xBE41, 0xBE5A },
+    { 0xBE61, 0xBE7A },
+    { 0xBE81, 0xBEFE },
+    { 0xBF41, 0xBF5A },
+    { 0xBF61, 0xBF7A },
+    { 0xBF81, 0xBFFE },
+    { 0xC041, 0xC05A },
+    { 0xC061, 0xC07A },
+    { 0xC081, 0xC0FE },
+    { 0xC141, 0xC15A },
+    { 0xC161, 0xC17A },
+    { 0xC181, 0xC1FE },
+    { 0xC241, 0xC25A },
+    { 0xC261, 0xC27A },
+    { 0xC281, 0xC2FE },
+    { 0xC341, 0xC35A },
+    { 0xC361, 0xC37A },
+    { 0xC381, 0xC3FE },
+    { 0xC441, 0xC45A },
+    { 0xC461, 0xC47A },
+    { 0xC481, 0xC4FE },
+    { 0xC541, 0xC55A },
+    { 0xC561, 0xC57A },
+    { 0xC581, 0xC5FE },
+    { 0xC641, 0xC652 },
+    { 0xC6A1, 0xC6FE },
+    { 0xC7A1, 0xC7FE },
+    { 0xC8A1, 0xC8FE },
+    { 0xCAA1, 0xCAFE },
+    { 0xCBA1, 0xCBFE },
+    { 0xCCA1, 0xCCFE },
+    { 0xCDA1, 0xCDFE },
+    { 0xCEA1, 0xCEFE },
+    { 0xCFA1, 0xCFFE },
+    { 0xD0A1, 0xD0FE },
+    { 0xD1A1, 0xD1FE },
+    { 0xD2A1, 0xD2FE },
+    { 0xD3A1, 0xD3FE },
+    { 0xD4A1, 0xD4FE },
+    { 0xD5A1, 0xD5FE },
+    { 0xD6A1, 0xD6FE },
+    { 0xD7A1, 0xD7FE },
+    { 0xD8A1, 0xD8FE },
+    { 0xD9A1, 0xD9FE },
+    { 0xDAA1, 0xDAFE },
+    { 0xDBA1, 0xDBFE },
+    { 0xDCA1, 0xDCFE },
+    { 0xDDA1, 0xDDFE },
+    { 0xDEA1, 0xDEFE },
+    { 0xDFA1, 0xDFFE },
+    { 0xE0A1, 0xE0FE },
+    { 0xE1A1, 0xE1FE },
+    { 0xE2A1, 0xE2FE },
+    { 0xE3A1, 0xE3FE },
+    { 0xE4A1, 0xE4FE },
+    { 0xE5A1, 0xE5FE },
+    { 0xE6A1, 0xE6FE },
+    { 0xE7A1, 0xE7FE },
+    { 0xE8A1, 0xE8FE },
+    { 0xE9A1, 0xE9FE },
+    { 0xEAA1, 0xEAFE },
+    { 0xEBA1, 0xEBFE },
+    { 0xECA1, 0xECFE },
+    { 0xEDA1, 0xEDFE },
+    { 0xEEA1, 0xEEFE },
+    { 0xEFA1, 0xEFFE },
+    { 0xF0A1, 0xF0FE },
+    { 0xF1A1, 0xF1FE },
+    { 0xF2A1, 0xF2FE },
+    { 0xF3A1, 0xF3FE },
+    { 0xF4A1, 0xF4FE },
+    { 0xF5A1, 0xF5FE },
+    { 0xF6A1, 0xF6FE },
+    { 0xF7A1, 0xF7FE },
+    { 0xF8A1, 0xF8FE },
+    { 0xF9A1, 0xF9FE },
+    { 0xFAA1, 0xFAFE },
+    { 0xFBA1, 0xFBFE },
+    { 0xFCA1, 0xFCFE },
+    { 0xFDA1, 0xFDFE },
+};
+
+// generated from http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
+static const CharRange kBig5Ranges[] = {
+    { 0xA140, 0xA17E },
+    { 0xA1A1, 0xA1FE },
+    { 0xA240, 0xA27E },
+    { 0xA2A1, 0xA2FE },
+    { 0xA340, 0xA37E },
+    { 0xA3A1, 0xA3BF },
+    { 0xA3E1, 0xA3E1 },
+    { 0xA440, 0xA47E },
+    { 0xA4A1, 0xA4FE },
+    { 0xA540, 0xA57E },
+    { 0xA5A1, 0xA5FE },
+    { 0xA640, 0xA67E },
+    { 0xA6A1, 0xA6FE },
+    { 0xA740, 0xA77E },
+    { 0xA7A1, 0xA7FE },
+    { 0xA840, 0xA87E },
+    { 0xA8A1, 0xA8FE },
+    { 0xA940, 0xA97E },
+    { 0xA9A1, 0xA9FE },
+    { 0xAA40, 0xAA7E },
+    { 0xAAA1, 0xAAFE },
+    { 0xAB40, 0xAB7E },
+    { 0xABA1, 0xABFE },
+    { 0xAC40, 0xAC7E },
+    { 0xACA1, 0xACFE },
+    { 0xAD40, 0xAD7E },
+    { 0xADA1, 0xADFE },
+    { 0xAE40, 0xAE7E },
+    { 0xAEA1, 0xAEFE },
+    { 0xAF40, 0xAF7E },
+    { 0xAFA1, 0xAFFE },
+    { 0xB040, 0xB07E },
+    { 0xB0A1, 0xB0FE },
+    { 0xB140, 0xB17E },
+    { 0xB1A1, 0xB1FE },
+    { 0xB240, 0xB27E },
+    { 0xB2A1, 0xB2FE },
+    { 0xB340, 0xB37E },
+    { 0xB3A1, 0xB3FE },
+    { 0xB440, 0xB47E },
+    { 0xB4A1, 0xB4FE },
+    { 0xB540, 0xB57E },
+    { 0xB5A1, 0xB5FE },
+    { 0xB640, 0xB67E },
+    { 0xB6A1, 0xB6FE },
+    { 0xB740, 0xB77E },
+    { 0xB7A1, 0xB7FE },
+    { 0xB840, 0xB87E },
+    { 0xB8A1, 0xB8FE },
+    { 0xB940, 0xB97E },
+    { 0xB9A1, 0xB9FE },
+    { 0xBA40, 0xBA7E },
+    { 0xBAA1, 0xBAFE },
+    { 0xBB40, 0xBB7E },
+    { 0xBBA1, 0xBBFE },
+    { 0xBC40, 0xBC7E },
+    { 0xBCA1, 0xBCFE },
+    { 0xBD40, 0xBD7E },
+    { 0xBDA1, 0xBDFE },
+    { 0xBE40, 0xBE7E },
+    { 0xBEA1, 0xBEFE },
+    { 0xBF40, 0xBF7E },
+    { 0xBFA1, 0xBFFE },
+    { 0xC040, 0xC07E },
+    { 0xC0A1, 0xC0FE },
+    { 0xC140, 0xC17E },
+    { 0xC1A1, 0xC1FE },
+    { 0xC240, 0xC27E },
+    { 0xC2A1, 0xC2FE },
+    { 0xC340, 0xC37E },
+    { 0xC3A1, 0xC3FE },
+    { 0xC440, 0xC47E },
+    { 0xC4A1, 0xC4FE },
+    { 0xC540, 0xC57E },
+    { 0xC5A1, 0xC5FE },
+    { 0xC640, 0xC67E },
+    { 0xC940, 0xC97E },
+    { 0xC9A1, 0xC9FE },
+    { 0xCA40, 0xCA7E },
+    { 0xCAA1, 0xCAFE },
+    { 0xCB40, 0xCB7E },
+    { 0xCBA1, 0xCBFE },
+    { 0xCC40, 0xCC7E },
+    { 0xCCA1, 0xCCFE },
+    { 0xCD40, 0xCD7E },
+    { 0xCDA1, 0xCDFE },
+    { 0xCE40, 0xCE7E },
+    { 0xCEA1, 0xCEFE },
+    { 0xCF40, 0xCF7E },
+    { 0xCFA1, 0xCFFE },
+    { 0xD040, 0xD07E },
+    { 0xD0A1, 0xD0FE },
+    { 0xD140, 0xD17E },
+    { 0xD1A1, 0xD1FE },
+    { 0xD240, 0xD27E },
+    { 0xD2A1, 0xD2FE },
+    { 0xD340, 0xD37E },
+    { 0xD3A1, 0xD3FE },
+    { 0xD440, 0xD47E },
+    { 0xD4A1, 0xD4FE },
+    { 0xD540, 0xD57E },
+    { 0xD5A1, 0xD5FE },
+    { 0xD640, 0xD67E },
+    { 0xD6A1, 0xD6FE },
+    { 0xD740, 0xD77E },
+    { 0xD7A1, 0xD7FE },
+    { 0xD840, 0xD87E },
+    { 0xD8A1, 0xD8FE },
+    { 0xD940, 0xD97E },
+    { 0xD9A1, 0xD9FE },
+    { 0xDA40, 0xDA7E },
+    { 0xDAA1, 0xDAFE },
+    { 0xDB40, 0xDB7E },
+    { 0xDBA1, 0xDBFE },
+    { 0xDC40, 0xDC7E },
+    { 0xDCA1, 0xDCFE },
+    { 0xDD40, 0xDD7E },
+    { 0xDDA1, 0xDDFE },
+    { 0xDE40, 0xDE7E },
+    { 0xDEA1, 0xDEFE },
+    { 0xDF40, 0xDF7E },
+    { 0xDFA1, 0xDFFE },
+    { 0xE040, 0xE07E },
+    { 0xE0A1, 0xE0FE },
+    { 0xE140, 0xE17E },
+    { 0xE1A1, 0xE1FE },
+    { 0xE240, 0xE27E },
+    { 0xE2A1, 0xE2FE },
+    { 0xE340, 0xE37E },
+    { 0xE3A1, 0xE3FE },
+    { 0xE440, 0xE47E },
+    { 0xE4A1, 0xE4FE },
+    { 0xE540, 0xE57E },
+    { 0xE5A1, 0xE5FE },
+    { 0xE640, 0xE67E },
+    { 0xE6A1, 0xE6FE },
+    { 0xE740, 0xE77E },
+    { 0xE7A1, 0xE7FE },
+    { 0xE840, 0xE87E },
+    { 0xE8A1, 0xE8FE },
+    { 0xE940, 0xE97E },
+    { 0xE9A1, 0xE9FE },
+    { 0xEA40, 0xEA7E },
+    { 0xEAA1, 0xEAFE },
+    { 0xEB40, 0xEB7E },
+    { 0xEBA1, 0xEBFE },
+    { 0xEC40, 0xEC7E },
+    { 0xECA1, 0xECFE },
+    { 0xED40, 0xED7E },
+    { 0xEDA1, 0xEDFE },
+    { 0xEE40, 0xEE7E },
+    { 0xEEA1, 0xEEFE },
+    { 0xEF40, 0xEF7E },
+    { 0xEFA1, 0xEFFE },
+    { 0xF040, 0xF07E },
+    { 0xF0A1, 0xF0FE },
+    { 0xF140, 0xF17E },
+    { 0xF1A1, 0xF1FE },
+    { 0xF240, 0xF27E },
+    { 0xF2A1, 0xF2FE },
+    { 0xF340, 0xF37E },
+    { 0xF3A1, 0xF3FE },
+    { 0xF440, 0xF47E },
+    { 0xF4A1, 0xF4FE },
+    { 0xF540, 0xF57E },
+    { 0xF5A1, 0xF5FE },
+    { 0xF640, 0xF67E },
+    { 0xF6A1, 0xF6FE },
+    { 0xF740, 0xF77E },
+    { 0xF7A1, 0xF7FE },
+    { 0xF840, 0xF87E },
+    { 0xF8A1, 0xF8FE },
+    { 0xF940, 0xF97E },
+    { 0xF9A1, 0xF9FE },
+};
+
+static bool charMatchesEncoding(int ch, const CharRange* encodingRanges, int rangeCount) {
+    // Use binary search to see if the character is contained in the encoding
+    int low = 0;
+    int high = rangeCount;
+
+    while (low < high) {
+        int i = (low + high) / 2;
+        const CharRange* range = &encodingRanges[i];
+        if (ch >= range->first && ch <= range->last)
+            return true;
+        if (ch > range->last)
+            low = i + 1;
+        else
+            high = i;
+    }
+
+    return false;
+}
+
+extern uint32_t findPossibleEncodings(int ch)
+{
+    // ASCII matches everything
+    if (ch < 256) return kEncodingAll;
+
+    int result = kEncodingNone;
+
+    if (charMatchesEncoding(ch, kShiftJISRanges, ARRAY_SIZE(kShiftJISRanges)))
+        result |= kEncodingShiftJIS;
+    if (charMatchesEncoding(ch, kGBKRanges, ARRAY_SIZE(kGBKRanges)))
+        result |= kEncodingGBK;
+    if (charMatchesEncoding(ch, kBig5Ranges, ARRAY_SIZE(kBig5Ranges)))
+        result |= kEncodingBig5;
+    if (charMatchesEncoding(ch, kEUCKRRanges, ARRAY_SIZE(kEUCKRRanges)))
+        result |= kEncodingEUCKR;
+
+    return result;
+}
diff --git a/media/libmedia/autodetect.h b/media/libmedia/autodetect.h
new file mode 100644
index 0000000..9675db3
--- /dev/null
+++ b/media/libmedia/autodetect.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2008 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 AUTODETECT_H
+#define AUTODETECT_H
+
+#include <inttypes.h>
+
+// flags used for native encoding detection
+enum {
+    kEncodingNone               = 0,
+    kEncodingShiftJIS           = (1 << 0),
+    kEncodingGBK                = (1 << 1),
+    kEncodingBig5               = (1 << 2),
+    kEncodingEUCKR              = (1 << 3),
+
+    kEncodingAll                = (kEncodingShiftJIS | kEncodingGBK | kEncodingBig5 | kEncodingEUCKR),
+};
+
+
+// returns a bitfield containing the possible native encodings for the given character
+extern uint32_t findPossibleEncodings(int ch);
+
+#endif // AUTODETECT_H
diff --git a/media/libmediaplayerservice/Android.mk b/media/libmediaplayerservice/Android.mk
index fb569da..5e59710 100644
--- a/media/libmediaplayerservice/Android.mk
+++ b/media/libmediaplayerservice/Android.mk
@@ -18,8 +18,10 @@
 
 ifeq ($(BUILD_WITH_FULL_STAGEFRIGHT),true)
 
-LOCAL_SRC_FILES +=              \
-    StagefrightPlayer.cpp
+LOCAL_SRC_FILES +=                      \
+    StagefrightMetadataRetriever.cpp    \
+    StagefrightPlayer.cpp               \
+    StagefrightRecorder.cpp
 
 LOCAL_CFLAGS += -DBUILD_WITH_FULL_STAGEFRIGHT=1
 
@@ -35,12 +37,19 @@
 	libbinder             \
 	libvorbisidec         \
 	libsonivox            \
-	libopencore_player    \
-	libopencore_author    \
 	libmedia              \
 	libandroid_runtime    \
 	libstagefright        \
-	libstagefright_omx
+	libstagefright_omx    \
+	libstagefright_color_conversion
+
+ifneq ($(BUILD_WITHOUT_PV),true)
+LOCAL_SHARED_LIBRARIES += \
+	libopencore_player    \
+	libopencore_author
+else
+LOCAL_CFLAGS += -DNO_OPENCORE
+endif
 
 ifneq ($(TARGET_SIMULATOR),true)
 LOCAL_SHARED_LIBRARIES += libdl
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index df673a4..8e71700 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -202,7 +202,6 @@
 };
 
 // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
-/* static */ const uint32_t MediaPlayerService::AudioOutput::kAudioVideoDelayMs = 0;
 /* static */ int MediaPlayerService::AudioOutput::mMinBufferCount = 4;
 /* static */ bool MediaPlayerService::AudioOutput::mIsOnEmulator = false;
 
@@ -366,11 +365,44 @@
         size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
 extern "C" void free_malloc_leak_info(uint8_t* info);
 
+// Use the String-class below instead of String8 to allocate all memory
+// beforehand and not reenter the heap while we are examining it...
+struct MyString8 {
+    static const size_t MAX_SIZE = 256 * 1024;
+
+    MyString8()
+        : mPtr((char *)malloc(MAX_SIZE)) {
+        *mPtr = '\0';
+    }
+
+    ~MyString8() {
+        free(mPtr);
+    }
+
+    void append(const char *s) {
+        strcat(mPtr, s);
+    }
+
+    const char *string() const {
+        return mPtr;
+    }
+
+    size_t size() const {
+        return strlen(mPtr);
+    }
+
+private:
+    char *mPtr;
+
+    MyString8(const MyString8 &);
+    MyString8 &operator=(const MyString8 &);
+};
+
 void memStatus(int fd, const Vector<String16>& args)
 {
     const size_t SIZE = 256;
     char buffer[SIZE];
-    String8 result;
+    MyString8 result;
 
     typedef struct {
         size_t size;
@@ -688,6 +720,12 @@
         }
     }
 
+    if (!strncasecmp(url, "http://", 7)) {
+        // For now, we're going to use PV for http-based playback,
+        // until we can clear up a few more issues.
+        return PV_PLAYER;
+    }
+
     return getDefaultPlayerType();
 }
 
@@ -1452,7 +1490,7 @@
     LOGV("setVolume");
     t->setVolume(mLeftVolume, mRightVolume);
     mMsecsPerFrame = 1.e3 / (float) sampleRate;
-    mLatency = t->latency() + kAudioVideoDelayMs;
+    mLatency = t->latency();
     mTrack = t;
     return NO_ERROR;
 }
diff --git a/media/libmediaplayerservice/MediaPlayerService.h b/media/libmediaplayerservice/MediaPlayerService.h
index b00f5b7..1c90cf9 100644
--- a/media/libmediaplayerservice/MediaPlayerService.h
+++ b/media/libmediaplayerservice/MediaPlayerService.h
@@ -108,8 +108,6 @@
         float                   mMsecsPerFrame;
         uint32_t                mLatency;
 
-        // TODO: Find real cause of Audio/Video delay in PV framework and remove this workaround
-        static const uint32_t   kAudioVideoDelayMs;
         static bool             mIsOnEmulator;
         static int              mMinBufferCount;  // 12 for emulator; otherwise 4
 
diff --git a/media/libmediaplayerservice/MediaRecorderClient.cpp b/media/libmediaplayerservice/MediaRecorderClient.cpp
index 95ee3e4..c507669 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.cpp
+++ b/media/libmediaplayerservice/MediaRecorderClient.cpp
@@ -24,12 +24,17 @@
 #include <unistd.h>
 #include <string.h>
 #include <cutils/atomic.h>
+#include <cutils/properties.h> // for property_get
 #include <android_runtime/ActivityManager.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
 #include <binder/MemoryHeapBase.h>
 #include <binder/MemoryBase.h>
+
+#ifndef NO_OPENCORE
 #include <media/PVMediaRecorder.h>
+#endif
+
 #include <utils/String16.h>
 
 #include <media/AudioTrack.h>
@@ -37,6 +42,8 @@
 #include "MediaRecorderClient.h"
 #include "MediaPlayerService.h"
 
+#include "StagefrightRecorder.h"
+
 namespace android {
 
 const char* cameraPermission = "android.permission.CAMERA";
@@ -286,7 +293,24 @@
 {
     LOGV("Client constructor");
     mPid = pid;
-    mRecorder = new PVMediaRecorder();
+
+#if BUILD_WITH_FULL_STAGEFRIGHT
+    char value[PROPERTY_VALUE_MAX];
+    if (property_get("media.stagefright.enable-record", value, NULL)
+        && (!strcmp(value, "1") || !strcasecmp(value, "true"))) {
+        mRecorder = new StagefrightRecorder;
+    } else
+#endif
+#ifndef NO_OPENCORE
+    {
+        mRecorder = new PVMediaRecorder();
+    }
+#else
+    {
+        mRecorder = NULL;
+    }
+#endif
+
     mMediaPlayerService = service;
 }
 
diff --git a/media/libmediaplayerservice/MediaRecorderClient.h b/media/libmediaplayerservice/MediaRecorderClient.h
index 6260441..e07306b 100644
--- a/media/libmediaplayerservice/MediaRecorderClient.h
+++ b/media/libmediaplayerservice/MediaRecorderClient.h
@@ -22,8 +22,7 @@
 
 namespace android {
 
-class PVMediaRecorder;
-class ISurface;
+class MediaRecorderBase;
 class MediaPlayerService;
 
 class MediaRecorderClient : public BnMediaRecorder
@@ -59,7 +58,7 @@
 
     pid_t			 mPid;
     Mutex			 mLock;
-    PVMediaRecorder              *mRecorder;
+    MediaRecorderBase            *mRecorder;
     sp<MediaPlayerService>       mMediaPlayerService;
 };
 
diff --git a/media/libmediaplayerservice/MetadataRetrieverClient.cpp b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
index d51ce66..3572b52 100644
--- a/media/libmediaplayerservice/MetadataRetrieverClient.cpp
+++ b/media/libmediaplayerservice/MetadataRetrieverClient.cpp
@@ -38,6 +38,7 @@
 #include "VorbisMetadataRetriever.h"
 #include "MidiMetadataRetriever.h"
 #include "MetadataRetrieverClient.h"
+#include "StagefrightMetadataRetriever.h"
 
 /* desktop Linux needs a little help with gettid() */
 #if defined(HAVE_GETTID) && !defined(HAVE_ANDROID_OS)
@@ -104,6 +105,17 @@
 {
     sp<MediaMetadataRetrieverBase> p;
     switch (playerType) {
+#if BUILD_WITH_FULL_STAGEFRIGHT
+        case STAGEFRIGHT_PLAYER:
+            // For now we are going to keep using PV for meta-data support
+            // until stagefright is up to par.
+
+            // LOGV("create StagefrightMetadataRetriever");
+            // p = new StagefrightMetadataRetriever;
+            // break;
+
+            // fall through to PV_PLAYER
+#endif
 #ifndef NO_OPENCORE
         case PV_PLAYER:
             LOGV("create pv metadata retriever");
@@ -120,7 +132,7 @@
             break;
         default:
             // TODO:
-            // support for STAGEFRIGHT_PLAYER and TEST_PLAYER
+            // support for TEST_PLAYER
             LOGE("player type %d is not supported",  playerType);
             break;
     }
@@ -138,12 +150,6 @@
         return UNKNOWN_ERROR;
     }
     player_type playerType = getPlayerType(url);
-#if !defined(NO_OPENCORE) && defined(BUILD_WITH_FULL_STAGEFRIGHT)
-    if (playerType == STAGEFRIGHT_PLAYER) {
-        // Stagefright doesn't support metadata in this branch yet.
-        playerType = PV_PLAYER;
-    }
-#endif
     LOGV("player type = %d", playerType);
     sp<MediaMetadataRetrieverBase> p = createRetriever(playerType);
     if (p == NULL) return NO_INIT;
@@ -182,12 +188,6 @@
     }
 
     player_type playerType = getPlayerType(fd, offset, length);
-#if !defined(NO_OPENCORE) && defined(BUILD_WITH_FULL_STAGEFRIGHT)
-    if (playerType == STAGEFRIGHT_PLAYER) {
-        // Stagefright doesn't support metadata in this branch yet.
-        playerType = PV_PLAYER;
-    }
-#endif
     LOGV("player type = %d", playerType);
     sp<MediaMetadataRetrieverBase> p = createRetriever(playerType);
     if (p == NULL) {
diff --git a/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp b/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp
new file mode 100644
index 0000000..42c1877
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightMetadataRetriever.cpp
@@ -0,0 +1,197 @@
+/*
+**
+** Copyright 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.
+*/
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "StagefrightMetadataRetriever"
+#include <utils/Log.h>
+
+#include "StagefrightMetadataRetriever.h"
+
+#include <media/stagefright/CachingDataSource.h>
+#include <media/stagefright/ColorConverter.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/FileSource.h>
+#include <media/stagefright/HTTPDataSource.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXCodec.h>
+
+namespace android {
+
+StagefrightMetadataRetriever::StagefrightMetadataRetriever() {
+    LOGV("StagefrightMetadataRetriever()");
+
+    DataSource::RegisterDefaultSniffers();
+    CHECK_EQ(mClient.connect(), OK);
+}
+
+StagefrightMetadataRetriever::~StagefrightMetadataRetriever() {
+    LOGV("~StagefrightMetadataRetriever()");
+    mClient.disconnect();
+}
+
+status_t StagefrightMetadataRetriever::setDataSource(const char *uri) {
+    LOGV("setDataSource(%s)", uri);
+
+    mExtractor = MediaExtractor::CreateFromURI(uri);
+
+    return mExtractor.get() != NULL ? OK : UNKNOWN_ERROR;
+}
+
+status_t StagefrightMetadataRetriever::setDataSource(
+        int fd, int64_t offset, int64_t length) {
+    LOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
+
+    mExtractor = MediaExtractor::Create(
+            new FileSource(fd, offset, length));
+
+    return OK;
+}
+
+VideoFrame *StagefrightMetadataRetriever::captureFrame() {
+    LOGV("captureFrame");
+
+    if (mExtractor.get() == NULL) {
+        LOGV("no extractor.");
+        return NULL;
+    }
+
+    size_t n = mExtractor->countTracks();
+    size_t i;
+    for (i = 0; i < n; ++i) {
+        sp<MetaData> meta = mExtractor->getTrackMetaData(i);
+
+        const char *mime;
+        CHECK(meta->findCString(kKeyMIMEType, &mime));
+
+        if (!strncasecmp(mime, "video/", 6)) {
+            break;
+        }
+    }
+
+    if (i == n) {
+        LOGV("no video track found.");
+        return NULL;
+    }
+
+    sp<MetaData> trackMeta = mExtractor->getTrackMetaData(
+            i, MediaExtractor::kIncludeExtensiveMetaData);
+
+    sp<MediaSource> source = mExtractor->getTrack(i);
+
+    if (source.get() == NULL) {
+        LOGV("unable to instantiate video track.");
+        return NULL;
+    }
+
+    sp<MetaData> meta = source->getFormat();
+
+    sp<MediaSource> decoder =
+        OMXCodec::Create(
+                mClient.interface(), meta, false, source,
+                NULL, OMXCodec::kPreferSoftwareCodecs);
+
+    if (decoder.get() == NULL) {
+        LOGV("unable to instantiate video decoder.");
+
+        return NULL;
+    }
+
+    decoder->start();
+
+    // Read one output buffer, ignore format change notifications
+    // and spurious empty buffers.
+
+    MediaSource::ReadOptions options;
+    int64_t thumbNailTime;
+    if (trackMeta->findInt64(kKeyThumbnailTime, &thumbNailTime)) {
+        options.setSeekTo(thumbNailTime);
+    }
+
+    MediaBuffer *buffer = NULL;
+    status_t err;
+    do {
+        if (buffer != NULL) {
+            buffer->release();
+            buffer = NULL;
+        }
+        err = decoder->read(&buffer, &options);
+        options.clearSeekTo();
+    } while (err == INFO_FORMAT_CHANGED
+             || (buffer != NULL && buffer->range_length() == 0));
+
+    if (err != OK) {
+        CHECK_EQ(buffer, NULL);
+
+        LOGV("decoding frame failed.");
+        decoder->stop();
+
+        return NULL;
+    }
+
+    LOGV("successfully decoded video frame.");
+
+    meta = decoder->getFormat();
+
+    int32_t width, height;
+    CHECK(meta->findInt32(kKeyWidth, &width));
+    CHECK(meta->findInt32(kKeyHeight, &height));
+
+    VideoFrame *frame = new VideoFrame;
+    frame->mWidth = width;
+    frame->mHeight = height;
+    frame->mDisplayWidth = width;
+    frame->mDisplayHeight = height;
+    frame->mSize = width * height * 2;
+    frame->mData = new uint8_t[frame->mSize];
+
+    int32_t srcFormat;
+    CHECK(meta->findInt32(kKeyColorFormat, &srcFormat));
+
+    ColorConverter converter(
+            (OMX_COLOR_FORMATTYPE)srcFormat, OMX_COLOR_Format16bitRGB565);
+    CHECK(converter.isValid());
+
+    converter.convert(
+            width, height,
+            (const uint8_t *)buffer->data() + buffer->range_offset(),
+            0,
+            frame->mData, width * 2);
+
+    buffer->release();
+    buffer = NULL;
+
+    decoder->stop();
+
+    return frame;
+}
+
+MediaAlbumArt *StagefrightMetadataRetriever::extractAlbumArt() {
+    LOGV("extractAlbumArt (extractor: %s)", mExtractor.get() != NULL ? "YES" : "NO");
+
+    return NULL;
+}
+
+const char *StagefrightMetadataRetriever::extractMetadata(int keyCode) {
+    LOGV("extractMetadata %d (extractor: %s)",
+         keyCode, mExtractor.get() != NULL ? "YES" : "NO");
+
+    return NULL;
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/StagefrightMetadataRetriever.h b/media/libmediaplayerservice/StagefrightMetadataRetriever.h
new file mode 100644
index 0000000..16127d7
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightMetadataRetriever.h
@@ -0,0 +1,53 @@
+/*
+**
+** Copyright 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 STAGEFRIGHT_METADATA_RETRIEVER_H_
+
+#define STAGEFRIGHT_METADATA_RETRIEVER_H_
+
+#include <media/MediaMetadataRetrieverInterface.h>
+
+#include <media/stagefright/OMXClient.h>
+
+namespace android {
+
+class MediaExtractor;
+
+struct StagefrightMetadataRetriever : public MediaMetadataRetrieverInterface {
+    StagefrightMetadataRetriever();
+    virtual ~StagefrightMetadataRetriever();
+
+    virtual status_t setDataSource(const char *url);
+    virtual status_t setDataSource(int fd, int64_t offset, int64_t length);
+
+    virtual VideoFrame *captureFrame();
+    virtual MediaAlbumArt *extractAlbumArt();
+    virtual const char *extractMetadata(int keyCode);
+
+private:
+    OMXClient mClient;
+    sp<MediaExtractor> mExtractor;
+
+    StagefrightMetadataRetriever(const StagefrightMetadataRetriever &);
+
+    StagefrightMetadataRetriever &operator=(
+            const StagefrightMetadataRetriever &);
+};
+
+}  // namespace android
+
+#endif  // STAGEFRIGHT_METADATA_RETRIEVER_H_
diff --git a/media/libmediaplayerservice/StagefrightPlayer.cpp b/media/libmediaplayerservice/StagefrightPlayer.cpp
index dbee451..5915105 100644
--- a/media/libmediaplayerservice/StagefrightPlayer.cpp
+++ b/media/libmediaplayerservice/StagefrightPlayer.cpp
@@ -3,19 +3,24 @@
 #include <utils/Log.h>
 
 #include "StagefrightPlayer.h"
-#include <media/stagefright/MediaPlayerImpl.h>
+
+#include "AwesomePlayer.h"
 
 namespace android {
 
 StagefrightPlayer::StagefrightPlayer()
-    : mPlayer(NULL) {
+    : mPlayer(new AwesomePlayer) {
     LOGV("StagefrightPlayer");
+
+    mPlayer->setListener(this);
 }
 
 StagefrightPlayer::~StagefrightPlayer() {
     LOGV("~StagefrightPlayer");
     reset();
-    LOGV("~StagefrightPlayer done.");
+
+    delete mPlayer;
+    mPlayer = NULL;
 }
 
 status_t StagefrightPlayer::initCheck() {
@@ -25,62 +30,32 @@
 
 status_t StagefrightPlayer::setDataSource(const char *url) {
     LOGV("setDataSource('%s')", url);
-
-    reset();
-    mPlayer = new MediaPlayerImpl(url);
-
-    status_t err = mPlayer->initCheck();
-    if (err != OK) {
-        delete mPlayer;
-        mPlayer = NULL;
-    } else {
-        mPlayer->setAudioSink(mAudioSink);
-    }
-
-    return err;
+    return mPlayer->setDataSource(url);
 }
 
 // Warning: The filedescriptor passed into this method will only be valid until
 // the method returns, if you want to keep it, dup it!
 status_t StagefrightPlayer::setDataSource(int fd, int64_t offset, int64_t length) {
     LOGV("setDataSource(%d, %lld, %lld)", fd, offset, length);
-
-    reset();
-    mPlayer = new MediaPlayerImpl(dup(fd), offset, length);
-
-    status_t err = mPlayer->initCheck();
-    if (err != OK) {
-        delete mPlayer;
-        mPlayer = NULL;
-    } else {
-        mPlayer->setAudioSink(mAudioSink);
-    }
-
-    return err;
+    return mPlayer->setDataSource(dup(fd), offset, length);
 }
 
 status_t StagefrightPlayer::setVideoSurface(const sp<ISurface> &surface) {
     LOGV("setVideoSurface");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
-    }
-
     mPlayer->setISurface(surface);
-
     return OK;
 }
 
 status_t StagefrightPlayer::prepare() {
     LOGV("prepare");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
+    int32_t width, height;
+    if (mPlayer->getVideoDimensions(&width, &height) != OK) {
+        width = height = 0;
     }
 
-    sendEvent(
-            MEDIA_SET_VIDEO_SIZE,
-            mPlayer->getWidth(), mPlayer->getHeight());
+    sendEvent(MEDIA_SET_VIDEO_SIZE, width, height);
 
     return OK;
 }
@@ -102,92 +77,76 @@
 status_t StagefrightPlayer::start() {
     LOGV("start");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
-    }
-
-    mPlayer->play();
-
-    return OK;
+    return mPlayer->play();
 }
 
 status_t StagefrightPlayer::stop() {
     LOGV("stop");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
-    }
-
-    reset();
-
-    return OK;
+    return pause();  // what's the difference?
 }
 
 status_t StagefrightPlayer::pause() {
     LOGV("pause");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
-    }
-
-    mPlayer->pause();
-
-    return OK;
+    return mPlayer->pause();
 }
 
 bool StagefrightPlayer::isPlaying() {
     LOGV("isPlaying");
-    return mPlayer != NULL && mPlayer->isPlaying();
+    return mPlayer->isPlaying();
 }
 
 status_t StagefrightPlayer::seekTo(int msec) {
     LOGV("seekTo");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
-    }
-
     status_t err = mPlayer->seekTo((int64_t)msec * 1000);
 
-    sendEvent(MEDIA_SEEK_COMPLETE);
-
     return err;
 }
 
 status_t StagefrightPlayer::getCurrentPosition(int *msec) {
     LOGV("getCurrentPosition");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
+    int64_t positionUs;
+    status_t err = mPlayer->getPosition(&positionUs);
+
+    if (err != OK) {
+        return err;
     }
 
-    *msec = mPlayer->getPosition() / 1000;
+    *msec = (positionUs + 500) / 1000;
+
     return OK;
 }
 
 status_t StagefrightPlayer::getDuration(int *msec) {
     LOGV("getDuration");
 
-    if (mPlayer == NULL) {
-        return NO_INIT;
+    int64_t durationUs;
+    status_t err = mPlayer->getDuration(&durationUs);
+
+    if (err != OK) {
+        return err;
     }
 
-    *msec = mPlayer->getDuration() / 1000;
+    *msec = (durationUs + 500) / 1000;
+
     return OK;
 }
 
 status_t StagefrightPlayer::reset() {
     LOGV("reset");
 
-    delete mPlayer;
-    mPlayer = NULL;
+    mPlayer->reset();
 
     return OK;
 }
 
 status_t StagefrightPlayer::setLooping(int loop) {
     LOGV("setLooping");
-    return UNKNOWN_ERROR;
+
+    return mPlayer->setLooping(loop);
 }
 
 player_type StagefrightPlayer::playerType() {
@@ -202,9 +161,7 @@
 void StagefrightPlayer::setAudioSink(const sp<AudioSink> &audioSink) {
     MediaPlayerInterface::setAudioSink(audioSink);
 
-    if (mPlayer != NULL) {
-        mPlayer->setAudioSink(audioSink);
-    }
+    mPlayer->setAudioSink(audioSink);
 }
 
 }  // namespace android
diff --git a/media/libmediaplayerservice/StagefrightPlayer.h b/media/libmediaplayerservice/StagefrightPlayer.h
index f214872..9d005cb 100644
--- a/media/libmediaplayerservice/StagefrightPlayer.h
+++ b/media/libmediaplayerservice/StagefrightPlayer.h
@@ -22,7 +22,7 @@
 
 namespace android {
 
-class MediaPlayerImpl;
+struct AwesomePlayer;
 
 class StagefrightPlayer : public MediaPlayerInterface {
 public:
@@ -49,7 +49,7 @@
     virtual void setAudioSink(const sp<AudioSink> &audioSink);
 
 private:
-    MediaPlayerImpl *mPlayer;
+    AwesomePlayer *mPlayer;
 
     StagefrightPlayer(const StagefrightPlayer &);
     StagefrightPlayer &operator=(const StagefrightPlayer &);
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
new file mode 100644
index 0000000..a55273d
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "StagefrightRecorder"
+#include <utils/Log.h>
+
+#include "StagefrightRecorder.h"
+
+#include <media/stagefright/CameraSource.h>
+#include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXClient.h>
+#include <media/stagefright/OMXCodec.h>
+#include <ui/ICamera.h>
+#include <ui/ISurface.h>
+#include <utils/Errors.h>
+
+namespace android {
+
+StagefrightRecorder::StagefrightRecorder() {
+    reset();
+}
+
+StagefrightRecorder::~StagefrightRecorder() {
+    stop();
+
+    if (mOutputFd >= 0) {
+        ::close(mOutputFd);
+        mOutputFd = -1;
+    }
+}
+
+status_t StagefrightRecorder::init() {
+    return OK;
+}
+
+status_t StagefrightRecorder::setAudioSource(audio_source as) {
+    mAudioSource = as;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setVideoSource(video_source vs) {
+    mVideoSource = vs;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setOutputFormat(output_format of) {
+    mOutputFormat = of;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setAudioEncoder(audio_encoder ae) {
+    mAudioEncoder = ae;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setVideoEncoder(video_encoder ve) {
+    mVideoEncoder = ve;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setVideoSize(int width, int height) {
+    mVideoWidth = width;
+    mVideoHeight = height;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setVideoFrameRate(int frames_per_second) {
+    mFrameRate = frames_per_second;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setCamera(const sp<ICamera> &camera) {
+    mCamera = camera;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setPreviewSurface(const sp<ISurface> &surface) {
+    mPreviewSurface = surface;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setOutputFile(const char *path) {
+    // We don't actually support this at all, as the media_server process
+    // no longer has permissions to create files.
+
+    return UNKNOWN_ERROR;
+}
+
+status_t StagefrightRecorder::setOutputFile(int fd, int64_t offset, int64_t length) {
+    // These don't make any sense, do they?
+    CHECK_EQ(offset, 0);
+    CHECK_EQ(length, 0);
+
+    if (mOutputFd >= 0) {
+        ::close(mOutputFd);
+    }
+    mOutputFd = dup(fd);
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setParameters(const String8 &params) {
+    mParams = params;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::setListener(const sp<IMediaPlayerClient> &listener) {
+    mListener = listener;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::prepare() {
+    return OK;
+}
+
+status_t StagefrightRecorder::start() {
+    if (mWriter != NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    if (mVideoSource == VIDEO_SOURCE_CAMERA) {
+        CHECK(mCamera != NULL);
+
+        sp<CameraSource> cameraSource =
+            CameraSource::CreateFromICamera(mCamera);
+
+        CHECK(cameraSource != NULL);
+
+        cameraSource->setPreviewSurface(mPreviewSurface);
+
+        sp<MetaData> enc_meta = new MetaData;
+        switch (mVideoEncoder) {
+            case VIDEO_ENCODER_H263:
+                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
+                break;
+
+            case VIDEO_ENCODER_MPEG_4_SP:
+                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
+                break;
+
+            case VIDEO_ENCODER_H264:
+                enc_meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
+                break;
+
+            default:
+                CHECK(!"Should not be here, unsupported video encoding.");
+                break;
+        }
+
+        sp<MetaData> meta = cameraSource->getFormat();
+
+        int32_t width, height;
+        CHECK(meta->findInt32(kKeyWidth, &width));
+        CHECK(meta->findInt32(kKeyHeight, &height));
+
+        enc_meta->setInt32(kKeyWidth, width);
+        enc_meta->setInt32(kKeyHeight, height);
+
+        OMXClient client;
+        CHECK_EQ(client.connect(), OK);
+
+        sp<MediaSource> encoder =
+            OMXCodec::Create(
+                    client.interface(), enc_meta,
+                    true /* createEncoder */, cameraSource);
+
+        CHECK(mOutputFd >= 0);
+        mWriter = new MPEG4Writer(dup(mOutputFd));
+        mWriter->addSource(encoder);
+        mWriter->start();
+    }
+
+    return OK;
+}
+
+status_t StagefrightRecorder::stop() {
+    if (mWriter == NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    mWriter->stop();
+    mWriter = NULL;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::close() {
+    stop();
+
+    return OK;
+}
+
+status_t StagefrightRecorder::reset() {
+    stop();
+
+    mAudioSource = AUDIO_SOURCE_LIST_END;
+    mVideoSource = VIDEO_SOURCE_LIST_END;
+    mOutputFormat = OUTPUT_FORMAT_LIST_END;
+    mAudioEncoder = AUDIO_ENCODER_LIST_END;
+    mVideoEncoder = VIDEO_ENCODER_LIST_END;
+    mVideoWidth = -1;
+    mVideoHeight = -1;
+    mFrameRate = -1;
+    mOutputFd = -1;
+
+    return OK;
+}
+
+status_t StagefrightRecorder::getMaxAmplitude(int *max) {
+    return UNKNOWN_ERROR;
+}
+
+}  // namespace android
diff --git a/media/libmediaplayerservice/StagefrightRecorder.h b/media/libmediaplayerservice/StagefrightRecorder.h
new file mode 100644
index 0000000..56c4e0e
--- /dev/null
+++ b/media/libmediaplayerservice/StagefrightRecorder.h
@@ -0,0 +1,76 @@
+/*
+ * 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 STAGEFRIGHT_RECORDER_H_
+
+#define STAGEFRIGHT_RECORDER_H_
+
+#include <media/MediaRecorderBase.h>
+#include <utils/String8.h>
+
+namespace android {
+
+class MPEG4Writer;
+
+struct StagefrightRecorder : public MediaRecorderBase {
+    StagefrightRecorder();
+    virtual ~StagefrightRecorder();
+
+    virtual status_t init();
+    virtual status_t setAudioSource(audio_source as);
+    virtual status_t setVideoSource(video_source vs);
+    virtual status_t setOutputFormat(output_format of);
+    virtual status_t setAudioEncoder(audio_encoder ae);
+    virtual status_t setVideoEncoder(video_encoder ve);
+    virtual status_t setVideoSize(int width, int height);
+    virtual status_t setVideoFrameRate(int frames_per_second);
+    virtual status_t setCamera(const sp<ICamera>& camera);
+    virtual status_t setPreviewSurface(const sp<ISurface>& surface);
+    virtual status_t setOutputFile(const char *path);
+    virtual status_t setOutputFile(int fd, int64_t offset, int64_t length);
+    virtual status_t setParameters(const String8& params);
+    virtual status_t setListener(const sp<IMediaPlayerClient>& listener);
+    virtual status_t prepare();
+    virtual status_t start();
+    virtual status_t stop();
+    virtual status_t close();
+    virtual status_t reset();
+    virtual status_t getMaxAmplitude(int *max);
+
+private:
+    sp<ICamera> mCamera;
+    sp<ISurface> mPreviewSurface;
+    sp<IMediaPlayerClient> mListener;
+    sp<MPEG4Writer> mWriter;
+
+    audio_source mAudioSource;
+    video_source mVideoSource;
+    output_format mOutputFormat;
+    audio_encoder mAudioEncoder;
+    video_encoder mVideoEncoder;
+    int mVideoWidth, mVideoHeight;
+    int mFrameRate;
+    String8 mParams;
+    int mOutputFd;
+
+    StagefrightRecorder(const StagefrightRecorder &);
+    StagefrightRecorder &operator=(const StagefrightRecorder &);
+};
+
+}  // namespace android
+
+#endif  // STAGEFRIGHT_RECORDER_H_
+
diff --git a/media/libmediaplayerservice/TestPlayerStub.cpp b/media/libmediaplayerservice/TestPlayerStub.cpp
index 8627708..aa49429 100644
--- a/media/libmediaplayerservice/TestPlayerStub.cpp
+++ b/media/libmediaplayerservice/TestPlayerStub.cpp
@@ -176,7 +176,7 @@
     mContentUrl = NULL;
 
     if (mPlayer) {
-        LOG_ASSERT(mDeletePlayer != NULL);
+        LOG_ASSERT(mDeletePlayer != NULL, "mDeletePlayer is null");
         (*mDeletePlayer)(mPlayer);
         mPlayer = NULL;
     }
diff --git a/media/libstagefright/AMRExtractor.cpp b/media/libstagefright/AMRExtractor.cpp
index 8d85ce2..bdd7550 100644
--- a/media/libstagefright/AMRExtractor.cpp
+++ b/media/libstagefright/AMRExtractor.cpp
@@ -18,7 +18,8 @@
 #define LOG_TAG "AMRExtractor"
 #include <utils/Log.h>
 
-#include <media/stagefright/AMRExtractor.h>
+#include "include/AMRExtractor.h"
+
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
@@ -32,7 +33,10 @@
 
 class AMRSource : public MediaSource {
 public:
-    AMRSource(const sp<DataSource> &source, bool isWide);
+    AMRSource(const sp<DataSource> &source,
+              const sp<MetaData> &meta,
+              size_t frameSize,
+              bool isWide);
 
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
@@ -47,6 +51,8 @@
 
 private:
     sp<DataSource> mDataSource;
+    sp<MetaData> mMeta;
+    size_t mFrameSize;
     bool mIsWide;
 
     off_t mOffset;
@@ -60,15 +66,63 @@
 
 ////////////////////////////////////////////////////////////////////////////////
 
+static size_t getFrameSize(bool isWide, unsigned FT) {
+    static const size_t kFrameSizeNB[8] = {
+        95, 103, 118, 134, 148, 159, 204, 244
+    };
+    static const size_t kFrameSizeWB[9] = {
+        132, 177, 253, 285, 317, 365, 397, 461, 477
+    };
+
+    size_t frameSize = isWide ? kFrameSizeWB[FT] : kFrameSizeNB[FT];
+
+    // Round up bits to bytes and add 1 for the header byte.
+    frameSize = (frameSize + 7) / 8 + 1;
+
+    return frameSize;
+}
+
 AMRExtractor::AMRExtractor(const sp<DataSource> &source)
     : mDataSource(source),
       mInitCheck(NO_INIT) {
     String8 mimeType;
     float confidence;
-    if (SniffAMR(mDataSource, &mimeType, &confidence)) {
-        mInitCheck = OK;
-        mIsWide = (mimeType == MEDIA_MIMETYPE_AUDIO_AMR_WB);
+    if (!SniffAMR(mDataSource, &mimeType, &confidence)) {
+        return;
     }
+
+    mIsWide = (mimeType == MEDIA_MIMETYPE_AUDIO_AMR_WB);
+
+    mMeta = new MetaData;
+    mMeta->setCString(
+            kKeyMIMEType, mIsWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB
+                                  : MEDIA_MIMETYPE_AUDIO_AMR_NB);
+
+    mMeta->setInt32(kKeyChannelCount, 1);
+    mMeta->setInt32(kKeySampleRate, mIsWide ? 16000 : 8000);
+
+    size_t offset = mIsWide ? 9 : 6;
+    uint8_t header;
+    if (mDataSource->readAt(offset, &header, 1) != 1) {
+        return;
+    }
+
+    unsigned FT = (header >> 3) & 0x0f;
+
+    if (FT > 8 || (!mIsWide && FT > 7)) {
+        return;
+    }
+
+    mFrameSize = getFrameSize(mIsWide, FT);
+
+    off_t streamSize;
+    if (mDataSource->getSize(&streamSize) == OK) {
+        off_t numFrames = streamSize / mFrameSize;
+
+        mMeta->setInt64(kKeyDuration, 20000ll * numFrames);
+    }
+
+    mInitCheck = OK;
 }
 
 AMRExtractor::~AMRExtractor() {
@@ -83,34 +137,25 @@
         return NULL;
     }
 
-    return new AMRSource(mDataSource, mIsWide);
+    return new AMRSource(mDataSource, mMeta, mFrameSize, mIsWide);
 }
 
-sp<MetaData> AMRExtractor::getTrackMetaData(size_t index) {
+sp<MetaData> AMRExtractor::getTrackMetaData(size_t index, uint32_t flags) {
     if (mInitCheck != OK || index != 0) {
         return NULL;
     }
 
-    return makeAMRFormat(mIsWide);
-}
-
-// static
-sp<MetaData> AMRExtractor::makeAMRFormat(bool isWide) {
-    sp<MetaData> meta = new MetaData;
-    meta->setCString(
-            kKeyMIMEType, isWide ? MEDIA_MIMETYPE_AUDIO_AMR_WB
-                                 : MEDIA_MIMETYPE_AUDIO_AMR_NB);
-
-    meta->setInt32(kKeyChannelCount, 1);
-    meta->setInt32(kKeySampleRate, isWide ? 16000 : 8000);
-
-    return meta;
+    return mMeta;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 
-AMRSource::AMRSource(const sp<DataSource> &source, bool isWide)
+AMRSource::AMRSource(
+        const sp<DataSource> &source, const sp<MetaData> &meta,
+        size_t frameSize, bool isWide)
     : mDataSource(source),
+      mMeta(meta),
+      mFrameSize(frameSize),
       mIsWide(isWide),
       mOffset(mIsWide ? 9 : 6),
       mCurrentTimeUs(0),
@@ -147,15 +192,22 @@
 }
 
 sp<MetaData> AMRSource::getFormat() {
-    return AMRExtractor::makeAMRFormat(mIsWide);
+    return mMeta;
 }
 
 status_t AMRSource::read(
         MediaBuffer **out, const ReadOptions *options) {
     *out = NULL;
 
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        int64_t seekFrame = seekTimeUs / 20000ll;  // 20ms per frame.
+        mCurrentTimeUs = seekFrame * 20000ll;
+        mOffset = seekFrame * mFrameSize + (mIsWide ? 9 : 6);
+    }
+
     uint8_t header;
-    ssize_t n = mDataSource->read_at(mOffset, &header, 1);
+    ssize_t n = mDataSource->readAt(mOffset, &header, 1);
 
     if (n < 1) {
         return ERROR_IO;
@@ -179,19 +231,10 @@
         return ERROR_MALFORMED;
     }
 
-    static const size_t kFrameSizeNB[8] = {
-        95, 103, 118, 134, 148, 159, 204, 244
-    };
-    static const size_t kFrameSizeWB[9] = {
-        132, 177, 253, 285, 317, 365, 397, 461, 477
-    };
+    size_t frameSize = getFrameSize(mIsWide, FT);
+    CHECK_EQ(frameSize, mFrameSize);
 
-    size_t frameSize = mIsWide ? kFrameSizeWB[FT] : kFrameSizeNB[FT];
-
-    // Round up bits to bytes and add 1 for the header byte.
-    frameSize = (frameSize + 7) / 8 + 1;
-
-    n = mDataSource->read_at(mOffset, buffer->data(), frameSize);
+    n = mDataSource->readAt(mOffset, buffer->data(), frameSize);
 
     if (n != (ssize_t)frameSize) {
         buffer->release();
@@ -201,10 +244,7 @@
     }
 
     buffer->set_range(0, frameSize);
-    buffer->meta_data()->setInt32(
-            kKeyTimeUnits, (mCurrentTimeUs + 500) / 1000);
-    buffer->meta_data()->setInt32(
-            kKeyTimeScale, 1000);
+    buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs);
 
     mOffset += frameSize;
     mCurrentTimeUs += 20000;  // Each frame is 20ms
@@ -220,7 +260,7 @@
         const sp<DataSource> &source, String8 *mimeType, float *confidence) {
     char header[9];
 
-    if (source->read_at(0, header, sizeof(header)) != sizeof(header)) {
+    if (source->readAt(0, header, sizeof(header)) != sizeof(header)) {
         return false;
     }
 
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 9f71dae..f7df69c 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -16,25 +16,27 @@
 
 LOCAL_SRC_FILES +=                \
         AMRExtractor.cpp          \
+        AudioPlayer.cpp           \
+        AwesomePlayer.cpp         \
         CachingDataSource.cpp     \
+        CameraSource.cpp          \
         DataSource.cpp            \
         FileSource.cpp            \
         HTTPDataSource.cpp        \
         HTTPStream.cpp            \
         JPEGSource.cpp            \
-        MediaExtractor.cpp        \
         MP3Extractor.cpp          \
         MPEG4Extractor.cpp        \
         MPEG4Writer.cpp           \
-        MediaPlayerImpl.cpp       \
-        MmapSource.cpp            \
+        MediaExtractor.cpp        \
         SampleTable.cpp           \
         ShoutcastSource.cpp       \
         TimeSource.cpp            \
         TimedEventQueue.cpp       \
-        AudioPlayer.cpp           \
-        stagefright_string.cpp
+        WAVExtractor.cpp          \
+        string.cpp
 
+LOCAL_CFLAGS += -DBUILD_WITH_FULL_STAGEFRIGHT
 endif
 
 LOCAL_C_INCLUDES:= \
@@ -49,6 +51,24 @@
         libcutils         \
         libui
 
+ifeq ($(BUILD_WITH_FULL_STAGEFRIGHT),true)
+
+LOCAL_STATIC_LIBRARIES := \
+        libstagefright_aacdec \
+        libstagefright_amrnbdec \
+        libstagefright_amrnbenc \
+        libstagefright_amrwbdec \
+        libstagefright_avcdec \
+        libstagefright_m4vh263dec \
+        libstagefright_mp3dec
+
+LOCAL_SHARED_LIBRARIES += \
+        libstagefright_amrnb_common \
+        libstagefright_avc_common \
+        libstagefright_color_conversion
+
+endif
+
 ifeq ($(TARGET_OS)-$(TARGET_SIMULATOR),linux-true)
         LOCAL_LDLIBS += -lpthread
 endif
diff --git a/media/libstagefright/AudioPlayer.cpp b/media/libstagefright/AudioPlayer.cpp
index 538facb..4280683 100644
--- a/media/libstagefright/AudioPlayer.cpp
+++ b/media/libstagefright/AudioPlayer.cpp
@@ -47,6 +47,12 @@
     }
 }
 
+void AudioPlayer::setListenerCallback(
+        void (*notify)(void *cookie, int what), void *cookie) {
+    mListenerCallback = notify;
+    mListenerCookie = cookie;
+}
+
 void AudioPlayer::setSource(const sp<MediaSource> &source) {
     CHECK_EQ(mSource, NULL);
     mSource = source;
@@ -195,7 +201,6 @@
                     mInputBuffer->release();
                     mInputBuffer = NULL;
                 }
-                mSeeking = false;
             }
         }
 
@@ -205,20 +210,26 @@
             CHECK((err == OK && mInputBuffer != NULL)
                    || (err != OK && mInputBuffer == NULL));
 
+            if (mSeeking) {
+                mSeeking = false;
+
+                if (mListenerCallback) {
+                    (*mListenerCallback)(mListenerCookie, SEEK_COMPLETE);
+                }
+            }
+
             if (err != OK) {
+                if (mListenerCallback) {
+                    (*mListenerCallback)(mListenerCookie, REACHED_EOS);
+                }
+
                 memset((char *)data + size_done, 0, size_remaining);
                 break;
             }
 
-            int32_t units, scale;
-            bool success =
-                mInputBuffer->meta_data()->findInt32(kKeyTimeUnits, &units);
-            success = success &&
-                mInputBuffer->meta_data()->findInt32(kKeyTimeScale, &scale);
-            CHECK(success);
-
             Mutex::Autolock autoLock(mLock);
-            mPositionTimeMediaUs = (int64_t)units * 1000000 / scale;
+            CHECK(mInputBuffer->meta_data()->findInt64(
+                        kKeyTime, &mPositionTimeMediaUs));
 
             mPositionTimeRealUs =
                 ((mNumFramesPlayed + size_done / mFrameSize) * 1000000)
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
new file mode 100644
index 0000000..9e388f9
--- /dev/null
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -0,0 +1,708 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "AwesomePlayer"
+#include <utils/Log.h>
+
+#include "include/AwesomePlayer.h"
+#include "include/SoftwareRenderer.h"
+
+#include <binder/IPCThreadState.h>
+#include <media/stagefright/AudioPlayer.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/FileSource.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXCodec.h>
+namespace android {
+
+struct AwesomeEvent : public TimedEventQueue::Event {
+    AwesomeEvent(AwesomePlayer *player, int32_t code)
+        : mPlayer(player),
+          mCode(code) {
+    }
+
+protected:
+    virtual ~AwesomeEvent() {}
+
+    virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) {
+        mPlayer->onEvent(mCode);
+    }
+
+private:
+    AwesomePlayer *mPlayer;
+    int32_t mCode;
+
+    AwesomeEvent(const AwesomeEvent &);
+    AwesomeEvent &operator=(const AwesomeEvent &);
+};
+
+struct AwesomeRemoteRenderer : public AwesomeRenderer {
+    AwesomeRemoteRenderer(const sp<IOMXRenderer> &target)
+        : mTarget(target) {
+    }
+
+    virtual void render(MediaBuffer *buffer) {
+        void *id;
+        if (buffer->meta_data()->findPointer(kKeyBufferID, &id)) {
+            mTarget->render((IOMX::buffer_id)id);
+        }
+    }
+
+private:
+    sp<IOMXRenderer> mTarget;
+
+    AwesomeRemoteRenderer(const AwesomeRemoteRenderer &);
+    AwesomeRemoteRenderer &operator=(const AwesomeRemoteRenderer &);
+};
+
+struct AwesomeLocalRenderer : public AwesomeRenderer {
+    AwesomeLocalRenderer(
+            OMX_COLOR_FORMATTYPE colorFormat,
+            const sp<ISurface> &surface,
+            size_t displayWidth, size_t displayHeight,
+            size_t decodedWidth, size_t decodedHeight)
+        : mTarget(new SoftwareRenderer(
+                    colorFormat, surface, displayWidth, displayHeight,
+                    decodedWidth, decodedHeight)) {
+    }
+
+    virtual void render(MediaBuffer *buffer) {
+        mTarget->render(
+                (const uint8_t *)buffer->data() + buffer->range_offset(),
+                buffer->range_length(), NULL);
+    }
+
+protected:
+    virtual ~AwesomeLocalRenderer() {
+        delete mTarget;
+        mTarget = NULL;
+    }
+
+private:
+    SoftwareRenderer *mTarget;
+
+    AwesomeLocalRenderer(const AwesomeLocalRenderer &);
+    AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);;
+};
+
+AwesomePlayer::AwesomePlayer()
+    : mTimeSource(NULL),
+      mAudioPlayer(NULL),
+      mLastVideoBuffer(NULL),
+      mVideoBuffer(NULL) {
+    CHECK_EQ(mClient.connect(), OK);
+
+    DataSource::RegisterDefaultSniffers();
+
+    mVideoEvent = new AwesomeEvent(this, 0);
+    mVideoEventPending = false;
+    mStreamDoneEvent = new AwesomeEvent(this, 1);
+    mStreamDoneEventPending = false;
+
+    mQueue.start();
+
+    reset();
+}
+
+AwesomePlayer::~AwesomePlayer() {
+    mQueue.stop();
+
+    reset();
+
+    mClient.disconnect();
+}
+
+void AwesomePlayer::cancelPlayerEvents() {
+    mQueue.cancelEvent(mVideoEvent->eventID());
+    mVideoEventPending = false;
+    mQueue.cancelEvent(mStreamDoneEvent->eventID());
+    mStreamDoneEventPending = false;
+}
+
+void AwesomePlayer::setListener(const sp<MediaPlayerBase> &listener) {
+    Mutex::Autolock autoLock(mLock);
+    mListener = listener;
+}
+
+status_t AwesomePlayer::setDataSource(const char *uri) {
+    Mutex::Autolock autoLock(mLock);
+
+    reset_l();
+
+    sp<MediaExtractor> extractor = MediaExtractor::CreateFromURI(uri);
+
+    if (extractor == NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    return setDataSource_l(extractor);
+}
+
+status_t AwesomePlayer::setDataSource(
+        int fd, int64_t offset, int64_t length) {
+    Mutex::Autolock autoLock(mLock);
+
+    reset_l();
+
+    sp<DataSource> source = new FileSource(fd, offset, length);
+
+    status_t err = source->initCheck();
+
+    if (err != OK) {
+        return err;
+    }
+
+    sp<MediaExtractor> extractor = MediaExtractor::Create(source);
+
+    if (extractor == NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    return setDataSource_l(extractor);
+}
+
+status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {
+    reset_l();
+
+    bool haveAudio = false;
+    bool haveVideo = false;
+    for (size_t i = 0; i < extractor->countTracks(); ++i) {
+        sp<MetaData> meta = extractor->getTrackMetaData(i);
+
+        const char *mime;
+        CHECK(meta->findCString(kKeyMIMEType, &mime));
+
+        if (!haveVideo && !strncasecmp(mime, "video/", 6)) {
+            if (setVideoSource(extractor->getTrack(i)) == OK) {
+                haveVideo = true;
+            }
+        } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) {
+            if (setAudioSource(extractor->getTrack(i)) == OK) {
+                haveAudio = true;
+            }
+        }
+
+        if (haveAudio && haveVideo) {
+            break;
+        }
+    }
+
+    return !haveAudio && !haveVideo ? UNKNOWN_ERROR : OK;
+}
+
+void AwesomePlayer::reset() {
+    Mutex::Autolock autoLock(mLock);
+    reset_l();
+}
+
+void AwesomePlayer::reset_l() {
+    cancelPlayerEvents();
+
+    if (mLastVideoBuffer) {
+        mLastVideoBuffer->release();
+        mLastVideoBuffer = NULL;
+    }
+
+    if (mVideoBuffer) {
+        mVideoBuffer->release();
+        mVideoBuffer = NULL;
+    }
+
+    if (mVideoSource != NULL) {
+        mVideoSource->stop();
+        mVideoSource.clear();
+    }
+
+    mAudioSource.clear();
+
+    if (mTimeSource != mAudioPlayer) {
+        delete mTimeSource;
+    }
+    mTimeSource = NULL;
+
+    delete mAudioPlayer;
+    mAudioPlayer = NULL;
+
+    mVideoRenderer.clear();
+
+    mDurationUs = -1;
+    mFlags = 0;
+    mVideoWidth = mVideoHeight = -1;
+    mTimeSourceDeltaUs = 0;
+    mVideoTimeUs = 0;
+
+    mSeeking = false;
+    mSeekTimeUs = 0;
+}
+
+// static
+void AwesomePlayer::AudioNotify(void *_me, int what) {
+    AwesomePlayer *me = (AwesomePlayer *)_me;
+
+    Mutex::Autolock autoLock(me->mLock);
+
+    switch (what) {
+        case AudioPlayer::REACHED_EOS:
+            me->postStreamDoneEvent_l();
+            break;
+
+        case AudioPlayer::SEEK_COMPLETE:
+        {
+            if (me->mListener != NULL) {
+                me->mListener->sendEvent(MEDIA_SEEK_COMPLETE);
+            }
+
+            break;
+        }
+
+        default:
+            CHECK(!"should not be here.");
+            break;
+    }
+}
+
+void AwesomePlayer::onStreamDone() {
+    // Posted whenever any stream finishes playing.
+
+    Mutex::Autolock autoLock(mLock);
+    mStreamDoneEventPending = false;
+
+    if (mFlags & LOOPING) {
+        seekTo_l(0);
+
+        if (mVideoRenderer != NULL) {
+            postVideoEvent_l();
+        }
+    } else {
+        if (mListener != NULL) {
+            mListener->sendEvent(MEDIA_PLAYBACK_COMPLETE);
+        }
+
+        pause_l();
+    }
+}
+
+status_t AwesomePlayer::play() {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mFlags & PLAYING) {
+        return OK;
+    }
+
+    mFlags |= PLAYING;
+    mFlags |= FIRST_FRAME;
+
+    bool deferredAudioSeek = false;
+
+    if (mAudioSource != NULL) {
+        if (mAudioPlayer == NULL) {
+            if (mAudioSink != NULL) {
+                mAudioPlayer = new AudioPlayer(mAudioSink);
+
+                mAudioPlayer->setListenerCallback(
+                        &AwesomePlayer::AudioNotify, this);
+
+                mAudioPlayer->setSource(mAudioSource);
+                mAudioPlayer->start();
+
+                delete mTimeSource;
+                mTimeSource = mAudioPlayer;
+
+                deferredAudioSeek = true;
+            }
+        } else {
+            mAudioPlayer->resume();
+        }
+    }
+
+    if (mTimeSource == NULL && mAudioPlayer == NULL) {
+        mTimeSource = new SystemTimeSource;
+    }
+
+    if (mVideoSource != NULL) {
+        if (mVideoRenderer == NULL) {
+            initRenderer_l();
+        }
+
+        if (mVideoRenderer != NULL) {
+            // Kick off video playback
+            postVideoEvent_l();
+        }
+    }
+
+    if (deferredAudioSeek) {
+        // If there was a seek request while we were paused
+        // and we're just starting up again, honor the request now.
+        seekAudioIfNecessary_l();
+    }
+
+    return OK;
+}
+
+void AwesomePlayer::initRenderer_l() {
+    if (mISurface != NULL) {
+        sp<MetaData> meta = mVideoSource->getFormat();
+
+        int32_t format;
+        const char *component;
+        int32_t decodedWidth, decodedHeight;
+        CHECK(meta->findInt32(kKeyColorFormat, &format));
+        CHECK(meta->findCString(kKeyDecoderComponent, &component));
+        CHECK(meta->findInt32(kKeyWidth, &decodedWidth));
+        CHECK(meta->findInt32(kKeyHeight, &decodedHeight));
+
+        mVideoRenderer.clear();
+
+        // Must ensure that mVideoRenderer's destructor is actually executed
+        // before creating a new one.
+        IPCThreadState::self()->flushCommands();
+
+        if (!strncmp("OMX.", component, 4)) {
+            // Our OMX codecs allocate buffers on the media_server side
+            // therefore they require a remote IOMXRenderer that knows how
+            // to display them.
+            mVideoRenderer = new AwesomeRemoteRenderer(
+                mClient.interface()->createRenderer(
+                        mISurface, component,
+                        (OMX_COLOR_FORMATTYPE)format,
+                        decodedWidth, decodedHeight,
+                        mVideoWidth, mVideoHeight));
+        } else {
+            // Other decoders are instantiated locally and as a consequence
+            // allocate their buffers in local address space.
+            mVideoRenderer = new AwesomeLocalRenderer(
+                (OMX_COLOR_FORMATTYPE)format,
+                mISurface,
+                mVideoWidth, mVideoHeight,
+                decodedWidth, decodedHeight);
+        }
+    }
+}
+
+status_t AwesomePlayer::pause() {
+    Mutex::Autolock autoLock(mLock);
+    return pause_l();
+}
+
+status_t AwesomePlayer::pause_l() {
+    if (!(mFlags & PLAYING)) {
+        return OK;
+    }
+
+    cancelPlayerEvents();
+
+    if (mAudioPlayer != NULL) {
+        mAudioPlayer->pause();
+    }
+
+    mFlags &= ~PLAYING;
+
+    return OK;
+}
+
+bool AwesomePlayer::isPlaying() const {
+    Mutex::Autolock autoLock(mLock);
+
+    return mFlags & PLAYING;
+}
+
+void AwesomePlayer::setISurface(const sp<ISurface> &isurface) {
+    Mutex::Autolock autoLock(mLock);
+
+    mISurface = isurface;
+}
+
+void AwesomePlayer::setAudioSink(
+        const sp<MediaPlayerBase::AudioSink> &audioSink) {
+    Mutex::Autolock autoLock(mLock);
+
+    mAudioSink = audioSink;
+}
+
+status_t AwesomePlayer::setLooping(bool shouldLoop) {
+    Mutex::Autolock autoLock(mLock);
+
+    mFlags = mFlags & ~LOOPING;
+
+    if (shouldLoop) {
+        mFlags |= LOOPING;
+    }
+
+    return OK;
+}
+
+status_t AwesomePlayer::getDuration(int64_t *durationUs) {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mDurationUs < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    *durationUs = mDurationUs;
+
+    return OK;
+}
+
+status_t AwesomePlayer::getPosition(int64_t *positionUs) {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mVideoRenderer != NULL) {
+        *positionUs = mVideoTimeUs;
+    } else if (mAudioPlayer != NULL) {
+        *positionUs = mAudioPlayer->getMediaTimeUs();
+    } else {
+        *positionUs = 0;
+    }
+
+    return OK;
+}
+
+status_t AwesomePlayer::seekTo(int64_t timeUs) {
+    Mutex::Autolock autoLock(mLock);
+    return seekTo_l(timeUs);
+}
+
+status_t AwesomePlayer::seekTo_l(int64_t timeUs) {
+    mSeeking = true;
+    mSeekTimeUs = timeUs;
+
+    seekAudioIfNecessary_l();
+
+    return OK;
+}
+
+void AwesomePlayer::seekAudioIfNecessary_l() {
+    if (mSeeking && mVideoRenderer == NULL && mAudioPlayer != NULL) {
+        mAudioPlayer->seekTo(mSeekTimeUs);
+
+        mSeeking = false;
+    }
+}
+
+status_t AwesomePlayer::getVideoDimensions(
+        int32_t *width, int32_t *height) const {
+    Mutex::Autolock autoLock(mLock);
+
+    if (mVideoWidth < 0 || mVideoHeight < 0) {
+        return UNKNOWN_ERROR;
+    }
+
+    *width = mVideoWidth;
+    *height = mVideoHeight;
+
+    return OK;
+}
+
+status_t AwesomePlayer::setAudioSource(const sp<MediaSource> &source) {
+    if (source == NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    mAudioSource = OMXCodec::Create(
+            mClient.interface(), source->getFormat(),
+            false, // createEncoder
+            source);
+
+    if (mAudioSource != NULL) {
+        int64_t durationUs;
+        if (source->getFormat()->findInt64(kKeyDuration, &durationUs)) {
+            if (mDurationUs < 0 || durationUs > mDurationUs) {
+                mDurationUs = durationUs;
+            }
+        }
+    }
+
+    return mAudioSource != NULL ? OK : UNKNOWN_ERROR;
+}
+
+status_t AwesomePlayer::setVideoSource(const sp<MediaSource> &source) {
+    if (source == NULL) {
+        return UNKNOWN_ERROR;
+    }
+
+    mVideoSource = OMXCodec::Create(
+            mClient.interface(), source->getFormat(),
+            false, // createEncoder
+            source);
+
+    if (mVideoSource != NULL) {
+        int64_t durationUs;
+        if (source->getFormat()->findInt64(kKeyDuration, &durationUs)) {
+            if (mDurationUs < 0 || durationUs > mDurationUs) {
+                mDurationUs = durationUs;
+            }
+        }
+
+        CHECK(source->getFormat()->findInt32(kKeyWidth, &mVideoWidth));
+        CHECK(source->getFormat()->findInt32(kKeyHeight, &mVideoHeight));
+
+        mVideoSource->start();
+    }
+
+    return mVideoSource != NULL ? OK : UNKNOWN_ERROR;
+}
+
+void AwesomePlayer::onEvent(int32_t code) {
+    if (code == 1) {
+        onStreamDone();
+        return;
+    }
+
+    Mutex::Autolock autoLock(mLock);
+    mVideoEventPending = false;
+
+    if (mSeeking) {
+        if (mLastVideoBuffer) {
+            mLastVideoBuffer->release();
+            mLastVideoBuffer = NULL;
+        }
+
+        if (mVideoBuffer) {
+            mVideoBuffer->release();
+            mVideoBuffer = NULL;
+        }
+    }
+
+    if (!mVideoBuffer) {
+        MediaSource::ReadOptions options;
+        if (mSeeking) {
+            LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6);
+
+            options.setSeekTo(mSeekTimeUs);
+        }
+        for (;;) {
+            status_t err = mVideoSource->read(&mVideoBuffer, &options);
+            options.clearSeekTo();
+
+            if (err != OK) {
+                CHECK_EQ(mVideoBuffer, NULL);
+
+                if (err == INFO_FORMAT_CHANGED) {
+                    LOGV("VideoSource signalled format change.");
+
+                    initRenderer_l();
+                    continue;
+                }
+
+                postStreamDoneEvent_l();
+                return;
+            }
+
+            if (mVideoBuffer->range_length() == 0) {
+                // Some decoders, notably the PV AVC software decoder
+                // return spurious empty buffers that we just want to ignore.
+
+                mVideoBuffer->release();
+                mVideoBuffer = NULL;
+                continue;
+            }
+
+            break;
+        }
+    }
+
+    int64_t timeUs;
+    CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
+
+    mVideoTimeUs = timeUs;
+
+    if (mSeeking) {
+        if (mAudioPlayer != NULL) {
+            LOGV("seeking audio to %lld us (%.2f secs).", timeUs, timeUs / 1E6);
+
+            mAudioPlayer->seekTo(timeUs);
+        } else {
+            // If we're playing video only, report seek complete now,
+            // otherwise audio player will notify us later.
+            if (mListener != NULL) {
+                mListener->sendEvent(MEDIA_SEEK_COMPLETE);
+            }
+        }
+
+        mFlags |= FIRST_FRAME;
+        mSeeking = false;
+    }
+
+    if (mFlags & FIRST_FRAME) {
+        mFlags &= ~FIRST_FRAME;
+
+        mTimeSourceDeltaUs = mTimeSource->getRealTimeUs() - timeUs;
+    }
+
+    int64_t realTimeUs, mediaTimeUs;
+    if (mAudioPlayer != NULL
+        && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) {
+        mTimeSourceDeltaUs = realTimeUs - mediaTimeUs;
+    }
+
+    int64_t nowUs = mTimeSource->getRealTimeUs() - mTimeSourceDeltaUs;
+
+    int64_t latenessUs = nowUs - timeUs;
+
+    if (latenessUs > 40000) {
+        // We're more than 40ms late.
+        LOGI("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
+
+        mVideoBuffer->release();
+        mVideoBuffer = NULL;
+
+        postVideoEvent_l();
+        return;
+    }
+
+    if (latenessUs < -10000) {
+        // We're more than 10ms early.
+
+        postVideoEvent_l(10000);
+        return;
+    }
+
+    mVideoRenderer->render(mVideoBuffer);
+
+    if (mLastVideoBuffer) {
+        mLastVideoBuffer->release();
+        mLastVideoBuffer = NULL;
+    }
+    mLastVideoBuffer = mVideoBuffer;
+    mVideoBuffer = NULL;
+
+    postVideoEvent_l();
+}
+
+void AwesomePlayer::postVideoEvent_l(int64_t delayUs) {
+    if (mVideoEventPending) {
+        return;
+    }
+
+    mVideoEventPending = true;
+    mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs);
+}
+
+void AwesomePlayer::postStreamDoneEvent_l() {
+    if (mStreamDoneEventPending) {
+        return;
+    }
+    mStreamDoneEventPending = true;
+    mQueue.postEvent(mStreamDoneEvent);
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/CachingDataSource.cpp b/media/libstagefright/CachingDataSource.cpp
index fd00576..23f4897 100644
--- a/media/libstagefright/CachingDataSource.cpp
+++ b/media/libstagefright/CachingDataSource.cpp
@@ -61,11 +61,11 @@
     mData = NULL;
 }
 
-status_t CachingDataSource::InitCheck() const {
-    return OK;
+status_t CachingDataSource::initCheck() const {
+    return mSource->initCheck();
 }
 
-ssize_t CachingDataSource::read_at(off_t offset, void *data, size_t size) {
+ssize_t CachingDataSource::readAt(off_t offset, void *data, size_t size) {
     Mutex::Autolock autoLock(mLock);
 
     size_t total = 0;
@@ -82,7 +82,7 @@
         if (page == NULL) {
             page = allocate_page();
             page->mOffset = offset - offset % mPageSize;
-            ssize_t n = mSource->read_at(page->mOffset, page->mData, mPageSize);
+            ssize_t n = mSource->readAt(page->mOffset, page->mData, mPageSize);
             if (n < 0) {
                 page->mLength = 0;
             } else {
diff --git a/media/libstagefright/CameraSource.cpp b/media/libstagefright/CameraSource.cpp
index 596ab67..bd862e0 100644
--- a/media/libstagefright/CameraSource.cpp
+++ b/media/libstagefright/CameraSource.cpp
@@ -19,122 +19,168 @@
 #include <OMX_Component.h>
 
 #include <binder/IServiceManager.h>
+#include <cutils/properties.h> // for property_get
 #include <media/stagefright/CameraSource.h>
 #include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaErrors.h>
 #include <media/stagefright/MetaData.h>
-#include <ui/ICameraClient.h>
-#include <ui/ICameraService.h>
+#include <ui/Camera.h>
+#include <ui/CameraParameters.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/ISurface.h>
 #include <ui/Overlay.h>
-#include <utils/String16.h>
+#include <utils/String8.h>
 
 namespace android {
 
-class CameraBuffer : public MediaBuffer {
-public:
-    CameraBuffer(const sp<IMemory> &frame)
-        : MediaBuffer(frame->pointer(), frame->size()),
-          mFrame(frame) {
-    }
+static int64_t getNowUs() {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
 
-    sp<IMemory> releaseFrame() {
-        sp<IMemory> frame = mFrame;
-        mFrame.clear();
-        return frame;
-    }
+    return (int64_t)tv.tv_usec + tv.tv_sec * 1000000;
+}
 
-private:
-    sp<IMemory> mFrame;
-};
-
-class CameraSourceClient : public BnCameraClient {
-public:
-    CameraSourceClient()
-        : mSource(NULL) {
-    }
-
-    virtual void notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2) {
-        CHECK(mSource != NULL);
-        mSource->notifyCallback(msgType, ext1, ext2);
-    }
-
-    virtual void dataCallback(int32_t msgType, const sp<IMemory> &data) {
-        CHECK(mSource != NULL);
-        mSource->dataCallback(msgType, data);
-    }
-
-    void setCameraSource(CameraSource *source) {
-        mSource = source;
-    }
-
-private:
-    CameraSource *mSource;
-};
-
-class DummySurface : public BnSurface {
-public:
+struct DummySurface : public BnSurface {
     DummySurface() {}
 
+    virtual sp<GraphicBuffer> requestBuffer(int bufferIdx, int usage) {
+        return NULL;
+    }
+
     virtual status_t registerBuffers(const BufferHeap &buffers) {
         return OK;
     }
 
-    virtual void postBuffer(ssize_t offset) {
-    }
+    virtual void postBuffer(ssize_t offset) {}
+    virtual void unregisterBuffers() {}
 
-    virtual void unregisterBuffers() {
-    }
-    
     virtual sp<OverlayRef> createOverlay(
             uint32_t w, uint32_t h, int32_t format) {
         return NULL;
     }
+
+protected:
+    virtual ~DummySurface() {}
+
+    DummySurface(const DummySurface &);
+    DummySurface &operator=(const DummySurface &);
 };
 
+struct CameraSourceListener : public CameraListener {
+    CameraSourceListener(const sp<CameraSource> &source);
+
+    virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2);
+    virtual void postData(int32_t msgType, const sp<IMemory> &dataPtr);
+
+    virtual void postDataTimestamp(
+            nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr);
+
+protected:
+    virtual ~CameraSourceListener();
+
+private:
+    wp<CameraSource> mSource;
+
+    CameraSourceListener(const CameraSourceListener &);
+    CameraSourceListener &operator=(const CameraSourceListener &);
+};
+
+CameraSourceListener::CameraSourceListener(const sp<CameraSource> &source)
+    : mSource(source) {
+}
+
+CameraSourceListener::~CameraSourceListener() {
+}
+
+void CameraSourceListener::notify(int32_t msgType, int32_t ext1, int32_t ext2) {
+    LOGV("notify(%d, %d, %d)", msgType, ext1, ext2);
+}
+
+void CameraSourceListener::postData(int32_t msgType, const sp<IMemory> &dataPtr) {
+    LOGV("postData(%d, ptr:%p, size:%d)",
+         msgType, dataPtr->pointer(), dataPtr->size());
+
+    sp<CameraSource> source = mSource.promote();
+    if (source.get() != NULL) {
+        source->dataCallback(msgType, dataPtr);
+    }
+}
+
+void CameraSourceListener::postDataTimestamp(
+        nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr) {
+    LOGV("postDataTimestamp(%lld, %d, ptr:%p, size:%d)",
+         timestamp, msgType, dataPtr->pointer(), dataPtr->size());
+}
+
 // static
 CameraSource *CameraSource::Create() {
-    sp<IServiceManager> sm = defaultServiceManager();
+    sp<Camera> camera = Camera::connect();
 
-    sp<ICameraService> service =
-        interface_cast<ICameraService>(
-                sm->getService(String16("media.camera")));
+    if (camera.get() == NULL) {
+        return NULL;
+    }
 
-    sp<CameraSourceClient> client = new CameraSourceClient;
-    sp<ICamera> camera = service->connect(client);
-
-    CameraSource *source = new CameraSource(camera, client);
-    client->setCameraSource(source);
-
-    return source;
+    return new CameraSource(camera);
 }
 
-CameraSource::CameraSource(
-        const sp<ICamera> &camera, const sp<ICameraClient> &client)
+// static
+CameraSource *CameraSource::CreateFromICamera(const sp<ICamera> &icamera) {
+    sp<Camera> camera = Camera::create(icamera);
+
+    if (camera.get() == NULL) {
+        return NULL;
+    }
+
+    return new CameraSource(camera);
+}
+
+CameraSource::CameraSource(const sp<Camera> &camera)
     : mCamera(camera),
-      mCameraClient(client),
+      mWidth(0),
+      mHeight(0),
+      mFirstFrameTimeUs(0),
       mNumFrames(0),
       mStarted(false) {
-    printf("params: \"%s\"\n", mCamera->getParameters().string());
+    char value[PROPERTY_VALUE_MAX];
+    if (property_get("ro.hardware", value, NULL) && !strcmp(value, "sholes")) {
+        // The hardware encoder(s) do not support yuv420, but only YCbYCr,
+        // fortunately the camera also supports this, so we needn't transcode.
+        mCamera->setParameters(String8("preview-format=yuv422i-yuyv"));
+    }
+
+    String8 s = mCamera->getParameters();
+    printf("params: \"%s\"\n", s.string());
+
+    CameraParameters params(s);
+    params.getPreviewSize(&mWidth, &mHeight);
 }
 
 CameraSource::~CameraSource() {
     if (mStarted) {
         stop();
     }
+}
 
-    mCamera->disconnect();
+void CameraSource::setPreviewSurface(const sp<ISurface> &surface) {
+    mPreviewSurface = surface;
 }
 
 status_t CameraSource::start(MetaData *) {
     CHECK(!mStarted);
 
-    status_t err = mCamera->lock();
+    mCamera->setListener(new CameraSourceListener(this));
+
+    status_t err =
+        mCamera->setPreviewDisplay(
+                mPreviewSurface != NULL ? mPreviewSurface : new DummySurface);
     CHECK_EQ(err, OK);
 
-    err = mCamera->setPreviewDisplay(new DummySurface);
-    CHECK_EQ(err, OK);
-    mCamera->setPreviewCallbackFlag(1);
-    mCamera->startPreview();
+    mCamera->setPreviewCallbackFlags(
+            FRAME_CALLBACK_FLAG_ENABLE_MASK
+            | FRAME_CALLBACK_FLAG_COPY_OUT_MASK);
+
+    err = mCamera->startPreview();
     CHECK_EQ(err, OK);
 
     mStarted = true;
@@ -146,7 +192,6 @@
     CHECK(mStarted);
 
     mCamera->stopPreview();
-    mCamera->unlock();
 
     mStarted = false;
 
@@ -157,8 +202,8 @@
     sp<MetaData> meta = new MetaData;
     meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
     meta->setInt32(kKeyColorFormat, OMX_COLOR_FormatYUV420SemiPlanar);
-    meta->setInt32(kKeyWidth, 480);
-    meta->setInt32(kKeyHeight, 320);
+    meta->setInt32(kKeyWidth, mWidth);
+    meta->setInt32(kKeyHeight, mHeight);
 
     return meta;
 }
@@ -175,6 +220,7 @@
     }
 
     sp<IMemory> frame;
+    int64_t frameTime;
 
     {
         Mutex::Autolock autoLock(mLock);
@@ -184,41 +230,33 @@
 
         frame = *mFrames.begin();
         mFrames.erase(mFrames.begin());
+
+        frameTime = *mFrameTimes.begin();
+        mFrameTimes.erase(mFrameTimes.begin());
     }
 
-    int count = mNumFrames++;
-
-    *buffer = new CameraBuffer(frame);
+    *buffer = new MediaBuffer(frame->size());
+    memcpy((*buffer)->data(), frame->pointer(), frame->size());
+    (*buffer)->set_range(0, frame->size());
 
     (*buffer)->meta_data()->clear();
-    (*buffer)->meta_data()->setInt32(kKeyTimeScale, 15);
-    (*buffer)->meta_data()->setInt32(kKeyTimeUnits, count);
-
-    (*buffer)->add_ref();
-    (*buffer)->setObserver(this);
+    (*buffer)->meta_data()->setInt64(kKeyTime, frameTime);
 
     return OK;
 }
 
-void CameraSource::notifyCallback(int32_t msgType, int32_t ext1, int32_t ext2) {
-    printf("notifyCallback %d, %d, %d\n", msgType, ext1, ext2);
-}
-
 void CameraSource::dataCallback(int32_t msgType, const sp<IMemory> &data) {
     Mutex::Autolock autoLock(mLock);
 
+    int64_t nowUs = getNowUs();
+    if (mNumFrames == 0) {
+        mFirstFrameTimeUs = nowUs;
+    }
+    ++mNumFrames;
+
     mFrames.push_back(data);
+    mFrameTimes.push_back(nowUs - mFirstFrameTimeUs);
     mFrameAvailableCondition.signal();
 }
 
-void CameraSource::signalBufferReturned(MediaBuffer *_buffer) {
-    CameraBuffer *buffer = static_cast<CameraBuffer *>(_buffer);
-
-    mCamera->releaseRecordingFrame(buffer->releaseFrame());
-
-    buffer->setObserver(NULL);
-    buffer->release();
-    buffer = NULL;
-}
-
 }  // namespace android
diff --git a/media/libstagefright/DataSource.cpp b/media/libstagefright/DataSource.cpp
index daac539..2a6dbc4 100644
--- a/media/libstagefright/DataSource.cpp
+++ b/media/libstagefright/DataSource.cpp
@@ -14,11 +14,13 @@
  * limitations under the License.
  */
 
-#include <media/stagefright/AMRExtractor.h>
+#include "include/AMRExtractor.h"
+#include "include/MP3Extractor.h"
+#include "include/MPEG4Extractor.h"
+#include "include/WAVExtractor.h"
+
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/MP3Extractor.h>
-#include <media/stagefright/MPEG4Extractor.h>
 #include <utils/String8.h>
 
 namespace android {
@@ -27,7 +29,7 @@
     *x = 0;
 
     uint8_t byte[2];
-    if (read_at(offset, byte, 2) != 2) {
+    if (readAt(offset, byte, 2) != 2) {
         return false;
     }
 
@@ -86,6 +88,7 @@
     RegisterSniffer(SniffMP3);
     RegisterSniffer(SniffMPEG4);
     RegisterSniffer(SniffAMR);
+    RegisterSniffer(SniffWAV);
 }
 
 }  // namespace android
diff --git a/media/libstagefright/ESDS.cpp b/media/libstagefright/ESDS.cpp
index 53b92a0..28d338c 100644
--- a/media/libstagefright/ESDS.cpp
+++ b/media/libstagefright/ESDS.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include <media/stagefright/ESDS.h>
+#include "include/ESDS.h"
 
 #include <string.h>
 
diff --git a/media/libstagefright/FileSource.cpp b/media/libstagefright/FileSource.cpp
index f6b90b2..37c2450 100644
--- a/media/libstagefright/FileSource.cpp
+++ b/media/libstagefright/FileSource.cpp
@@ -20,7 +20,17 @@
 namespace android {
 
 FileSource::FileSource(const char *filename)
-    : mFile(fopen(filename, "rb")) {
+    : mFile(fopen(filename, "rb")),
+      mOffset(0),
+      mLength(-1) {
+}
+
+FileSource::FileSource(int fd, int64_t offset, int64_t length)
+    : mFile(fdopen(fd, "rb")),
+      mOffset(offset),
+      mLength(length) {
+    CHECK(offset >= 0);
+    CHECK(length >= 0);
 }
 
 FileSource::~FileSource() {
@@ -30,19 +40,40 @@
     }
 }
 
-status_t FileSource::InitCheck() const {
+status_t FileSource::initCheck() const {
     return mFile != NULL ? OK : NO_INIT;
 }
 
-ssize_t FileSource::read_at(off_t offset, void *data, size_t size) {
+ssize_t FileSource::readAt(off_t offset, void *data, size_t size) {
     Mutex::Autolock autoLock(mLock);
 
-    int err = fseeko(mFile, offset, SEEK_SET);
+    if (mLength >= 0) {
+        if (offset >= mLength) {
+            return 0;  // read beyond EOF.
+        }
+        int64_t numAvailable = mLength - offset;
+        if ((int64_t)size > numAvailable) {
+            size = numAvailable;
+        }
+    }
+
+    int err = fseeko(mFile, offset + mOffset, SEEK_SET);
     CHECK(err != -1);
 
-    ssize_t result = fread(data, 1, size, mFile);
+    return fread(data, 1, size, mFile);
+}
 
-    return result;
+status_t FileSource::getSize(off_t *size) {
+    if (mLength >= 0) {
+        *size = mLength;
+
+        return OK;
+    }
+
+    fseek(mFile, 0, SEEK_END);
+    *size = ftello(mFile);
+
+    return OK;
 }
 
 }  // namespace android
diff --git a/media/libstagefright/HTTPDataSource.cpp b/media/libstagefright/HTTPDataSource.cpp
index 4dedebd..5536801 100644
--- a/media/libstagefright/HTTPDataSource.cpp
+++ b/media/libstagefright/HTTPDataSource.cpp
@@ -14,17 +14,19 @@
  * limitations under the License.
  */
 
+#include "include/stagefright_string.h"
+#include "include/HTTPStream.h"
+
 #include <stdlib.h>
 
 #include <media/stagefright/HTTPDataSource.h>
-#include <media/stagefright/HTTPStream.h>
 #include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/stagefright_string.h>
 
 namespace android {
 
 HTTPDataSource::HTTPDataSource(const char *uri)
-    : mHost(NULL),
+    : mHttp(new HTTPStream),
+      mHost(NULL),
       mPort(0),
       mPath(NULL),
       mBuffer(malloc(kBufferSize)),
@@ -65,33 +67,40 @@
     mPort = port;
     mPath = strdup(path.c_str());
 
-    status_t err = mHttp.connect(mHost, mPort);
-    CHECK_EQ(err, OK);
+    mInitCheck = mHttp->connect(mHost, mPort);
 }
 
 HTTPDataSource::HTTPDataSource(const char *host, int port, const char *path)
-    : mHost(strdup(host)),
+    : mHttp(new HTTPStream),
+      mHost(strdup(host)),
       mPort(port),
       mPath(strdup(path)),
       mBuffer(malloc(kBufferSize)),
       mBufferLength(0),
       mBufferOffset(0) {
-    status_t err = mHttp.connect(mHost, mPort);
-    CHECK_EQ(err, OK);
+    mInitCheck = mHttp->connect(mHost, mPort);
+}
+
+status_t HTTPDataSource::initCheck() const {
+    return mInitCheck;
 }
 
 HTTPDataSource::~HTTPDataSource() {
-    mHttp.disconnect();
+    mHttp->disconnect();
 
     free(mBuffer);
     mBuffer = NULL;
 
     free(mPath);
     mPath = NULL;
+
+    delete mHttp;
+    mHttp = NULL;
 }
 
-ssize_t HTTPDataSource::read_at(off_t offset, void *data, size_t size) {
-    if (offset >= mBufferOffset && offset < mBufferOffset + mBufferLength) {
+ssize_t HTTPDataSource::readAt(off_t offset, void *data, size_t size) {
+    if (offset >= mBufferOffset
+            && offset < (off_t)(mBufferOffset + mBufferLength)) {
         size_t num_bytes_available = mBufferLength - (offset - mBufferOffset);
 
         size_t copy = num_bytes_available;
@@ -119,19 +128,19 @@
     status_t err;
     int attempt = 1;
     for (;;) {
-        if ((err = mHttp.send("GET ")) != OK
-            || (err = mHttp.send(mPath)) != OK
-            || (err = mHttp.send(" HTTP/1.1\r\n")) != OK
-            || (err = mHttp.send(host)) != OK
-            || (err = mHttp.send(range)) != OK
-            || (err = mHttp.send("\r\n")) != OK
-            || (err = mHttp.receive_header(&http_status)) != OK) {
+        if ((err = mHttp->send("GET ")) != OK
+            || (err = mHttp->send(mPath)) != OK
+            || (err = mHttp->send(" HTTP/1.1\r\n")) != OK
+            || (err = mHttp->send(host)) != OK
+            || (err = mHttp->send(range)) != OK
+            || (err = mHttp->send("\r\n")) != OK
+            || (err = mHttp->receive_header(&http_status)) != OK) {
 
             if (attempt == 3) {
                 return err;
             }
 
-            mHttp.connect(mHost, mPort);
+            mHttp->connect(mHost, mPort);
             ++attempt;
         } else {
             break;
@@ -143,14 +152,14 @@
     }
 
     string value;
-    if (!mHttp.find_header_value("Content-Length", &value)) {
+    if (!mHttp->find_header_value("Content-Length", &value)) {
         return UNKNOWN_ERROR;
     }
 
     char *end;
     unsigned long contentLength = strtoul(value.c_str(), &end, 10);
 
-    ssize_t num_bytes_received = mHttp.receive(mBuffer, contentLength);
+    ssize_t num_bytes_received = mHttp->receive(mBuffer, contentLength);
 
     if (num_bytes_received <= 0) {
         return num_bytes_received;
diff --git a/media/libstagefright/HTTPStream.cpp b/media/libstagefright/HTTPStream.cpp
index 6af7df9..02f9439 100644
--- a/media/libstagefright/HTTPStream.cpp
+++ b/media/libstagefright/HTTPStream.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include "include/HTTPStream.h"
+
 #include <sys/socket.h>
 
 #include <arpa/inet.h>
@@ -25,7 +27,6 @@
 #include <string.h>
 #include <unistd.h>
 
-#include <media/stagefright/HTTPStream.h>
 #include <media/stagefright/MediaDebug.h>
 
 namespace android {
diff --git a/media/libstagefright/JPEGSource.cpp b/media/libstagefright/JPEGSource.cpp
index d1dfd83..a4be2dd 100644
--- a/media/libstagefright/JPEGSource.cpp
+++ b/media/libstagefright/JPEGSource.cpp
@@ -119,7 +119,7 @@
     MediaBuffer *buffer;
     mGroup->acquire_buffer(&buffer);
 
-    ssize_t n = mSource->read_at(mOffset, buffer->data(), mSize - mOffset);
+    ssize_t n = mSource->readAt(mOffset, buffer->data(), mSize - mOffset);
 
     if (n <= 0) {
         buffer->release();
@@ -156,13 +156,13 @@
 
     for (;;) {
         uint8_t marker;
-        if (mSource->read_at(i++, &marker, 1) != 1) {
+        if (mSource->readAt(i++, &marker, 1) != 1) {
             return ERROR_IO;
         }
 
         CHECK_EQ(marker, 0xff);
 
-        if (mSource->read_at(i++, &marker, 1) != 1) {
+        if (mSource->readAt(i++, &marker, 1) != 1) {
             return ERROR_IO;
         }
 
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 7fd699f..14e6177 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -18,8 +18,9 @@
 #define LOG_TAG "MP3Extractor"
 #include <utils/Log.h>
 
+#include "include/MP3Extractor.h"
+
 #include <media/stagefright/DataSource.h>
-#include <media/stagefright/MP3Extractor.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
@@ -32,6 +33,10 @@
 
 namespace android {
 
+// Everything must match except for
+// protection, bitrate, padding, private bits and mode extension.
+static const uint32_t kMask = 0xfffe0ccf;
+
 static bool get_mp3_frame_size(
         uint32_t header, size_t *frame_size,
         int *out_sampling_rate = NULL, int *out_channels = NULL,
@@ -59,7 +64,7 @@
     if (version == 0x01) {
         return false;
     }
-    
+
     unsigned layer = (header >> 17) & 3;
 
     if (layer == 0x00) {
@@ -147,7 +152,12 @@
             *out_bitrate = bitrate;
         }
 
-        *frame_size = 144000 * bitrate / sampling_rate + padding;
+        if (version == 3 /* V1 */) {
+            *frame_size = 144000 * bitrate / sampling_rate + padding;
+        } else {
+            // V2 or V2.5
+            *frame_size = 72000 * bitrate / sampling_rate + padding;
+        }
     }
 
     if (out_sampling_rate) {
@@ -163,16 +173,166 @@
     return true;
 }
 
+static bool parse_xing_header(
+        const sp<DataSource> &source, off_t first_frame_pos,
+        int32_t *frame_number = NULL, int32_t *byte_number = NULL,
+        char *table_of_contents = NULL, int32_t *quality_indicator = NULL,
+        int64_t *duration = NULL) {
+
+    if (frame_number) {
+        *frame_number = 0;
+    }
+    if (byte_number) {
+        *byte_number = 0;
+    }
+    if (table_of_contents) {
+        table_of_contents[0] = 0;
+    }
+    if (quality_indicator) {
+        *quality_indicator = 0;
+    }
+    if (duration) {
+        *duration = 0;
+    }
+
+    uint8_t buffer[4];
+    int offset = first_frame_pos;
+    if (source->readAt(offset, &buffer, 4) < 4) { // get header
+        return false;
+    }
+    offset += 4;
+
+    uint8_t id, layer, sr_index, mode;
+    layer = (buffer[1] >> 1) & 3;
+    id = (buffer[1] >> 3) & 3;
+    sr_index = (buffer[2] >> 2) & 3;
+    mode = (buffer[3] >> 6) & 3;
+    if (layer == 0) {
+        return false;
+    }
+    if (id == 1) {
+        return false;
+    }
+    if (sr_index == 3) {
+        return false;
+    }
+    // determine offset of XING header
+    if(id&1) { // mpeg1
+        if (mode != 3) offset += 32;
+        else offset += 17;
+    } else { // mpeg2
+        if (mode != 3) offset += 17;
+        else offset += 9;
+    }
+
+    if (source->readAt(offset, &buffer, 4) < 4) { // XING header ID
+        return false;
+    }
+    offset += 4;
+    // Check XING ID
+    if ((buffer[0] != 'X') || (buffer[1] != 'i')
+                || (buffer[2] != 'n') || (buffer[3] != 'g')) {
+        if ((buffer[0] != 'I') || (buffer[1] != 'n')
+                    || (buffer[2] != 'f') || (buffer[3] != 'o')) {
+            return false;
+        }
+    }
+
+    if (source->readAt(offset, &buffer, 4) < 4) { // flags
+        return false;
+    }
+    offset += 4;
+    uint32_t flags = U32_AT(buffer);
+
+    if (flags & 0x0001) {  // Frames field is present
+        if (source->readAt(offset, buffer, 4) < 4) {
+             return false;
+        }
+        if (frame_number) {
+           *frame_number = U32_AT(buffer);
+        }
+        int32_t frame = U32_AT(buffer);
+        // Samples per Frame: 1. index = MPEG Version ID, 2. index = Layer
+        const int samplesPerFrames[2][3] =
+        {
+            { 384, 1152, 576  }, // MPEG 2, 2.5: layer1, layer2, layer3
+            { 384, 1152, 1152 }, // MPEG 1: layer1, layer2, layer3
+        };
+        // sampling rates in hertz: 1. index = MPEG Version ID, 2. index = sampling rate index
+        const int samplingRates[4][3] =
+        {
+            { 11025, 12000, 8000,  },    // MPEG 2.5
+            { 0,     0,     0,     },    // reserved
+            { 22050, 24000, 16000, },    // MPEG 2
+            { 44100, 48000, 32000, }     // MPEG 1
+        };
+        if (duration) {
+            *duration = (int64_t)frame * samplesPerFrames[id&1][3-layer] * 1000000LL
+                / samplingRates[id][sr_index];
+        }
+        offset += 4;
+    }
+    if (flags & 0x0002) {  // Bytes field is present
+        if (byte_number) {
+            if (source->readAt(offset, buffer, 4) < 4) {
+                return false;
+            }
+            *byte_number = U32_AT(buffer);
+        }
+        offset += 4;
+    }
+    if (flags & 0x0004) {  // TOC field is present
+       if (table_of_contents) {
+            if (source->readAt(offset + 1, table_of_contents, 99) < 99) {
+                return false;
+            }
+        }
+        offset += 100;
+    }
+    if (flags & 0x0008) {  // Quality indicator field is present
+        if (quality_indicator) {
+            if (source->readAt(offset, buffer, 4) < 4) {
+                return false;
+            }
+            *quality_indicator = U32_AT(buffer);
+        }
+    }
+    return true;
+}
+
 static bool Resync(
         const sp<DataSource> &source, uint32_t match_header,
         off_t *inout_pos, uint32_t *out_header) {
-    // Everything must match except for
-    // protection, bitrate, padding, private bits and mode extension.
-    const uint32_t kMask = 0xfffe0ccf;
+    if (*inout_pos == 0) {
+        // Skip an optional ID3 header if syncing at the very beginning
+        // of the datasource.
+
+        uint8_t id3header[10];
+        if (source->readAt(0, id3header, sizeof(id3header))
+                < (ssize_t)sizeof(id3header)) {
+            // If we can't even read these 10 bytes, we might as well bail out,
+            // even if there _were_ 10 bytes of valid mp3 audio data...
+            return false;
+        }
+
+        if (id3header[0] == 'I' && id3header[1] == 'D' && id3header[2] == '3') {
+            // Skip the ID3v2 header.
+
+            size_t len =
+                ((id3header[6] & 0x7f) << 21)
+                | ((id3header[7] & 0x7f) << 14)
+                | ((id3header[8] & 0x7f) << 7)
+                | (id3header[9] & 0x7f);
+
+            len += 10;
+
+            *inout_pos += len;
+        }
+    }
 
     const size_t kMaxFrameSize = 4096;
     uint8_t *buffer = new uint8_t[kMaxFrameSize];
-    
+
     off_t pos = *inout_pos - kMaxFrameSize;
     size_t buffer_offset = kMaxFrameSize;
     size_t buffer_length = kMaxFrameSize;
@@ -195,7 +355,7 @@
             buffer_length = buffer_length - buffer_offset;
             buffer_offset = 0;
 
-            ssize_t n = source->read_at(
+            ssize_t n = source->readAt(
                     pos, &buffer[buffer_length], kMaxFrameSize - buffer_length);
 
             if (n <= 0) {
@@ -232,11 +392,11 @@
         valid = true;
         for (int j = 0; j < 3; ++j) {
             uint8_t tmp[4];
-            if (source->read_at(test_pos, tmp, 4) < 4) {
+            if (source->readAt(test_pos, tmp, 4) < 4) {
                 valid = false;
                 break;
             }
-            
+
             uint32_t test_header = U32_AT(tmp);
 
             LOGV("subsequent header is %08x", test_header);
@@ -281,7 +441,8 @@
 public:
     MP3Source(
             const sp<MetaData> &meta, const sp<DataSource> &source,
-            off_t first_frame_pos, uint32_t fixed_header);
+            off_t first_frame_pos, uint32_t fixed_header,
+            int32_t byte_number, const char *table_of_contents);
 
     virtual status_t start(MetaData *params = NULL);
     virtual status_t stop();
@@ -302,7 +463,9 @@
     off_t mCurrentPos;
     int64_t mCurrentTimeUs;
     bool mStarted;
-
+    int32_t mByteNumber; // total number of bytes in this MP3
+    // TOC entries in XING header. Skip the first one since it's always 0.
+    char mTableOfContents[99];
     MediaBufferGroup *mGroup;
 
     MP3Source(const MP3Source &);
@@ -312,7 +475,8 @@
 MP3Extractor::MP3Extractor(const sp<DataSource> &source)
     : mDataSource(source),
       mFirstFramePos(-1),
-      mFixedHeader(0) {
+      mFixedHeader(0),
+      mByteNumber(0) {
     off_t pos = 0;
     uint32_t header;
     bool success = Resync(mDataSource, 0, &pos, &header);
@@ -333,15 +497,22 @@
 
         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;
-        if (mDataSource->getSize(&fileSize) == OK) {
-            mMeta->setInt32(
-                    kKeyDuration,
-                    8 * (fileSize - mFirstFramePos) / bitrate);
-            mMeta->setInt32(kKeyTimeScale, 1000);
+        int64_t duration;
+        parse_xing_header(
+                mDataSource, mFirstFramePos, NULL, &mByteNumber,
+                mTableOfContents, NULL, &duration);
+        if (duration > 0) {
+            mMeta->setInt64(kKeyDuration, duration);
+        } else {
+            off_t fileSize;
+            if (mDataSource->getSize(&fileSize) == OK) {
+                mMeta->setInt64(
+                        kKeyDuration,
+                        8000LL * (fileSize - mFirstFramePos) / bitrate);
+            }
         }
     }
 }
@@ -359,10 +530,11 @@
     }
 
     return new MP3Source(
-            mMeta, mDataSource, mFirstFramePos, mFixedHeader);
+            mMeta, mDataSource, mFirstFramePos, mFixedHeader,
+            mByteNumber, mTableOfContents);
 }
 
-sp<MetaData> MP3Extractor::getTrackMetaData(size_t index) {
+sp<MetaData> MP3Extractor::getTrackMetaData(size_t index, uint32_t flags) {
     if (mFirstFramePos < 0 || index != 0) {
         return NULL;
     }
@@ -374,7 +546,8 @@
 
 MP3Source::MP3Source(
         const sp<MetaData> &meta, const sp<DataSource> &source,
-        off_t first_frame_pos, uint32_t fixed_header)
+        off_t first_frame_pos, uint32_t fixed_header,
+        int32_t byte_number, const char *table_of_contents)
     : mMeta(meta),
       mDataSource(source),
       mFirstFramePos(first_frame_pos),
@@ -382,7 +555,9 @@
       mCurrentPos(0),
       mCurrentTimeUs(0),
       mStarted(false),
+      mByteNumber(byte_number),
       mGroup(NULL) {
+    memcpy (mTableOfContents, table_of_contents, strlen(table_of_contents));
 }
 
 MP3Source::~MP3Source() {
@@ -430,14 +605,42 @@
     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;
+        // interpolate in TOC to get file seek point in bytes
+        int64_t duration;
+        if ((mByteNumber > 0) && (mTableOfContents[0] > 0)
+            && mMeta->findInt64(kKeyDuration, &duration)) {
+            float percent = (float)seekTimeUs * 100 / duration;
+            float fx;
+            if( percent <= 0.0f ) {
+                fx = 0.0f;
+            } else if( percent >= 100.0f ) {
+                fx = 256.0f;
+            } else {
+                int a = (int)percent;
+                float fa, fb;
+                if ( a == 0 ) {
+                    fa = 0.0f;
+                } else {
+                    fa = (float)mTableOfContents[a-1];
+                }
+                if ( a < 99 ) {
+                    fb = (float)mTableOfContents[a];
+                } else {
+                    fb = 256.0f;
+                }
+                fx = fa + (fb-fa)*(percent-a);
+            }
+            mCurrentPos = mFirstFramePos + (int)((1.0f/256.0f)*fx*mByteNumber);
+        } else {
+            mCurrentPos = mFirstFramePos + seekTimeUs * bitrate / 8000000;
+        }
     }
 
     MediaBuffer *buffer;
@@ -448,7 +651,7 @@
 
     size_t frame_size;
     for (;;) {
-        ssize_t n = mDataSource->read_at(mCurrentPos, buffer->data(), 4);
+        ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), 4);
         if (n < 4) {
             buffer->release();
             buffer = NULL;
@@ -457,8 +660,9 @@
         }
 
         uint32_t header = U32_AT((const uint8_t *)buffer->data());
-        
-        if (get_mp3_frame_size(header, &frame_size)) {
+
+        if ((header & kMask) == (mFixedHeader & kMask)
+            && get_mp3_frame_size(header, &frame_size)) {
             break;
         }
 
@@ -482,7 +686,7 @@
 
     CHECK(frame_size <= buffer->size());
 
-    ssize_t n = mDataSource->read_at(mCurrentPos, buffer->data(), frame_size);
+    ssize_t n = mDataSource->readAt(mCurrentPos, buffer->data(), frame_size);
     if (n < (ssize_t)frame_size) {
         buffer->release();
         buffer = NULL;
@@ -492,8 +696,7 @@
 
     buffer->set_range(0, frame_size);
 
-    buffer->meta_data()->setInt32(kKeyTimeUnits, mCurrentTimeUs / 1000);
-    buffer->meta_data()->setInt32(kKeyTimeScale, 1000);
+    buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs);
 
     mCurrentPos += frame_size;
     mCurrentTimeUs += 1152 * 1000000 / 44100;
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index 9174d19..143e8ee 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -17,6 +17,9 @@
 #define LOG_TAG "MPEG4Extractor"
 #include <utils/Log.h>
 
+#include "include/MPEG4Extractor.h"
+#include "include/SampleTable.h"
+
 #include <arpa/inet.h>
 
 #include <ctype.h>
@@ -25,14 +28,12 @@
 #include <string.h>
 
 #include <media/stagefright/DataSource.h>
-#include <media/stagefright/MPEG4Extractor.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaSource.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/SampleTable.h>
 #include <media/stagefright/Utils.h>
 #include <utils/String8.h>
 
@@ -43,6 +44,7 @@
     // Caller retains ownership of both "dataSource" and "sampleTable".
     MPEG4Source(const sp<MetaData> &format,
                 const sp<DataSource> &dataSource,
+                int32_t timeScale,
                 const sp<SampleTable> &sampleTable);
 
     virtual status_t start(MetaData *params = NULL);
@@ -177,7 +179,8 @@
     return n;
 }
 
-sp<MetaData> MPEG4Extractor::getTrackMetaData(size_t index) {
+sp<MetaData> MPEG4Extractor::getTrackMetaData(
+        size_t index, uint32_t flags) {
     status_t err;
     if ((err = readMetaData()) != OK) {
         return NULL;
@@ -197,6 +200,25 @@
         return NULL;
     }
 
+    if ((flags & kIncludeExtensiveMetaData)
+            && !track->includes_expensive_metadata) {
+        track->includes_expensive_metadata = true;
+
+        const char *mime;
+        CHECK(track->meta->findCString(kKeyMIMEType, &mime));
+        if (!strncasecmp("video/", mime, 6)) {
+            uint32_t sampleIndex;
+            uint32_t sampleTime;
+            if (track->sampleTable->findThumbnailSample(&sampleIndex) == OK
+                    && track->sampleTable->getDecodingTime(
+                        sampleIndex, &sampleTime) == OK) {
+                track->meta->setInt64(
+                        kKeyThumbnailTime,
+                        ((int64_t)sampleTime * 1000000) / track->timescale);
+            }
+        }
+    }
+
     return track->meta;
 }
 
@@ -227,7 +249,7 @@
 
 status_t MPEG4Extractor::parseChunk(off_t *offset, int depth) {
     uint32_t hdr[2];
-    if (mDataSource->read_at(*offset, hdr, 8) < 8) {
+    if (mDataSource->readAt(*offset, hdr, 8) < 8) {
         return ERROR_IO;
     }
     uint64_t chunk_size = ntohl(hdr[0]);
@@ -235,7 +257,7 @@
     off_t data_offset = *offset + 8;
 
     if (chunk_size == 1) {
-        if (mDataSource->read_at(*offset + 8, &chunk_size, 8) < 8) {
+        if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
             return ERROR_IO;
         }
         chunk_size = ntoh64(chunk_size);
@@ -252,7 +274,7 @@
 
     char buffer[256];
     if (chunk_size <= sizeof(buffer)) {
-        if (mDataSource->read_at(*offset, buffer, chunk_size) < chunk_size) {
+        if (mDataSource->readAt(*offset, buffer, chunk_size) < chunk_size) {
             return ERROR_IO;
         }
 
@@ -298,7 +320,7 @@
             CHECK(chunk_data_size >= 4);
 
             uint8_t version;
-            if (mDataSource->read_at(data_offset, &version, 1) < 1) {
+            if (mDataSource->readAt(data_offset, &version, 1) < 1) {
                 return ERROR_IO;
             }
 
@@ -312,7 +334,7 @@
                 }
 
                 uint8_t buffer[36 + 60];
-                if (mDataSource->read_at(
+                if (mDataSource->readAt(
                             data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
                     return ERROR_IO;
                 }
@@ -329,7 +351,7 @@
                 }
 
                 uint8_t buffer[24 + 60];
-                if (mDataSource->read_at(
+                if (mDataSource->readAt(
                             data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
                     return ERROR_IO;
                 }
@@ -351,6 +373,7 @@
             mLastTrack = track;
 
             track->meta = new MetaData;
+            track->includes_expensive_metadata = false;
             track->timescale = 0;
             track->sampleTable = new SampleTable(mDataSource);
             track->meta->setCString(kKeyMIMEType, "application/octet-stream");
@@ -366,7 +389,7 @@
             }
 
             uint8_t version;
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, &version, sizeof(version))
                     < (ssize_t)sizeof(version)) {
                 return ERROR_IO;
@@ -383,18 +406,17 @@
             }
 
             uint32_t timescale;
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         timescale_offset, &timescale, sizeof(timescale))
                     < (ssize_t)sizeof(timescale)) {
                 return ERROR_IO;
             }
 
             mLastTrack->timescale = ntohl(timescale);
-            mLastTrack->meta->setInt32(kKeyTimeScale, mLastTrack->timescale);
 
             int64_t duration;
             if (version == 1) {
-                if (mDataSource->read_at(
+                if (mDataSource->readAt(
                             timescale_offset + 4, &duration, sizeof(duration))
                         < (ssize_t)sizeof(duration)) {
                     return ERROR_IO;
@@ -402,14 +424,15 @@
                 duration = ntoh64(duration);
             } else {
                 int32_t duration32;
-                if (mDataSource->read_at(
+                if (mDataSource->readAt(
                             timescale_offset + 4, &duration32, sizeof(duration32))
                         < (ssize_t)sizeof(duration32)) {
                     return ERROR_IO;
                 }
                 duration = ntohl(duration32);
             }
-            mLastTrack->meta->setInt32(kKeyDuration, duration);
+            mLastTrack->meta->setInt64(
+                    kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
 
             *offset += chunk_size;
             break;
@@ -422,7 +445,7 @@
             }
 
             uint8_t buffer[24];
-            if (mDataSource->read_at(data_offset, buffer, 24) < 24) {
+            if (mDataSource->readAt(data_offset, buffer, 24) < 24) {
                 return ERROR_IO;
             }
 
@@ -449,7 +472,7 @@
 
             uint8_t buffer[8];
             CHECK(chunk_data_size >= (off_t)sizeof(buffer));
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, buffer, 8) < 8) {
                 return ERROR_IO;
             }
@@ -492,7 +515,7 @@
                 return ERROR_MALFORMED;
             }
 
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
                 return ERROR_IO;
             }
@@ -511,8 +534,8 @@
             uint16_t sample_size = U16_AT(&buffer[18]);
             uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
 
-            printf("*** coding='%s' %d channels, size %d, rate %d\n",
-                   chunk, num_channels, sample_size, sample_rate);
+            // printf("*** coding='%s' %d channels, size %d, rate %d\n",
+            //        chunk, num_channels, sample_size, sample_rate);
 
             mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
             mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
@@ -544,7 +567,7 @@
                 return ERROR_MALFORMED;
             }
 
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
                 return ERROR_IO;
             }
@@ -553,8 +576,8 @@
             uint16_t width = U16_AT(&buffer[6 + 18]);
             uint16_t height = U16_AT(&buffer[6 + 20]);
 
-            printf("*** coding='%s' width=%d height=%d\n",
-                   chunk, width, height);
+            // printf("*** coding='%s' width=%d height=%d\n",
+            //        chunk, width, height);
 
             mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
             mLastTrack->meta->setInt32(kKeyWidth, width);
@@ -612,6 +635,15 @@
                 return err;
             }
 
+            size_t max_size;
+            CHECK_EQ(mLastTrack->sampleTable->getMaxSampleSize(&max_size), OK);
+
+            // Assume that a given buffer only contains at most 10 fragments,
+            // each fragment originally prefixed with a 2 byte length will
+            // have a 4 byte header (0x00 0x00 0x00 0x01) after conversion,
+            // and thus will grow by 2 bytes per fragment.
+            mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
+
             *offset += chunk_size;
             break;
         }
@@ -655,7 +687,7 @@
                 return ERROR_BUFFER_TOO_SMALL;
             }
 
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, buffer, chunk_data_size) < chunk_data_size) {
                 return ERROR_IO;
             }
@@ -679,7 +711,7 @@
                 return ERROR_BUFFER_TOO_SMALL;
             }
 
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         data_offset, buffer, chunk_data_size) < chunk_data_size) {
                 return ERROR_IO;
             }
@@ -722,7 +754,7 @@
     }
 
     return new MPEG4Source(
-            track->meta, mDataSource, track->sampleTable);
+            track->meta, mDataSource, track->timescale, track->sampleTable);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -730,10 +762,11 @@
 MPEG4Source::MPEG4Source(
         const sp<MetaData> &format,
         const sp<DataSource> &dataSource,
+        int32_t timeScale,
         const sp<SampleTable> &sampleTable)
     : mFormat(format),
       mDataSource(dataSource),
-      mTimescale(0),
+      mTimescale(timeScale),
       mSampleTable(sampleTable),
       mCurrentSampleIndex(0),
       mIsAVC(false),
@@ -746,9 +779,6 @@
     bool success = mFormat->findCString(kKeyMIMEType, &mime);
     CHECK(success);
 
-    success = mFormat->findInt32(kKeyTimeScale, &mTimescale);
-    CHECK(success);
-
     mIsAVC = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
 }
 
@@ -771,15 +801,10 @@
 
     mGroup = new MediaBufferGroup;
 
-    size_t max_size;
-    status_t err = mSampleTable->getMaxSampleSize(&max_size);
-    CHECK_EQ(err, OK);
+    int32_t max_size;
+    CHECK(mFormat->findInt32(kKeyMaxInputSize, &max_size));
 
-    // Assume that a given buffer only contains at most 10 fragments,
-    // each fragment originally prefixed with a 2 byte length will
-    // have a 4 byte header (0x00 0x00 0x00 0x01) after conversion,
-    // and thus will grow by 2 bytes per fragment.
-    mGroup->add_buffer(new MediaBuffer(max_size + 10 * 2));
+    mGroup->add_buffer(new MediaBuffer(max_size));
 
     mSrcBuffer = new uint8_t[max_size];
 
@@ -868,7 +893,7 @@
     if (!mIsAVC || mWantsNALFragments) {
         if (newBuffer) {
             ssize_t num_bytes_read =
-                mDataSource->read_at(offset, (uint8_t *)mBuffer->data(), size);
+                mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
 
             if (num_bytes_read < (ssize_t)size) {
                 mBuffer->release();
@@ -879,8 +904,8 @@
 
             mBuffer->set_range(0, size);
             mBuffer->meta_data()->clear();
-            mBuffer->meta_data()->setInt32(kKeyTimeUnits, dts);
-            mBuffer->meta_data()->setInt32(kKeyTimeScale, mTimescale);
+            mBuffer->meta_data()->setInt64(
+                    kKeyTime, ((int64_t)dts * 1000000) / mTimescale);
             ++mCurrentSampleIndex;
         }
 
@@ -923,7 +948,7 @@
         // the start code (0x00 00 00 01).
 
         ssize_t num_bytes_read =
-            mDataSource->read_at(offset, mSrcBuffer, size);
+            mDataSource->readAt(offset, mSrcBuffer, size);
 
         if (num_bytes_read < (ssize_t)size) {
             mBuffer->release();
@@ -959,8 +984,8 @@
 
         mBuffer->set_range(0, dstOffset);
         mBuffer->meta_data()->clear();
-        mBuffer->meta_data()->setInt32(kKeyTimeUnits, dts);
-        mBuffer->meta_data()->setInt32(kKeyTimeScale, mTimescale);
+        mBuffer->meta_data()->setInt64(
+                kKeyTime, ((int64_t)dts * 1000000) / mTimescale);
         ++mCurrentSampleIndex;
 
         *out = mBuffer;
@@ -974,13 +999,14 @@
         const sp<DataSource> &source, String8 *mimeType, float *confidence) {
     uint8_t header[8];
 
-    ssize_t n = source->read_at(4, header, sizeof(header));
+    ssize_t n = source->readAt(4, header, sizeof(header));
     if (n < (ssize_t)sizeof(header)) {
         return false;
     }
 
     if (!memcmp(header, "ftyp3gp", 7) || !memcmp(header, "ftypmp42", 8)
-        || !memcmp(header, "ftypisom", 8) || !memcmp(header, "ftypM4V ", 8)) {
+        || !memcmp(header, "ftypisom", 8) || !memcmp(header, "ftypM4V ", 8)
+        || !memcmp(header, "ftypM4A ", 8)) {
         *mimeType = MEDIA_MIMETYPE_CONTAINER_MPEG4;
         *confidence = 0.1;
 
diff --git a/media/libstagefright/MPEG4Writer.cpp b/media/libstagefright/MPEG4Writer.cpp
index fa35768..367459f 100644
--- a/media/libstagefright/MPEG4Writer.cpp
+++ b/media/libstagefright/MPEG4Writer.cpp
@@ -75,6 +75,13 @@
     CHECK(mFile != NULL);
 }
 
+MPEG4Writer::MPEG4Writer(int fd)
+    : mFile(fdopen(fd, "wb")),
+      mOffset(0),
+      mMdatOffset(0) {
+    CHECK(mFile != NULL);
+}
+
 MPEG4Writer::~MPEG4Writer() {
     stop();
 
@@ -203,6 +210,27 @@
     return old_offset;
 }
 
+off_t MPEG4Writer::addLengthPrefixedSample(MediaBuffer *buffer) {
+    Mutex::Autolock autoLock(mLock);
+
+    off_t old_offset = mOffset;
+
+    size_t length = buffer->range_length();
+    CHECK(length < 65536);
+
+    uint8_t x = length >> 8;
+    fwrite(&x, 1, 1, mFile);
+    x = length & 0xff;
+    fwrite(&x, 1, 1, mFile);
+
+    fwrite((const uint8_t *)buffer->data() + buffer->range_offset(),
+           1, length, mFile);
+
+    mOffset += length + 2;
+
+    return old_offset;
+}
+
 void MPEG4Writer::beginBox(const char *fourcc) {
     CHECK_EQ(strlen(fourcc), 4);
 
@@ -348,11 +376,12 @@
 }
 
 void MPEG4Writer::Track::threadEntry() {
-    bool is_mpeg4 = false;
     sp<MetaData> meta = mSource->getFormat();
     const char *mime;
     meta->findCString(kKeyMIMEType, &mime);
-    is_mpeg4 = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4);
+    bool is_mpeg4 = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_MPEG4);
+    bool is_avc = !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC);
+    int32_t count = 0;
 
     MediaBuffer *buffer;
     while (!mDone && mSource->read(&buffer) == OK) {
@@ -363,6 +392,55 @@
             continue;
         }
 
+        ++count;
+
+        if (is_avc && count < 3) {
+            size_t size = buffer->range_length();
+
+            switch (count) {
+                case 1:
+                {
+                    CHECK_EQ(mCodecSpecificData, NULL);
+                    mCodecSpecificData = malloc(size + 8);
+                    uint8_t *header = (uint8_t *)mCodecSpecificData;
+                    header[0] = 1;
+                    header[1] = 0x42;  // profile
+                    header[2] = 0x80;
+                    header[3] = 0x1e;  // level
+                    header[4] = 0xfc | 3;
+                    header[5] = 0xe0 | 1;
+                    header[6] = size >> 8;
+                    header[7] = size & 0xff;
+                    memcpy(&header[8],
+                            (const uint8_t *)buffer->data() + buffer->range_offset(),
+                            size);
+
+                    mCodecSpecificDataSize = size + 8;
+                    break;
+                }
+
+                case 2:
+                {
+                    size_t offset = mCodecSpecificDataSize;
+                    mCodecSpecificDataSize += size + 3;
+                    mCodecSpecificData = realloc(mCodecSpecificData, mCodecSpecificDataSize);
+                    uint8_t *header = (uint8_t *)mCodecSpecificData;
+                    header[offset] = 1;
+                    header[offset + 1] = size >> 8;
+                    header[offset + 2] = size & 0xff;
+                    memcpy(&header[offset + 3],
+                            (const uint8_t *)buffer->data() + buffer->range_offset(),
+                            size);
+                    break;
+                }
+            }
+
+            buffer->release();
+            buffer = NULL;
+
+            continue;
+        }
+
         if (mCodecSpecificData == NULL && is_mpeg4) {
             const uint8_t *data =
                 (const uint8_t *)buffer->data() + buffer->range_offset();
@@ -393,21 +471,18 @@
             buffer->set_range(buffer->range_offset() + offset, size - offset);
         }
 
-        off_t offset = mOwner->addSample(buffer);
+        off_t offset = is_avc ? mOwner->addLengthPrefixedSample(buffer)
+                              : mOwner->addSample(buffer);
 
         SampleInfo info;
-        info.size = buffer->range_length();
+        info.size = is_avc ? buffer->range_length() + 2 : buffer->range_length();
         info.offset = offset;
 
-        int32_t units, scale;
-        bool success =
-            buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
-        CHECK(success);
-        success =
-            buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
-        CHECK(success);
+        int64_t timestampUs;
+        CHECK(buffer->meta_data()->findInt64(kKeyTime, &timestampUs));
 
-        info.timestamp = (int64_t)units * 1000 / scale;
+        // Our timestamp is in ms.
+        info.timestamp = (timestampUs + 500) / 1000;
 
         mSampleInfos.push_back(info);
 
@@ -560,6 +635,8 @@
                     mOwner->beginBox("mp4v");
                 } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
                     mOwner->beginBox("s263");
+                } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
+                    mOwner->beginBox("avc1");
                 } else {
                     LOGE("Unknown mime type '%s'.", mime);
                     CHECK(!"should not be here, unknown mime type.");
@@ -635,8 +712,13 @@
                           mOwner->writeInt8(0);   // profile: 0
 
                       mOwner->endBox();  // d263
+                  } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
+                      mOwner->beginBox("avcC");
+                        mOwner->write(mCodecSpecificData, mCodecSpecificDataSize);
+                      mOwner->endBox();  // avcC
                   }
-                mOwner->endBox();  // mp4v or s263
+
+                mOwner->endBox();  // mp4v, s263 or avc1
             }
           mOwner->endBox();  // stsd
 
diff --git a/media/libstagefright/MediaBuffer.cpp b/media/libstagefright/MediaBuffer.cpp
index f3c0e73..b973745 100644
--- a/media/libstagefright/MediaBuffer.cpp
+++ b/media/libstagefright/MediaBuffer.cpp
@@ -108,10 +108,10 @@
 }
 
 void MediaBuffer::set_range(size_t offset, size_t length) {
-    if (offset < 0 || offset + length > mSize) {
+    if (offset + length > mSize) {
         LOGE("offset = %d, length = %d, mSize = %d", offset, length, mSize);
     }
-    CHECK(offset >= 0 && offset + length <= mSize);
+    CHECK(offset + length <= mSize);
 
     mRangeOffset = offset;
     mRangeLength = length;
diff --git a/media/libstagefright/MediaDefs.cpp b/media/libstagefright/MediaDefs.cpp
index 87b5b24..04b1454 100644
--- a/media/libstagefright/MediaDefs.cpp
+++ b/media/libstagefright/MediaDefs.cpp
@@ -32,5 +32,6 @@
 const char *MEDIA_MIMETYPE_AUDIO_RAW = "audio/raw";
 
 const char *MEDIA_MIMETYPE_CONTAINER_MPEG4 = "video/mpeg4";
+const char *MEDIA_MIMETYPE_CONTAINER_WAV = "audio/wav";
 
 }  // namespace android
diff --git a/media/libstagefright/MediaExtractor.cpp b/media/libstagefright/MediaExtractor.cpp
index 8535f52..9d3deb7 100644
--- a/media/libstagefright/MediaExtractor.cpp
+++ b/media/libstagefright/MediaExtractor.cpp
@@ -18,11 +18,16 @@
 #define LOG_TAG "MediaExtractor"
 #include <utils/Log.h>
 
-#include <media/stagefright/AMRExtractor.h>
+#include "include/AMRExtractor.h"
+#include "include/MP3Extractor.h"
+#include "include/MPEG4Extractor.h"
+#include "include/WAVExtractor.h"
+
+#include <media/stagefright/CachingDataSource.h>
 #include <media/stagefright/DataSource.h>
+#include <media/stagefright/FileSource.h>
+#include <media/stagefright/HTTPDataSource.h>
 #include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MP3Extractor.h>
-#include <media/stagefright/MPEG4Extractor.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <utils/String8.h>
 
@@ -41,7 +46,7 @@
         }
 
         mime = tmp.string();
-        LOGI("Autodetected media content as '%s' with confidence %.2f",
+        LOGV("Autodetected media content as '%s' with confidence %.2f",
              mime, confidence);
     }
 
@@ -53,9 +58,32 @@
     } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_NB)
             || !strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_AMR_WB)) {
         return new AMRExtractor(source);
+    } else if (!strcasecmp(mime, MEDIA_MIMETYPE_CONTAINER_WAV)) {
+        return new WAVExtractor(source);
     }
 
     return NULL;
 }
 
+// static
+sp<MediaExtractor> MediaExtractor::CreateFromURI(
+        const char *uri, const char *mime) {
+    sp<DataSource> source;
+    if (!strncasecmp("file://", uri, 7)) {
+        source = new FileSource(uri + 7);
+    } else if (!strncasecmp("http://", uri, 7)) {
+        source = new HTTPDataSource(uri);
+        source = new CachingDataSource(source, 64 * 1024, 10);
+    } else {
+        // Assume it's a filename.
+        source = new FileSource(uri);
+    }
+
+    if (source == NULL || source->initCheck() != OK) {
+        return NULL;
+    }
+
+    return Create(source, mime);
+}
+
 }  // namespace android
diff --git a/media/libstagefright/MediaPlayerImpl.cpp b/media/libstagefright/MediaPlayerImpl.cpp
deleted file mode 100644
index 8300422..0000000
--- a/media/libstagefright/MediaPlayerImpl.cpp
+++ /dev/null
@@ -1,671 +0,0 @@
-/*
- * 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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MediaPlayerImpl"
-#include "utils/Log.h"
-
-#include <OMX_Component.h>
-
-#include <unistd.h>
-
-#include <media/stagefright/AudioPlayer.h>
-#include <media/stagefright/CachingDataSource.h>
-// #include <media/stagefright/CameraSource.h>
-#include <media/stagefright/HTTPDataSource.h>
-#include <media/stagefright/HTTPStream.h>
-#include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/MediaExtractor.h>
-#include <media/stagefright/MediaPlayerImpl.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/MmapSource.h>
-#include <media/stagefright/OMXCodec.h>
-#include <media/stagefright/ShoutcastSource.h>
-#include <media/stagefright/TimeSource.h>
-#include <ui/PixelFormat.h>
-#include <ui/Surface.h>
-
-namespace android {
-
-static void releaseBufferIfNonNULL(MediaBuffer **buffer) {
-    if (*buffer) {
-        (*buffer)->release();
-        *buffer = NULL;
-    }
-}
-
-MediaPlayerImpl::MediaPlayerImpl(const char *uri)
-    : mInitCheck(NO_INIT),
-      mTimeSource(NULL),
-      mAudioPlayer(NULL),
-      mVideoWidth(0),
-      mVideoHeight(0),
-      mVideoPosition(0),
-      mDuration(0),
-      mPlaying(false),
-      mPaused(false),
-      mSeeking(false) {
-    LOGV("MediaPlayerImpl(%s)", uri);
-    DataSource::RegisterDefaultSniffers();
-
-    status_t err = mClient.connect();
-    if (err != OK) {
-        LOGE("Failed to connect to OMXClient.");
-        return;
-    }
-
-    if (!strncasecmp("shoutcast://", uri, 12)) {
-        setAudioSource(makeShoutcastSource(uri));
-#if 0
-    } else if (!strncasecmp("camera:", uri, 7)) {
-        mVideoWidth = 480;
-        mVideoHeight = 320;
-        mVideoDecoder = CameraSource::Create();
-#endif
-    } else {
-        sp<DataSource> source;
-        if (!strncasecmp("file://", uri, 7)) {
-            source = new MmapSource(uri + 7);
-        } else if (!strncasecmp("http://", uri, 7)) {
-            source = new HTTPDataSource(uri);
-            source = new CachingDataSource(source, 64 * 1024, 10);
-        } else {
-            // Assume it's a filename.
-            source = new MmapSource(uri);
-        }
-
-        mExtractor = MediaExtractor::Create(source);
-
-        if (mExtractor == NULL) {
-            return;
-        }
-    }
-
-    init();
-
-    mInitCheck = OK;
-}
-
-MediaPlayerImpl::MediaPlayerImpl(int fd, int64_t offset, int64_t length)
-    : mInitCheck(NO_INIT),
-      mTimeSource(NULL),
-      mAudioPlayer(NULL),
-      mVideoWidth(0),
-      mVideoHeight(0),
-      mVideoPosition(0),
-      mDuration(0),
-      mPlaying(false),
-      mPaused(false),
-      mSeeking(false) {
-    LOGV("MediaPlayerImpl(%d, %lld, %lld)", fd, offset, length);
-    DataSource::RegisterDefaultSniffers();
-
-    status_t err = mClient.connect();
-    if (err != OK) {
-        LOGE("Failed to connect to OMXClient.");
-        return;
-    }
-
-    mExtractor = MediaExtractor::Create(
-            new MmapSource(fd, offset, length));
-
-    if (mExtractor == NULL) {
-        return;
-    }
-
-    init();
-
-    mInitCheck = OK;
-}
-
-status_t MediaPlayerImpl::initCheck() const {
-    return mInitCheck;
-}
-
-MediaPlayerImpl::~MediaPlayerImpl() {
-    stop();
-    setSurface(NULL);
-
-    if (mInitCheck == OK) {
-        mClient.disconnect();
-    }
-
-    LOGV("~MediaPlayerImpl done.");
-}
-
-void MediaPlayerImpl::play() {
-    LOGV("play");
-
-    if (mPlaying) {
-        if (mPaused) {
-            if (mAudioSource != NULL) {
-                mAudioPlayer->resume();
-            }
-            mPaused = false;
-        }
-        return;
-    }
-
-    mPlaying = true;
-
-    if (mAudioSource != NULL) {
-        mAudioPlayer = new AudioPlayer(mAudioSink);
-        mAudioPlayer->setSource(mAudioDecoder);
-
-        if (mVideoDecoder == NULL) {
-            // If there is no video, start playing right away,
-            // otherwise we'll start the audio player after we decode
-            // the first video frame, this way we won't be behind right
-            // away.
-            mAudioPlayer->start();
-        }
-
-        mTimeSource = mAudioPlayer;
-    } else {
-        mTimeSource = new SystemTimeSource;
-    }
-
-    if (mVideoDecoder != NULL) {
-        pthread_attr_t attr;
-        pthread_attr_init(&attr);
-        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
-        pthread_create(&mVideoThread, &attr, VideoWrapper, this);
-
-        pthread_attr_destroy(&attr);
-    }
-}
-
-void MediaPlayerImpl::pause() {
-    if (!mPlaying || mPaused) {
-        return;
-    }
-
-    if (mAudioSource != NULL) {
-        mAudioPlayer->pause();
-    }
-
-    mPaused = true;
-}
-
-void MediaPlayerImpl::stop() {
-    if (!mPlaying) {
-        return;
-    }
-
-    mPlaying = false;
-
-    if (mVideoDecoder != NULL) {
-        void *dummy;
-        pthread_join(mVideoThread, &dummy);
-    }
-
-    if (mAudioSource != NULL) {
-        mAudioPlayer->stop();
-
-        delete mAudioPlayer;
-        mAudioPlayer = NULL;
-    } else {
-        delete mTimeSource;
-    }
-
-    mTimeSource = NULL;
-}
-
-// static
-void *MediaPlayerImpl::VideoWrapper(void *me) {
-    ((MediaPlayerImpl *)me)->videoEntry();
-
-    return NULL;
-}
-
-void MediaPlayerImpl::videoEntry() {
-    bool firstFrame = true;
-    bool eof = false;
-
-    MediaBuffer *lastBuffer = NULL;
-
-    status_t err = mVideoDecoder->start();
-    CHECK_EQ(err, OK);
-
-    while (mPlaying) {
-        MediaBuffer *buffer;
-
-        MediaSource::ReadOptions options;
-        bool seeking = false;
-
-        {
-            Mutex::Autolock autoLock(mLock);
-            if (mSeeking) {
-                releaseBufferIfNonNULL(&lastBuffer);
-
-                LOGV("seek-options to %lld", mSeekTimeUs);
-                options.setSeekTo(mSeekTimeUs);
-
-                mSeeking = false;
-                seeking = true;
-                eof = false;
-            }
-        }
-
-        if (eof || mPaused) {
-            usleep(100000);
-            continue;
-        }
-
-        status_t err = mVideoDecoder->read(&buffer, &options);
-        CHECK((err == OK && buffer != NULL) || (err != OK && buffer == NULL));
-
-        if (err == ERROR_END_OF_STREAM || err != OK) {
-            eof = true;
-            continue;
-        }
-
-        if (buffer->range_length() == 0) {
-            // The final buffer is empty.
-            buffer->release();
-            continue;
-        }
-
-        int32_t units, scale;
-        bool success =
-            buffer->meta_data()->findInt32(kKeyTimeUnits, &units);
-        CHECK(success);
-        success =
-            buffer->meta_data()->findInt32(kKeyTimeScale, &scale);
-        CHECK(success);
-
-        int64_t pts_us = (int64_t)units * 1000000 / scale;
-        {
-            Mutex::Autolock autoLock(mLock);
-            mVideoPosition = pts_us;
-
-            LOGV("now_video = %.2f secs (%lld ms)",
-                 pts_us / 1E6, (pts_us + 500) / 1000);
-        }
-
-        if (seeking && mAudioPlayer != NULL) {
-            // Now that we know where exactly video seeked (taking sync-samples
-            // into account), we will seek the audio track to the same time.
-            mAudioPlayer->seekTo(pts_us);
-        }
-
-        if (firstFrame || seeking) {
-            if (firstFrame && mAudioPlayer != NULL) {
-                // We've deferred starting the audio player until now.
-                mAudioPlayer->start();
-            }
-            mTimeSourceDeltaUs = mTimeSource->getRealTimeUs() - pts_us;
-            firstFrame = false;
-        }
-
-        displayOrDiscardFrame(&lastBuffer, buffer, pts_us);
-    }
-
-    releaseBufferIfNonNULL(&lastBuffer);
-
-    mVideoDecoder->stop();
-}
-
-void MediaPlayerImpl::displayOrDiscardFrame(
-        MediaBuffer **lastBuffer,
-        MediaBuffer *buffer, int64_t pts_us) {
-    for (;;) {
-        if (!mPlaying || mPaused) {
-            releaseBufferIfNonNULL(lastBuffer);
-            *lastBuffer = buffer;
-            return;
-        }
-
-        int64_t realtime_us, mediatime_us;
-        if (mAudioPlayer != NULL
-            && mAudioPlayer->getMediaTimeMapping(&realtime_us, &mediatime_us)) {
-            mTimeSourceDeltaUs = realtime_us - mediatime_us;
-            LOGV("mTimeSourceDeltaUs = %.2f secs", mTimeSourceDeltaUs / 1E6);
-        }
-
-        int64_t now_us = mTimeSource->getRealTimeUs();
-        now_us -= mTimeSourceDeltaUs;
-
-        int64_t delay_us = pts_us - now_us;
-
-        if (delay_us < -15000) {
-            // We're late.
-
-            LOGV("we're late by %lld ms, dropping a frame\n",
-                 -delay_us / 1000);
-
-            releaseBufferIfNonNULL(lastBuffer);
-            *lastBuffer = buffer;
-            return;
-        } else if (delay_us > 100000) {
-            usleep(100000);
-            continue;
-        } else if (delay_us > 0) {
-            usleep(delay_us);
-        }
-
-        break;
-    }
-
-    {
-        Mutex::Autolock autoLock(mLock);
-
-        if (mVideoRenderer.get() != NULL) {
-            sendFrameToISurface(buffer);
-        }
-    }
-
-    releaseBufferIfNonNULL(lastBuffer);
-    *lastBuffer = buffer;
-}
-
-void MediaPlayerImpl::init() {
-    if (mExtractor != NULL) {
-        size_t num_tracks = mExtractor->countTracks();
-
-        mDuration = 0;
-
-        for (size_t i = 0; i < num_tracks; ++i) {
-            const sp<MetaData> meta = mExtractor->getTrackMetaData(i);
-            CHECK(meta != NULL);
-
-            const char *mime;
-            if (!meta->findCString(kKeyMIMEType, &mime)) {
-                continue;
-            }
-
-            bool is_audio = false;
-            bool is_acceptable = false;
-            if (!strncasecmp(mime, "audio/", 6)) {
-                is_audio = true;
-                is_acceptable = (mAudioSource == NULL);
-            } else if (!strncasecmp(mime, "video/", 6)) {
-                is_acceptable = (mVideoSource == NULL);
-            }
-
-            if (!is_acceptable) {
-                continue;
-            }
-
-            sp<MediaSource> source = mExtractor->getTrack(i);
-
-            int32_t units, scale;
-            if (meta->findInt32(kKeyDuration, &units)
-                && meta->findInt32(kKeyTimeScale, &scale)) {
-                int64_t duration_us = (int64_t)units * 1000000 / scale;
-                if (duration_us > mDuration) {
-                    mDuration = duration_us;
-                }
-            }
-
-            if (is_audio) {
-                setAudioSource(source);
-            } else {
-                setVideoSource(source);
-            }
-        }
-    }
-}
-
-void MediaPlayerImpl::setAudioSource(const sp<MediaSource> &source) {
-    LOGV("setAudioSource");
-    mAudioSource = source;
-
-    sp<MetaData> meta = source->getFormat();
-
-    mAudioDecoder = OMXCodec::Create(
-            mClient.interface(), meta, false /* createEncoder */, source);
-}
-
-void MediaPlayerImpl::setVideoSource(const sp<MediaSource> &source) {
-    LOGV("setVideoSource");
-    mVideoSource = source;
-
-    sp<MetaData> meta = source->getFormat();
-
-    bool success = meta->findInt32(kKeyWidth, &mVideoWidth);
-    CHECK(success);
-
-    success = meta->findInt32(kKeyHeight, &mVideoHeight);
-    CHECK(success);
-
-    mVideoDecoder = OMXCodec::Create(
-            mClient.interface(), meta, false /* createEncoder */, source);
-
-    if (mISurface.get() != NULL || mSurface.get() != NULL) {
-        depopulateISurface();
-        populateISurface();
-    }
-}
-
-void MediaPlayerImpl::setSurface(const sp<Surface> &surface) {
-    LOGV("setSurface %p", surface.get());
-    Mutex::Autolock autoLock(mLock);
-
-    depopulateISurface();
-
-    mSurface = surface;
-    mISurface = NULL;
-
-    if (mSurface.get() != NULL) {
-        populateISurface();
-    }
-}
-
-void MediaPlayerImpl::setISurface(const sp<ISurface> &isurface) {
-    LOGV("setISurface %p", isurface.get());
-    Mutex::Autolock autoLock(mLock);
-
-    depopulateISurface();
-
-    mSurface = NULL;
-    mISurface = isurface;
-
-    if (mISurface.get() != NULL) {
-        populateISurface();
-    }
-}
-
-MediaSource *MediaPlayerImpl::makeShoutcastSource(const char *uri) {
-    if (strncasecmp(uri, "shoutcast://", 12)) {
-        return NULL;
-    }
-
-    string host;
-    string path;
-    int port;
-
-    char *slash = strchr(uri + 12, '/');
-    if (slash == NULL) {
-        host = uri + 12;
-        path = "/";
-    } else {
-        host = string(uri + 12, slash - (uri + 12));
-        path = slash;
-    }
-
-    char *colon = strchr(host.c_str(), ':');
-    if (colon == NULL) {
-        port = 80;
-    } else {
-        char *end;
-        long tmp = strtol(colon + 1, &end, 10);
-        CHECK(end > colon + 1);
-        CHECK(tmp > 0 && tmp < 65536);
-        port = tmp;
-
-        host = string(host, 0, colon - host.c_str());
-    }
-
-    LOGV("Connecting to host '%s', port %d, path '%s'",
-         host.c_str(), port, path.c_str());
-
-    HTTPStream *http = new HTTPStream;
-    int http_status;
-
-    for (;;) {
-        status_t err = http->connect(host.c_str(), port);
-        CHECK_EQ(err, OK);
-
-        err = http->send("GET ");
-        err = http->send(path.c_str());
-        err = http->send(" HTTP/1.1\r\n");
-        err = http->send("Host: ");
-        err = http->send(host.c_str());
-        err = http->send("\r\n");
-        err = http->send("Icy-MetaData: 1\r\n\r\n");
-
-        CHECK_EQ(OK, http->receive_header(&http_status));
-
-        if (http_status == 301 || http_status == 302) {
-            string location;
-            CHECK(http->find_header_value("Location", &location));
-
-            CHECK(string(location, 0, 7) == "http://");
-            location.erase(0, 7);
-            string::size_type slashPos = location.find('/');
-            if (slashPos == string::npos) {
-                slashPos = location.size();
-                location += '/';
-            }
-
-            http->disconnect();
-
-            LOGV("Redirecting to %s\n", location.c_str());
-
-            host = string(location, 0, slashPos);
-
-            string::size_type colonPos = host.find(':');
-            if (colonPos != string::npos) {
-                const char *start = host.c_str() + colonPos + 1;
-                char *end;
-                long tmp = strtol(start, &end, 10);
-                CHECK(end > start && (*end == '\0'));
-
-                port = (tmp >= 0 && tmp < 65536) ? (int)tmp : 80;
-            } else {
-                port = 80;
-            }
-
-            path = string(location, slashPos);
-
-            continue;
-        }
-
-        break;
-    }
-
-    if (http_status != 200) {
-        LOGE("Connection failed: http_status = %d", http_status);
-        return NULL;
-    }
-
-    MediaSource *source = new ShoutcastSource(http);
-
-    return source;
-}
-
-bool MediaPlayerImpl::isPlaying() const {
-    return mPlaying && !mPaused;
-}
-
-int64_t MediaPlayerImpl::getDuration() {
-    return mDuration;
-}
-
-int64_t MediaPlayerImpl::getPosition() {
-    int64_t position = 0;
-    if (mVideoSource != NULL) {
-        Mutex::Autolock autoLock(mLock);
-        position = mVideoPosition;
-    } else if (mAudioPlayer != NULL) {
-        position = mAudioPlayer->getMediaTimeUs();
-    }
-
-    return position;
-}
-
-status_t MediaPlayerImpl::seekTo(int64_t time) {
-    LOGV("seekTo %lld", time);
-
-    if (mPaused) {
-        return UNKNOWN_ERROR;
-    }
-
-    if (mVideoSource == NULL && mAudioPlayer != NULL) {
-        mAudioPlayer->seekTo(time);
-    } else {
-        Mutex::Autolock autoLock(mLock);
-        mSeekTimeUs = time;
-        mSeeking = true;
-    }
-
-    return OK;
-}
-
-void MediaPlayerImpl::populateISurface() {
-    if (mVideoSource == NULL) {
-        return;
-    }
-
-    sp<MetaData> meta = mVideoDecoder->getFormat();
-
-    int32_t format;
-    const char *component;
-    int32_t decodedWidth, decodedHeight;
-    bool success = meta->findInt32(kKeyColorFormat, &format);
-    success = success && meta->findCString(kKeyDecoderComponent, &component);
-    success = success && meta->findInt32(kKeyWidth, &decodedWidth);
-    success = success && meta->findInt32(kKeyHeight, &decodedHeight);
-    CHECK(success);
-
-    if (mSurface.get() != NULL) {
-        mVideoRenderer =
-            mClient.interface()->createRenderer(
-                    mSurface, component,
-                    (OMX_COLOR_FORMATTYPE)format,
-                    decodedWidth, decodedHeight,
-                    mVideoWidth, mVideoHeight);
-    } else {
-        mVideoRenderer =
-            mClient.interface()->createRenderer(
-                    mISurface, component,
-                    (OMX_COLOR_FORMATTYPE)format,
-                    decodedWidth, decodedHeight,
-                    mVideoWidth, mVideoHeight);
-    }
-}
-
-void MediaPlayerImpl::depopulateISurface() {
-    mVideoRenderer.clear();
-}
-
-void MediaPlayerImpl::sendFrameToISurface(MediaBuffer *buffer) {
-    void *id;
-    if (buffer->meta_data()->findPointer(kKeyBufferID, &id)) {
-        mVideoRenderer->render((IOMX::buffer_id)id);
-    }
-}
-
-void MediaPlayerImpl::setAudioSink(
-        const sp<MediaPlayerBase::AudioSink> &audioSink) {
-    LOGV("setAudioSink %p", audioSink.get());
-    mAudioSink = audioSink;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/MetaData.cpp b/media/libstagefright/MetaData.cpp
index 6b067cb..63b476e 100644
--- a/media/libstagefright/MetaData.cpp
+++ b/media/libstagefright/MetaData.cpp
@@ -58,6 +58,10 @@
     return setData(key, TYPE_INT32, &value, sizeof(value));
 }
 
+bool MetaData::setInt64(uint32_t key, int64_t value) {
+    return setData(key, TYPE_INT64, &value, sizeof(value));
+}
+
 bool MetaData::setFloat(uint32_t key, float value) {
     return setData(key, TYPE_FLOAT, &value, sizeof(value));
 }
@@ -94,6 +98,21 @@
     return true;
 }
 
+bool MetaData::findInt64(uint32_t key, int64_t *value) {
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (!findData(key, &type, &data, &size) || type != TYPE_INT64) {
+        return false;
+    }
+
+    CHECK_EQ(size, sizeof(*value));
+
+    *value = *(int64_t *)data;
+
+    return true;
+}
+
 bool MetaData::findFloat(uint32_t key, float *value) {
     uint32_t type;
     const void *data;
diff --git a/media/libstagefright/MmapSource.cpp b/media/libstagefright/MmapSource.cpp
deleted file mode 100644
index 47d95f9..0000000
--- a/media/libstagefright/MmapSource.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "MmapSource"
-#include <utils/Log.h>
-
-#include <sys/mman.h>
-
-#include <fcntl.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/MmapSource.h>
-
-namespace android {
-
-MmapSource::MmapSource(const char *filename)
-    : mFd(open(filename, O_RDONLY)),
-      mBase(NULL),
-      mSize(0) {
-    LOGV("MmapSource '%s'", filename);
-    CHECK(mFd >= 0);
-
-    off_t size = lseek(mFd, 0, SEEK_END);
-    mSize = (size_t)size;
-
-    mBase = mmap(0, mSize, PROT_READ, MAP_FILE | MAP_SHARED, mFd, 0);
-
-    if (mBase == (void *)-1) {
-        mBase = NULL;
-
-        close(mFd);
-        mFd = -1;
-    }
-}
-
-MmapSource::MmapSource(int fd, int64_t offset, int64_t length)
-    : mFd(fd),
-      mBase(NULL),
-      mSize(length) {
-    LOGV("MmapSource fd:%d offset:%lld length:%lld", fd, offset, length);
-    CHECK(fd >= 0);
-
-    mBase = mmap(0, mSize, PROT_READ, MAP_FILE | MAP_SHARED, mFd, offset);
-
-    if (mBase == (void *)-1) {
-        mBase = NULL;
-
-        close(mFd);
-        mFd = -1;
-    }
-
-}
-
-MmapSource::~MmapSource() {
-    if (mFd != -1) {
-        munmap(mBase, mSize);
-        mBase = NULL;
-        mSize = 0;
-
-        close(mFd);
-        mFd = -1;
-    }
-}
-
-status_t MmapSource::InitCheck() const {
-    return mFd == -1 ? NO_INIT : OK;
-}
-
-ssize_t MmapSource::read_at(off_t offset, void *data, size_t size) {
-    LOGV("read_at offset:%ld data:%p size:%d", offset, data, size);
-    CHECK(offset >= 0);
-
-    size_t avail = 0;
-    if (offset >= 0 && offset < (off_t)mSize) {
-        avail = mSize - offset;
-    }
-
-    if (size > avail) {
-        size = avail;
-    }
-
-    memcpy(data, (const uint8_t *)mBase + offset, size);
-
-    return (ssize_t)size;
-}
-
-status_t MmapSource::getSize(off_t *size) {
-    *size = mSize;
-
-    return OK;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index ebf1e0c..d8bd25d 100644
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -18,18 +18,28 @@
 #define LOG_TAG "OMXCodec"
 #include <utils/Log.h>
 
+#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/M4vH263Decoder.h"
+#include "include/MP3Decoder.h"
+#endif
+
+#include "include/ESDS.h"
+
 #include <binder/IServiceManager.h>
 #include <binder/MemoryDealer.h>
 #include <binder/ProcessState.h>
 #include <media/IMediaPlayerService.h>
-#include <media/stagefright/ESDS.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MediaExtractor.h>
 #include <media/stagefright/MetaData.h>
-#include <media/stagefright/MmapSource.h>
 #include <media/stagefright/OMXCodec.h>
 #include <media/stagefright/Utils.h>
 #include <utils/Vector.h>
@@ -39,34 +49,95 @@
 
 namespace android {
 
+static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
+
 struct CodecInfo {
     const char *mime;
     const char *codec;
 };
 
+#if BUILD_WITH_FULL_STAGEFRIGHT
+#define OPTIONAL(x,y) { x, y },
+
+#define FACTORY_CREATE(name) \
+static sp<MediaSource> Make##name(const sp<MediaSource> &source) { \
+    return new name(source); \
+}
+
+#define FACTORY_REF(name) { #name, Make##name },
+
+FACTORY_CREATE(MP3Decoder)
+FACTORY_CREATE(AMRNBDecoder)
+FACTORY_CREATE(AMRWBDecoder)
+FACTORY_CREATE(AACDecoder)
+FACTORY_CREATE(AVCDecoder)
+FACTORY_CREATE(M4vH263Decoder)
+FACTORY_CREATE(AMRNBEncoder)
+
+static sp<MediaSource> InstantiateSoftwareCodec(
+        const char *name, const sp<MediaSource> &source) {
+    struct FactoryInfo {
+        const char *name;
+        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &);
+    };
+
+    static const FactoryInfo kFactoryInfo[] = {
+        FACTORY_REF(MP3Decoder)
+        FACTORY_REF(AMRNBDecoder)
+        FACTORY_REF(AMRWBDecoder)
+        FACTORY_REF(AACDecoder)
+        FACTORY_REF(AVCDecoder)
+        FACTORY_REF(M4vH263Decoder)
+        FACTORY_REF(AMRNBEncoder)
+    };
+    for (size_t i = 0;
+         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
+        if (!strcmp(name, kFactoryInfo[i].name)) {
+            return (*kFactoryInfo[i].CreateFunc)(source);
+        }
+    }
+
+    return NULL;
+}
+
+#undef FACTORY_REF
+#undef FACTORY_CREATE
+
+#else
+#define OPTIONAL(x,y)
+#endif
+
 static const CodecInfo kDecoderInfo[] = {
     { MEDIA_MIMETYPE_IMAGE_JPEG, "OMX.TI.JPEG.decode" },
     { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.TI.MP3.decode" },
+    OPTIONAL(MEDIA_MIMETYPE_AUDIO_MPEG, "MP3Decoder")
     { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.PV.mp3dec" },
     { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.decode" },
+    OPTIONAL(MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBDecoder")
     { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.PV.amrdec" },
     { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.decode" },
+    OPTIONAL(MEDIA_MIMETYPE_AUDIO_AMR_WB, "AMRWBDecoder")
     { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.PV.amrdec" },
     { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.decode" },
+    OPTIONAL(MEDIA_MIMETYPE_AUDIO_AAC, "AACDecoder")
     { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.PV.aacdec" },
     { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.video.decoder.mpeg4" },
     { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.TI.Video.Decoder" },
+    OPTIONAL(MEDIA_MIMETYPE_VIDEO_MPEG4, "M4vH263Decoder")
     { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.PV.mpeg4dec" },
     { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.video.decoder.h263" },
     { MEDIA_MIMETYPE_VIDEO_H263, "OMX.TI.Video.Decoder" },
+    OPTIONAL(MEDIA_MIMETYPE_VIDEO_H263, "M4vH263Decoder")
     { MEDIA_MIMETYPE_VIDEO_H263, "OMX.PV.h263dec" },
     { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.video.decoder.avc" },
     { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.TI.Video.Decoder" },
+    OPTIONAL(MEDIA_MIMETYPE_VIDEO_AVC, "AVCDecoder")
     { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.PV.avcdec" },
 };
 
 static const CodecInfo kEncoderInfo[] = {
     { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.encode" },
+    OPTIONAL(MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBEncoder")
     { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.PV.amrencnb" },
     { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.encode" },
     { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.encode" },
@@ -81,6 +152,8 @@
     { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.PV.avcenc" },
 };
 
+#undef OPTIONAL
+
 #define CODEC_LOGI(x, ...) LOGI("[%s] "x, mComponentName, ##__VA_ARGS__)
 #define CODEC_LOGV(x, ...) LOGV("[%s] "x, mComponentName, ##__VA_ARGS__)
 
@@ -169,52 +242,51 @@
     params->nVersion.s.nStep = 0;
 }
 
-// static
-sp<OMXCodec> OMXCodec::Create(
-        const sp<IOMX> &omx,
-        const sp<MetaData> &meta, bool createEncoder,
-        const sp<MediaSource> &source,
-        const char *matchComponentName) {
-    const char *mime;
-    bool success = meta->findCString(kKeyMIMEType, &mime);
-    CHECK(success);
-
-    const char *componentName = NULL;
-    sp<OMXCodecObserver> observer = new OMXCodecObserver;
-    IOMX::node_id node = 0;
-    for (int index = 0;; ++index) {
-        if (createEncoder) {
-            componentName = GetCodec(
-                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
-                    mime, index);
-        } else {
-            componentName = GetCodec(
-                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
-                    mime, index);
-        }
-
-        if (!componentName) {
-            return NULL;
-        }
-
-        // If a specific codec is requested, skip the non-matching ones.
-        if (matchComponentName && strcmp(componentName, matchComponentName)) {
-            continue;
-        }
-
-        LOGV("Attempting to allocate OMX node '%s'", componentName);
-
-        status_t err = omx->allocateNode(componentName, observer, &node);
-        if (err == OK) {
-            LOGI("Successfully allocated OMX node '%s'", componentName);
-            break;
-        }
+static bool IsSoftwareCodec(const char *componentName) {
+    if (!strncmp("OMX.PV.", componentName, 7)) {
+        return true;
     }
 
+    return false;
+}
+
+// A sort order in which non-OMX components are first,
+// followed by software codecs, i.e. OMX.PV.*, followed
+// by all the others.
+static int CompareSoftwareCodecsFirst(
+        const String8 *elem1, const String8 *elem2) {
+    bool isNotOMX1 = strncmp(elem1->string(), "OMX.", 4);
+    bool isNotOMX2 = strncmp(elem2->string(), "OMX.", 4);
+
+    if (isNotOMX1) {
+        if (isNotOMX2) { return 0; }
+        return -1;
+    }
+    if (isNotOMX2) {
+        return 1;
+    }
+
+    bool isSoftwareCodec1 = IsSoftwareCodec(elem1->string());
+    bool isSoftwareCodec2 = IsSoftwareCodec(elem2->string());
+
+    if (isSoftwareCodec1) {
+        if (isSoftwareCodec2) { return 0; }
+        return -1;
+    }
+
+    if (isSoftwareCodec2) {
+        return 1;
+    }
+
+    return 0;
+}
+
+// static
+uint32_t OMXCodec::getComponentQuirks(const char *componentName) {
     uint32_t quirks = 0;
+
     if (!strcmp(componentName, "OMX.PV.avcdec")) {
         quirks |= kWantsNALFragments;
-        quirks |= kOutputDimensionsAre16Aligned;
     }
     if (!strcmp(componentName, "OMX.TI.MP3.decode")) {
         quirks |= kNeedsFlushBeforeDisable;
@@ -222,20 +294,15 @@
     if (!strcmp(componentName, "OMX.TI.AAC.decode")) {
         quirks |= kNeedsFlushBeforeDisable;
         quirks |= kRequiresFlushCompleteEmulation;
-
-        // The following is currently necessary for proper shutdown
-        // behaviour, but NOT enabled by default in order to make the
-        // bug reproducible...
-        // quirks |= kRequiresFlushBeforeShutdown;
     }
     if (!strncmp(componentName, "OMX.qcom.video.encoder.", 23)) {
         quirks |= kRequiresLoadedToIdleAfterAllocation;
         quirks |= kRequiresAllocateBufferOnInputPorts;
+        quirks |= kRequiresAllocateBufferOnOutputPorts;
     }
     if (!strncmp(componentName, "OMX.qcom.video.decoder.", 23)) {
         // XXX Required on P....on only.
         quirks |= kRequiresAllocateBufferOnOutputPorts;
-        quirks |= kOutputDimensionsAre16Aligned;
     }
 
     if (!strncmp(componentName, "OMX.TI.", 7)) {
@@ -248,8 +315,105 @@
         quirks |= kRequiresAllocateBufferOnOutputPorts;
     }
 
+    return quirks;
+}
+
+// static
+void OMXCodec::findMatchingCodecs(
+        const char *mime,
+        bool createEncoder, const char *matchComponentName,
+        uint32_t flags,
+        Vector<String8> *matchingCodecs) {
+    matchingCodecs->clear();
+
+    for (int index = 0;; ++index) {
+        const char *componentName;
+
+        if (createEncoder) {
+            componentName = GetCodec(
+                    kEncoderInfo,
+                    sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
+                    mime, index);
+        } else {
+            componentName = GetCodec(
+                    kDecoderInfo,
+                    sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
+                    mime, index);
+        }
+
+        if (!componentName) {
+            break;
+        }
+
+        // If a specific codec is requested, skip the non-matching ones.
+        if (matchComponentName && strcmp(componentName, matchComponentName)) {
+            continue;
+        }
+
+        matchingCodecs->push(String8(componentName));
+    }
+
+    if (flags & kPreferSoftwareCodecs) {
+        matchingCodecs->sort(CompareSoftwareCodecsFirst);
+    }
+}
+
+// static
+sp<MediaSource> OMXCodec::Create(
+        const sp<IOMX> &omx,
+        const sp<MetaData> &meta, bool createEncoder,
+        const sp<MediaSource> &source,
+        const char *matchComponentName,
+        uint32_t flags) {
+    const char *mime;
+    bool success = meta->findCString(kKeyMIMEType, &mime);
+    CHECK(success);
+
+    Vector<String8> matchingCodecs;
+    findMatchingCodecs(
+            mime, createEncoder, matchComponentName, flags, &matchingCodecs);
+
+    if (matchingCodecs.isEmpty()) {
+        return NULL;
+    }
+
+    sp<OMXCodecObserver> observer = new OMXCodecObserver;
+    IOMX::node_id node = 0;
+    success = false;
+
+    const char *componentName;
+    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
+        componentName = matchingCodecs[i].string();
+
+#if BUILD_WITH_FULL_STAGEFRIGHT
+        sp<MediaSource> softwareCodec =
+            InstantiateSoftwareCodec(componentName, source);
+
+        if (softwareCodec != NULL) {
+            LOGV("Successfully allocated software codec '%s'", componentName);
+
+            return softwareCodec;
+        }
+#endif
+
+        LOGV("Attempting to allocate OMX node '%s'", componentName);
+
+        status_t err = omx->allocateNode(componentName, observer, &node);
+        if (err == OK) {
+            LOGV("Successfully allocated OMX node '%s'", componentName);
+
+            success = true;
+            break;
+        }
+    }
+
+    if (!success) {
+        return NULL;
+    }
+
     sp<OMXCodec> codec = new OMXCodec(
-            omx, node, quirks, createEncoder, mime, componentName,
+            omx, node, getComponentQuirks(componentName),
+            createEncoder, mime, componentName,
             source);
 
     observer->setCodec(codec);
@@ -266,14 +430,9 @@
         esds.getCodecSpecificInfo(
                 &codec_specific_data, &codec_specific_data_size);
 
-        printf("found codec-specific data of size %d\n",
-               codec_specific_data_size);
-
         codec->addCodecSpecificData(
                 codec_specific_data, codec_specific_data_size);
     } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
-        printf("found avcc of size %d\n", size);
-
         // Parse the AVCDecoderConfigurationRecord
 
         const uint8_t *ptr = (const uint8_t *)data;
@@ -283,7 +442,9 @@
         uint8_t profile = ptr[1];
         uint8_t level = ptr[3];
 
-        CHECK((ptr[4] >> 2) == 0x3f);  // reserved
+        // There is decodable content out there that fails the following
+        // assertion, let's be lenient for now...
+        // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
 
         size_t lengthSize = 1 + (ptr[4] & 3);
 
@@ -331,7 +492,7 @@
             size -= length;
         }
 
-        LOGI("AVC profile = %d (%s), level = %d",
+        LOGV("AVC profile = %d (%s), level = %d",
              (int)profile, AVCProfileToString(profile), (int)level / 10);
 
         if (!strcmp(componentName, "OMX.TI.Video.Decoder")
@@ -346,10 +507,10 @@
     }
 
     if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mime)) {
-        codec->setAMRFormat();
+        codec->setAMRFormat(false /* isWAMR */);
     }
     if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mime)) {
-        codec->setAMRWBFormat();
+        codec->setAMRFormat(true /* isWAMR */);
     }
     if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mime)) {
         int32_t numChannels, sampleRate;
@@ -394,7 +555,7 @@
     }
 
     int32_t maxInputSize;
-    if (createEncoder && meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
+    if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
         codec->setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
     }
 
@@ -419,12 +580,18 @@
 
     if (def.nBufferSize < size) {
         def.nBufferSize = size;
-
     }
 
     err = mOMX->setParameter(
             mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
     CHECK_EQ(err, OK);
+
+    err = mOMX->getParameter(
+            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
+    CHECK_EQ(err, OK);
+
+    // Make sure the setting actually stuck.
+    CHECK(def.nBufferSize >= size);
 }
 
 status_t OMXCodec::setVideoPortFormatType(
@@ -452,7 +619,7 @@
         // CHECK_EQ(format.nIndex, index);
 
 #if 1
-        CODEC_LOGI("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d",
+        CODEC_LOGV("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d",
              portIndex,
              index, format.eCompressionFormat, format.eColorFormat);
 #endif
@@ -493,9 +660,25 @@
     return err;
 }
 
+static size_t getFrameSize(
+        OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) {
+    switch (colorFormat) {
+        case OMX_COLOR_FormatYCbYCr:
+        case OMX_COLOR_FormatCbYCrY:
+            return width * height * 2;
+
+        case OMX_COLOR_FormatYUV420SemiPlanar:
+            return (width * height * 3) / 2;
+
+        default:
+            CHECK(!"Should not be here. Unsupported color format.");
+            break;
+    }
+}
+
 void OMXCodec::setVideoInputFormat(
         const char *mime, OMX_U32 width, OMX_U32 height) {
-    CODEC_LOGI("setVideoInputFormat width=%ld, height=%ld", width, height);
+    CODEC_LOGV("setVideoInputFormat width=%ld, height=%ld", width, height);
 
     OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
     if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
@@ -509,19 +692,18 @@
         CHECK(!"Should not be here. Not a supported video mime type.");
     }
 
-    OMX_COLOR_FORMATTYPE colorFormat =
-        0 ? OMX_COLOR_FormatYCbYCr : OMX_COLOR_FormatCbYCrY;
-
-    if (!strncmp("OMX.qcom.video.encoder.", mComponentName, 23)) {
-        colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
+    OMX_COLOR_FORMATTYPE colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
+    if (!strcasecmp("OMX.TI.Video.encoder", mComponentName)) {
+        colorFormat = OMX_COLOR_FormatYCbYCr;
     }
 
-    setVideoPortFormatType(
+    CHECK_EQ(setVideoPortFormatType(
             kPortIndexInput, OMX_VIDEO_CodingUnused,
-            colorFormat);
+            colorFormat), OK);
 
-    setVideoPortFormatType(
-            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused);
+    CHECK_EQ(setVideoPortFormatType(
+            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused),
+            OK);
 
     OMX_PARAM_PORTDEFINITIONTYPE def;
     InitOMXParams(&def);
@@ -554,8 +736,8 @@
             mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
     CHECK_EQ(err, OK);
 
-    def.nBufferSize = (width * height * 2); // (width * height * 3) / 2;
-    CODEC_LOGI("Setting nBufferSize = %ld", def.nBufferSize);
+    def.nBufferSize = getFrameSize(colorFormat, width, height);
+    CODEC_LOGV("Setting nBufferSize = %ld", def.nBufferSize);
 
     CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
 
@@ -564,14 +746,172 @@
     video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
     video_def->eColorFormat = colorFormat;
 
+    video_def->xFramerate = 24 << 16;  // XXX crucial!
+
     err = mOMX->setParameter(
             mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
     CHECK_EQ(err, OK);
+
+    switch (compressionFormat) {
+        case OMX_VIDEO_CodingMPEG4:
+        {
+            CHECK_EQ(setupMPEG4EncoderParameters(), OK);
+            break;
+        }
+
+        case OMX_VIDEO_CodingH263:
+            break;
+
+        case OMX_VIDEO_CodingAVC:
+        {
+            CHECK_EQ(setupAVCEncoderParameters(), OK);
+            break;
+        }
+
+        default:
+            CHECK(!"Support for this compressionFormat to be implemented.");
+            break;
+    }
+}
+
+status_t OMXCodec::setupMPEG4EncoderParameters() {
+    OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type;
+    InitOMXParams(&mpeg4type);
+    mpeg4type.nPortIndex = kPortIndexOutput;
+
+    status_t err = mOMX->getParameter(
+            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
+    CHECK_EQ(err, OK);
+
+    mpeg4type.nSliceHeaderSpacing = 0;
+    mpeg4type.bSVH = OMX_FALSE;
+    mpeg4type.bGov = OMX_FALSE;
+
+    mpeg4type.nAllowedPictureTypes =
+        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
+
+    mpeg4type.nPFrames = 23;
+    mpeg4type.nBFrames = 0;
+
+    mpeg4type.nIDCVLCThreshold = 0;
+    mpeg4type.bACPred = OMX_TRUE;
+    mpeg4type.nMaxPacketSize = 256;
+    mpeg4type.nTimeIncRes = 1000;
+    mpeg4type.nHeaderExtension = 0;
+    mpeg4type.bReversibleVLC = OMX_FALSE;
+
+    mpeg4type.eProfile = OMX_VIDEO_MPEG4ProfileCore;
+    mpeg4type.eLevel = OMX_VIDEO_MPEG4Level2;
+
+    err = mOMX->setParameter(
+            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
+    CHECK_EQ(err, OK);
+
+    // ----------------
+
+    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
+    InitOMXParams(&bitrateType);
+    bitrateType.nPortIndex = kPortIndexOutput;
+
+    err = mOMX->getParameter(
+            mNode, OMX_IndexParamVideoBitrate,
+            &bitrateType, sizeof(bitrateType));
+    CHECK_EQ(err, OK);
+
+    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
+    bitrateType.nTargetBitrate = 1000000;
+
+    err = mOMX->setParameter(
+            mNode, OMX_IndexParamVideoBitrate,
+            &bitrateType, sizeof(bitrateType));
+    CHECK_EQ(err, OK);
+
+    // ----------------
+
+    OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
+    InitOMXParams(&errorCorrectionType);
+    errorCorrectionType.nPortIndex = kPortIndexOutput;
+
+    err = mOMX->getParameter(
+            mNode, OMX_IndexParamVideoErrorCorrection,
+            &errorCorrectionType, sizeof(errorCorrectionType));
+    CHECK_EQ(err, OK);
+
+    errorCorrectionType.bEnableHEC = OMX_FALSE;
+    errorCorrectionType.bEnableResync = OMX_TRUE;
+    errorCorrectionType.nResynchMarkerSpacing = 256;
+    errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
+    errorCorrectionType.bEnableRVLC = OMX_FALSE;
+
+    err = mOMX->setParameter(
+            mNode, OMX_IndexParamVideoErrorCorrection,
+            &errorCorrectionType, sizeof(errorCorrectionType));
+    CHECK_EQ(err, OK);
+
+    return OK;
+}
+
+status_t OMXCodec::setupAVCEncoderParameters() {
+    OMX_VIDEO_PARAM_AVCTYPE h264type;
+    InitOMXParams(&h264type);
+    h264type.nPortIndex = kPortIndexOutput;
+
+    status_t err = mOMX->getParameter(
+            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
+    CHECK_EQ(err, OK);
+
+    h264type.nAllowedPictureTypes =
+        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
+
+    h264type.nSliceHeaderSpacing = 0;
+    h264type.nBFrames = 0;
+    h264type.bUseHadamard = OMX_TRUE;
+    h264type.nRefFrames = 1;
+    h264type.nRefIdx10ActiveMinus1 = 0;
+    h264type.nRefIdx11ActiveMinus1 = 0;
+    h264type.bEnableUEP = OMX_FALSE;
+    h264type.bEnableFMO = OMX_FALSE;
+    h264type.bEnableASO = OMX_FALSE;
+    h264type.bEnableRS = OMX_FALSE;
+    h264type.eProfile = OMX_VIDEO_AVCProfileBaseline;
+    h264type.eLevel = OMX_VIDEO_AVCLevel1b;
+    h264type.bFrameMBsOnly = OMX_TRUE;
+    h264type.bMBAFF = OMX_FALSE;
+    h264type.bEntropyCodingCABAC = OMX_FALSE;
+    h264type.bWeightedPPrediction = OMX_FALSE;
+    h264type.bconstIpred = OMX_FALSE;
+    h264type.bDirect8x8Inference = OMX_FALSE;
+    h264type.bDirectSpatialTemporal = OMX_FALSE;
+    h264type.nCabacInitIdc = 0;
+    h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable;
+
+    err = mOMX->setParameter(
+            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
+    CHECK_EQ(err, OK);
+
+    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
+    InitOMXParams(&bitrateType);
+    bitrateType.nPortIndex = kPortIndexOutput;
+
+    err = mOMX->getParameter(
+            mNode, OMX_IndexParamVideoBitrate,
+            &bitrateType, sizeof(bitrateType));
+    CHECK_EQ(err, OK);
+
+    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
+    bitrateType.nTargetBitrate = 1000000;
+
+    err = mOMX->setParameter(
+            mNode, OMX_IndexParamVideoBitrate,
+            &bitrateType, sizeof(bitrateType));
+    CHECK_EQ(err, OK);
+
+    return OK;
 }
 
 void OMXCodec::setVideoOutputFormat(
         const char *mime, OMX_U32 width, OMX_U32 height) {
-    CODEC_LOGI("setVideoOutputFormat width=%ld, height=%ld", width, height);
+    CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height);
 
     OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
     if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
@@ -639,6 +979,7 @@
     video_def->nFrameWidth = width;
     video_def->nFrameHeight = height;
 
+    video_def->eCompressionFormat = compressionFormat;
     video_def->eColorFormat = OMX_COLOR_FormatUnused;
 
     err = mOMX->setParameter(
@@ -668,7 +1009,6 @@
     CHECK_EQ(err, OK);
 }
 
-
 OMXCodec::OMXCodec(
         const sp<IOMX> &omx, IOMX::node_id node, uint32_t quirks,
         bool isEncoder,
@@ -687,6 +1027,7 @@
       mInitialBufferSubmit(true),
       mSignalledEOS(false),
       mNoMoreOutputData(false),
+      mOutputPortSettingsHaveChanged(false),
       mSeekTimeUs(-1) {
     mPortStatus[kPortIndexInput] = ENABLED;
     mPortStatus[kPortIndexOutput] = ENABLED;
@@ -882,7 +1223,7 @@
              portIndex == kPortIndexInput ? "input" : "output");
     }
 
-    dumpPortStatus(portIndex);
+    // dumpPortStatus(portIndex);
 
     return OK;
 }
@@ -932,7 +1273,6 @@
                 CHECK_EQ(mPortStatus[kPortIndexInput], ENABLED);
                 drainInputBuffer(&buffers->editItemAt(i));
             }
-
             break;
         }
 
@@ -941,12 +1281,10 @@
             IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
             OMX_U32 flags = msg.u.extended_buffer_data.flags;
 
-            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx)",
+            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
                  buffer,
                  msg.u.extended_buffer_data.range_length,
-                 flags);
-
-            CODEC_LOGV("FILL_BUFFER_DONE(timestamp: %lld us (%.2f secs))",
+                 flags,
                  msg.u.extended_buffer_data.timestamp,
                  msg.u.extended_buffer_data.timestamp / 1E6);
 
@@ -974,11 +1312,13 @@
                 CHECK_EQ(err, OK);
 
                 buffers->removeAt(i);
+#if 0
             } else if (mPortStatus[kPortIndexOutput] == ENABLED
                        && (flags & OMX_BUFFERFLAG_EOS)) {
                 CODEC_LOGV("No more output data.");
                 mNoMoreOutputData = true;
                 mBufferFilled.signal();
+#endif
             } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
                 CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
 
@@ -990,16 +1330,15 @@
 
                 buffer->meta_data()->clear();
 
-                buffer->meta_data()->setInt32(
-                        kKeyTimeUnits,
-                        (msg.u.extended_buffer_data.timestamp + 500) / 1000);
-
-                buffer->meta_data()->setInt32(
-                        kKeyTimeScale, 1000);
+                buffer->meta_data()->setInt64(
+                        kKeyTime, msg.u.extended_buffer_data.timestamp);
 
                 if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
                     buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
                 }
+                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
+                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
+                }
 
                 buffer->meta_data()->setPointer(
                         kKeyPlatformPrivate,
@@ -1011,6 +1350,11 @@
 
                 mFilledBuffers.push_back(i);
                 mBufferFilled.signal();
+
+                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
+                    CODEC_LOGV("No more output data.");
+                    mNoMoreOutputData = true;
+                }
             }
 
             break;
@@ -1034,7 +1378,7 @@
 
         case OMX_EventError:
         {
-            LOGE("ERROR(%ld, %ld)", data1, data2);
+            LOGE("ERROR(0x%08lx, %ld)", data1, data2);
 
             setState(ERROR);
             break;
@@ -1046,6 +1390,7 @@
             break;
         }
 
+#if 0
         case OMX_EventBufferFlag:
         {
             CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
@@ -1055,6 +1400,7 @@
             }
             break;
         }
+#endif
 
         default:
         {
@@ -1064,6 +1410,71 @@
     }
 }
 
+// Has the format changed in any way that the client would have to be aware of?
+static bool formatHasNotablyChanged(
+        const sp<MetaData> &from, const sp<MetaData> &to) {
+    if (from.get() == NULL && to.get() == NULL) {
+        return false;
+    }
+
+    if ((from.get() == NULL && to.get() != NULL)
+        || (from.get() != NULL && to.get() == NULL)) {
+        return true;
+    }
+
+    const char *mime_from, *mime_to;
+    CHECK(from->findCString(kKeyMIMEType, &mime_from));
+    CHECK(to->findCString(kKeyMIMEType, &mime_to));
+
+    if (strcasecmp(mime_from, mime_to)) {
+        return true;
+    }
+
+    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
+        int32_t colorFormat_from, colorFormat_to;
+        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
+        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
+
+        if (colorFormat_from != colorFormat_to) {
+            return true;
+        }
+
+        int32_t width_from, width_to;
+        CHECK(from->findInt32(kKeyWidth, &width_from));
+        CHECK(to->findInt32(kKeyWidth, &width_to));
+
+        if (width_from != width_to) {
+            return true;
+        }
+
+        int32_t height_from, height_to;
+        CHECK(from->findInt32(kKeyHeight, &height_from));
+        CHECK(to->findInt32(kKeyHeight, &height_to));
+
+        if (height_from != height_to) {
+            return true;
+        }
+    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
+        int32_t numChannels_from, numChannels_to;
+        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
+        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
+
+        if (numChannels_from != numChannels_to) {
+            return true;
+        }
+
+        int32_t sampleRate_from, sampleRate_to;
+        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
+        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
+
+        if (sampleRate_from != sampleRate_to) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
 void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
     switch (cmd) {
         case OMX_CommandStateSet:
@@ -1086,6 +1497,15 @@
             if (mState == RECONFIGURING) {
                 CHECK_EQ(portIndex, kPortIndexOutput);
 
+                sp<MetaData> oldOutputFormat = mOutputFormat;
+                initOutputFormat(mSource->getFormat());
+
+                // Don't notify clients if the output port settings change
+                // wasn't of importance to them, i.e. it may be that just the
+                // number of buffers has changed and nothing else.
+                mOutputPortSettingsHaveChanged =
+                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
+
                 enablePortAsync(portIndex);
 
                 status_t err = allocateBuffersOnPort(portIndex);
@@ -1151,13 +1571,6 @@
                     CODEC_LOGV("Finished flushing both ports, now continuing from"
                          " seek-time.");
 
-                    // Clear this flag in case the decoder sent us either
-                    // the EVENT_BUFFER_FLAG(1) or an output buffer with
-                    // the EOS flag set _while_ flushing. Since we're going
-                    // to submit "fresh" input data now, this flag no longer
-                    // applies to our future.
-                    mNoMoreOutputData = false;
-
                     drainInputBuffers();
                     fillOutputBuffers();
                 }
@@ -1418,6 +1831,8 @@
             memcpy(info->mMem->pointer(), specific->mData, specific->mSize);
         }
 
+        mNoMoreOutputData = false;
+
         status_t err = mOMX->emptyBuffer(
                 mNode, info->mBuffer, 0, size,
                 OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
@@ -1435,7 +1850,9 @@
     if (mSeekTimeUs >= 0) {
         MediaSource::ReadOptions options;
         options.setSeekTo(mSeekTimeUs);
+
         mSeekTimeUs = -1;
+        mBufferFilled.signal();
 
         err = mSource->read(&srcBuffer, &options);
     } else {
@@ -1443,7 +1860,7 @@
     }
 
     OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
-    OMX_TICKS timestamp = 0;
+    OMX_TICKS timestampUs = 0;
     size_t srcLength = 0;
 
     if (err != OK) {
@@ -1452,6 +1869,8 @@
 
         mSignalledEOS = true;
     } else {
+        mNoMoreOutputData = false;
+
         srcLength = srcBuffer->range_length();
 
         if (info->mMem->size() < srcLength) {
@@ -1463,15 +1882,11 @@
                (const uint8_t *)srcBuffer->data() + srcBuffer->range_offset(),
                srcLength);
 
-        int32_t units, scale;
-        if (srcBuffer->meta_data()->findInt32(kKeyTimeUnits, &units)
-            && srcBuffer->meta_data()->findInt32(kKeyTimeScale, &scale)) {
-            timestamp = ((OMX_TICKS)units * 1000000) / scale;
-
-            CODEC_LOGV("Calling empty_buffer on buffer %p (length %d)",
-                 info->mBuffer, srcLength);
-            CODEC_LOGV("Calling empty_buffer with timestamp %lld us (%.2f secs)",
-                 timestamp, timestamp / 1E6);
+        if (srcBuffer->meta_data()->findInt64(kKeyTime, &timestampUs)) {
+            CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
+                       "timestamp %lld us (%.2f secs)",
+                       info->mBuffer, srcLength,
+                       timestampUs, timestampUs / 1E6);
         }
     }
 
@@ -1482,7 +1897,7 @@
 
     err = mOMX->emptyBuffer(
             mNode, info->mBuffer, 0, srcLength,
-            flags, timestamp);
+            flags, timestampUs);
 
     if (err != OK) {
         setState(ERROR);
@@ -1490,6 +1905,13 @@
     }
 
     info->mOwnedByComponent = true;
+
+    // This component does not ever signal the EOS flag on output buffers,
+    // Thanks for nothing.
+    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
+        mNoMoreOutputData = true;
+        mBufferFilled.signal();
+    }
 }
 
 void OMXCodec::fillOutputBuffer(BufferInfo *info) {
@@ -1574,54 +1996,24 @@
     CHECK_EQ(err, OK);
 }
 
-void OMXCodec::setAMRFormat() {
-    if (!mIsEncoder) {
-        OMX_AUDIO_PARAM_AMRTYPE def;
-        InitOMXParams(&def);
-        def.nPortIndex = kPortIndexInput;
+void OMXCodec::setAMRFormat(bool isWAMR) {
+    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
 
-        status_t err =
-            mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
+    OMX_AUDIO_PARAM_AMRTYPE def;
+    InitOMXParams(&def);
+    def.nPortIndex = portIndex;
 
-        CHECK_EQ(err, OK);
+    status_t err =
+        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
 
-        def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
-        def.eAMRBandMode = OMX_AUDIO_AMRBandModeNB0;
+    CHECK_EQ(err, OK);
 
-        err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
-        CHECK_EQ(err, OK);
-    }
+    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
+    def.eAMRBandMode =
+        isWAMR ? OMX_AUDIO_AMRBandModeWB0 : OMX_AUDIO_AMRBandModeNB0;
 
-    ////////////////////////
-
-    if (mIsEncoder) {
-        sp<MetaData> format = mSource->getFormat();
-        int32_t sampleRate;
-        int32_t numChannels;
-        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
-        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
-
-        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
-    }
-}
-
-void OMXCodec::setAMRWBFormat() {
-    if (!mIsEncoder) {
-        OMX_AUDIO_PARAM_AMRTYPE def;
-        InitOMXParams(&def);
-        def.nPortIndex = kPortIndexInput;
-
-        status_t err =
-            mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
-
-        CHECK_EQ(err, OK);
-
-        def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
-        def.eAMRBandMode = OMX_AUDIO_AMRBandModeWB0;
-
-        err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
-        CHECK_EQ(err, OK);
-    }
+    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
+    CHECK_EQ(err, OK);
 
     ////////////////////////
 
@@ -1794,6 +2186,7 @@
     mInitialBufferSubmit = true;
     mSignalledEOS = false;
     mNoMoreOutputData = false;
+    mOutputPortSettingsHaveChanged = false;
     mSeekTimeUs = -1;
     mFilledBuffers.clear();
 
@@ -1864,6 +2257,8 @@
 }
 
 sp<MetaData> OMXCodec::getFormat() {
+    Mutex::Autolock autoLock(mLock);
+
     return mOutputFormat;
 }
 
@@ -1908,7 +2303,6 @@
         CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
 
         mSignalledEOS = false;
-        mNoMoreOutputData = false;
 
         CHECK(seekTimeUs >= 0);
         mSeekTimeUs = seekTimeUs;
@@ -1927,6 +2321,10 @@
         if (emulateOutputFlushCompletion) {
             onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
         }
+
+        while (mSeekTimeUs >= 0) {
+            mBufferFilled.wait(mLock);
+        }
     }
 
     while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
@@ -1941,6 +2339,12 @@
         return ERROR_END_OF_STREAM;
     }
 
+    if (mOutputPortSettingsHaveChanged) {
+        mOutputPortSettingsHaveChanged = false;
+
+        return INFO_FORMAT_CHANGED;
+    }
+
     size_t index = *mFilledBuffers.begin();
     mFilledBuffers.erase(mFilledBuffers.begin());
 
@@ -2041,8 +2445,6 @@
 
     size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
 
-    static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
-
     if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
         return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
     } else if (type < 0 || (size_t)type >= numNames) {
@@ -2410,7 +2812,7 @@
                 CHECK(!"Unknown compression format.");
             }
 
-            if (mQuirks & kOutputDimensionsAre16Aligned) {
+            if (!strcmp(mComponentName, "OMX.PV.avcdec")) {
                 // This component appears to be lying to me.
                 mOutputFormat->setInt32(
                         kKeyWidth, (video_def->nFrameWidth + 15) & -16);
diff --git a/media/libstagefright/SampleTable.cpp b/media/libstagefright/SampleTable.cpp
index 8efa7c7..4aec0e9 100644
--- a/media/libstagefright/SampleTable.cpp
+++ b/media/libstagefright/SampleTable.cpp
@@ -17,11 +17,12 @@
 #define LOG_TAG "SampleTable"
 #include <utils/Log.h>
 
+#include "include/SampleTable.h"
+
 #include <arpa/inet.h>
 
 #include <media/stagefright/DataSource.h>
 #include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/SampleTable.h>
 #include <media/stagefright/Utils.h>
 
 namespace android {
@@ -54,7 +55,7 @@
 }
 
 status_t SampleTable::setChunkOffsetParams(
-        uint32_t type, off_t data_offset, off_t data_size) {
+        uint32_t type, off_t data_offset, size_t data_size) {
     if (mChunkOffsetOffset >= 0) {
         return ERROR_MALFORMED;
     }
@@ -69,7 +70,7 @@
     }
 
     uint8_t header[8];
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
         return ERROR_IO;
     }
@@ -95,7 +96,7 @@
 }
 
 status_t SampleTable::setSampleToChunkParams(
-        off_t data_offset, off_t data_size) {
+        off_t data_offset, size_t data_size) {
     if (mSampleToChunkOffset >= 0) {
         return ERROR_MALFORMED;
     }
@@ -107,7 +108,7 @@
     }
 
     uint8_t header[8];
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
         return ERROR_IO;
     }
@@ -127,7 +128,7 @@
 }
 
 status_t SampleTable::setSampleSizeParams(
-        uint32_t type, off_t data_offset, off_t data_size) {
+        uint32_t type, off_t data_offset, size_t data_size) {
     if (mSampleSizeOffset >= 0) {
         return ERROR_MALFORMED;
     }
@@ -141,7 +142,7 @@
     }
 
     uint8_t header[12];
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
         return ERROR_IO;
     }
@@ -187,13 +188,13 @@
 }
 
 status_t SampleTable::setTimeToSampleParams(
-        off_t data_offset, off_t data_size) {
+        off_t data_offset, size_t data_size) {
     if (mTimeToSample != NULL || data_size < 8) {
         return ERROR_MALFORMED;
     }
 
     uint8_t header[8];
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
         return ERROR_IO;
     }
@@ -207,7 +208,7 @@
     mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
 
     size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
         return ERROR_IO;
     }
@@ -219,7 +220,7 @@
     return OK;
 }
 
-status_t SampleTable::setSyncSampleParams(off_t data_offset, off_t data_size) {
+status_t SampleTable::setSyncSampleParams(off_t data_offset, size_t data_size) {
     if (mSyncSampleOffset >= 0 || data_size < 8) {
         return ERROR_MALFORMED;
     }
@@ -227,7 +228,7 @@
     mSyncSampleOffset = data_offset;
 
     uint8_t header[8];
-    if (mDataSource->read_at(
+    if (mDataSource->readAt(
                 data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
         return ERROR_IO;
     }
@@ -263,7 +264,7 @@
     if (mChunkOffsetType == kChunkOffsetType32) {
         uint32_t offset32;
 
-        if (mDataSource->read_at(
+        if (mDataSource->readAt(
                     mChunkOffsetOffset + 8 + 4 * chunk_index,
                     &offset32,
                     sizeof(offset32)) < (ssize_t)sizeof(offset32)) {
@@ -275,7 +276,7 @@
         CHECK_EQ(mChunkOffsetType, kChunkOffsetType64);
 
         uint64_t offset64;
-        if (mDataSource->read_at(
+        if (mDataSource->readAt(
                     mChunkOffsetOffset + 8 + 8 * chunk_index,
                     &offset64,
                     sizeof(offset64)) < (ssize_t)sizeof(offset64)) {
@@ -312,7 +313,7 @@
     uint32_t index = 0;
     while (index < mNumSampleToChunkOffsets) {
         uint8_t buffer[12];
-        if (mDataSource->read_at(mSampleToChunkOffset + 8 + index * 12,
+        if (mDataSource->readAt(mSampleToChunkOffset + 8 + index * 12,
                                  buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
             return ERROR_IO;
         }
@@ -361,7 +362,7 @@
     switch (mSampleSizeFieldSize) {
         case 32:
         {
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         mSampleSizeOffset + 12 + 4 * sample_index,
                         sample_size, sizeof(*sample_size)) < (ssize_t)sizeof(*sample_size)) {
                 return ERROR_IO;
@@ -374,7 +375,7 @@
         case 16:
         {
             uint16_t x;
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         mSampleSizeOffset + 12 + 2 * sample_index,
                         &x, sizeof(x)) < (ssize_t)sizeof(x)) {
                 return ERROR_IO;
@@ -387,7 +388,7 @@
         case 8:
         {
             uint8_t x;
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         mSampleSizeOffset + 12 + sample_index,
                         &x, sizeof(x)) < (ssize_t)sizeof(x)) {
                 return ERROR_IO;
@@ -402,7 +403,7 @@
             CHECK_EQ(mSampleSizeFieldSize, 4);
 
             uint8_t x;
-            if (mDataSource->read_at(
+            if (mDataSource->readAt(
                         mSampleSizeOffset + 12 + sample_index / 2,
                         &x, sizeof(x)) < (ssize_t)sizeof(x)) {
                 return ERROR_IO;
@@ -553,7 +554,7 @@
     uint32_t right = mNumSyncSamples;
     while (left < right) {
         uint32_t mid = (left + right) / 2;
-        if (mDataSource->read_at(
+        if (mDataSource->readAt(
                     mSyncSampleOffset + 8 + (mid - 1) * 4, &x, 4) != 4) {
             return ERROR_IO;
         }
@@ -574,5 +575,52 @@
     return OK;
 }
 
+status_t SampleTable::findThumbnailSample(uint32_t *sample_index) {
+    if (mSyncSampleOffset < 0) {
+        // All samples are sync-samples.
+        *sample_index = 0;
+        return OK;
+    }
+
+    uint32_t bestSampleIndex = 0;
+    size_t maxSampleSize = 0;
+
+    static const size_t kMaxNumSyncSamplesToScan = 20;
+
+    // Consider the first kMaxNumSyncSamplesToScan sync samples and
+    // pick the one with the largest (compressed) size as the thumbnail.
+
+    size_t numSamplesToScan = mNumSyncSamples;
+    if (numSamplesToScan > kMaxNumSyncSamplesToScan) {
+        numSamplesToScan = kMaxNumSyncSamplesToScan;
+    }
+
+    for (size_t i = 0; i < numSamplesToScan; ++i) {
+        uint32_t x;
+        if (mDataSource->readAt(
+                    mSyncSampleOffset + 8 + i * 4, &x, 4) != 4) {
+            return ERROR_IO;
+        }
+        x = ntohl(x);
+        --x;
+
+        // Now x is a sample index.
+        size_t sampleSize;
+        status_t err = getSampleSize(x, &sampleSize);
+        if (err != OK) {
+            return err;
+        }
+
+        if (i == 0 || sampleSize > maxSampleSize) {
+            bestSampleIndex = x;
+            maxSampleSize = sampleSize;
+        }
+    }
+
+    *sample_index = bestSampleIndex;
+
+    return OK;
+}
+
 }  // namespace android
 
diff --git a/media/libstagefright/ShoutcastSource.cpp b/media/libstagefright/ShoutcastSource.cpp
index 346b5aa..ec25430 100644
--- a/media/libstagefright/ShoutcastSource.cpp
+++ b/media/libstagefright/ShoutcastSource.cpp
@@ -14,16 +14,17 @@
  * limitations under the License.
  */
 
+#include "include/stagefright_string.h"
+#include "include/HTTPStream.h"
+
 #include <stdlib.h>
 
-#include <media/stagefright/HTTPStream.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaBufferGroup.h>
 #include <media/stagefright/MediaDebug.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/ShoutcastSource.h>
-#include <media/stagefright/stagefright_string.h>
 
 namespace android {
 
diff --git a/media/libstagefright/TimedEventQueue.cpp b/media/libstagefright/TimedEventQueue.cpp
index 3d85f75..d079e70 100644
--- a/media/libstagefright/TimedEventQueue.cpp
+++ b/media/libstagefright/TimedEventQueue.cpp
@@ -22,15 +22,17 @@
 #define LOG_TAG "TimedEventQueue"
 #include <utils/Log.h>
 
+#include "include/TimedEventQueue.h"
+
 #include <sys/time.h>
 
 #include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/TimedEventQueue.h>
 
 namespace android {
 
 TimedEventQueue::TimedEventQueue()
-    : mRunning(false),
+    : mNextEventID(1),
+      mRunning(false),
       mStopped(false) {
 }
 
@@ -75,26 +77,29 @@
     mRunning = false;
 }
 
-void TimedEventQueue::postEvent(const sp<Event> &event) {
+TimedEventQueue::event_id TimedEventQueue::postEvent(const sp<Event> &event) {
     // Reserve an earlier timeslot an INT64_MIN to be able to post
     // the StopEvent to the absolute head of the queue.
-    postTimedEvent(event, INT64_MIN + 1);
+    return postTimedEvent(event, INT64_MIN + 1);
 }
 
-void TimedEventQueue::postEventToBack(const sp<Event> &event) {
-    postTimedEvent(event, INT64_MAX);
+TimedEventQueue::event_id TimedEventQueue::postEventToBack(
+        const sp<Event> &event) {
+    return postTimedEvent(event, INT64_MAX);
 }
 
-void TimedEventQueue::postEventWithDelay(
+TimedEventQueue::event_id TimedEventQueue::postEventWithDelay(
         const sp<Event> &event, int64_t delay_us) {
     CHECK(delay_us >= 0);
-    postTimedEvent(event, getRealTimeUs() + delay_us);
+    return postTimedEvent(event, getRealTimeUs() + delay_us);
 }
 
-void TimedEventQueue::postTimedEvent(
+TimedEventQueue::event_id TimedEventQueue::postTimedEvent(
         const sp<Event> &event, int64_t realtime_us) {
     Mutex::Autolock autoLock(mLock);
 
+    event->setEventID(mNextEventID++);
+
     List<QueueItem>::iterator it = mQueue.begin();
     while (it != mQueue.end() && realtime_us >= (*it).realtime_us) {
         ++it;
@@ -111,29 +116,63 @@
     mQueue.insert(it, item);
 
     mQueueNotEmptyCondition.signal();
+
+    return event->eventID();
 }
 
-bool TimedEventQueue::cancelEvent(const sp<Event> &event) {
-    Mutex::Autolock autoLock(mLock);
+static bool MatchesEventID(
+        void *cookie, const sp<TimedEventQueue::Event> &event) {
+    TimedEventQueue::event_id *id =
+        static_cast<TimedEventQueue::event_id *>(cookie);
 
-    List<QueueItem>::iterator it = mQueue.begin();
-    while (it != mQueue.end() && (*it).event != event) {
-        ++it;
-    }
-
-    if (it == mQueue.end()) {
+    if (event->eventID() != *id) {
         return false;
     }
 
-    if (it == mQueue.begin()) {
-        mQueueHeadChangedCondition.signal();
-    }
-
-    mQueue.erase(it);
+    *id = 0;
 
     return true;
 }
 
+bool TimedEventQueue::cancelEvent(event_id id) {
+    if (id == 0) {
+        return false;
+    }
+
+    cancelEvents(&MatchesEventID, &id, true /* stopAfterFirstMatch */);
+
+    // if MatchesEventID found a match, it will have set id to 0
+    // (which is not a valid event_id).
+
+    return id == 0;
+}
+
+void TimedEventQueue::cancelEvents(
+        bool (*predicate)(void *cookie, const sp<Event> &event),
+        void *cookie,
+        bool stopAfterFirstMatch) {
+    Mutex::Autolock autoLock(mLock);
+
+    List<QueueItem>::iterator it = mQueue.begin();
+    while (it != mQueue.end()) {
+        if (!(*predicate)(cookie, (*it).event)) {
+            ++it;
+            continue;
+        }
+
+        if (it == mQueue.begin()) {
+            mQueueHeadChangedCondition.signal();
+        }
+
+        (*it).event->setEventID(0);
+        it = mQueue.erase(it);
+
+        if (stopAfterFirstMatch) {
+            return;
+        }
+    }
+}
+
 // static
 int64_t TimedEventQueue::getRealTimeUs() {
     struct timeval tv;
@@ -192,7 +231,12 @@
                 }
             }
 
+            if (mQueue.empty()) {
+                continue;
+            }
+
             event = (*it).event;
+            event->setEventID(0);
             mQueue.erase(it);
         }
 
diff --git a/media/libstagefright/WAVExtractor.cpp b/media/libstagefright/WAVExtractor.cpp
new file mode 100644
index 0000000..542c764
--- /dev/null
+++ b/media/libstagefright/WAVExtractor.cpp
@@ -0,0 +1,317 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "WAVExtractor"
+#include <utils/Log.h>
+
+#include "include/WAVExtractor.h"
+
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <utils/String8.h>
+
+namespace android {
+
+static uint16_t WAVE_FORMAT_PCM = 1;
+
+static uint32_t U32_LE_AT(const uint8_t *ptr) {
+    return ptr[3] << 24 | ptr[2] << 16 | ptr[1] << 8 | ptr[0];
+}
+
+static uint16_t U16_LE_AT(const uint8_t *ptr) {
+    return ptr[1] << 8 | ptr[0];
+}
+
+struct WAVSource : public MediaSource {
+    WAVSource(
+            const sp<DataSource> &dataSource,
+            int32_t sampleRate, int32_t numChannels,
+            off_t offset, size_t size);
+
+    virtual status_t start(MetaData *params = NULL);
+    virtual status_t stop();
+    virtual sp<MetaData> getFormat();
+
+    virtual status_t read(
+            MediaBuffer **buffer, const ReadOptions *options = NULL);
+
+protected:
+    virtual ~WAVSource();
+
+private:
+    static const size_t kMaxFrameSize;
+
+    sp<DataSource> mDataSource;
+    int32_t mSampleRate;
+    int32_t mNumChannels;
+    off_t mOffset;
+    size_t mSize;
+    bool mStarted;
+    MediaBufferGroup *mGroup;
+    off_t mCurrentPos;
+
+    WAVSource(const WAVSource &);
+    WAVSource &operator=(const WAVSource &);
+};
+
+WAVExtractor::WAVExtractor(const sp<DataSource> &source)
+    : mDataSource(source),
+      mValidFormat(false) {
+    mInitCheck = init();
+}
+
+WAVExtractor::~WAVExtractor() {
+}
+
+size_t WAVExtractor::countTracks() {
+    return mInitCheck == OK ? 1 : 0;
+}
+
+sp<MediaSource> WAVExtractor::getTrack(size_t index) {
+    if (mInitCheck != OK || index > 0) {
+        return NULL;
+    }
+
+    return new WAVSource(
+            mDataSource, mSampleRate, mNumChannels, mDataOffset, mDataSize);
+}
+
+sp<MetaData> WAVExtractor::getTrackMetaData(
+        size_t index, uint32_t flags) {
+    if (mInitCheck != OK || index > 0) {
+        return NULL;
+    }
+
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
+    meta->setInt32(kKeyChannelCount, mNumChannels);
+    meta->setInt32(kKeySampleRate, mSampleRate);
+
+    int64_t durationUs =
+        1000000LL * (mDataSize / (mNumChannels * 2)) / mSampleRate;
+
+    meta->setInt64(kKeyDuration, durationUs);
+
+    return meta;
+}
+
+status_t WAVExtractor::init() {
+    uint8_t header[12];
+    if (mDataSource->readAt(
+                0, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return NO_INIT;
+    }
+
+    if (memcmp(header, "RIFF", 4) || memcmp(&header[8], "WAVE", 4)) {
+        return NO_INIT;
+    }
+
+    size_t totalSize = U32_LE_AT(&header[4]);
+
+    off_t offset = 12;
+    size_t remainingSize = totalSize;
+    while (remainingSize >= 8) {
+        uint8_t chunkHeader[8];
+        if (mDataSource->readAt(offset, chunkHeader, 8) < 8) {
+            return NO_INIT;
+        }
+
+        remainingSize -= 8;
+        offset += 8;
+        
+        uint32_t chunkSize = U32_LE_AT(&chunkHeader[4]);
+
+        if (chunkSize > remainingSize) {
+            return NO_INIT;
+        }
+
+        if (!memcmp(chunkHeader, "fmt ", 4)) {
+            if (chunkSize < 16) {
+                return NO_INIT;
+            }
+
+            uint8_t formatSpec[16];
+            if (mDataSource->readAt(offset, formatSpec, 16) < 16) {
+                return NO_INIT;
+            }
+
+            uint16_t format = U16_LE_AT(formatSpec);
+            if (format != WAVE_FORMAT_PCM) {
+                return ERROR_UNSUPPORTED;
+            }
+
+            mNumChannels = U16_LE_AT(&formatSpec[2]);
+            if (mNumChannels != 1 && mNumChannels != 2) {
+                return ERROR_UNSUPPORTED;
+            }
+
+            mSampleRate = U32_LE_AT(&formatSpec[4]);
+
+            if (U16_LE_AT(&formatSpec[14]) != 16) {
+                return ERROR_UNSUPPORTED;
+            }
+
+            mValidFormat = true;
+        } else if (!memcmp(chunkHeader, "data", 4)) {
+            if (mValidFormat) {
+                mDataOffset = offset;
+                mDataSize = chunkSize;
+
+                return OK;
+            }
+        }
+
+        offset += chunkSize;
+    }
+
+    return NO_INIT;
+}
+
+const size_t WAVSource::kMaxFrameSize = 32768;
+
+WAVSource::WAVSource(
+        const sp<DataSource> &dataSource,
+        int32_t sampleRate, int32_t numChannels,
+        off_t offset, size_t size)
+    : mDataSource(dataSource),
+      mSampleRate(sampleRate),
+      mNumChannels(numChannels),
+      mOffset(offset),
+      mSize(size),
+      mStarted(false),
+      mGroup(NULL) {
+}
+
+WAVSource::~WAVSource() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+status_t WAVSource::start(MetaData *params) {
+    LOGV("WAVSource::start");
+
+    CHECK(!mStarted);
+
+    mGroup = new MediaBufferGroup;
+    mGroup->add_buffer(new MediaBuffer(kMaxFrameSize));
+
+    mCurrentPos = mOffset;
+
+    mStarted = true;
+
+    return OK;
+}
+
+status_t WAVSource::stop() {
+    LOGV("WAVSource::stop");
+
+    CHECK(mStarted);
+
+    delete mGroup;
+    mGroup = NULL;
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> WAVSource::getFormat() {
+    LOGV("WAVSource::getFormat");
+
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
+    meta->setInt32(kKeyChannelCount, mNumChannels);
+    meta->setInt32(kKeySampleRate, mSampleRate);
+
+    int64_t durationUs =
+        1000000LL * (mSize / (mNumChannels * 2)) / mSampleRate;
+
+    meta->setInt64(kKeyDuration, durationUs);
+
+    return meta;
+}
+
+status_t WAVSource::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options != NULL && options->getSeekTo(&seekTimeUs)) {
+        int64_t pos = (seekTimeUs * mSampleRate) / 1000000 * mNumChannels * 2;
+        if (pos > mSize) {
+            pos = mSize;
+        }
+        mCurrentPos = pos + mOffset;
+    }
+
+    MediaBuffer *buffer;
+    status_t err = mGroup->acquire_buffer(&buffer);
+    if (err != OK) {
+        return err;
+    }
+
+    ssize_t n = mDataSource->readAt(
+            mCurrentPos, buffer->data(), kMaxFrameSize);
+
+    if (n <= 0) {
+        buffer->release();
+        buffer = NULL;
+
+        return ERROR_END_OF_STREAM;
+    }
+
+    mCurrentPos += n;
+
+    buffer->set_range(0, n);
+    buffer->meta_data()->setInt64(
+            kKeyTime,
+            1000000LL * (mCurrentPos - mOffset)
+                / (mNumChannels * 2) / mSampleRate);
+
+
+    *out = buffer;
+
+    return OK;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+bool SniffWAV(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence) {
+    char header[12];
+    if (source->readAt(0, header, sizeof(header)) < (ssize_t)sizeof(header)) {
+        return false;
+    }
+
+    if (memcmp(header, "RIFF", 4) || memcmp(&header[8], "WAVE", 4)) {
+        return false;
+    }
+
+    *mimeType = MEDIA_MIMETYPE_CONTAINER_WAV;
+    *confidence = 0.3f;
+
+    return true;
+}
+
+}  // namespace android
+
diff --git a/media/libstagefright/codecs/Android.mk b/media/libstagefright/codecs/Android.mk
new file mode 100644
index 0000000..1fa7e93
--- /dev/null
+++ b/media/libstagefright/codecs/Android.mk
@@ -0,0 +1,8 @@
+ifeq ($(BUILD_WITH_FULL_STAGEFRIGHT),true)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
+endif
diff --git a/media/libstagefright/codecs/aacdec/AACDecoder.cpp b/media/libstagefright/codecs/aacdec/AACDecoder.cpp
new file mode 100644
index 0000000..92059c5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/AACDecoder.cpp
@@ -0,0 +1,225 @@
+/*
+ * 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 "AACDecoder.h"
+
+#include "../../include/ESDS.h"
+
+#include "pvmp4audiodecoder_api.h"
+
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+AACDecoder::AACDecoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mBufferGroup(NULL),
+      mConfig(new tPVMP4AudioDecoderExternal),
+      mDecoderBuf(NULL),
+      mAnchorTimeUs(0),
+      mNumSamplesOutput(0),
+      mInputBuffer(NULL) {
+}
+
+AACDecoder::~AACDecoder() {
+    if (mStarted) {
+        stop();
+    }
+
+    delete mConfig;
+    mConfig = NULL;
+}
+
+status_t AACDecoder::start(MetaData *params) {
+    CHECK(!mStarted);
+
+    mBufferGroup = new MediaBufferGroup;
+    mBufferGroup->add_buffer(new MediaBuffer(2048 * 2));
+
+    mConfig->outputFormat = OUTPUTFORMAT_16PCM_INTERLEAVED;
+    mConfig->aacPlusUpsamplingFactor = 0;
+    mConfig->aacPlusEnabled = false;
+
+    int32_t numChannels;
+    CHECK(mSource->getFormat()->findInt32(kKeyChannelCount, &numChannels));
+    mConfig->desiredChannels = numChannels;
+
+    UInt32 memRequirements = PVMP4AudioDecoderGetMemRequirements();
+    mDecoderBuf = malloc(memRequirements);
+
+    CHECK_EQ(PVMP4AudioDecoderInitLibrary(mConfig, mDecoderBuf),
+             MP4AUDEC_SUCCESS);
+
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (mSource->getFormat()->findData(kKeyESDS, &type, &data, &size)) {
+        ESDS esds((const char *)data, size);
+        CHECK_EQ(esds.InitCheck(), OK);
+
+        const void *codec_specific_data;
+        size_t codec_specific_data_size;
+        esds.getCodecSpecificInfo(
+                &codec_specific_data, &codec_specific_data_size);
+
+        mConfig->pInputBuffer = (UChar *)codec_specific_data;
+        mConfig->inputBufferCurrentLength = codec_specific_data_size;
+        mConfig->inputBufferMaxLength = 0;
+        mConfig->inputBufferUsedLength = 0;
+        mConfig->remainderBits = 0;
+
+        mConfig->pOutputBuffer = NULL;
+        mConfig->pOutputBuffer_plus = NULL;
+        mConfig->repositionFlag = false;
+
+        CHECK_EQ(PVMP4AudioDecoderConfig(mConfig, mDecoderBuf),
+                 MP4AUDEC_SUCCESS);
+    }
+
+    mSource->start();
+
+    mAnchorTimeUs = 0;
+    mNumSamplesOutput = 0;
+    mStarted = true;
+
+    return OK;
+}
+
+status_t AACDecoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    free(mDecoderBuf);
+    mDecoderBuf = NULL;
+
+    delete mBufferGroup;
+    mBufferGroup = NULL;
+
+    mSource->stop();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> AACDecoder::getFormat() {
+    sp<MetaData> srcFormat = mSource->getFormat();
+
+    int32_t numChannels;
+    int32_t sampleRate;
+    CHECK(srcFormat->findInt32(kKeyChannelCount, &numChannels));
+    CHECK(srcFormat->findInt32(kKeySampleRate, &sampleRate));
+
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
+    meta->setInt32(kKeyChannelCount, numChannels);
+    meta->setInt32(kKeySampleRate, sampleRate);
+
+    int64_t durationUs;
+    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
+        meta->setInt64(kKeyDuration, durationUs);
+    }
+
+    return meta;
+}
+
+status_t AACDecoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    status_t err;
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        CHECK(seekTimeUs >= 0);
+
+        mNumSamplesOutput = 0;
+
+        if (mInputBuffer) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+    } else {
+        seekTimeUs = -1;
+    }
+
+    if (mInputBuffer == NULL) {
+        err = mSource->read(&mInputBuffer, options);
+
+        if (err != OK) {
+            return err;
+        }
+
+        int64_t timeUs;
+        if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
+            mAnchorTimeUs = timeUs;
+            mNumSamplesOutput = 0;
+        } else {
+            // We must have a new timestamp after seeking.
+            CHECK(seekTimeUs < 0);
+        }
+    }
+
+    MediaBuffer *buffer;
+    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
+
+    mConfig->pInputBuffer =
+        (UChar *)mInputBuffer->data() + mInputBuffer->range_offset();
+
+    mConfig->inputBufferCurrentLength = mInputBuffer->range_length();
+    mConfig->inputBufferMaxLength = 0;
+    mConfig->inputBufferUsedLength = 0;
+    mConfig->remainderBits = 0;
+
+    mConfig->pOutputBuffer = static_cast<Int16 *>(buffer->data());
+    mConfig->pOutputBuffer_plus = NULL;
+    mConfig->repositionFlag = false;
+
+    CHECK_EQ(PVMP4AudioDecodeFrame(mConfig, mDecoderBuf), MP4AUDEC_SUCCESS);
+
+    buffer->set_range(
+            0, mConfig->frameLength * sizeof(int16_t) * mConfig->desiredChannels);
+
+    mInputBuffer->set_range(
+            mInputBuffer->range_offset() + mConfig->inputBufferUsedLength,
+            mInputBuffer->range_length() - mConfig->inputBufferUsedLength);
+
+    if (mInputBuffer->range_length() == 0) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    buffer->meta_data()->setInt64(
+            kKeyTime,
+            mAnchorTimeUs
+                + (mNumSamplesOutput * 1000000) / mConfig->samplingRate);
+
+    mNumSamplesOutput += mConfig->frameLength;
+
+    *out = buffer;
+
+    return OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/aacdec/Android.mk b/media/libstagefright/codecs/aacdec/Android.mk
new file mode 100644
index 0000000..d5d8f3e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/Android.mk
@@ -0,0 +1,154 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	analysis_sub_band.cpp \
+ 	apply_ms_synt.cpp \
+ 	apply_tns.cpp \
+ 	buf_getbits.cpp \
+ 	byte_align.cpp \
+ 	calc_auto_corr.cpp \
+ 	calc_gsfb_table.cpp \
+ 	calc_sbr_anafilterbank.cpp \
+ 	calc_sbr_envelope.cpp \
+ 	calc_sbr_synfilterbank.cpp \
+ 	check_crc.cpp \
+ 	dct16.cpp \
+ 	dct64.cpp \
+ 	decode_huff_cw_binary.cpp \
+ 	decode_noise_floorlevels.cpp \
+ 	deinterleave.cpp \
+ 	digit_reversal_tables.cpp \
+ 	dst16.cpp \
+ 	dst32.cpp \
+ 	dst8.cpp \
+ 	esc_iquant_scaling.cpp \
+ 	extractframeinfo.cpp \
+ 	fft_rx4_long.cpp \
+ 	fft_rx4_short.cpp \
+ 	fft_rx4_tables_fxp.cpp \
+ 	find_adts_syncword.cpp \
+ 	fwd_long_complex_rot.cpp \
+ 	fwd_short_complex_rot.cpp \
+ 	gen_rand_vector.cpp \
+ 	get_adif_header.cpp \
+ 	get_adts_header.cpp \
+ 	get_audio_specific_config.cpp \
+ 	get_dse.cpp \
+ 	get_ele_list.cpp \
+ 	get_ga_specific_config.cpp \
+ 	get_ics_info.cpp \
+ 	get_prog_config.cpp \
+ 	get_pulse_data.cpp \
+ 	get_sbr_bitstream.cpp \
+ 	get_sbr_startfreq.cpp \
+ 	get_sbr_stopfreq.cpp \
+ 	get_tns.cpp \
+ 	getfill.cpp \
+ 	getgroup.cpp \
+ 	getics.cpp \
+ 	getmask.cpp \
+ 	hcbtables_binary.cpp \
+ 	huffcb.cpp \
+ 	huffdecode.cpp \
+ 	hufffac.cpp \
+ 	huffspec_fxp.cpp \
+ 	idct16.cpp \
+ 	idct32.cpp \
+ 	idct8.cpp \
+ 	imdct_fxp.cpp \
+ 	infoinit.cpp \
+ 	init_sbr_dec.cpp \
+ 	intensity_right.cpp \
+ 	inv_long_complex_rot.cpp \
+ 	inv_short_complex_rot.cpp \
+ 	iquant_table.cpp \
+ 	long_term_prediction.cpp \
+ 	long_term_synthesis.cpp \
+ 	lt_decode.cpp \
+ 	mdct_fxp.cpp \
+ 	mdct_tables_fxp.cpp \
+ 	mdst.cpp \
+ 	mix_radix_fft.cpp \
+ 	ms_synt.cpp \
+ 	pns_corr.cpp \
+ 	pns_intensity_right.cpp \
+ 	pns_left.cpp \
+ 	ps_all_pass_filter_coeff.cpp \
+ 	ps_all_pass_fract_delay_filter.cpp \
+ 	ps_allocate_decoder.cpp \
+ 	ps_applied.cpp \
+ 	ps_bstr_decoding.cpp \
+ 	ps_channel_filtering.cpp \
+ 	ps_decode_bs_utils.cpp \
+ 	ps_decorrelate.cpp \
+ 	ps_fft_rx8.cpp \
+ 	ps_hybrid_analysis.cpp \
+ 	ps_hybrid_filter_bank_allocation.cpp \
+ 	ps_hybrid_synthesis.cpp \
+ 	ps_init_stereo_mixing.cpp \
+ 	ps_pwr_transient_detection.cpp \
+ 	ps_read_data.cpp \
+ 	ps_stereo_processing.cpp \
+ 	pulse_nc.cpp \
+ 	pv_div.cpp \
+ 	pv_log2.cpp \
+ 	pv_normalize.cpp \
+ 	pv_pow2.cpp \
+ 	pv_sine.cpp \
+ 	pv_sqrt.cpp \
+ 	pvmp4audiodecoderconfig.cpp \
+ 	pvmp4audiodecoderframe.cpp \
+ 	pvmp4audiodecodergetmemrequirements.cpp \
+ 	pvmp4audiodecoderinitlibrary.cpp \
+ 	pvmp4audiodecoderresetbuffer.cpp \
+ 	q_normalize.cpp \
+ 	qmf_filterbank_coeff.cpp \
+ 	sbr_aliasing_reduction.cpp \
+ 	sbr_applied.cpp \
+ 	sbr_code_book_envlevel.cpp \
+ 	sbr_crc_check.cpp \
+ 	sbr_create_limiter_bands.cpp \
+ 	sbr_dec.cpp \
+ 	sbr_decode_envelope.cpp \
+ 	sbr_decode_huff_cw.cpp \
+ 	sbr_downsample_lo_res.cpp \
+ 	sbr_envelope_calc_tbl.cpp \
+ 	sbr_envelope_unmapping.cpp \
+ 	sbr_extract_extended_data.cpp \
+ 	sbr_find_start_andstop_band.cpp \
+ 	sbr_generate_high_freq.cpp \
+ 	sbr_get_additional_data.cpp \
+ 	sbr_get_cpe.cpp \
+ 	sbr_get_dir_control_data.cpp \
+ 	sbr_get_envelope.cpp \
+ 	sbr_get_header_data.cpp \
+ 	sbr_get_noise_floor_data.cpp \
+ 	sbr_get_sce.cpp \
+ 	sbr_inv_filt_levelemphasis.cpp \
+ 	sbr_open.cpp \
+ 	sbr_read_data.cpp \
+ 	sbr_requantize_envelope_data.cpp \
+ 	sbr_reset_dec.cpp \
+ 	sbr_update_freq_scale.cpp \
+ 	set_mc_info.cpp \
+ 	sfb.cpp \
+ 	shellsort.cpp \
+ 	synthesis_sub_band.cpp \
+ 	tns_ar_filter.cpp \
+ 	tns_decode_coef.cpp \
+ 	tns_inv_filter.cpp \
+ 	trans4m_freq_2_time_fxp.cpp \
+ 	trans4m_time_2_freq_fxp.cpp \
+ 	unpack_idx.cpp \
+ 	window_tables_fxp.cpp \
+ 	pvmp4setaudioconfig.cpp \
+        AACDecoder.cpp
+
+LOCAL_CFLAGS := -DAAC_PLUS -DHQ_SBR -DPARAMETRICSTEREO -DOSCL_IMPORT_REF= -DOSCL_EXPORT_REF= -DOSCL_UNUSED_ARG=
+
+LOCAL_C_INCLUDES := frameworks/base/media/libstagefright/include
+
+LOCAL_MODULE := libstagefright_aacdec
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/aacdec/aac_mem_funcs.h b/media/libstagefright/codecs/aacdec/aac_mem_funcs.h
new file mode 100644
index 0000000..ce7cb12
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/aac_mem_funcs.h
@@ -0,0 +1,50 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Filename: aac_mem_funcs.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#include <string.h>
+
+#ifndef AAC_MEM_FUNCS_H
+#define AAC_MEM_FUNCS_H
+
+#define pv_memset(to, c, n)         memset(to, c, n)
+
+
+#define pv_memcpy(to, from, n)      memcpy(to, from, n)
+#define pv_memmove(to, from, n)     memmove(to, from, n)
+#define pv_memcmp(p, q, n)          memcmp(p, q, n)
+
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/analysis_sub_band.cpp b/media/libstagefright/codecs/aacdec/analysis_sub_band.cpp
new file mode 100644
index 0000000..2786dcc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/analysis_sub_band.cpp
@@ -0,0 +1,289 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: analysis_sub_band.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 vec[],            Input vector, 32-bit
+    const Int32 *cosTerms,  Cosine Terms
+    Int   maxbands          number of bands used
+    Int32 *scratch_mem      Scratch memory
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement root squared of a number
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "analysis_sub_band.h"
+#include "dst32.h"
+#include "idct32.h"
+#include "mdst.h"
+
+#include "aac_mem_funcs.h"
+#include "pv_audio_type_defs.h"
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+
+#ifdef HQ_SBR
+
+
+const Int32 exp_1_5_phi[32] =
+{
+
+    0x7FEA04B6,  0x7F380E1C, 0x7DD6176E, 0x7BC6209F,
+    0x790A29A4,  0x75A6326E, 0x719E3AF3, 0x6CF94326,
+    0x67BD4AFB,  0x61F15269, 0x5B9D5964, 0x54CA5FE4,
+    0x4D8165DE,  0x45CD6B4B, 0x3DB87023, 0x354E7460,
+    0x2C9977FB,  0x23A77AEF, 0x1A837D3A, 0x113A7ED6,
+    0x07D97FC2,  0xFE6E7FFE, 0xF5057F87, 0xEBAB7E60,
+    0xE26D7C89,  0xD9587A06, 0xD07976D9, 0xC7DB7308,
+    0xBF8C6E97,  0xB796698C, 0xB00563EF, 0xA8E25DC8,
+
+};
+
+#endif
+
+
+/*----------------------------------------------------------------------------
+; 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 analysis_sub_band_LC(Int32 vec[64],
+                          Int32 cosine_total[],
+                          Int32 maxBand,
+                          Int32 scratch_mem[][64])
+{
+    Int32 i;
+    Int32 *cosine_term = &scratch_mem[0][0];
+    Int32 *sine_term   = &scratch_mem[0][32];
+
+    Int32 *pt_cos_t;
+
+
+    Int32 *pt_vec    =  &vec[0];
+    Int32 *pt_vec_32 =  &vec[32];
+
+    Int32 *pt_cos = cosine_term;
+    Int32 *pt_sin = sine_term;
+
+    for (i = 8; i != 0; i--)
+    {
+        Int32 tmp1 = *(pt_vec_32++);
+        Int32 tmp3 = *(pt_vec_32++);
+        Int32 tmp2 = *(pt_vec++);
+        Int32 tmp4 = *(pt_vec++);
+        *(pt_cos++) = (tmp1 - tmp2) >> 1;
+        *(pt_cos++) = (tmp3 - tmp4) >> 1;
+        *(pt_sin++) = (tmp1 + tmp2);
+        *(pt_sin++) = (tmp3 + tmp4);
+        tmp1 = *(pt_vec_32++);
+        tmp3 = *(pt_vec_32++);
+        tmp2 = *(pt_vec++);
+        tmp4 = *(pt_vec++);
+        *(pt_cos++) = (tmp1 - tmp2) >> 1;
+        *(pt_cos++) = (tmp3 - tmp4) >> 1;
+        *(pt_sin++) = (tmp1 + tmp2);
+        *(pt_sin++) = (tmp3 + tmp4);
+    }
+
+
+    idct_32(cosine_term, scratch_mem[1]);
+
+    dst_32(sine_term, scratch_mem[1]);
+
+    pt_cos  = cosine_term;
+    pt_sin  = sine_term;
+
+    pt_cos_t  = cosine_total;
+
+    for (i = 0; i < maxBand; i += 4)
+    {
+        *(pt_cos_t++) = (*(pt_cos++) + *(pt_sin++));
+        *(pt_cos_t++) = (-*(pt_cos++) + *(pt_sin++));
+        *(pt_cos_t++) = (-*(pt_cos++) - *(pt_sin++));
+        *(pt_cos_t++) = (*(pt_cos++) - *(pt_sin++));
+    }
+
+    pt_cos_t  = &cosine_total[maxBand];
+
+    for (i = (32 - maxBand); i != 0; i--)
+    {
+        *(pt_cos_t++) =   0;
+    }
+}
+
+
+#ifdef HQ_SBR
+
+
+void analysis_sub_band(Int32 vec[64],
+                       Int32 cosine_total[],
+                       Int32 sine_total[],
+                       Int32 maxBand,
+                       Int32 scratch_mem[][64])
+{
+    Int32 i;
+    Int32 *sine_term1   = &scratch_mem[0][0];
+    Int32 *sine_term2   = &scratch_mem[0][32];
+
+    Int32 temp1;
+    Int32 temp2;
+    Int32 temp3;
+    Int32 temp4;
+
+    const Int32 *pt_exp;
+    Int32 exp_1_5;
+
+    Int32 *pt_vec    =  &vec[0];
+    Int32 *pt_vec_32 =  &vec[32];
+
+    Int32 *pt_cos1 = pt_vec;
+    Int32 *pt_sin1 = sine_term1;
+    Int32 *pt_cos2 = pt_vec_32;
+    Int32 *pt_sin2 = sine_term2;
+
+
+    pv_memcpy(sine_term1, vec, 64*sizeof(*vec));
+
+    mdst_32(sine_term1, scratch_mem[1]);
+    mdst_32(sine_term2, scratch_mem[1]);
+
+    mdct_32(&vec[ 0]);
+    mdct_32(&vec[32]);
+
+    pt_cos1 = &vec[ 0];
+    pt_cos2 = &vec[32];
+
+
+    pt_sin1 = sine_term1;
+    pt_sin2 = sine_term2;
+
+    pt_vec     = cosine_total;
+    pt_vec_32  =   sine_total;
+    pt_exp  = exp_1_5_phi;
+
+    temp3 = (*(pt_cos1++) - *(pt_sin2++));
+    temp4 = (*(pt_sin1++) + *(pt_cos2++));
+
+    for (i = 0; i < maxBand; i += 2)
+    {
+
+        exp_1_5 = *(pt_exp++);
+        temp1    =  cmplx_mul32_by_16(temp3,  temp4, exp_1_5);
+        temp2    =  cmplx_mul32_by_16(temp4, -temp3, exp_1_5);
+
+        *(pt_vec++)    =  shft_lft_1(temp1);
+        *(pt_vec_32++) =  shft_lft_1(temp2);
+
+        temp3 = (*(pt_cos1++) + *(pt_sin2++));
+        temp4 = (*(pt_sin1++) - *(pt_cos2++));
+
+        exp_1_5 = *(pt_exp++);
+        temp1    =  cmplx_mul32_by_16(temp3,  temp4, exp_1_5);
+        temp2    =  cmplx_mul32_by_16(temp4, -temp3, exp_1_5);
+
+        *(pt_vec++)    =  shft_lft_1(temp1);
+        *(pt_vec_32++) =  shft_lft_1(temp2);
+
+        temp3 = (*(pt_cos1++) - *(pt_sin2++));
+        temp4 = (*(pt_sin1++) + *(pt_cos2++));
+    }
+
+
+    pt_cos1  = &cosine_total[maxBand];  /* in the chance that maxband is not even */
+    pt_sin1  = &sine_total[maxBand];
+
+    for (i = (32 - maxBand); i != 0; i--)
+    {
+        *(pt_cos1++) =  0;
+        *(pt_sin1++) =  0;
+    }
+
+}
+
+
+#endif
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/analysis_sub_band.h b/media/libstagefright/codecs/aacdec/analysis_sub_band.h
new file mode 100644
index 0000000..815456c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/analysis_sub_band.h
@@ -0,0 +1,82 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/analysis_sub_band.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef ANALYSIS_SUB_BAND_H
+#define ANALYSIS_SUB_BAND_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    void analysis_sub_band_LC(Int32 vec[64],
+    Int32 cosine_total[],
+    Int32 maxBand,
+    Int32 scratch_mem[][64]);
+
+#ifdef HQ_SBR
+
+
+    void analysis_sub_band(Int32 vec[64],
+                           Int32 cosine_total[],
+                           Int32 sine_total[],
+                           Int32 maxBand,
+                           Int32 scratch_mem[][64]);
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* ANALYSIS_SUB_BAND_H */
diff --git a/media/libstagefright/codecs/aacdec/apply_ms_synt.cpp b/media/libstagefright/codecs/aacdec/apply_ms_synt.cpp
new file mode 100644
index 0000000..ab36c6a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/apply_ms_synt.cpp
@@ -0,0 +1,454 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/apply_ms_synt.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated pseudocode to correct capitalized format for the IF
+ FOR and WHILE statements.
+
+ Description: Delete local variable start_indx, since it is never used.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    pFrameInfo = Pointer to structure that holds information about each group.
+                 (long block flag, number of windows, scalefactor bands
+                  per group, etc.)
+                 [const pFrameInfo * const]
+
+    group      = Array that contains indexes of the
+                 first window in the next group.
+                 [const Int *, length 8]
+
+    mask_map   = Array that denotes whether M/S stereo is turned on for
+                 each grouped scalefactor band.
+                 [const Int *, length MAX_SFB]
+
+    codebook_map = Array that denotes which Huffman codebook was used for
+                   the encoding of each grouped scalefactor band.
+                   [const Int *, length MAX_SFB]
+
+    coefLeft = Array containing the fixed-point spectral coefficients
+                       for the left channel.
+                       [Int32 *, length 1024]
+
+    coefRight = Array containing the fixed-point spectral coefficients
+                        for the right channel.
+                        [Int32 *, length 1024]
+
+    q_formatLeft = The Q-format for the left channel's fixed-point spectral
+                   coefficients, on a per-scalefactor band, non-grouped basis.
+                   [Int *, length MAX_SFB]
+
+    q_formatRight = The Q-format for the right channel's fixed-point spectral
+                    coefficients, on a per-scalefactor band, non-grouped basis.
+                    [Int *, length MAX_SFB]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coefLeft  = Contains the new spectral information.
+
+    coefRight = Contains the new spectral information.
+
+    q_formatLeft      = Q-format may be updated with changed to fixed-point
+                        data in coefLeft.
+
+    q_formatRight     = Q-format may be updated with changed to fixed-point
+                        data in coefRight.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function steps through all of the tools that are applied on a
+ scalefactor band basis.
+
+ The use of M/S stereo is checked for.  For M/S decoding to take
+ place, ms_mask_map must be TRUE for that particular SFB, AND the Huffman
+ codebook used must be < NOISE_HCB.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.7.1   M/S stereo
+        Subpart 4.6.2     ScaleFactors
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pCoefRight = coefRight;
+    pCoefLeft = coefLeft;
+
+    window_start = 0;
+    tot_sfb = 0;
+
+    coef_per_win = pFrameInfo->coef_per_win[0];
+
+    sfb_per_win = pFrameInfo->sfb_per_win[0];
+
+    DO
+
+        pBand     = pFrameInfo->win_sfb_top[window_start];
+
+        partition = *(pGroup);
+
+        pGroup = pGroup + 1;
+
+        band_start = 0;
+
+        wins_in_group = (partition - window_start);
+
+        FOR (sfb = sfb_per_win; sfb > 0; sfb--)
+
+            band_stop = *(pBand);
+
+            pBand = pBand + 1;
+
+            codebook = *(pCodebookMap);
+
+            pCodebookMap = pCodebookMap + 1;
+
+            mask_enabled = *(pMaskMap);
+
+            pMaskMap = pMaskMap + 1;
+
+            IF (codebook < NOISE_HCB)
+            THEN
+                IF (mask_enabled != FALSE)
+                THEN
+                    band_length = band_stop - band_start;
+
+                    CALL
+                        ms_synt(
+                            wins_in_group,
+                            coef_per_win,
+                            sfb_per_win,
+                            band_length,
+                           &(pCoefLeft[band_start]),
+                           &(pCoefRight[band_start]),
+                           &(q_formatLeft[tot_sfb]),
+                           &(q_formatRight[tot_sfb]) );
+
+                    MODIFYING
+                        &(pCoefLeft[band_start]),
+                        &(pCoefRight[band_start]),
+                        &(q_formatLeft[tot_sfb]),
+                        &(q_formatRight[tot_sfb])
+
+                    RETURNING
+                        None
+                ENDIF
+            ENDIF
+            band_start = band_stop;
+
+            tot_sfb = tot_sfb + 1;
+
+        ENDFOR
+
+        pCoefRight = pCoefRight + coef_per_win * wins_in_group;
+        pCoefLeft  = pCoefLeft  + coef_per_win * wins_in_group;
+
+        wins_in_group = wins_in_group - 1;
+
+        tot_sfb = tot_sfb + sfb_per_win * wins_in_group;
+
+        window_start = partition;
+
+    WHILE (partition < pFrameInfo->num_win);
+
+    return;
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor 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 "pv_audio_type_defs.h"
+#include "apply_ms_synt.h"
+#include "e_huffmanconst.h"
+#include "ms_synt.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 apply_ms_synt(
+    const FrameInfo * const pFrameInfo,
+    const Int        group[],
+    const Bool       mask_map[],
+    const Int        codebook_map[],
+    Int32      coefLeft[],
+    Int32      coefRight[],
+    Int        q_formatLeft[MAXBANDS],
+    Int        q_formatRight[MAXBANDS])
+
+{
+
+    Int32   *pCoefRight;
+
+    Int32   *pCoefLeft;
+
+    Int     tot_sfb;
+    Int     sfb;
+
+    Int     band_length;
+    Int     band_start;
+    Int     band_stop;
+    Int     coef_per_win;
+
+    Int     codebook;
+    Int     partition;
+    Int     window_start;
+
+    Int     sfb_per_win;
+    Int     wins_in_group;
+
+    const Int16 *pBand;
+    const Int   *pCodebookMap  = codebook_map;
+    const Int   *pGroup        = group;
+    const Bool  *pMaskMap      = mask_map;
+
+    Bool mask_enabled;
+
+    pCoefRight = coefRight;
+    pCoefLeft = coefLeft;
+
+    window_start = 0;
+    tot_sfb = 0;
+
+    /*
+     * Each window in the frame should have the same number of coef's,
+     * so coef_per_win is constant in all the loops
+     */
+    coef_per_win = pFrameInfo->coef_per_win[0];
+
+    /*
+     * Because the number of scalefactor bands per window should be
+     * constant for each frame, sfb_per_win can be determined outside
+     * of the loop.
+     *
+     * For 44.1 kHz sampling rate   sfb_per_win = 14 for short windows
+     *                              sfb_per_win = 49 for long  windows
+     */
+
+    sfb_per_win = pFrameInfo->sfb_per_win[0];
+
+    do
+    {
+        pBand     = pFrameInfo->win_sfb_top[window_start];
+
+        /*
+         * Partition is equal to the first window in the next group
+         *
+         * { Group 0    }{      Group 1      }{    Group 2 }{Group 3}
+         * [win 0][win 1][win 2][win 3][win 4][win 5][win 6][win 7]
+         *
+         * pGroup[0] = 2
+         * pGroup[1] = 5
+         * pGroup[2] = 7
+         * pGroup[3] = 8
+         */
+
+        partition = *(pGroup++);
+
+        band_start = 0;
+
+        wins_in_group = (partition - window_start);
+
+        for (sfb = sfb_per_win; sfb > 0; sfb--)
+        {
+            /* band is offset table, band_stop is last coef in band */
+            band_stop = *(pBand++);
+
+            codebook = *(pCodebookMap++);
+
+            mask_enabled = *(pMaskMap++);
+
+            /*
+             * When a codebook < NOISE_HCB is found, apply M/S to that
+             * scalefactorband.
+             *
+             * Example...  sfb[3] == NOISE_HCB
+             *
+             * [ Group 1                                      ]
+             * [win 0                 ][win 1                 ]
+             * [0][1][2][X][4][5][6][7][0][1][2][X][4][5][6][7]
+             *
+             * The for(sfb) steps through the sfb's 0-7 in win 0.
+             *
+             * Finding sfb[3]'s codebook == NOISE_HCB, the code
+             * steps through all the windows in the group (they share
+             * the same scalefactors) and replaces that sfb with noise.
+             */
+
+            if (codebook < NOISE_HCB)
+            {
+                if (mask_enabled != FALSE)
+                {
+                    band_length = band_stop - band_start;
+
+                    ms_synt(
+                        wins_in_group,
+                        coef_per_win,
+                        sfb_per_win,
+                        band_length,
+                        &(pCoefLeft[band_start]),
+                        &(pCoefRight[band_start]),
+                        &(q_formatLeft[tot_sfb]),
+                        &(q_formatRight[tot_sfb]));
+                }
+            }
+            band_start = band_stop;
+
+            tot_sfb++;
+
+        } /* for (sfb) */
+
+        /*
+         * Increment pCoefRight and pCoefLeft by
+         * coef_per_win * the number of windows
+         */
+
+        pCoefRight += coef_per_win * wins_in_group;
+        pCoefLeft  += coef_per_win * wins_in_group--;
+
+        /*
+         * Increase tot_sfb by sfb_per_win times the number of windows minus 1.
+         * The minus 1 comes from the fact that tot_sfb is already pointing
+         * to the first sfb in the 2nd window of the group.
+         */
+        tot_sfb += sfb_per_win * wins_in_group;
+
+        window_start = partition;
+
+    }
+    while (partition < pFrameInfo->num_win);
+
+    /* pFrameInfo->num_win = 1 for long windows, 8 for short_windows */
+
+    return;
+
+} /* apply_ms_synt() */
+
+
diff --git a/media/libstagefright/codecs/aacdec/apply_ms_synt.h b/media/libstagefright/codecs/aacdec/apply_ms_synt.h
new file mode 100644
index 0000000..ed7fb7a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/apply_ms_synt.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/apply_ms_synt.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes the function declaration for apply_ms_synt().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef APPLY_MS_SYNT_H
+#define APPLY_MS_SYNT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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 apply_ms_synt(
+    const FrameInfo * const pFrameInfo,
+    const Int        group[],
+    const Bool       mask_map[],
+    const Int        codebook_map[],
+    Int32      coefLeft[],
+    Int32      coefRight[],
+    Int        q_formatLeft[MAXBANDS],
+    Int        q_formatRight[MAXBANDS]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/apply_tns.cpp b/media/libstagefright/codecs/aacdec/apply_tns.cpp
new file mode 100644
index 0000000..96ecd27
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/apply_tns.cpp
@@ -0,0 +1,424 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: apply_tns.c
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    coef =       Array of input coefficients.
+                 [Int32 *, length 1024]
+
+    q_format   = Array of q-formats, one per scalefactor band, for the
+                 entire frame.  In the case of tns_inv_filter, only the
+                 first element is used, since the input to tns_inv_filter
+                 is all of the same q-format.
+                 [Int * const, length MAX_SFB]
+
+    pFrameInfo = Pointer to structure that holds information about each group.
+                 (long block flag, number of windows, scalefactor bands
+                  per group, etc.)
+                 [const FrameInfo * const]
+
+    pTNS_frame_info = pointer to structure containing the details on each
+                      TNS filter (order, filter coefficients,
+                      coefficient res., etc.)
+                      [TNS_frame_info * const]
+
+    inverse_flag   = TRUE  if inverse filter is to be applied.
+                     FALSE if forward filter is to be applied.
+                     [Bool]
+
+    scratch_Int_buffer = Pointer to scratch memory to store the
+                           filter's state memory.  Used by both
+                           tns_inv_filter.
+                           [Int *, length TNS_MAX_ORDER]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coef[]   = TNS altered data.
+    q_format = q-formats in TNS scalefactor bands may be modified.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    This function applies either the TNS forward or TNS inverse filter, based
+    on inverse_flag being FALSE or TRUE, respectively.
+
+    For the TNS forward filter, the data fed into tns_ar_filter is normalized
+    all to the same q-format.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    The input, coef, should use all 32-bits, else the scaling by tns_ar_filter
+    may eliminate the data.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.8 (Temporal Noise Shaping)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    NO PSEUDO-CODE
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor
+     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 "pv_audio_type_defs.h"
+#include "s_tns_frame_info.h"
+#include "s_tnsfilt.h"
+#include "s_frameinfo.h"
+#include "tns_inv_filter.h"
+#include "tns_ar_filter.h"
+#include "apply_tns.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 apply_tns(
+    Int32                  coef[],
+    Int                    q_format[],
+    const FrameInfo      * const pFrameInfo,
+    TNS_frame_info * const pTNS_frame_info,
+    const Bool                   inverse_flag,
+    Int32                  scratch_Int_buffer[])
+{
+    Int num_tns_bands;
+    Int num_TNS_coef;
+
+    Int f;
+
+    Int tempInt;
+    Int tempInt2;
+
+    Int sfb_per_win;
+    Int sfbWidth;
+
+    Int coef_per_win;
+    Int min_q;
+    Int win;
+
+    Int32 *pCoef = coef;
+    Int32 *pTempCoef;
+
+    Int   *pStartQformat = q_format;
+
+    Int   *pQformat;
+    Int32 *pLpcCoef;
+
+    Int sfb_offset;
+
+    const Int16 *pWinSfbTop;
+
+    TNSfilt *pFilt;
+
+    coef_per_win = pFrameInfo->coef_per_win[0];
+    sfb_per_win  = pFrameInfo->sfb_per_win[0];
+
+    win = 0;
+
+    pLpcCoef = pTNS_frame_info->lpc_coef;
+
+    pFilt = pTNS_frame_info->filt;
+
+    do
+    {
+        for (f = pTNS_frame_info->n_filt[win]; f > 0; f--)
+        {
+            /* Skip to the next filter if the order is 0 */
+            tempInt = pFilt->order;
+
+            if (tempInt > 0)
+            {
+                /*
+                 * Do not call tns_ar_filter or tns_inv_filter
+                 * if the difference
+                 * between start_coef and stop_stop is <= 0.
+                 *
+                 */
+                num_TNS_coef = (pFilt->stop_coef - pFilt->start_coef);
+
+                if (num_TNS_coef > 0)
+                {
+                    if (inverse_flag != FALSE)
+                    {
+                        tns_inv_filter(
+                            &(pCoef[pFilt->start_coef]),
+                            num_TNS_coef,
+                            pFilt->direction,
+                            pLpcCoef,
+                            pFilt->q_lpc,
+                            pFilt->order,
+                            scratch_Int_buffer);
+                    }
+                    else
+                    {
+                        num_tns_bands = (pFilt->stop_band - pFilt->start_band);
+
+                        /*
+                         * pQformat is initialized only once.
+                         *
+                         * Here is how TNS is applied on scalefactor bands
+                         *
+                         * [0][1][2][3][4][5][6][7][8]
+                         *  |                        \
+                         * start_band               stop_band
+                         *
+                         * In this example, TNS would be applied to 8
+                         * scalefactor bands, 0-7.
+                         *
+                         * pQformat is initially set to &(pStartQformat[8])
+                         *
+                         * 1st LOOP
+                         *      Entry: pQformat = &(pStartQformat[8])
+                         *
+                         *      pQformat is pre-decremented 8 times in the
+                         *      search for min_q
+                         *
+                         *      Exit:  pQformat = &(pStartQformat[0])
+                         *
+                         * 2nd LOOP
+                         *      Entry: pQformat = &(pStartQformat[0])
+                         *
+                         *      pQformat is post-incremented 8 times in the
+                         *      normalization of the data loop.
+                         *
+                         *      Exit:  pQformat = &(pStartQformat[8]
+                         *
+                         *
+                         * shift_amt = tns_ar_filter(...)
+                         *
+                         * 3rd LOOP
+                         *      Entry: pQformat = &(pStartQformat[8])
+                         *
+                         *      pQformat is pre-decremented 8 times in the
+                         *      adjustment of the q-format to min_q - shift_amt
+                         *
+                         *      Exit:  pQformat = &(pStartQformat[0])
+                         *
+                         */
+
+                        pQformat =
+                            &(pStartQformat[pFilt->stop_band]);
+
+                        /*
+                         * Scan the array of q-formats and find the minimum over
+                         * the range where the filter is to be applied.
+                         *
+                         * At the end of this scan,
+                         * pQformat = &(q-format[pFilt->start_band]);
+                         *
+                         */
+
+                        min_q = INT16_MAX;
+
+                        for (tempInt = num_tns_bands; tempInt > 0; tempInt--)
+                        {
+                            tempInt2 = *(--pQformat);
+
+                            if (tempInt2 < min_q)
+                            {
+                                min_q = tempInt2;
+                            }
+                        } /* for(tempInt = num_bands; tempInt > 0; tempInt--)*/
+
+                        /*
+                         * Set up the pointers so we can index into coef[]
+                         * on a scalefactor band basis.
+                         */
+                        tempInt = pFilt->start_band;
+
+                        tempInt--;
+
+                        /* Initialize sfb_offset and pWinSfbTop */
+                        if (tempInt >= 0)
+                        {
+                            pWinSfbTop =
+                                &(pFrameInfo->win_sfb_top[win][tempInt]);
+
+                            sfb_offset = *(pWinSfbTop++);
+                        }
+                        else
+                        {
+                            pWinSfbTop = pFrameInfo->win_sfb_top[win];
+                            sfb_offset = 0;
+                        }
+
+                        pTempCoef = pCoef + pFilt->start_coef;
+
+                        /* Scale the data in the TNS bands to min_q q-format */
+                        for (tempInt = num_tns_bands; tempInt > 0; tempInt--)
+                        {
+                            sfbWidth  = *(pWinSfbTop++) - sfb_offset;
+
+                            sfb_offset += sfbWidth;
+
+                            tempInt2 = *(pQformat++) - min_q;
+
+                            /*
+                             * This should zero out the data in one scalefactor
+                             * band if it is so much less than the neighboring
+                             * scalefactor bands.
+                             *
+                             * The only way this "should" happen is if one
+                             * scalefactor band contains zero data.
+                             *
+                             * Zero data can be of any q-format, but we always
+                             * set it very high to avoid the zero-data band being
+                             * picked as the one to normalize to in the scan for
+                             * min_q.
+                             *
+                             */
+                            if (tempInt2 > 31)
+                            {
+                                tempInt2 = 31;
+                            }
+
+                            for (sfbWidth >>= 2; sfbWidth > 0; sfbWidth--)
+                            {
+                                *(pTempCoef++) >>= tempInt2;
+                                *(pTempCoef++) >>= tempInt2;
+                                *(pTempCoef++) >>= tempInt2;
+                                *(pTempCoef++) >>= tempInt2;
+                            }
+
+                        } /* for(tempInt = num_bands; tempInt > 0; tempInt--)*/
+
+                        tempInt2 =
+                            tns_ar_filter(
+                                &(pCoef[pFilt->start_coef]),
+                                num_TNS_coef,
+                                pFilt->direction,
+                                pLpcCoef,
+                                pFilt->q_lpc,
+                                pFilt->order);
+
+                        /*
+                         * Update the q-format for all the scalefactor bands
+                         * taking into account the adjustment caused by
+                         * tns_ar_filter
+                         */
+
+                        min_q -= tempInt2;
+
+                        for (tempInt = num_tns_bands; tempInt > 0; tempInt--)
+                        {
+                            *(--pQformat) = min_q;
+                        }
+
+                    } /* if (inverse_flag != FALSE) */
+
+                } /* if (num_TNS_coef > 0) */
+
+                pLpcCoef += pFilt->order;
+
+            } /* if (tempInt > 0) */
+
+            pFilt++;
+
+        } /* for (f = pTNSinfo->n_filt; f > 0; f--) */
+
+        pCoef += coef_per_win;
+        pStartQformat += sfb_per_win;
+
+        win++;
+
+    }
+    while (win < pFrameInfo->num_win);
+
+    return;
+
+} /* apply_tns() */
diff --git a/media/libstagefright/codecs/aacdec/apply_tns.h b/media/libstagefright/codecs/aacdec/apply_tns.h
new file mode 100644
index 0000000..85fb851
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/apply_tns.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/apply_tns.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated per review comments.
+
+ Description: Changed function prototype to mirror changes made in apply_tns.c
+
+ Description: The scratch memory was mistakenly declared here as type "Int32"
+ It should have been "Int"
+
+ Who:                       Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the function declaration for
+ apply_tns.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef APPLY_TNS_H
+#define APPLY_TNS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_tns_frame_info.h"
+#include "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void apply_tns(
+        Int32                  coef[],
+        Int                    q_format[],
+        const FrameInfo      * const pFrameInfo,
+        TNS_frame_info * const pTNS_frame_info,
+        const Bool                   inverse_flag,
+        Int32                  scratch_Int_buffer[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/bit_reversal_swap.h b/media/libstagefright/codecs/aacdec/bit_reversal_swap.h
new file mode 100644
index 0000000..2669f87
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/bit_reversal_swap.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Pathname: ./include/bit_reversal_swap.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Changed definitions from Int to Int32 for Data[]
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function bit_reversal_swap()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BIT_REVERSAL_SWAP_H
+#define BIT_REVERSAL_SWAP_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 Int Index_64_a[];
+extern const Int Index_64_b[];
+
+extern const Int Index_512_a[];
+extern const Int Index_512_b[];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+void bit_reversal_swap(
+    Int32        Data[],
+    const Int *pIndex_a,
+    const Int *pIndex_b);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* BIT_REVERSAL_SWAP_H */
diff --git a/media/libstagefright/codecs/aacdec/buf_getbits.cpp b/media/libstagefright/codecs/aacdec/buf_getbits.cpp
new file mode 100644
index 0000000..34f4f60
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/buf_getbits.cpp
@@ -0,0 +1,167 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: buf_getbits.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:   hBitBuf Handle to Bitbuffer
+              n       Number of bits to read
+
+ Return:      bits
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+            Reads n bits from Bitbuffer
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include    "buf_getbits.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
+----------------------------------------------------------------------------*/
+
+UInt32 buf_getbits(BIT_BUFFER * hBitBuf, Int32 n)
+{
+
+    /* read bits from MSB side */
+    if (hBitBuf->buffered_bits <= 16)
+    {
+        hBitBuf->buffer_word    = (hBitBuf->buffer_word << 16) | (*(hBitBuf->char_ptr++) << 8);
+        hBitBuf->buffer_word   |= *(hBitBuf->char_ptr++);
+        hBitBuf->buffered_bits += 16;
+    }
+
+    hBitBuf->buffered_bits -= n;
+    hBitBuf->nrBitsRead    += n;
+
+    return ((hBitBuf->buffer_word >> hBitBuf->buffered_bits) & ((1 << n) - 1));
+
+}
+
+
+UInt32 buf_get_1bit(BIT_BUFFER * hBitBuf)
+{
+
+    /* read bits from MSB side */
+    if (hBitBuf->buffered_bits <= 16)
+    {
+        hBitBuf->buffer_word    = (hBitBuf->buffer_word << 16) | (*(hBitBuf->char_ptr++) << 8);
+        hBitBuf->buffer_word   |= *(hBitBuf->char_ptr++);
+        hBitBuf->buffered_bits += 16;
+    }
+
+    hBitBuf->buffered_bits--;
+    hBitBuf->nrBitsRead++;
+
+    return ((hBitBuf->buffer_word >> hBitBuf->buffered_bits) & 1);
+
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/buf_getbits.h b/media/libstagefright/codecs/aacdec/buf_getbits.h
new file mode 100644
index 0000000..1b5d252
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/buf_getbits.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Filename: buf_getbits.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BUF_GETBITS_H
+#define BUF_GETBITS_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_bit_buffer.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+    UInt32 buf_getbits(BIT_BUFFER * hBitBuf, Int32 n);
+
+    UInt32 buf_get_1bit(BIT_BUFFER * hBitBuf);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/buffer_normalization.h b/media/libstagefright/codecs/aacdec/buffer_normalization.h
new file mode 100644
index 0000000..031216a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/buffer_normalization.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/buffer_normalization.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Changed definitions from Int to Int32 for IO_buffer[]
+
+ Description:  Added copyrigth notice, added 'const' definitions to function
+
+ Who:                          Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function buffer_normalization()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BUFFER_NORMALIZATION_H
+#define BUFFER_NORMALIZATION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define     ALL_ZEROS_BUFFER     -100
+
+/*----------------------------------------------------------------------------
+; 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 buffer_normalization(
+    Int     q_format,
+    Int32   IO_buffer[],
+    const Int     buffer_size,
+    Int   * const pExp);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* BUFFER_NORMALIZATION_H */
diff --git a/media/libstagefright/codecs/aacdec/byte_align.cpp b/media/libstagefright/codecs/aacdec/byte_align.cpp
new file mode 100644
index 0000000..e75c79e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/byte_align.cpp
@@ -0,0 +1,179 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pInputStream = pointer to a BITS structure that holds information
+                   regarding the input stream.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pInputStream->usedBits is rounded up to a number that represents the next
+    byte boundary.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Makes the input stream structure pointed to align to the next byte boundary.
+ If it is already at a byte boundary it is left alone.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+  This function shall not use global or static variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void byte_align(
+    BITS  *pInputStream)
+
+    MODIFYING(pInputStream->usedBits = pInputStream->usedBits +
+                (pInputStream->usedBits + 7) % 8)
+
+    RETURN(nothing)
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+
+ STACK USAGE:
+
+     where:
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+
+#include "pv_audio_type_defs.h"
+#include "s_bits.h"
+#include "ibstream.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*
+ * A negative number was used for this mask so that it works on both
+ * 16-bit or 32-bit machines. The mask must be cast to unsigned int to
+ * work with TI compiler, ver 1.80.
+ */
+#define BYTE_ALIGN_MASK    ((UInt)(-8))
+
+#define BYTE_ALIGN_ROUNDUP  7
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void byte_align(
+    BITS  *pInputStream)
+{
+    /*
+     * Round up to the next byte by adding 7 and masking off with
+     * FFF8 or FFFFFFF8. The masking operation is a faster way to
+     * perform modulo arithmetic if the number is a power of 2.
+     *
+     * This code is the same as
+     * pInputStream->usedBits += (pInputStream->usedBits + 7) % 8
+     */
+    pInputStream->usedBits += BYTE_ALIGN_ROUNDUP;
+    pInputStream->usedBits &= BYTE_ALIGN_MASK;
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/aacdec/calc_auto_corr.cpp b/media/libstagefright/codecs/aacdec/calc_auto_corr.cpp
new file mode 100644
index 0000000..ee32398
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_auto_corr.cpp
@@ -0,0 +1,416 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: calc_auto_corr.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+
+#include    "calc_auto_corr.h"
+#include    "aac_mem_funcs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#include    "fxp_mul32.h"
+#include    "pv_normalize.h"
+
+#define N   2
+
+/*----------------------------------------------------------------------------
+; 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 calc_auto_corr_LC(struct ACORR_COEFS *ac,
+                       Int32  realBuf[][32],
+                       Int32  bd,
+                       Int32  len)
+{
+    Int32 j;
+    Int32 temp1;
+    Int32 temp3;
+    Int32 temp5;
+
+    int64_t temp_r01r;
+    int64_t temp_r02r;
+    int64_t temp_r11r;
+    int64_t temp_r12r;
+    int64_t temp_r22r;
+    int64_t max = 0;
+
+
+    temp1 = (realBuf[ 0][bd]) >> N;
+    temp3 = (realBuf[-1][bd]) >> N;
+    temp5 = (realBuf[-2][bd]) >> N;
+
+
+    temp_r11r = fxp_mac64_Q31(0, temp3, temp3);   /* [j-1]*[j-1]  */
+    temp_r12r = fxp_mac64_Q31(0, temp3, temp5);   /* [j-1]*[j-2]  */
+    temp_r22r = fxp_mac64_Q31(0, temp5, temp5);   /* [j-2]*[j-2]  */
+
+    temp_r01r = 0;
+    temp_r02r = 0;
+
+    for (j = 1; j < len; j++)
+    {
+        temp_r01r = fxp_mac64_Q31(temp_r01r, temp1, temp3);    /* [j  ]*[j-1]  */
+        temp_r02r = fxp_mac64_Q31(temp_r02r, temp1, temp5);    /* [j  ]*[j-2]  */
+        temp_r11r = fxp_mac64_Q31(temp_r11r, temp1, temp1);    /* [j-1]*[j-1]  */
+
+        temp5 = temp3;
+        temp3 = temp1;
+        temp1 = (realBuf[j][bd]) >> N;
+    }
+
+
+    temp_r22r += temp_r11r;
+    temp_r12r += temp_r01r;          /* [j-1]*[j-2]  */
+
+    temp_r22r  = fxp_mac64_Q31(temp_r22r, -temp3, temp3);
+
+    temp_r01r = fxp_mac64_Q31(temp_r01r, temp1, temp3);
+    temp_r02r = fxp_mac64_Q31(temp_r02r, temp1, temp5);
+
+    max  |= temp_r01r ^(temp_r01r >> 63);
+    max  |= temp_r02r ^(temp_r02r >> 63);
+    max  |= temp_r11r;
+    max  |= temp_r12r ^(temp_r12r >> 63);
+    max  |= temp_r22r;
+
+    if (max)
+    {
+        temp1 = (UInt32)(max >> 32);
+        if (temp1)
+        {
+            temp3 = 33 - pv_normalize(temp1);
+            ac->r01r = (Int32)(temp_r01r >> temp3);
+            ac->r02r = (Int32)(temp_r02r >> temp3);
+            ac->r11r = (Int32)(temp_r11r >> temp3);
+            ac->r12r = (Int32)(temp_r12r >> temp3);
+            ac->r22r = (Int32)(temp_r22r >> temp3);
+
+        }
+        else
+        {
+            temp3 = pv_normalize(((UInt32)max) >> 1) - 2;
+
+            if (temp3 > 0)
+            {
+                ac->r01r = (Int32)(temp_r01r << temp3);
+                ac->r02r = (Int32)(temp_r02r << temp3);
+                ac->r11r = (Int32)(temp_r11r << temp3);
+                ac->r12r = (Int32)(temp_r12r << temp3);
+                ac->r22r = (Int32)(temp_r22r << temp3);
+            }
+            else
+            {
+                temp3 = -temp3;
+                ac->r01r = (Int32)(temp_r01r >> temp3);
+                ac->r02r = (Int32)(temp_r02r >> temp3);
+                ac->r11r = (Int32)(temp_r11r >> temp3);
+                ac->r12r = (Int32)(temp_r12r >> temp3);
+                ac->r22r = (Int32)(temp_r22r >> temp3);
+            }
+
+        }
+
+        /*
+         *  ac->det = ac->r11r*ac->r22r - rel*(ac->r12r*ac->r12r);
+         */
+        /* 1/(1 + 1e-6) == 1 - 1e-6 */
+        /* 2^-20 == 1e-6 */
+        ac->det  = fxp_mul32_Q30(ac->r12r, ac->r12r);
+
+        ac->det -= ac->det >> 20;
+
+        ac->det  = fxp_mul32_Q30(ac->r11r, ac->r22r) - ac->det;
+    }
+    else
+    {
+        pv_memset((void *)ac, 0, sizeof(struct ACORR_COEFS));
+    }
+
+
+}
+
+
+#ifdef HQ_SBR
+
+
+void calc_auto_corr(struct ACORR_COEFS *ac,
+                    Int32  realBuf[][32],
+                    Int32  imagBuf[][32],
+                    Int32  bd,
+                    Int32  len)
+{
+
+
+    Int32 j;
+    Int32 temp1;
+    Int32 temp2;
+    Int32 temp3;
+    Int32 temp4;
+    Int32 temp5;
+    Int32 temp6;
+
+    int64_t accu1 = 0;
+    int64_t accu2 = 0;
+    int64_t accu3 = 0;
+    int64_t accu4 = 0;
+    int64_t accu5 = 0;
+
+
+    int64_t temp_r12r;
+    int64_t temp_r12i;
+    int64_t temp_r22r;
+    int64_t max = 0;
+
+
+    temp1 = realBuf[0  ][bd] >> N;
+    temp2 = imagBuf[0  ][bd] >> N;
+    temp3 = realBuf[0-1][bd] >> N;
+    temp4 = imagBuf[0-1][bd] >> N;
+    temp5 = realBuf[0-2][bd] >> N;
+    temp6 = imagBuf[0-2][bd] >> N;
+
+    temp_r22r =  fxp_mac64_Q31(0, temp5, temp5);
+    temp_r22r =  fxp_mac64_Q31(temp_r22r, temp6, temp6);
+    temp_r12r =  fxp_mac64_Q31(0, temp3, temp5);
+    temp_r12r =  fxp_mac64_Q31(temp_r12r, temp4, temp6);
+    temp_r12i = -fxp_mac64_Q31(0, temp3, temp6);
+    temp_r12i =  fxp_mac64_Q31(temp_r12i, temp4, temp5);
+
+    for (j = 1; j < len; j++)
+    {
+        accu1  = fxp_mac64_Q31(accu1, temp3, temp3);
+        accu1  = fxp_mac64_Q31(accu1, temp4, temp4);
+        accu2  = fxp_mac64_Q31(accu2, temp1, temp3);
+        accu2  = fxp_mac64_Q31(accu2, temp2, temp4);
+        accu3  = fxp_mac64_Q31(accu3, temp2, temp3);
+        accu3  = fxp_mac64_Q31(accu3, -temp1, temp4);
+        accu4  = fxp_mac64_Q31(accu4, temp1, temp5);
+        accu4  = fxp_mac64_Q31(accu4, temp2, temp6);
+        accu5  = fxp_mac64_Q31(accu5, temp2, temp5);
+        accu5  = fxp_mac64_Q31(accu5, -temp1, temp6);
+
+        temp5 = temp3;
+        temp6 = temp4;
+        temp3 = temp1;
+        temp4 = temp2;
+        temp1 = realBuf[j][bd] >> N;
+        temp2 = imagBuf[j][bd] >> N;
+    }
+
+
+    temp_r22r += accu1;
+    temp_r12r += accu2;
+    temp_r12i += accu3;
+
+
+    accu1  = fxp_mac64_Q31(accu1, temp3, temp3);
+    accu1  = fxp_mac64_Q31(accu1, temp4, temp4);
+    accu2  = fxp_mac64_Q31(accu2, temp1, temp3);
+    accu2  = fxp_mac64_Q31(accu2, temp2, temp4);
+    accu3  = fxp_mac64_Q31(accu3, temp2, temp3);
+    accu3  = fxp_mac64_Q31(accu3, -temp1, temp4);
+    accu4  = fxp_mac64_Q31(accu4, temp1, temp5);
+    accu4  = fxp_mac64_Q31(accu4, temp2, temp6);
+    accu5  = fxp_mac64_Q31(accu5, temp2, temp5);
+    accu5  = fxp_mac64_Q31(accu5, -temp1, temp6);
+
+
+    max  |= accu5 ^(accu5 >> 63);
+    max  |= accu4 ^(accu4 >> 63);
+    max  |= accu3 ^(accu3 >> 63);
+    max  |= accu2 ^(accu2 >> 63);
+    max  |= accu1;
+    max  |= temp_r12r ^(temp_r12r >> 63);
+    max  |= temp_r12i ^(temp_r12i >> 63);
+    max  |= temp_r22r;
+
+    if (max)
+    {
+
+        temp1 = (UInt32)(max >> 32);
+        if (temp1)
+        {
+            temp1 = 34 - pv_normalize(temp1);
+            ac->r11r = (Int32)(accu1 >> temp1);
+            ac->r01r = (Int32)(accu2 >> temp1);
+            ac->r01i = (Int32)(accu3 >> temp1);
+            ac->r02r = (Int32)(accu4 >> temp1);
+            ac->r02i = (Int32)(accu5 >> temp1);
+            ac->r12r = (Int32)(temp_r12r >> temp1);
+            ac->r12i = (Int32)(temp_r12i >> temp1);
+            ac->r22r = (Int32)(temp_r22r >> temp1);
+        }
+        else
+        {
+            temp1 = pv_normalize(((UInt32)max) >> 1) - 3;
+
+            if (temp1 > 0)
+            {
+                ac->r11r = (Int32)(accu1 << temp1);
+                ac->r01r = (Int32)(accu2 << temp1);
+                ac->r01i = (Int32)(accu3 << temp1);
+                ac->r02r = (Int32)(accu4 << temp1);
+                ac->r02i = (Int32)(accu5 << temp1);
+                ac->r12r = (Int32)(temp_r12r << temp1);
+                ac->r12i = (Int32)(temp_r12i << temp1);
+                ac->r22r = (Int32)(temp_r22r << temp1);
+            }
+            else
+            {
+                temp1 = -temp1;
+                ac->r11r = (Int32)(accu1 >> temp1);
+                ac->r01r = (Int32)(accu2 >> temp1);
+                ac->r01i = (Int32)(accu3 >> temp1);
+                ac->r02r = (Int32)(accu4 >> temp1);
+                ac->r02i = (Int32)(accu5 >> temp1);
+                ac->r12r = (Int32)(temp_r12r >> temp1);
+                ac->r12i = (Int32)(temp_r12i >> temp1);
+                ac->r22r = (Int32)(temp_r22r >> temp1);
+            }
+
+        }
+
+        /*
+         *  ac->det = ac->r11r*ac->r22r - rel*(ac->r12r*ac->r12r);
+         */
+        /* 1/(1 + 1e-6) == 1 - 1e-6 */
+        /* 2^-20 == 1e-6 */
+
+        ac->det =   fxp_mul32_Q29(ac->r12i, ac->r12i);
+        ac->det =   fxp_mac32_Q29(ac->r12r, ac->r12r, ac->det);
+
+        ac->det -= ac->det >> 20;
+
+        ac->det =  -fxp_msu32_Q29(ac->r11r, ac->r22r, ac->det);
+
+    }
+    else
+    {
+        pv_memset((void *)ac, 0, sizeof(struct ACORR_COEFS));
+    }
+
+}
+
+#endif
+
+
+
+
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/calc_auto_corr.h b/media/libstagefright/codecs/aacdec/calc_auto_corr.h
new file mode 100644
index 0000000..0f0dae2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_auto_corr.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: calc_auto_corr.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CALC_AUTO_CORR_H
+#define CALC_AUTO_CORR_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+struct ACORR_COEFS
+{
+    Int32  r11r;
+    Int32  r01r;
+    Int32  r02r;
+    Int32  r12r;
+    Int32  r22r;
+#ifdef HQ_SBR
+    Int32  r01i;
+    Int32  r02i;
+    Int32  r12i;
+#endif
+    Int32  det;
+};
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void calc_auto_corr_LC(struct ACORR_COEFS *ac,
+    Int32  realBuf[][32],
+    Int32  bd,
+    Int32  len);
+
+
+#ifdef HQ_SBR
+
+    void calc_auto_corr(struct ACORR_COEFS *ac,
+                        Int32  realBuf[][32],
+                        Int32  imagBuf[][32],
+                        Int32  bd,
+                        Int32  len);
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/calc_gsfb_table.cpp b/media/libstagefright/codecs/aacdec/calc_gsfb_table.cpp
new file mode 100644
index 0000000..4047502
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_gsfb_table.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/calc_gsfb_table.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description: (1) Modified to bring in-line with PV standards
+              (2) Removed if(pFrameInfo->islong), only short windows will
+                  call this routine from getics.c
+
+ Description: Modified per review comments
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pFrameInfo  = pointer to structure that holds information for current
+                  frame. Data type FrameInfo
+
+    group[]     = array that contains the grouping information of short
+                  windows (stop index of windows in each group).
+                  Data type Int
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pFrameInfo -> frame_sfb_top   contains the cumulative bandwidth of
+                                    scalefactor bands in each group
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is only invoked when short windows are present. It calculates
+ the number of groups in one frame, and the scalefactor bandwidth of each
+ scalefactor band in each group.
+ All windows within one group share the same scalefactors and are interleaved
+ on a scalefactor band basis. Within each group, the actual length of one
+ scalefactor band equals to the number of windows times the number of
+ coefficients in a regular scalefactor band.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall replace the contents of pFrameInfo->frame_sfb_top
+ with the cumulative bandwidth of each scalefactor band in each group
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4       p54.    4.5.2.3.2   decoding process
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    offset      = 0;
+    group_idx   = 0;
+
+    DO
+        pFrameInfo->group_len[group_idx] = group[group_idx] - offset;
+        offset = group[group_idx];
+        group_idx++;
+
+    WHILE (offset < NUM_SHORT_WINDOWS);
+
+
+    pFrameInfo->num_groups = group_idx;
+
+    pFrameSfbTop = pFrameInfo->frame_sfb_top;
+    offset = 0;
+
+    FOR (group_idx = 0; group_idx < pFrameInfo->num_groups; group_idx++)
+
+        len = pFrameInfo->group_len[group_idx];
+
+        FOR (sfb = 0; sfb < pFrameInfo->sfb_per_win[group_idx]; sfb++)
+
+            offset += pFrameInfo->sfb_width_128[sfb] * len;
+            *pFrameSfbTop++ = offset;
+
+        ENDFOR
+
+    ENDFOR
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "huffman.h"
+#include    "aac_mem_funcs.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  calc_gsfb_table(
+    FrameInfo   *pFrameInfo,
+    Int         group[])
+{
+
+    Int      group_idx;
+    Int      offset;
+    Int     *pFrameSfbTop;
+    Int     *pSfbWidth128;
+    Int      sfb;
+    Int      nsfb;
+    Int      len;
+    Int      ngroups;
+
+    /* clear out the default values set by infoinit */
+    /* */
+    pv_memset(pFrameInfo->frame_sfb_top,
+              0,
+              MAXBANDS*sizeof(pFrameInfo->frame_sfb_top[0]));
+    /* */
+    /* first calculate the group length*/
+    offset      = 0;
+    ngroups     = 0;
+    do
+    {
+        pFrameInfo->group_len[ngroups] = group[ngroups] - offset;
+        offset = group[ngroups];
+        ngroups++;
+
+    }
+    while (offset < NUM_SHORT_WINDOWS);
+
+
+    /* calculate the cumulative scalefactor bandwidth for one frame */
+    pFrameInfo->num_groups = ngroups;
+
+    pFrameSfbTop = pFrameInfo->frame_sfb_top;
+    offset = 0;
+
+
+    for (group_idx = 0; group_idx < ngroups; group_idx++)
+    {
+        len  = pFrameInfo->group_len[  group_idx];
+        nsfb = pFrameInfo->sfb_per_win[group_idx];
+
+        pSfbWidth128 = pFrameInfo->sfb_width_128;
+
+        for (sfb = nsfb; sfb > 0; sfb--)
+        {
+            offset += *pSfbWidth128++ * len;
+            *pFrameSfbTop++ = offset;
+        }
+    }
+
+
+} /* calc_gsfb_table */
+
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.cpp b/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.cpp
new file mode 100644
index 0000000..5ec3f69
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.cpp
@@ -0,0 +1,360 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: calc_sbr_anafilterbank.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "calc_sbr_anafilterbank.h"
+#include    "qmf_filterbank_coeff.h"
+#include    "analysis_sub_band.h"
+
+#include    "aac_mem_funcs.h"
+#include    "fxp_mul32.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 calc_sbr_anafilterbank_LC(Int32 * Sr,
+                               Int16 * X,
+                               Int32 scratch_mem[][64],
+                               Int32 maxBand)
+{
+
+    Int i;
+    Int32   *p_Y_1;
+    Int32   *p_Y_2;
+
+    Int16 * pt_X_1;
+    Int16 * pt_X_2;
+    Int32 realAccu1;
+    Int32 realAccu2;
+
+    Int32 tmp1;
+    Int32 tmp2;
+
+
+    const Int32 * pt_C;
+
+    p_Y_1 = scratch_mem[0];
+
+
+    p_Y_2 = p_Y_1 + 63;
+    pt_C   = &sbrDecoderFilterbankCoefficients_an_filt_LC[0];
+
+    pt_X_1 = X;
+
+
+    realAccu1  =  fxp_mul32_by_16(Qfmt27(-0.51075594183097F),   pt_X_1[-192]);
+
+    realAccu1  =  fxp_mac32_by_16(Qfmt27(-0.51075594183097F), -pt_X_1[-128], realAccu1);
+    realAccu1  =  fxp_mac32_by_16(Qfmt27(-0.01876919066980F),  pt_X_1[-256], realAccu1);
+    *(p_Y_1++) =  fxp_mac32_by_16(Qfmt27(-0.01876919066980F), -pt_X_1[ -64], realAccu1);
+
+
+    /* create array Y */
+
+    pt_X_1 = &X[-1];
+    pt_X_2 = &X[-319];
+
+
+    for (i = 15; i != 0; i--)
+    {
+        tmp1 = *(pt_X_1--);
+        tmp2 = *(pt_X_2++);
+
+        realAccu1  = fxp_mul32_by_16(*(pt_C), tmp1);
+        realAccu2  = fxp_mul32_by_16(*(pt_C++), tmp2);
+        tmp1 = pt_X_1[ -63];
+        tmp2 = pt_X_2[ +63];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -127];
+        tmp2 = pt_X_2[ +127];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -191];
+        tmp2 = pt_X_2[ +191];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -255];
+        tmp2 = pt_X_2[ +255];
+        *(p_Y_1++) = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        *(p_Y_2--) = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+
+        tmp1 = *(pt_X_1--);
+        tmp2 = *(pt_X_2++);
+        realAccu1  = fxp_mul32_by_16(*(pt_C), tmp1);
+        realAccu2  = fxp_mul32_by_16(*(pt_C++), tmp2);
+
+        tmp1 = pt_X_1[ -63];
+        tmp2 = pt_X_2[ +63];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -127];
+        tmp2 = pt_X_2[ +127];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -191];
+        tmp2 = pt_X_2[ +191];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -255];
+        tmp2 = pt_X_2[ +255];
+        *(p_Y_1++) = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        *(p_Y_2--) = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+
+    }
+
+
+    tmp1 = *(pt_X_1--);
+    tmp2 = *(pt_X_2++);
+    realAccu1  = fxp_mul32_by_16(*(pt_C), tmp1);
+    realAccu2  = fxp_mul32_by_16(*(pt_C++), tmp2);
+
+    tmp1 = pt_X_1[ -63];
+    tmp2 = pt_X_2[ +63];
+    realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+    realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+    tmp1 = pt_X_1[ -127];
+    tmp2 = pt_X_2[ +127];
+    realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+    realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+    tmp1 = pt_X_1[ -191];
+    tmp2 = pt_X_2[ +191];
+    realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+    realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+    tmp1 = pt_X_1[ -255];
+    tmp2 = pt_X_2[ +255];
+    *(p_Y_1++) = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+    *(p_Y_2--) = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+
+
+    pt_X_1 = X;
+
+    realAccu2  = fxp_mul32_by_16(Qfmt27(0.00370548843500F), X[ -32]);
+
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.00370548843500F), pt_X_1[-288], realAccu2);
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.09949460091720F), pt_X_1[ -96], realAccu2);
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.09949460091720F), pt_X_1[-224], realAccu2);
+    *(p_Y_1++) = fxp_mac32_by_16(Qfmt27(1.20736865027288F), pt_X_1[-160], realAccu2);
+
+
+    analysis_sub_band_LC(scratch_mem[0],
+                         Sr,
+                         maxBand,
+                         (Int32(*)[64])scratch_mem[1]);
+
+}
+
+
+
+#ifdef HQ_SBR
+
+void calc_sbr_anafilterbank(Int32 * Sr,
+                            Int32 * Si,
+                            Int16 * X,
+                            Int32 scratch_mem[][64],
+                            Int32   maxBand)
+{
+    Int i;
+    Int32   *p_Y_1;
+    Int32   *p_Y_2;
+
+
+
+
+    const Int32 * pt_C;
+    Int16 * pt_X_1;
+    Int16 * pt_X_2;
+    Int32 realAccu1;
+    Int32 realAccu2;
+
+    Int32 tmp1;
+    Int32 tmp2;
+
+
+    p_Y_1 = scratch_mem[0];
+
+
+    p_Y_2 = p_Y_1 + 63;
+    pt_C   = &sbrDecoderFilterbankCoefficients_an_filt[0];
+
+    realAccu1  =  fxp_mul32_by_16(Qfmt27(-0.36115899F),   X[-192]);
+
+
+    realAccu1  =  fxp_mac32_by_16(Qfmt27(-0.36115899F),  -X[-128], realAccu1);
+    realAccu1  =  fxp_mac32_by_16(Qfmt27(-0.013271822F),  X[-256], realAccu1);
+    *(p_Y_1++) =  fxp_mac32_by_16(Qfmt27(-0.013271822F), -X[ -64], realAccu1);
+
+    /* create array Y */
+
+    pt_X_1 = &X[-1];
+    pt_X_2 = &X[-319];
+
+
+    for (i = 31; i != 0; i--)
+    {
+        tmp1 = *(pt_X_1--);
+        tmp2 = *(pt_X_2++);
+        realAccu1  = fxp_mul32_by_16(*(pt_C), tmp1);
+        realAccu2  = fxp_mul32_by_16(*(pt_C++), tmp2);
+        tmp1 = pt_X_1[ -63];
+        tmp2 = pt_X_2[  63];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -127];
+        tmp2 = pt_X_2[  127];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -191];
+        tmp2 = pt_X_2[  191];
+        realAccu1  = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        realAccu2  = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+        tmp1 = pt_X_1[ -255];
+        tmp2 = pt_X_2[  255];
+        *(p_Y_1++) = fxp_mac32_by_16(*(pt_C), tmp1, realAccu1);
+        *(p_Y_2--) = fxp_mac32_by_16(*(pt_C++), tmp2, realAccu2);
+    }
+
+
+    realAccu2  = fxp_mul32_by_16(Qfmt27(0.002620176F), X[ -32]);
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.002620176F), X[-288], realAccu2);
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.070353307F), X[ -96], realAccu2);
+    realAccu2  = fxp_mac32_by_16(Qfmt27(0.070353307F), X[-224], realAccu2);
+
+
+    *(p_Y_1++) = fxp_mac32_by_16(Qfmt27(0.85373856F), (X[-160]), realAccu2);
+
+
+    analysis_sub_band(scratch_mem[0],
+                      Sr,
+                      Si,
+                      maxBand,
+                      (Int32(*)[64])scratch_mem[1]);
+
+}
+
+
+#endif
+
+
+
+#endif   /*  AAC_PLUS */
+
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.h b/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.h
new file mode 100644
index 0000000..c93848e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_anafilterbank.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: calc_sbr_anafilterbank.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CALC_SBR_ANAFILTERBANK_H
+#define CALC_SBR_ANAFILTERBANK_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+#define ROUND_ANAFIL     0
+//#define ROUND_ANAFIL     0
+#define ROUND_ANAFIL_LC  (0)
+
+    /*----------------------------------------------------------------------------
+    ; 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 calc_sbr_anafilterbank_LC(Int32 * Sr,
+    Int16 * X,
+    Int32 scratch_mem[][64],
+    Int32 maxBand);
+
+
+#ifdef HQ_SBR
+
+    void calc_sbr_anafilterbank(Int32 * Sr,
+                                Int32 * Si,
+                                Int16 * X,
+                                Int32 scratch_mem[][64],
+                                Int32 maxBand);
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /*  CALC_SBR_ANAFILTERBANK_H */
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_envelope.cpp b/media/libstagefright/codecs/aacdec/calc_sbr_envelope.cpp
new file mode 100644
index 0000000..4fb3535
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_envelope.cpp
@@ -0,0 +1,2203 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Filename: calc_sbr_envelope.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "calc_sbr_envelope.h"
+#include    "sbr_envelope_calc_tbl.h"
+#include    "sbr_create_limiter_bands.h"
+#include    "aac_mem_funcs.h"
+
+#include    "fxp_mul32.h"
+#include    "pv_normalize.h"
+
+#include    "sbr_aliasing_reduction.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#include    "pv_sqrt.h"
+
+#include    "pv_div.h"
+#include    "fxp_mul32.h"
+#include    "pv_normalize.h"
+
+#define Q30fmt(x)   (Int32)(x*((Int32)1<<30) + (x>=0?0.5F:-0.5F))
+#define Q28fmt(x)   (Int32)(x*((Int32)1<<28) + (x>=0?0.5F:-0.5F))
+#define Q15fmt(x)   (Int32)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void envelope_application_LC(Int32  *aBufR,
+    Int32  *nrg_gain_man,
+    Int32  *nrg_gain_exp,
+    Int32  *noise_level_man,
+    Int32  *noise_level_exp,
+    Int32  *nrg_tone_man,
+    Int32  *nrg_tone_exp,
+    Int32  band_nrg_tone_detector,
+    const Int32 *frame_info,
+    Int32  *harm_index,
+    Int32  *phase_index,
+    Int32  i,
+    Int32  lowSubband,
+    Int32  noSubbands,
+    Int32  noNoiseFlag);
+
+
+    void energy_estimation_LC(Int32 *aBufR,
+                              Int32 *nrg_est_man,
+                              Int32 *nrg_est_exp,
+                              const Int32 *frame_info,
+                              Int32 i,
+                              Int32 k,
+                              Int32 c,
+                              Int32 ui2);
+
+#ifdef HQ_SBR
+
+
+    void envelope_application(Int32  *aBufR,
+                              Int32  *aBufI,
+                              Int32  *nrg_gain_man,
+                              Int32  *nrg_gain_exp,
+                              Int32  *noise_level_man,
+                              Int32  *noise_level_exp,
+                              Int32  *nrg_tone_man,
+                              Int32  *nrg_tone_exp,
+                              Int32 *fBuf_man[64],
+                              Int32 *fBuf_exp[64],
+                              Int32 *fBufN_man[64],
+                              Int32 *fBufN_exp[64],
+                              const Int32 *frame_info,
+                              Int32  *harm_index,
+                              Int32  *phase_index,
+                              Int32  i,
+                              Int32  lowSubband,
+                              Int32  noSubbands,
+                              Int32  noNoiseFlag,
+                              Int32  band_nrg_tone_detector,
+                              Int32  maxSmoothLength,
+                              Int32  smooth_length);
+
+
+    void energy_estimation(Int32 *aBufR,
+                           Int32 *aBufI,
+                           Int32 *nrg_est_man,
+                           Int32 *nrg_est_exp,
+                           const Int32 *frame_info,
+                           Int32 i,
+                           Int32 k,
+                           Int32 c,
+                           Int32 ui2);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 calc_sbr_envelope(SBR_FRAME_DATA *frameData,
+                       Int32 *aBufR,
+                       Int32 *aBufI,
+                       Int freqBandTable1[2][MAX_FREQ_COEFFS + 1],
+                       const Int32 *nSfb,
+                       Int32 freqBandTable2[MAX_NOISE_COEFFS + 1],
+                       Int32 nNBands,
+                       Int32 reset,
+                       Int32 *degreeAlias,
+                       Int32 *harm_index,
+                       Int32 *phase_index,
+                       Int32 hFp[64],
+                       Int32 *sUp,
+                       Int32 limSbc[][13],
+                       Int32 *gateMode,
+#ifdef HQ_SBR
+                       Int32 *fBuf_man[64],
+                       Int32 *fBuf_exp[64],
+                       Int32 *fBufN_man[64],
+                       Int32 *fBufN_exp[64],
+#endif
+                       Int32 scratch_mem[][64],
+                       struct PATCH Patch,
+                       Int32  sqrt_cache[][4],
+                       Int32  LC_flag)
+{
+
+    Int32 c;
+    Int32 li;
+    Int32 ui;
+    Int32 i;
+    Int32 j;
+    Int32 k = 0;
+    Int32 l;
+    Int m = 0;
+    Int kk = 0;
+    Int o;
+    Int next = -1;
+    Int32 ui2;
+    Int flag;
+    Int noNoiseFlag;
+    Int *ptr;
+
+
+    UInt32 nrg = 0;
+    Int32 nrg_exp = 0;
+    struct intg_div   quotient;
+    struct intg_sqrt  root_sq;
+
+    Int32 aux1;
+
+    Int32 *nL_man       = frameData->sbrNoiseFloorLevel_man;
+    Int32 *nL_exp       = frameData->sbrNoiseFloorLevel_exp;
+
+    Int32 *sfb_nrg_man  = frameData->iEnvelope_man;
+    Int32 *sfb_nrg_exp  = frameData->iEnvelope_exp;
+
+    Int32 tmp_q1;
+    Int32 tmp_q2;
+
+    Int32 g_max_man;
+    Int32 g_max_exp;
+
+    Int32 p_ref_man;
+    Int32 p_ref_exp;
+
+    Int32 p_est_man;
+    Int32 p_est_exp;
+
+    Int32 p_adj_man;
+    Int32 p_adj_exp;
+    Int32 avg_gain;
+
+    Int32 boost_gain_q;
+
+    Int32 band_nrg_tone_detector;
+
+    Int32 *nrg_est_man     = scratch_mem[0];
+    Int32 *nrg_est_exp     = scratch_mem[1];
+    Int32 *nrg_ref_man     = scratch_mem[2];
+    Int32 *nrg_ref_exp     = scratch_mem[3];
+    Int32 *nrg_gain_man    = scratch_mem[4];
+    Int32 *nrg_gain_exp    = scratch_mem[5];
+    Int32 *noise_level_man = scratch_mem[6];
+    Int32 *noise_level_exp = scratch_mem[7];
+    Int32 *nrg_tone_man    = scratch_mem[8];
+    Int32 *nrg_tone_exp    = scratch_mem[9];
+    Int32 *hF              = scratch_mem[10];
+
+
+
+    const Int32 *frame_info = frameData->frameInfo;
+    Int32 int_mode          = frameData->sbr_header.interpolFreq;
+
+
+
+
+
+    Int32 dontUseTheseGainValues[64];
+
+#ifdef HQ_SBR
+
+    Int32 n;
+    Int32 smooth_length;
+    Int32 smoothingLength   = frameData->sbr_header.smoothingLength;
+    Int32 maxSmoothLength   = smoothLengths[0];
+
+#endif
+
+    Int32 limiterBand       = frameData->sbr_header.limiterBands;
+    Int32 limiterGains      = frameData->sbr_header.limiterGains;
+    Int32 *addHarmonics     = frameData->addHarmonics;
+
+    Int32 lowSubband        = freqBandTable1[LOW_RES][0];
+    Int32 noSubbands        = freqBandTable1[LOW_RES][nSfb[LOW_RES]] - lowSubband;
+    Int32 nEnv              = frame_info[0];
+    Int32 sEnv              = frame_info[(nEnv + 1)<<1];
+
+    /* ensure that noSubbands in the range [0,64] */
+    noSubbands = (noSubbands >> 31) ^ noSubbands;
+    if (noSubbands > 64)
+    {
+        noSubbands = 64;
+    }
+
+    if (reset)
+    {
+        *sUp = 1;
+        *phase_index = 0;
+        sbr_create_limiter_bands(limSbc,
+                                 gateMode,
+                                 freqBandTable1[LOW_RES],
+                                 Patch,
+                                 nSfb[LOW_RES]);
+    }
+
+    /* Mapping. */
+    pv_memset((void*)hF, 0, (sizeof(*hF) << 6));
+
+    ptr  = freqBandTable1[HI];
+    l = *(ptr++);
+
+    for (i = nSfb[HI]; i != 0; i--)
+    {
+        k     = *(ptr++);
+        j     = ((k + l) >> 1) - lowSubband;
+        l   = k;
+        hF[j] = *(addHarmonics++);
+    }
+
+
+    /* Envelope adjustment. */
+
+    for (i = 0; i < nEnv; i++)
+    {
+
+        if (frame_info[1+i] == frame_info[(nEnv<<1)+4+kk])
+        {
+            kk++, next++;
+        }
+
+        noNoiseFlag = (i == sEnv || i == frameData->prevEnvIsShort) ? 1 : 0;
+
+#ifdef HQ_SBR
+        smooth_length = (noNoiseFlag ? 0 : smoothLengths[smoothingLength]);
+#endif
+
+
+        /* Estimate levels. */
+        c = 0;
+        o = 0;
+
+        band_nrg_tone_detector = 0;
+
+        Int kkkk = freqBandTable1[ frame_info[nEnv+2+i] ][0];
+
+        for (j = 0; j <  nSfb[frame_info[nEnv+2+i]]; j++)
+        {
+            li = freqBandTable1[ frame_info[nEnv+2+i] ][j    ];
+            ui = freqBandTable1[ frame_info[nEnv+2+i] ][j + 1];
+            flag = 0;
+
+            for (k = li; k < ui; k++)
+            {                               /* Calculate the average energy over the current envelope, */
+                ui2   = (frame_info[1+i] << 1);
+
+                if (LC_flag == ON)
+                {
+                    energy_estimation_LC((Int32 *)aBufR,
+                                         nrg_est_man,
+                                         nrg_est_exp,
+                                         frame_info,
+                                         i,
+                                         k - kkkk,
+                                         c,
+                                         ui2);
+                }
+#ifdef HQ_SBR
+                else
+                {
+
+                    energy_estimation((Int32 *)aBufR,
+                                      (Int32 *)aBufI,
+                                      nrg_est_man,
+                                      nrg_est_exp,
+                                      frame_info,
+                                      i,
+                                      k - kkkk,
+                                      c,
+                                      ui2);
+                }
+#endif
+
+                flag = (hF[c] && (i >= sEnv || hFp[c+lowSubband])) ? 1 : flag;
+                c++;
+            }
+
+
+            ui2 = freqBandTable2[o+1];
+
+            if (!int_mode)
+            {                                /* If no interpolation is used,   */
+
+                tmp_q1 = -100;
+
+                for (k = c - (ui - li); k < c; k++)
+                {
+                    if (tmp_q1 < nrg_est_exp[k])
+                    {
+                        tmp_q1 = nrg_est_exp[k];
+                    }
+                }
+
+                nrg = 0;
+                for (k = c - (ui - li); k < c; k++)
+                {    /* average the energy in all the QMF bands, */
+                    nrg += nrg_est_man[k] >> (tmp_q1 - nrg_est_exp[k]); /* for the whole scalefactor band.  */
+                }
+                nrg /= (ui - li);
+                nrg_exp = tmp_q1;
+
+            }
+
+            c -= (ui - li);
+
+            for (k = 0; k < ui - li; k++)
+            {
+                o = (k + li >= ui2) ? o + 1 : o;
+                ui2 = freqBandTable2[o+1];
+                /*
+                 *  If no interpolation is used, use the averaged energy from above,
+                 *  otherwise do nothing.
+                 */
+
+
+                if (!int_mode)
+                {
+                    nrg_est_man[c] = nrg;
+                    nrg_est_exp[c] = nrg_exp;
+                }
+
+                if (LC_flag == ON)
+                {
+                    nrg_est_exp[c] += 1;
+
+                    if (flag)
+                    {
+                        dontUseTheseGainValues[k + li - lowSubband] = 1;
+                    }
+                    else
+                    {
+                        dontUseTheseGainValues[k + li - lowSubband] = 0;
+                    }
+                }
+
+                nrg_ref_man[c] = sfb_nrg_man[m];
+                nrg_ref_exp[c] = sfb_nrg_exp[m];
+
+                /*
+                 *  compute nL/(1 + nL);   where nL = nL_man*2^nL_exp
+                 */
+                aux1 = next * nNBands + o;
+
+                tmp_q1 = nL_exp[aux1];
+
+                if (tmp_q1 >= 0)
+                {
+                    pv_div(nL_man[aux1], nL_man[aux1] + (0x3FFFFFFF >> tmp_q1), &quotient);
+                }
+                else
+                {
+                    tmp_q1 = nL_man[aux1] >> (-tmp_q1);
+                    pv_div(tmp_q1, tmp_q1 + 0x3FFFFFFF, &quotient);
+                }
+
+                /*
+                 *  tmp_q1 = nL/(1 + nL)*nrg_ref[c];
+                 */
+
+                tmp_q1 = fxp_mul32_Q30(quotient.quotient >> quotient.shift_factor,  nrg_ref_man[c]);
+
+                if (flag)
+                {
+                    /*
+                     *  Calculate levels and gain, dependent on whether a synthetic, a sine is present or not.
+                     *
+                     *  nrg_gain[c]=(float)pv_sqrt( tmp/(nrg_est[c] + 1), sqrt_cache[1] );
+                     */
+
+
+                    pv_div(tmp_q1, nrg_est_man[c] + 1, &quotient);
+                    /*
+                     *  nrg_est_man[c] is an integer number, while tmp_q1 and quotient.quotient
+                     *  are fractions in Q30
+                     */
+
+                    tmp_q2 = nrg_ref_exp[c] - nrg_est_exp[c] - quotient.shift_factor - 30;
+
+                    pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[1]);
+                    nrg_gain_man[c] = root_sq.root;     /*  in Q28 format */
+                    nrg_gain_exp[c] = root_sq.shift_factor;
+
+
+                    /*
+                     *  nrg_tone[c]=(float)( (hF[c] && (i >= sEnv || hFp[c+lowSubband])) ?
+                     *                          pv_sqrt(nrg_ref[c]/(1+tmp_nL), sqrt_cache[2]) : 0);
+                     */
+                    if (hF[c] && (i >= sEnv || hFp[c+lowSubband]))
+                    {
+                        /*
+                         *  nrg_ref[c] and  nL, as well as quotient.quotient
+                         *  are fractions in Q30
+                         */
+
+                        /*  aux1 == next*nNBands + o */
+
+                        tmp_q2 = nL_exp[aux1];
+                        /*
+                         *  nrg_ref[c]/(1+tmp_nL)
+                         */
+
+                        if (tmp_q2 >= 0)
+                        {
+                            pv_div(nrg_ref_man[c], nL_man[aux1] + (0x3FFFFFFF >> tmp_q2), &quotient);
+                        }
+                        else
+                        {
+                            tmp_q2 = nL_man[aux1] >> (-tmp_q2);
+                            pv_div(nrg_ref_man[c], tmp_q2 + 0x3FFFFFFF, &quotient);
+                            tmp_q2 = 0;     /* exponent has been applied to the sum ((man>>exp) + 1)  */
+                        }
+
+                        tmp_q2 = nrg_ref_exp[c] - tmp_q2 - quotient.shift_factor;
+
+                        pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[2]);
+                        nrg_tone_man[c]    = root_sq.root;
+                        nrg_tone_exp[c]    = root_sq.shift_factor;
+
+                    }
+                    else
+                    {
+                        nrg_tone_man[c]    = 0;
+                        nrg_tone_exp[c]    = 0;
+                    }
+
+                }
+                else
+                {
+                    if (noNoiseFlag)
+                    {
+                        /*
+                         * nrg_gain[c] = (float) pv_sqrt(nrg_ref[c] /(nrg_est[c] + 1), sqrt_cache[3]);
+                         */
+
+                        pv_div(nrg_ref_man[c], nrg_est_man[c] + 1, &quotient);
+
+                        /*
+                         *  nrg_est_man[c] is an integer number, while nrg_ref_man[c] and
+                         *  quotient.quotient are fractions in Q30
+                         */
+
+                        tmp_q2 = nrg_ref_exp[c] - nrg_est_exp[c] - quotient.shift_factor - 30;
+
+                        pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[3]);
+                        nrg_gain_man[c] = root_sq.root;
+                        nrg_gain_exp[c] = root_sq.shift_factor;
+
+                    }
+                    else
+                    {
+                        /*
+                         *  nrg_gain[c] = (float) pv_sqrt(nrg_ref[c]/((nrg_est[c] + 1)*(1+tmp_nL)), sqrt_cache[4]);
+                         */
+                        /*  aux1 == next*nNBands + o */
+
+                        tmp_q2 = nL_exp[aux1];
+                        /*
+                         *  nrg_ref[c]/((nrg_est[c] + 1)*(1+tmp_nL))
+                         */
+
+                        if (nrg_est_man[c] == 0)
+                        {
+                            tmp_q2 = 0;     /*  avoid division by 0 in next if-else, this could be due to
+                                                rounding noise */
+                        }
+
+
+                        if (tmp_q2 >= 0)
+                        {
+
+                            tmp_q2 = fxp_mul32_Q30(nrg_est_man[c] + 1, nL_man[aux1] + (0x3FFFFFFF >> tmp_q2));
+                            pv_div(nrg_ref_man[c], tmp_q2, &quotient);
+                            /*
+                             *  nrg_est_man[c] is an integer number, while nrg_ref_man[c] and
+                             *  quotient.quotient are fractions in Q30
+                             */
+                            tmp_q2 = nrg_ref_exp[c] - quotient.shift_factor - 30 - nL_exp[aux1];
+                            if (nrg_est_man[c])
+                            {
+                                tmp_q2 -=  nrg_est_exp[c];
+                            }
+
+                            tmp_q2 = nrg_ref_exp[c] - nrg_est_exp[c] - quotient.shift_factor - 30 - nL_exp[aux1];
+                        }
+                        else
+                        {
+                            if (tmp_q2 > - 10)
+                            {
+                                tmp_q2 = nL_man[aux1] >> (-tmp_q2);
+
+                                tmp_q2 = fxp_mul32_Q30(nrg_est_man[c] + 1, tmp_q2 + 0x3FFFFFFF);
+                            }
+                            else
+                            {
+                                tmp_q2 = nrg_est_man[c] + 1;
+                            }
+
+
+                            pv_div(nrg_ref_man[c], tmp_q2, &quotient);
+                            /*
+                             *  nrg_est_man[c] is an integer number, while nrg_ref_man[c] and
+                             *  quotient.quotient are fractions in Q30
+                             */
+
+                            tmp_q2 = nrg_ref_exp[c] - quotient.shift_factor - 30;
+                            if (nrg_est_man[c])
+                            {
+                                tmp_q2 -=  nrg_est_exp[c];
+                            }
+
+                        }
+
+                        pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[4]);
+                        nrg_gain_man[c] = root_sq.root;
+                        nrg_gain_exp[c] = root_sq.shift_factor;
+
+                    }
+
+                    nrg_tone_man[c]    = 0;
+                    nrg_tone_exp[c]    = -100;
+
+                }
+
+                band_nrg_tone_detector |= nrg_tone_man[c];   /*  detect any tone activity  */
+
+                pv_sqrt(tmp_q1, nrg_ref_exp[c], &root_sq, sqrt_cache[5]);
+                noise_level_man[c] = root_sq.root;
+                noise_level_exp[c] = root_sq.shift_factor;
+
+                c++;
+
+            }   /* ---- end-for-loop (k) ------ */
+            m++;
+
+        }   /* -------- Estimate levels end-for-loop (j) ----- */
+
+
+
+        /*
+         *      Limiter
+         */
+
+
+        for (c = 0; c < gateMode[limiterBand]; c++)
+        {
+
+            p_ref_man = 0;
+            p_est_man = 0;
+
+            /*
+             *  get max exponent for the reference and estimated energy
+             */
+            p_ref_exp = -100;
+            p_est_exp = -100;
+
+            for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+            {
+                if (p_ref_exp < nrg_ref_exp[k])
+                {
+                    p_ref_exp = nrg_ref_exp[k];    /* max */
+                }
+                if (p_est_exp < nrg_est_exp[k])
+                {
+                    p_est_exp = nrg_est_exp[k];    /* max */
+                }
+            }
+
+            k -= limSbc[limiterBand][c];     /*  number of element used in the addition */
+
+            while (k != 0)      /*  bit guard protection depends on log2(k)  */
+            {
+                k >>= 1;
+                p_ref_exp++;       /*  add extra bit-overflow-guard, nrg_ref_exp is in Q30 format */
+            }
+
+
+            for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+            {   /*Calculate the average gain for the current limiter band.*/
+                p_ref_man += (nrg_ref_man[k] >> (p_ref_exp - nrg_ref_exp[k]));
+                p_est_man += (nrg_est_man[k] >> (p_est_exp - nrg_est_exp[k]));
+
+            }
+
+            if (p_est_man)
+            {
+                /*
+                 *  "average gain" (not equal to average of nrg_gain)
+                 */
+                pv_div(p_ref_man, p_est_man, &quotient);
+
+                tmp_q2 = p_ref_exp - 30 - p_est_exp - quotient.shift_factor;
+
+                /*
+                 *  avg_gain = sqrt(p_ref/p_est)
+                 */
+                pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[6]);
+                avg_gain  = root_sq.root;
+                g_max_exp = root_sq.shift_factor;
+
+                /*
+                 *  maximum gain allowed is calculated from table.
+                 */
+
+                /*
+                 *  g_max = avg_gain * limGains[limiterGains];
+                 */
+
+                g_max_man = fxp_mul32_Q30(avg_gain, limGains[limiterGains]);   /*  table is in Q30 */
+
+                if (limiterGains == 3)
+                {
+                    g_max_exp = limGains[4];
+                }
+
+                tmp_q1 = g_max_exp >= 16 ? g_max_exp : 16;
+
+                tmp_q2 = g_max_man >> (tmp_q1 - g_max_exp);
+                tmp_q1 = Q28fmt(1.52587890625F) >> (tmp_q1 - 16);
+
+                if (tmp_q2 > tmp_q1)
+                {
+                    /* upper limit, +100 dB */
+                    g_max_man = Q28fmt(1.52587890625F);
+                    g_max_exp = 16;
+                }
+            }
+            else
+            {
+                /*  Qfmt(1.52587890625F)    exp = 16 */
+                g_max_man = Q28fmt(1.52587890625F);
+                g_max_exp = 16;
+            }
+
+            /*
+             *  Compute Adjusted power p_adj
+             */
+            for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+            {
+
+                tmp_q1 = g_max_exp >= nrg_gain_exp[k] ? g_max_exp : nrg_gain_exp[k];
+
+                tmp_q2 = g_max_man >> (tmp_q1 - g_max_exp);
+                tmp_q1 = nrg_gain_man[k] >> (tmp_q1 - nrg_gain_exp[k]);
+                /*
+                 *  if(g_max <= nrg_gain[k])
+                 */
+                if (tmp_q2 <= tmp_q1)
+                {
+                    tmp_q1 = fxp_mul32_Q28(noise_level_man[k], g_max_man);
+                    pv_div(tmp_q1, nrg_gain_man[k], &quotient);
+                    noise_level_man[k] = quotient.quotient >> 2;   /* in Q28 */
+                    noise_level_exp[k] = noise_level_exp[k] + g_max_exp - quotient.shift_factor - nrg_gain_exp[k];
+
+                    nrg_gain_man[k] =  g_max_man;       /* gains with noise supression */
+                    nrg_gain_exp[k] =  g_max_exp;
+                }
+            }
+
+            p_adj_exp = -100;
+
+            for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+            {
+                tmp_q1 = nrg_est_exp[k] + (nrg_gain_exp[k] << 1) + 28;  /* 28 to match shift down by mult32_Q28  */
+
+                if (p_adj_exp < tmp_q1)
+                {
+                    p_adj_exp = tmp_q1;
+                }
+                if (nrg_tone_man[k])
+                {
+                    tmp_q1 = (nrg_tone_exp[k] << 1);
+                    if (p_adj_exp < tmp_q1)
+                    {
+                        p_adj_exp = tmp_q1;
+                    }
+                }
+                else if (!noNoiseFlag)
+                {
+                    tmp_q1 = (noise_level_exp[k] << 1);
+
+                    if (p_adj_exp < tmp_q1)
+                    {
+                        p_adj_exp = tmp_q1;
+                    }
+                }
+            }
+
+            p_adj_exp += 1; /* overflow bit-guard*/
+
+            p_adj_man = 0;
+
+            for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+            {
+                /*
+                 *  p_adj += nrg_gain[k]*nrg_gain[k]*nrg_est[k];
+                 */
+
+                if (p_adj_exp - (nrg_est_exp[k] + (nrg_gain_exp[k] << 1)) < 59)
+                {
+                    tmp_q1 = fxp_mul32_Q28(nrg_gain_man[k], nrg_gain_man[k]);
+                    tmp_q1 = fxp_mul32_Q28(tmp_q1, nrg_est_man[k]);
+                    p_adj_man += (tmp_q1 >> (p_adj_exp - (nrg_est_exp[k] + (nrg_gain_exp[k] << 1) + 28)));
+                }
+
+                if (nrg_tone_man[k])
+                {
+                    /*
+                     *  p_adj += nrg_tone[k]*nrg_tone[k];
+                     */
+                    if (p_adj_exp - (nrg_tone_exp[k] << 1) < 31)
+                    {
+                        tmp_q1 = fxp_mul32_Q28(nrg_tone_man[k], nrg_tone_man[k]);
+                        p_adj_man += (tmp_q1 >> (p_adj_exp - (nrg_tone_exp[k] << 1)));
+                    }
+                }
+                else if (!noNoiseFlag)
+                {
+                    /*
+                     *  p_adj += noise_level[k]*noise_level[k];
+                     */
+
+                    if (p_adj_exp - (noise_level_exp[k] << 1) < 31)
+                    {
+                        tmp_q1 = fxp_mul32_Q28(noise_level_man[k], noise_level_man[k]);
+                        p_adj_man += (tmp_q1 >> (p_adj_exp - (noise_level_exp[k] << 1)));
+                    }
+
+                }
+            }
+
+
+            if (p_adj_man)
+            {
+                pv_div(p_ref_man, p_adj_man, &quotient);
+                tmp_q2 = p_ref_exp - p_adj_exp - 58 - quotient.shift_factor;   /*  58 <> Q30 + Q28 */
+
+                pv_sqrt(quotient.quotient, tmp_q2, &root_sq, sqrt_cache[7]);
+
+                if (root_sq.shift_factor > -28)
+                {
+                    boost_gain_q = root_sq.root << (root_sq.shift_factor + 28);
+                }
+                else
+                {
+                    boost_gain_q = root_sq.root >> (-28 - root_sq.shift_factor);
+                }
+
+                tmp_q1 = root_sq.shift_factor >= -28 ? root_sq.shift_factor : -28;
+
+                tmp_q2 = root_sq.root >> (tmp_q1 - root_sq.shift_factor);
+                tmp_q1 = Q28fmt(1.584893192f) >> (tmp_q1 + 28);
+
+
+                if (tmp_q2 > tmp_q1)
+                {
+                    boost_gain_q = Q28fmt(1.584893192f);
+                }
+            }
+            else
+            {
+                boost_gain_q = Q28fmt(1.584893192f);
+            }
+
+            if (band_nrg_tone_detector)
+            {
+                for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+                {
+                    nrg_gain_man[k]    = fxp_mul32_Q28(nrg_gain_man[k], boost_gain_q);
+                    noise_level_man[k] = fxp_mul32_Q28(noise_level_man[k], boost_gain_q);
+                    nrg_tone_man[k]    = fxp_mul32_Q28(nrg_tone_man[k], boost_gain_q);
+                }
+            }
+            else
+            {
+
+                for (k = limSbc[limiterBand][c]; k < limSbc[limiterBand][c + 1]; k++)
+                {
+                    nrg_gain_man[k]    = fxp_mul32_Q28(nrg_gain_man[k], boost_gain_q);
+                    noise_level_man[k] = fxp_mul32_Q28(noise_level_man[k], boost_gain_q);
+                }
+
+
+            }
+
+        }   /* Limiter  End for loop (c) */
+
+
+        if (LC_flag == ON)
+        {
+
+            /*
+             *          Aliasing correction
+             */
+
+            sbr_aliasing_reduction(degreeAlias,
+                                   nrg_gain_man,
+                                   nrg_gain_exp,
+                                   nrg_est_man,
+                                   nrg_est_exp,
+                                   dontUseTheseGainValues,
+                                   noSubbands,
+                                   lowSubband,
+                                   sqrt_cache,
+                                   scratch_mem[3]);
+
+            if (*sUp)     /* Init only done once upon reset */
+            {
+                *sUp = 0;
+            }
+
+            envelope_application_LC((Int32 *)aBufR,
+                                    nrg_gain_man,
+                                    nrg_gain_exp,
+                                    noise_level_man,
+                                    noise_level_exp,
+                                    nrg_tone_man,
+                                    nrg_tone_exp,
+                                    band_nrg_tone_detector,
+                                    frame_info,
+                                    harm_index,
+                                    phase_index,
+                                    i,
+                                    lowSubband,
+                                    noSubbands,
+                                    noNoiseFlag);
+        }
+#ifdef HQ_SBR
+        else
+        {
+
+            if (*sUp)     /* Init only done once upon reset */
+            {
+                for (n = 0; n < maxSmoothLength; n++)
+                {
+                    pv_memcpy(fBuf_man[n],     nrg_gain_man, noSubbands*sizeof(*fBuf_man[n]));
+                    pv_memcpy(fBufN_man[n], noise_level_man, noSubbands*sizeof(*fBufN_man[n]));
+                    pv_memcpy(fBuf_exp[n],     nrg_gain_exp, noSubbands*sizeof(*fBuf_exp[n]));
+                    pv_memcpy(fBufN_exp[n], noise_level_exp, noSubbands*sizeof(*fBufN_exp[n]));
+                }
+                *sUp = 0;
+            }
+
+
+            envelope_application((Int32 *)aBufR,
+                                 (Int32 *)aBufI,
+                                 nrg_gain_man,
+                                 nrg_gain_exp,
+                                 noise_level_man,
+                                 noise_level_exp,
+                                 nrg_tone_man,
+                                 nrg_tone_exp,
+                                 fBuf_man,
+                                 fBuf_exp,
+                                 fBufN_man,
+                                 fBufN_exp,
+                                 frame_info,
+                                 harm_index,
+                                 phase_index,
+                                 i,
+                                 lowSubband,
+                                 noSubbands,
+                                 noNoiseFlag,
+                                 band_nrg_tone_detector,
+                                 maxSmoothLength,
+                                 smooth_length);
+
+        }
+#endif
+
+    }   /* -----  Envelope adjustment end for-loop (i) ---- */
+
+
+    pv_memcpy(&hFp[0] + lowSubband,
+              hF,
+              (64 - lowSubband)*sizeof(*hF));
+
+    if (sEnv == nEnv)
+    {
+        frameData->prevEnvIsShort = 0;
+    }
+    else
+    {
+        frameData->prevEnvIsShort = -1;
+    }
+
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void envelope_application_LC(Int32  *aBufR,
+                             Int32  *nrg_gain_man,
+                             Int32  *nrg_gain_exp,
+                             Int32  *noise_level_man,
+                             Int32  *noise_level_exp,
+                             Int32  *nrg_tone_man,
+                             Int32  *nrg_tone_exp,
+                             Int32  band_nrg_tone_detector,
+                             const Int32 *frame_info,
+                             Int32  *harm_index,
+                             Int32  *phase_index,
+                             Int32  i,
+                             Int32  lowSubband,
+                             Int32  noSubbands,
+                             Int32  noNoiseFlag)
+{
+
+    Int32 *ptrReal;
+    Int32 sb_gain_man;
+    Int32 sb_noise_man;
+    Int32 sb_noise_exp;
+    Int32 l;
+    Int32 k;
+    Int32 tmp_q1;
+    Int32 tmp_q2;
+    Int32 tone_count;
+    Int16 tmp_16;
+    Int32 indexMinus1;
+    Int32 indexPlus1;
+
+
+    /*
+     *          Application
+     */
+
+    if (band_nrg_tone_detector)     /* Add tone energy only if energy is detected  */
+    {
+
+        /*
+         *  pre-calculate tone application
+         */
+        for (k = 0; k < noSubbands; k++)
+        {
+            tmp_q2 = (-nrg_tone_exp[k]);
+            tmp_q1 = nrg_tone_man[k];
+            tmp_q2 = tmp_q1 >> tmp_q2;
+            tmp_q1 = fxp_mul32_by_16(tmp_q2, Q15fmt(0.0163f));
+            nrg_tone_man[k] = tmp_q2;
+            nrg_tone_exp[k] = tmp_q1;
+            noise_level_exp[k] += 1;
+            nrg_gain_exp[k] += 28;
+        }
+
+        for (l = (frame_info[1+i] << 1); l < (frame_info[2+i] << 1); l++)
+        {
+            ptrReal = (aBufR + l * SBR_NUM_BANDS);
+
+            tone_count = 0;
+
+            indexPlus1  = (*harm_index + 1) & 3;
+
+            if (indexPlus1 & 1)    /*  if indexPlus1 is odd */
+            {
+                for (k = 0; k < noSubbands; k++)
+                {
+
+                    sb_gain_man = nrg_gain_man[k];
+                    tmp_q1 = *ptrReal;
+                    tmp_q2 = nrg_gain_exp[k];
+                    tmp_q1 = fxp_mul32_Q28(tmp_q1, sb_gain_man);
+
+                    if (tmp_q2 < 0)
+                    {
+                        if (tmp_q2 > -32)
+                        {
+                            *ptrReal = tmp_q1 >> (-tmp_q2);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal = tmp_q1 << tmp_q2;
+                    }
+
+                    *phase_index = (*phase_index + 1) & 511;
+
+                    if (!nrg_tone_man[k] && !noNoiseFlag)
+
+                    {
+                        tmp_16 = rP_LCx[*phase_index];
+                        sb_noise_man = noise_level_man[k];
+                        sb_noise_exp = noise_level_exp[k];
+
+                        tmp_q1 = fxp_mul32_by_16(sb_noise_man, tmp_16);
+
+                        if (sb_noise_exp < 0)
+                        {
+                            if (sb_noise_exp > -32)
+                            {
+                                *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                            }
+                        }
+                        else
+                        {
+                            *ptrReal += tmp_q1 << sb_noise_exp;
+                        }
+                    }
+
+                    tmp_q1 = nrg_tone_man[k];
+
+                    if (*harm_index)
+                    {
+                        *ptrReal -= tmp_q1;
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1;
+                    }
+
+                    if (tmp_q1)
+                    {
+                        tone_count++;
+                    }
+
+                    ptrReal++;
+
+                }   /*  for-loop (k) */
+
+            }
+            else        /*  if indexPlus1 is even */
+            {
+                indexMinus1 = (*harm_index - 1) & 3;
+
+                /*  ---  k = 0  ----- */
+
+                sb_gain_man = nrg_gain_man[0];
+                tmp_q1 = *ptrReal;
+                tmp_q2 = nrg_gain_exp[0];
+                tmp_q1 = fxp_mul32_Q28(tmp_q1, sb_gain_man);
+
+                if (tmp_q2 < 0)
+                {
+                    if (tmp_q2 > -32)
+                    {
+                        *ptrReal = tmp_q1 >> (-tmp_q2);
+                    }
+                }
+                else
+                {
+                    *ptrReal = tmp_q1 << tmp_q2;
+                }
+
+                *phase_index = (*phase_index + 1) & 511;
+
+                tmp_q1 = nrg_tone_exp[0];
+                tmp_q2 = nrg_tone_exp[1];
+
+                if ((indexPlus1 != 0) ^((lowSubband & 1) != 0))
+                {
+                    *(ptrReal - 1) -= tmp_q1;
+                    *(ptrReal)   += tmp_q2;
+                }
+                else
+                {
+                    *(ptrReal - 1) += tmp_q1;
+                    *(ptrReal)   -= tmp_q2;
+                }
+
+                if (!nrg_tone_man[0] && !noNoiseFlag)
+                {
+                    tmp_16 = rP_LCx[*phase_index];
+                    sb_noise_man = noise_level_man[0];
+                    sb_noise_exp = noise_level_exp[0];
+
+                    tmp_q1 = fxp_mul32_by_16(sb_noise_man, tmp_16);
+
+                    if (sb_noise_exp < 0)
+                    {
+                        if (sb_noise_exp > -32)
+                        {
+                            *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1 << sb_noise_exp;
+                    }
+                }
+                else
+                {
+                    tone_count++;
+                }
+
+                ptrReal++;
+
+                /* ----  */
+
+                for (k = 1; k < noSubbands - 1; k++)
+                {
+
+                    sb_gain_man = nrg_gain_man[k];
+                    tmp_q1 = *ptrReal;
+                    tmp_q2 = nrg_gain_exp[k];
+                    tmp_q1 = fxp_mul32_Q28(tmp_q1, sb_gain_man);
+
+                    if (tmp_q2 < 0)
+                    {
+                        if (tmp_q2 > -32)
+                        {
+                            *ptrReal = tmp_q1 >> (-tmp_q2);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal = tmp_q1 << tmp_q2;
+                    }
+
+                    *phase_index = (*phase_index + 1) & 511;
+
+
+                    if (tone_count < 16)
+                    {
+                        tmp_q1 = nrg_tone_exp[k - 1];
+                        tmp_q2 = nrg_tone_exp[k + 1];
+
+                        tmp_q1 -= tmp_q2;
+
+
+                        if ((indexPlus1 != 0) ^(((k + lowSubband) & 1) != 0))
+                        {
+                            *(ptrReal) -= tmp_q1;
+                        }
+                        else
+                        {
+                            *(ptrReal) += tmp_q1;
+                        }
+                    }   /*   if (tone_count < 16)  */
+
+
+                    if (!nrg_tone_man[k] && !noNoiseFlag)
+                    {
+                        tmp_16 = rP_LCx[*phase_index];
+                        sb_noise_man = noise_level_man[k];
+                        sb_noise_exp = noise_level_exp[k];
+
+                        tmp_q1 = fxp_mul32_by_16(sb_noise_man, tmp_16);
+
+                        if (sb_noise_exp < 0)
+                        {
+                            if (sb_noise_exp > -32)
+                            {
+                                *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                            }
+                        }
+                        else
+                        {
+                            *ptrReal += tmp_q1 << sb_noise_exp;
+                        }
+                    }
+                    else
+                    {
+                        tone_count++;
+                    }
+
+                    ptrReal++;
+
+                }   /*  for-loop (k) */
+
+                sb_gain_man = nrg_gain_man[k];
+                tmp_q1 = *ptrReal;
+                tmp_q2 = nrg_gain_exp[k];
+                tmp_q1 = fxp_mul32_Q28(tmp_q1, sb_gain_man);
+
+                if (tmp_q2 < 0)
+                {
+                    if (tmp_q2 > -31)
+                    {
+                        *ptrReal = tmp_q1 >> (-tmp_q2);
+                    }
+                }
+                else
+                {
+                    *ptrReal = tmp_q1 << tmp_q2;
+                }
+
+                *phase_index = (*phase_index + 1) & 511;
+
+
+                if ((tone_count < 16) && !(indexMinus1 &1))
+                {
+                    tmp_q1 = nrg_tone_exp[k - 1];
+                    tmp_q2 = nrg_tone_exp[k    ];
+
+                    if ((indexMinus1 != 0) ^(((k + lowSubband) & 1) != 0))
+                    {
+                        *(ptrReal)   += tmp_q1;
+
+                        if (k + lowSubband < 62)
+                        {
+                            *(ptrReal + 1) -= tmp_q2;
+                        }
+                    }
+                    else
+                    {
+                        *(ptrReal)   -= tmp_q1;
+
+                        if (k + lowSubband < 62)
+                        {
+                            *(ptrReal + 1) += tmp_q2;
+                        }
+                    }
+                }   /*   if (tone_count < 16)  */
+
+
+                if (!nrg_tone_man[k] && !noNoiseFlag)
+                {
+                    tmp_16 = rP_LCx[*phase_index];
+                    sb_noise_man = noise_level_man[k];
+                    sb_noise_exp = noise_level_exp[k];
+
+                    tmp_q1 = fxp_mul32_by_16(sb_noise_man, tmp_16);
+
+                    if (sb_noise_exp < 0)
+                    {
+                        if (sb_noise_exp > -31)
+                        {
+                            *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1 << sb_noise_exp;
+                    }
+                }
+
+            }   /*  if indexPlus1 is odd */
+
+            *harm_index = indexPlus1;
+
+
+        }        /*  for-loop (l) */
+
+    }
+    else        /*   if ( band_nrg_tone_detector)   */
+    {
+
+        for (k = 0; k < noSubbands; k++)
+        {
+            tmp_q1 = noise_level_exp[k];
+            tmp_q2 = nrg_gain_exp[k];
+            noise_level_exp[k] =  tmp_q1 + 1;
+            nrg_gain_exp[k] = tmp_q2 + 28;
+        }
+
+        for (l = (frame_info[1+i] << 1); l < (frame_info[2+i] << 1); l++)
+        {
+            ptrReal = (aBufR + l * SBR_NUM_BANDS);
+
+            for (k = 0; k < noSubbands; k++)
+            {
+
+                tmp_q1 = *ptrReal;
+                sb_gain_man = nrg_gain_man[k];
+
+                tmp_q2 = nrg_gain_exp[k];
+
+                tmp_q1 = fxp_mul32_Q28(tmp_q1, sb_gain_man);
+
+                if (tmp_q2 < 0)
+                {
+                    if (tmp_q2 > -31)
+                    {
+                        *ptrReal = tmp_q1 >> (-tmp_q2);
+                    }
+                }
+                else
+                {
+                    *ptrReal = tmp_q1 << tmp_q2;
+                }
+
+                *phase_index = (*phase_index + 1) & 511;
+
+                if (! noNoiseFlag)
+                {
+                    tmp_16 = rP_LCx[*phase_index];
+                    sb_noise_man = noise_level_man[k];
+                    sb_noise_exp = noise_level_exp[k];
+
+                    tmp_q1 = fxp_mul32_by_16(sb_noise_man, tmp_16);
+
+                    if (sb_noise_exp < 0)
+                    {
+                        if (sb_noise_exp > -31)
+                        {
+                            *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1 << sb_noise_exp;
+                    }
+                }
+
+                ptrReal++;
+
+            }   /*  for-loop (k) */
+
+            *harm_index  = (*harm_index + 1) & 3;
+
+
+        }   /*  for-loop (l) */
+
+    }
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+#define Qfmt15(a)   (Int32)(a*((Int32)1<<15) + (a>=0?0.5F:-0.5F))
+
+
+const Int16 pow2[39] = { 0, 0, 1, 0, 2,
+                         0, Qfmt15(2 / 6.0f), 0, 3, 0, Qfmt15(2 / 10.0f), 0, Qfmt15(2 / 12.0f), 0, Qfmt15(2 / 14.0f), 0, 4,
+                         0, Qfmt15(2 / 18.0f),    0, Qfmt15(2 / 20.0f), 0, Qfmt15(2 / 22.0f), 0, Qfmt15(2 / 24.0f),
+                         0, Qfmt15(2 / 26.0f), 0, Qfmt15(2 / 28.0f), 0, Qfmt15(2 / 30.0f), 0, 5, 0, Qfmt15(2 / 34.0f),
+                         0, Qfmt15(2 / 36.0f), 0, Qfmt15(2 / 38.0f)
+                       };
+
+void energy_estimation_LC(Int32 *aBufR,
+                          Int32 *nrg_est_man,
+                          Int32 *nrg_est_exp,
+                          const Int32 *frame_info,
+                          Int32 i,
+                          Int32 k,
+                          Int32 c,
+                          Int32 ui2)
+{
+
+
+    Int32  aux1;
+    Int32  aux2;
+    Int32  l;
+
+
+    int64_t nrg_h = 0;
+    Int32 tmp1;
+    UInt32 tmp2;
+
+    for (l = ui2; l < (frame_info[2+i] << 1); l++)
+    {
+
+        aux1 = aBufR[l++*SBR_NUM_BANDS + k ];
+        aux2 = aBufR[l  *SBR_NUM_BANDS + k ];
+
+        nrg_h = fxp_mac64_Q31(nrg_h, aux1, aux1);
+        nrg_h = fxp_mac64_Q31(nrg_h, aux2, aux2);
+    }
+
+    /*
+     *  Check for overflow and saturate if needed
+     */
+    if (nrg_h < 0)
+    {
+        nrg_h = 0x7fffffff;
+    }
+
+
+    if (nrg_h)
+    {
+        tmp2 = (UInt32)(nrg_h >> 32);
+        if (tmp2)
+        {
+            aux2 = pv_normalize(tmp2);
+            aux2 -= 1;                  /*  ensure Q30 */
+            nrg_h = (nrg_h << aux2) >> 33;
+            tmp2 = (UInt32)(nrg_h);
+            nrg_est_exp[c] = 33 - aux2;
+        }
+        else
+        {
+            tmp2 = (UInt32)(nrg_h >> 2);
+            aux2 = pv_normalize(tmp2);
+            aux2 -= 1;                  /*  ensure Q30 */
+
+            tmp2 = (tmp2 << aux2);
+            nrg_est_exp[c] =  -aux2 + 2;
+        }
+
+        tmp1 = (l - ui2);
+
+        aux2 = pow2[tmp1];
+        if (tmp1 == (tmp1 & (-tmp1)))
+        {
+            nrg_est_man[c] = tmp2 >> aux2;
+        }
+        else
+        {
+            nrg_est_man[c] = fxp_mul32_by_16(tmp2, aux2);
+        }
+
+    }
+    else
+    {
+        nrg_est_man[c] = 0;
+        nrg_est_exp[c] = -100;
+    }
+
+
+
+
+
+}
+
+
+
+
+
+
+#if HQ_SBR
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void envelope_application(Int32  *aBufR,
+                          Int32  *aBufI,
+                          Int32  *nrg_gain_man,
+                          Int32  *nrg_gain_exp,
+                          Int32  *noise_level_man,
+                          Int32  *noise_level_exp,
+                          Int32  *nrg_tone_man,
+                          Int32  *nrg_tone_exp,
+                          Int32  *fBuf_man[64],
+                          Int32  *fBuf_exp[64],
+                          Int32  *fBufN_man[64],
+                          Int32  *fBufN_exp[64],
+                          const  Int32 *frame_info,
+                          Int32  *harm_index,
+                          Int32  *phase_index,
+                          Int32  i,
+                          Int32  lowSubband,
+                          Int32  noSubbands,
+                          Int32  noNoiseFlag,
+                          Int32  band_nrg_tone_detector,
+                          Int32  maxSmoothLength,
+                          Int32  smooth_length)
+{
+
+    Int32 *ptrReal;
+    Int32 *ptrImag;
+    Int32 sb_gain_man;
+    Int32 sb_gain_exp;
+    Int32 sb_noise_man;
+    Int32 sb_noise_exp;
+    Int32 l;
+    Int32 k;
+    Int32 n;
+    Int32 tmp_q1;
+    Int32 tmp_q2;
+    Int32  aux1;
+    Int32  aux2;
+    Int32  filter_history = 0;
+
+
+    if (band_nrg_tone_detector)     /* Add tone energy only if energy is detected  */
+    {
+
+        /*
+         *  pre-calculate tone application
+         */
+
+        ptrReal = nrg_tone_exp;
+        ptrImag = nrg_tone_man;
+        tmp_q1 = - *(ptrReal++);
+        aux1   =   *(ptrImag);
+        for (k = 0; k < noSubbands; k++)
+        {
+            *(ptrImag++) = aux1 >> tmp_q1;
+            tmp_q1 = - *(ptrReal++);
+            aux1   =   *(ptrImag);
+        }
+
+        /*
+         *          Application
+         */
+
+        for (l = (frame_info[1+i] << 1); l < (frame_info[2+i] << 1); l++)
+        {
+            ptrReal = (aBufR + l * SBR_NUM_BANDS);
+            ptrImag = (aBufI + l * SBR_NUM_BANDS);
+
+            if (filter_history <= maxSmoothLength)     /* no more update is needed as buffer will have same info */
+            {
+                pv_memmove(fBuf_man[maxSmoothLength], nrg_gain_man, noSubbands*sizeof(*nrg_gain_man));
+                pv_memmove(fBuf_exp[maxSmoothLength], nrg_gain_exp, noSubbands*sizeof(*nrg_gain_exp));
+                pv_memmove(fBufN_man[maxSmoothLength], noise_level_man, noSubbands*sizeof(*noise_level_man));
+                pv_memmove(fBufN_exp[maxSmoothLength], noise_level_exp, noSubbands*sizeof(*noise_level_exp));
+            }
+
+            /*
+             *  nrg_gain_max bounded to 1.584893192*1e5, which requires (32-bit) Q14 notation
+             */
+            for (k = 0; k < noSubbands; k++)
+            {
+                if (smooth_length == 0)     /* no filter-smooth needed */
+                {
+                    sb_gain_man = nrg_gain_man[k];
+                    sb_gain_exp = nrg_gain_exp[k];
+
+                    sb_noise_man = noise_level_man[k];
+                    sb_noise_exp = noise_level_exp[k];
+
+                }
+                else
+                {   /* else  smooth_length == 4  and fir_4 filter is being used */
+
+                    sb_gain_exp = fBuf_exp[maxSmoothLength][k];
+
+                    sb_noise_exp = fBufN_exp[maxSmoothLength][k];
+
+                    for (n = maxSmoothLength - smooth_length; n < maxSmoothLength; n++)
+                    {
+                        if (sb_gain_exp  < fBuf_exp[n][k])
+                        {
+                            sb_gain_exp = fBuf_exp[n][k];
+                        }
+
+                        if (sb_noise_exp  < fBufN_exp[n][k])
+                        {
+                            sb_noise_exp = fBufN_exp[n][k];
+                        }
+                    }
+
+                    sb_gain_man = fxp_mul32_Q30(fBuf_man[maxSmoothLength][k], Q30fmt(0.33333333333333f));
+                    sb_gain_man  = sb_gain_man >> (sb_gain_exp - fBuf_exp[maxSmoothLength][k]);
+
+                    sb_noise_man = fxp_mul32_Q30(fBufN_man[maxSmoothLength][k], Q30fmt(0.33333333333333f));
+                    sb_noise_man = sb_noise_man >> (sb_noise_exp - fBufN_exp[maxSmoothLength][k]);
+
+                    n = maxSmoothLength - smooth_length;
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.03183050093751f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.03183050093751f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.11516383427084f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.11516383427084f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.21816949906249f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.21816949906249f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.30150283239582f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.30150283239582f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n][k]);
+
+                }
+
+
+
+                /*
+                 *    *ptrReal  = *ptrReal * sb_gain ;
+                 *    *ptrImag  = *ptrImag * sb_gain;
+                 */
+                aux1 = *ptrReal;
+                aux2 = *ptrImag;
+                sb_gain_exp += 32;
+                aux1 = fxp_mul32_Q31(aux1, sb_gain_man);
+                aux2 = fxp_mul32_Q31(aux2, sb_gain_man);
+
+
+                if (sb_gain_exp < 0)
+                {
+                    sb_gain_exp = -sb_gain_exp;
+                    if (sb_gain_exp < 32)
+                    {
+                        *ptrReal = (aux1 >> sb_gain_exp);
+                        *ptrImag = (aux2 >> sb_gain_exp);
+                    }
+                }
+                else
+                {
+                    *ptrReal = (aux1 << sb_gain_exp);
+                    *ptrImag = (aux2 << sb_gain_exp);
+                }
+
+
+
+                /*
+                 *     if ( sb_noise != 0)
+                 *     {
+                 *         *ptrReal += sb_noise * rP[*phase_index][0];
+                 *         *ptrImag += sb_noise * rP[*phase_index][1];
+                 *     }
+                 */
+                *phase_index = (*phase_index + 1) & 511;
+
+                if (nrg_tone_man[k] || noNoiseFlag)
+                {
+                    sb_noise_man = 0;
+                    sb_noise_exp = 0;
+                }
+                else
+                {
+
+                    Int32 tmp = rPxx[*phase_index];
+                    sb_noise_exp += 1;
+                    tmp_q1 = fxp_mul32_by_16t(sb_noise_man, tmp);
+                    tmp_q2 = fxp_mul32_by_16b(sb_noise_man, tmp);
+
+
+                    if (sb_noise_exp < 0)
+                    {
+                        if (sb_noise_exp > -32)
+                        {
+                            *ptrReal += tmp_q1 >> (-sb_noise_exp);
+                            *ptrImag += tmp_q2 >> (-sb_noise_exp);
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1 << sb_noise_exp;
+                        *ptrImag += tmp_q2 << sb_noise_exp;
+                    }
+                }
+
+                /*
+                 *      tmp_q1 = nrg_tone[k]
+                 */
+
+                tmp_q1 = nrg_tone_man[k];
+
+                if (*harm_index & 1)
+                {
+                    if ((((k + lowSubband) & 1) != 0) ^(*harm_index != 1))
+                    {
+                        *ptrImag  -=  tmp_q1;
+                    }
+                    else
+                    {
+                        *ptrImag  +=  tmp_q1;
+                    }
+                }
+                else
+                {
+                    *ptrReal += (*harm_index) ? -tmp_q1 : tmp_q1;
+                }
+
+                *ptrReal++ <<= 10;
+                *ptrImag++ <<= 10;
+
+
+            }    /*  for-loop (k) */
+
+
+            *harm_index = (*harm_index + 1) & 3;
+
+            /*
+             *  Update smoothing filter history
+             */
+
+            if (filter_history++ < maxSmoothLength)     /* no more update is needed as buffer will have same info */
+            {
+                /*
+                 *  mantissas
+                 */
+
+                ptrReal = (Int32 *)fBuf_man[0];
+                ptrImag = (Int32 *)fBufN_man[0];
+
+                for (n = 0; n < maxSmoothLength; n++)
+                {
+                    fBuf_man[n]  = fBuf_man[n+1];
+                    fBufN_man[n] = fBufN_man[n+1];
+                }
+
+                fBuf_man[maxSmoothLength]  = ptrReal;
+                fBufN_man[maxSmoothLength] = ptrImag;
+
+                /*
+                 *  exponents
+                 */
+                ptrReal = (Int32 *)fBuf_exp[0];
+                ptrImag = (Int32 *)fBufN_exp[0];
+
+                for (n = 0; n < maxSmoothLength; n++)
+                {
+                    fBuf_exp[n]  = fBuf_exp[n+1];
+                    fBufN_exp[n] = fBufN_exp[n+1];
+                }
+
+                fBuf_exp[maxSmoothLength]  = ptrReal;
+                fBufN_exp[maxSmoothLength] = ptrImag;
+            }
+
+        }   /*  for-loop (l) */
+
+
+    }
+    else        /*   ----  if ( band_nrg_tone_detector) ---- */
+    {
+
+        /*
+         *          Application
+         */
+
+        for (l = (frame_info[1+i] << 1); l < (frame_info[2+i] << 1); l++)
+        {
+            ptrReal = (aBufR + l * SBR_NUM_BANDS);
+            ptrImag = (aBufI + l * SBR_NUM_BANDS);
+
+            if (filter_history <= maxSmoothLength)     /* no more update is needed as buffer will have same info */
+            {
+                pv_memmove(fBuf_man[maxSmoothLength], nrg_gain_man, noSubbands*sizeof(*nrg_gain_man));
+                pv_memmove(fBuf_exp[maxSmoothLength], nrg_gain_exp, noSubbands*sizeof(*nrg_gain_exp));
+                pv_memmove(fBufN_man[maxSmoothLength], noise_level_man, noSubbands*sizeof(*noise_level_man));
+                pv_memmove(fBufN_exp[maxSmoothLength], noise_level_exp, noSubbands*sizeof(*noise_level_exp));
+            }
+
+            /*
+             *  nrg_gain_max bounded to 1.584893192*1e5, which requires (32-bit) Q14 notation
+             */
+            for (k = 0; k < noSubbands; k++)
+            {
+                if (smooth_length == 0)     /* no filter-smooth needed */
+                {
+                    sb_gain_man = nrg_gain_man[k];
+                    sb_gain_exp = nrg_gain_exp[k];
+
+                    sb_noise_man = noise_level_man[k];
+                    sb_noise_exp = noise_level_exp[k];
+
+                }
+                else
+                {   /* else  smooth_length == 4  and fir_4 filter is being used */
+
+                    sb_gain_exp = fBuf_exp[maxSmoothLength][k];
+
+                    sb_noise_exp = fBufN_exp[maxSmoothLength][k];
+
+                    for (n = maxSmoothLength - smooth_length; n < maxSmoothLength; n++)
+                    {
+                        if (sb_gain_exp  < fBuf_exp[n][k])
+                        {
+                            sb_gain_exp = fBuf_exp[n][k];
+                        }
+
+                        if (sb_noise_exp  < fBufN_exp[n][k])
+                        {
+                            sb_noise_exp = fBufN_exp[n][k];
+                        }
+                    }
+
+                    sb_gain_man = fxp_mul32_Q30(fBuf_man[maxSmoothLength][k], Q30fmt(0.33333333333333f));
+                    sb_gain_man  = sb_gain_man >> (sb_gain_exp - fBuf_exp[maxSmoothLength][k]);
+
+                    sb_noise_man = fxp_mul32_Q30(fBufN_man[maxSmoothLength][k], Q30fmt(0.33333333333333f));
+                    sb_noise_man = sb_noise_man >> (sb_noise_exp - fBufN_exp[maxSmoothLength][k]);
+
+                    n = maxSmoothLength - smooth_length;
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.03183050093751f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.03183050093751f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.11516383427084f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.11516383427084f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.21816949906249f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.21816949906249f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n++][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBuf_man[n][k], Q30fmt(0.30150283239582f));
+                    sb_gain_man  += tmp_q1 >> (sb_gain_exp - fBuf_exp[n][k]);
+
+                    tmp_q1 = fxp_mul32_Q30(fBufN_man[n][k], Q30fmt(0.30150283239582f));
+                    sb_noise_man += tmp_q1 >> (sb_noise_exp - fBufN_exp[n][k]);
+
+                }
+
+
+
+                /*
+                 *    *ptrReal  = *ptrReal * sb_gain ;
+                 *    *ptrImag  = *ptrImag * sb_gain;
+                 */
+                aux1 = *ptrReal;
+                aux2 = *ptrImag;
+                sb_gain_exp += 32;
+                aux1 = fxp_mul32_Q31(aux1, sb_gain_man);
+                aux2 = fxp_mul32_Q31(aux2, sb_gain_man);
+
+
+
+                /*
+                 *     if ( sb_noise != 0)
+                 *     {
+                 *         *ptrReal += sb_noise * rP[*phase_index][0];
+                 *         *ptrImag += sb_noise * rP[*phase_index][1];
+                 *     }
+                 */
+
+
+                if (sb_gain_exp < 0)
+                {
+                    if (sb_gain_exp > -32)
+                    {
+                        if (sb_gain_exp > -10)
+                        {
+                            *ptrReal = aux1 << (10 + sb_gain_exp);
+                            *ptrImag = aux2 << (10 + sb_gain_exp);
+                        }
+                        else
+                        {
+                            *ptrReal = aux1 >> (-sb_gain_exp - 10);
+                            *ptrImag = aux2 >> (-sb_gain_exp - 10);
+                        }
+                    }
+                }
+                else
+                {
+                    *ptrReal = aux1 << (sb_gain_exp + 10);
+                    *ptrImag = aux2 << (sb_gain_exp + 10);
+                }
+
+
+
+
+                /*
+                 *     if ( sb_noise != 0)
+                 *     {
+                 *         *ptrReal += sb_noise * rP[*phase_index][0];
+                 *         *ptrImag += sb_noise * rP[*phase_index][1];
+                 *     }
+                 */
+                *phase_index = (*phase_index + 1) & 511;
+
+                if (!noNoiseFlag)
+                {
+
+                    Int32 tmp = rPxx[*phase_index];
+                    sb_noise_exp += 1;
+                    tmp_q1 = fxp_mul32_by_16t(sb_noise_man, tmp);
+                    tmp_q2 = fxp_mul32_by_16b(sb_noise_man, tmp);
+
+                    if (sb_noise_exp < 0)
+                    {
+                        if (sb_noise_exp > -32)
+                        {
+                            if (sb_noise_exp > -10)
+                            {
+                                *ptrReal += tmp_q1 << (10 + sb_noise_exp);
+                                *ptrImag += tmp_q2 << (10 + sb_noise_exp);
+                            }
+                            else
+                            {
+                                *ptrReal += tmp_q1 >> (-sb_noise_exp - 10);
+                                *ptrImag += tmp_q2 >> (-sb_noise_exp - 10);
+                            }
+                        }
+                    }
+                    else
+                    {
+                        *ptrReal += tmp_q1 << (sb_noise_exp + 10);
+                        *ptrImag += tmp_q2 << (sb_noise_exp + 10);
+                    }
+                }
+
+                ptrReal++;
+                ptrImag++;
+
+
+            }    /*  for-loop (k) */
+
+
+            *harm_index = (*harm_index + 1) & 3;
+
+            /*
+             *  Update smoothing filter history
+             */
+
+            if (filter_history++ < maxSmoothLength)     /* no more update is needed as buffer will have same info */
+            {
+                /*
+                 *  mantissas
+                 */
+
+                ptrReal = (Int32 *)fBuf_man[0];
+                ptrImag = (Int32 *)fBufN_man[0];
+
+                for (n = 0; n < maxSmoothLength; n++)
+                {
+                    fBuf_man[n]  = fBuf_man[n+1];
+                    fBufN_man[n] = fBufN_man[n+1];
+                }
+
+                fBuf_man[maxSmoothLength]  = ptrReal;
+                fBufN_man[maxSmoothLength] = ptrImag;
+
+                /*
+                 *  exponents
+                 */
+                ptrReal = (Int32 *)fBuf_exp[0];
+                ptrImag = (Int32 *)fBufN_exp[0];
+
+                for (n = 0; n < maxSmoothLength; n++)
+                {
+                    fBuf_exp[n]  = fBuf_exp[n+1];
+                    fBufN_exp[n] = fBufN_exp[n+1];
+                }
+
+                fBuf_exp[maxSmoothLength]  = ptrReal;
+                fBufN_exp[maxSmoothLength] = ptrImag;
+            }
+
+        }   /*  for-loop (l) */
+
+    }       /*  if ( band_nrg_tone_detector) */
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void energy_estimation(Int32 *aBufR,
+                       Int32 *aBufI,
+                       Int32 *nrg_est_man,
+                       Int32 *nrg_est_exp,
+                       const Int32 *frame_info,
+                       Int32 i,
+                       Int32 k,
+                       Int32 c,
+                       Int32 ui2)
+{
+
+    Int32  aux1;
+    Int32  aux2;
+    Int32  l;
+
+
+
+    int64_t nrg_h = 0;
+    Int32 tmp1;
+    Int32 tmp2;
+
+    aux1 = aBufR[ui2*SBR_NUM_BANDS + k];
+    aux2 = aBufI[ui2*SBR_NUM_BANDS + k];
+    for (l = ui2 + 1; l < (frame_info[2+i] << 1);  l++)
+    {
+        nrg_h = fxp_mac64_Q31(nrg_h, aux1, aux1);
+        nrg_h = fxp_mac64_Q31(nrg_h, aux2, aux2);
+        aux1 = aBufR[l*SBR_NUM_BANDS + k];
+        aux2 = aBufI[l*SBR_NUM_BANDS + k];
+    }
+    nrg_h = fxp_mac64_Q31(nrg_h, aux1, aux1);
+    nrg_h = fxp_mac64_Q31(nrg_h, aux2, aux2);
+
+
+    /*
+     *  Check for overflow and saturate if needed
+     */
+    if (nrg_h < 0)
+    {
+        nrg_h = 0x7fffffff;
+    }
+
+    if (nrg_h)
+    {
+
+        aux1 = (UInt32)(nrg_h >> 32);
+        if (aux1)
+        {
+            aux2 = pv_normalize(aux1);
+            if (aux2)
+            {
+                aux2 -= 1;                  /*  ensure Q30 */
+                nrg_h = (nrg_h << aux2) >> 33;
+                tmp2 = (UInt32)(nrg_h);
+                nrg_est_exp[c] = 33 - aux2;
+            }
+            else
+            {
+                tmp2 = (UInt32)(aux1 >> 1);
+                nrg_est_exp[c] = 33 ;
+
+
+            }
+        }
+        else
+        {
+            aux1 = (UInt32)(nrg_h >> 1);
+            aux2 = pv_normalize(aux1);
+
+            tmp2 = (aux1 << aux2);
+            nrg_est_exp[c] =  -aux2 + 1;
+
+
+        }
+
+
+
+        tmp1 = (l - ui2);
+        aux2 = pow2[tmp1];
+        if (tmp1 == (tmp1 & (-tmp1)))
+        {
+            nrg_est_man[c] = tmp2 >> aux2;
+        }
+        else
+        {
+            nrg_est_man[c] = fxp_mul32_by_16(tmp2, aux2);
+        }
+    }
+    else
+    {
+        nrg_est_man[c] = 0;
+        nrg_est_exp[c] = -100;
+    }
+
+
+}
+
+
+
+
+
+#endif
+
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_envelope.h b/media/libstagefright/codecs/aacdec/calc_sbr_envelope.h
new file mode 100644
index 0000000..2a6ae57
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_envelope.h
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: calc_sbr_envelope.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CALCULATE_SBR_ENVELOPE_H
+#define CALCULATE_SBR_ENVELOPE_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "s_sbr_frame_data.h"
+#include    "sbr_generate_high_freq.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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 calc_sbr_envelope(SBR_FRAME_DATA *frameData,
+    Int32 *aBufR,
+    Int32 *aBufI,
+    Int    freqBandTable1[2][MAX_FREQ_COEFFS + 1],
+    const Int32 *nSfb,
+    Int32   freqBandTable2[MAX_NOISE_COEFFS + 1],
+    Int32   nNBands,
+    Int32   reset,
+    Int32 *degreeAlias,
+    Int32 *harm_index,
+    Int32 *phase_index,
+    Int32 hFp[64],
+    Int32 *sUp,
+    Int32 limSbc[][13],
+    Int32 *gateMode,
+#ifdef HQ_SBR
+    Int32 *fBuf_man[64],
+    Int32 *fBuf_exp[64],
+    Int32 *fBufN_man[64],
+    Int32 *fBufN_exp[64],
+#endif
+    Int32 scratch_mem[][64],
+    struct PATCH Patch,
+    Int32  sqrt_cache[][4],
+    Int32  LC_flag);
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif   /*  CALCULATE_SBR_ENVELOPE_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.cpp b/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.cpp
new file mode 100644
index 0000000..e557aa1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.cpp
@@ -0,0 +1,639 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Filename: calc_sbr_synfilterbank.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#ifdef AAC_PLUS
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "calc_sbr_synfilterbank.h"
+#include    "qmf_filterbank_coeff.h"
+#include    "synthesis_sub_band.h"
+#include    "fxp_mul32.h"
+#include    "aac_mem_funcs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+#if defined (PV_ARM_V5)
+
+
+__inline Int16 sat(Int32 y)
+{
+    Int32 x;
+    __asm
+    {
+        qdadd y, y, y
+        mov y, y, asr #16
+    }
+
+    return((Int16)y);
+}
+
+#define saturate2( a, b, c, d)      *c = sat( a);   \
+                                    *d = sat( b);   \
+                                    c += 2;         \
+                                    d -= 2;
+
+
+#elif defined (PV_ARM_V4)
+
+
+__inline Int16 sat(Int32 y)
+{
+    Int32 x;
+    Int32 z = 31; /* rvct compiler problem */
+    __asm
+    {
+        sub y, y, y, asr 2
+        mov y, y, asr N
+        mov x, y, asr #15
+        teq x, y, asr z
+        eorne  y, INT16_MAX, y, asr #31
+    }
+
+    return((Int16)y);
+}
+
+#define saturate2( a, b, c, d)      *c = sat( a);   \
+                                    *d = sat( b);   \
+                                    c += 2;         \
+                                    d -= 2;
+
+#elif defined(PV_ARM_GCC_V5)
+
+__inline Int16 sat(Int32 y)
+{
+    register Int32 x;
+    register Int32 ra = y;
+
+
+    asm volatile(
+        "qdadd %0, %1, %1\n\t"
+        "mov %0, %0, asr #16"
+    : "=&r*i"(x)
+                : "r"(ra));
+
+    return ((Int16)x);
+}
+
+
+#define saturate2( a, b, c, d)      *c = sat( a);   \
+                                    *d = sat( b);   \
+                                    c += 2;         \
+                                    d -= 2;
+
+
+#elif defined(PV_ARM_MSC_EVC_V5)
+
+#include "armintr.h"
+
+#define saturate2( a, b, c, d)      *c = _DAddSatInt( a, a)>>16;   \
+                                    *d = _DAddSatInt( b, b)>>16;   \
+                                    c += 2;         \
+                                    d -= 2;
+
+#else
+
+
+#define   saturate2( a, b, c, d)    a -= (a>>2);                             \
+                                    a  = (a>>N);                     \
+                                    if((a>>15) != (a>>31))                   \
+                                    {                                        \
+                                        a = ((a >> 31) ^ INT16_MAX); \
+                                    }                                        \
+                                    *c = (Int16)a;                           \
+                                    c += 2;                                  \
+                                    b -= (b>>2);                             \
+                                    b =  (b>>N);                      \
+                                    if((b>>15) != (b>>31))                   \
+                                    {                                        \
+                                        b = ((b >> 31) ^ INT16_MAX); \
+                                    }                                        \
+                                    *d = (Int16)b;                           \
+                                    d -= 2;
+
+
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 calc_sbr_synfilterbank_LC(Int32 * Sr,
+                               Int16 * timeSig,
+                               Int16   V[1280],
+                               bool bDownSampleSBR)
+{
+    Int32 i;
+
+    Int32   realAccu1;
+    Int32   realAccu2;
+    const Int32 *pt_C2;
+
+    Int16 *pt_V1;
+    Int16 *pt_V2;
+
+
+    Int16 *pt_timeSig;
+
+    Int16 *pt_timeSig_2;
+    Int32  test1;
+    Int16  tmp1;
+    Int16  tmp2;
+
+    /* shift filterstates */
+
+    Int32 * pt_Sr = Sr;
+
+
+    if (bDownSampleSBR == false)
+    {
+
+        synthesis_sub_band_LC(pt_Sr, V);
+
+        /* content of V[] is at most 16 bits */
+
+        pt_timeSig   = &timeSig[0];
+        pt_timeSig_2 = &timeSig[64];
+
+
+        tmp1 = V[ 704];
+        tmp2 = V[ 768];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(0.853738560F), ROUND_SYNFIL);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.361158990F), realAccu1);
+        tmp1 = -V[ 512];
+        tmp2 =  V[ 960];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.361158990F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(0.070353307F), realAccu1);
+        tmp1 =  V[ 448];
+        tmp2 =  V[1024];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(0.070353307F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.013271822F), realAccu1);
+        tmp1 =  -V[ 256];
+        tmp2 =   V[ 192];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.013271822F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(0.002620176F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(V[1216], Qfmt(0.002620176F), realAccu1);
+
+        tmp1 = V[  32];
+        tmp2 = V[1248];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.000665042F), ROUND_SYNFIL);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.000665042F), realAccu2);
+        tmp1 = V[ 224];
+        tmp2 = V[1056];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.005271576F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.005271576F), realAccu2);
+        tmp1 = V[ 992];
+        tmp2 = V[ 288];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.058591568F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.058591568F), realAccu2);
+        tmp1 = V[ 480];
+        tmp2 = V[ 800];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.058370533F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.058370533F), realAccu2);
+        tmp1 = V[ 736];
+        tmp2 = V[ 544];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.702238872F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.702238872F), realAccu2);
+
+
+
+        saturate2(realAccu1, realAccu2, pt_timeSig, pt_timeSig_2);
+
+        pt_timeSig_2 = &timeSig[126];
+
+        pt_V1 = &V[1];
+        pt_V2 = &V[1279];
+
+        pt_C2 = &sbrDecoderFilterbankCoefficients[0];
+
+        for (i = 31; i != 0; i--)
+        {
+            test1 = *(pt_C2++);
+            tmp1 = *(pt_V1++);
+            tmp2 = *(pt_V2--);
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, ROUND_SYNFIL);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, ROUND_SYNFIL);
+            tmp1 = pt_V1[  191];
+            tmp2 = pt_V2[ -191];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  255];
+            tmp2 = pt_V2[ -255];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  447];
+            tmp2 = pt_V2[ -447];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  511];
+            tmp2 = pt_V2[ -511];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  703];
+            tmp2 = pt_V2[ -703];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  767];
+            tmp2 = pt_V2[ -767];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  959];
+            tmp2 = pt_V2[ -959];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  1023];
+            tmp2 = pt_V2[ -1023];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  1215];
+            tmp2 = pt_V2[ -1215];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            saturate2(realAccu1, realAccu2, pt_timeSig, pt_timeSig_2);
+
+        }
+    }
+    else
+    {
+
+        synthesis_sub_band_LC_down_sampled(Sr, V);
+
+        /*
+         *    window signal
+         *    calculate output samples
+         */
+
+
+        pt_V1 = &V[0];
+        pt_V2 = &V[96];
+
+
+        Int32 * pt_out = Sr;
+
+        for (i = 0; i < 8; i++)
+        {
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+        }
+
+        const Int32* pt_C1 = &sbrDecoderFilterbankCoefficients_down_smpl[0];
+        pt_C2 = &sbrDecoderFilterbankCoefficients_down_smpl[16];
+
+        for (int k = 0; k < 5; k++)
+        {
+            pt_out -= 32;
+            for (i = 0; i < 16; i++)
+            {
+                realAccu1   = fxp_mul_16_by_16bt(*(pt_V1++), *(pt_C1));
+                realAccu2   = fxp_mul_16_by_16bb(*(pt_V1++), *(pt_C1++));
+                realAccu1   = fxp_mac_16_by_16_bt(*(pt_V2++), *(pt_C2), realAccu1);
+                realAccu2   = fxp_mac_16_by_16_bb(*(pt_V2++), *(pt_C2++), realAccu2);
+                *(pt_out++) += realAccu1 >> 5;
+                *(pt_out++) += realAccu2 >> 5;
+
+            }
+            pt_V1 += 96;
+            pt_V2 += 96;
+            pt_C1 += 16;
+            pt_C2 += 16;
+        }
+        pt_out -= 32;
+
+        for (i = 0; i < 32; i++)
+        {
+            timeSig[2*i] = (Int16)((*(pt_out++) + 512) >> 10);
+        }
+
+    }
+
+}
+
+
+
+#ifdef HQ_SBR
+
+void calc_sbr_synfilterbank(Int32 * Sr,
+                            Int32 * Si,
+                            Int16 * timeSig,
+                            Int16   V[1280],
+                            bool bDownSampleSBR)
+{
+    Int32 i;
+
+    const Int32 *pt_C2;
+
+    Int32   realAccu1;
+    Int32   realAccu2;
+
+    Int16 *pt_V1;
+    Int16 *pt_V2;
+
+    Int16 *pt_timeSig;
+
+    Int16 *pt_timeSig_2;
+    Int32  test1;
+    Int16  tmp1;
+    Int16  tmp2;
+
+
+    if (bDownSampleSBR == false)
+    {
+        synthesis_sub_band(Sr, Si, V);
+
+        /* content of V[] is at most 16 bits */
+        pt_timeSig   = &timeSig[0];
+        pt_timeSig_2 = &timeSig[64];
+
+        tmp1 = V[ 704];
+        tmp2 = V[ 768];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(0.853738560F), ROUND_SYNFIL);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.361158990F), realAccu1);
+        tmp1 = -V[ 512];
+        tmp2 =  V[ 960];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.361158990F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(0.070353307F), realAccu1);
+        tmp1 =  V[ 448];
+        tmp2 =  V[1024];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(0.070353307F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.013271822F), realAccu1);
+        tmp1 =  -V[ 256];
+        tmp2 =   V[ 192];
+        realAccu1 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.013271822F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(tmp2, Qfmt(0.002620176F), realAccu1);
+        realAccu1 =  fxp_mac_16_by_16(V[1216], Qfmt(0.002620176F), realAccu1);
+
+        tmp1 = V[  32];
+        tmp2 = V[1248];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.000665042F), ROUND_SYNFIL);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.000665042F), realAccu2);
+        tmp1 = V[ 224];
+        tmp2 = V[1056];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.005271576F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.005271576F), realAccu2);
+        tmp1 = V[ 992];
+        tmp2 = V[ 288];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.058591568F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.058591568F), realAccu2);
+        tmp1 = V[ 480];
+        tmp2 = V[ 800];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(-0.058370533F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(-0.058370533F), realAccu2);
+        tmp1 = V[ 736];
+        tmp2 = V[ 544];
+        realAccu2 =  fxp_mac_16_by_16(tmp1, Qfmt(0.702238872F), realAccu2);
+        realAccu2 =  fxp_mac_16_by_16(tmp2, Qfmt(0.702238872F), realAccu2);
+
+
+        saturate2(realAccu1, realAccu2, pt_timeSig, pt_timeSig_2);
+
+        pt_timeSig_2 = &timeSig[126];
+
+        pt_V1 = &V[1];
+        pt_V2 = &V[1279];
+
+        pt_C2 = &sbrDecoderFilterbankCoefficients[0];
+
+        for (i = 31; i != 0; i--)
+        {
+            test1 = *(pt_C2++);
+            tmp1 = *(pt_V1++);
+            tmp2 = *(pt_V2--);
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, ROUND_SYNFIL);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, ROUND_SYNFIL);
+            tmp1 = pt_V1[  191];
+            tmp2 = pt_V2[ -191];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  255];
+            tmp2 = pt_V2[ -255];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  447];
+            tmp2 = pt_V2[ -447];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  511];
+            tmp2 = pt_V2[ -511];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  703];
+            tmp2 = pt_V2[ -703];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  767];
+            tmp2 = pt_V2[ -767];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  959];
+            tmp2 = pt_V2[ -959];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            test1 = *(pt_C2++);
+            tmp1 = pt_V1[  1023];
+            tmp2 = pt_V2[ -1023];
+            realAccu1 =  fxp_mac_16_by_16_bt(tmp1 , test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bt(tmp2 , test1, realAccu2);
+            tmp1 = pt_V1[  1215];
+            tmp2 = pt_V2[ -1215];
+            realAccu1 =  fxp_mac_16_by_16_bb(tmp1, test1, realAccu1);
+            realAccu2 =  fxp_mac_16_by_16_bb(tmp2, test1, realAccu2);
+
+            saturate2(realAccu1, realAccu2, pt_timeSig, pt_timeSig_2);
+        }
+
+    }
+    else
+    {
+
+        synthesis_sub_band_down_sampled(Sr,  Si,  V);
+
+
+        Int32 * pt_out = Sr;
+
+        for (i = 0; i < 8; i++)
+        {
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+            *(pt_out++) = 0;
+        }
+
+
+        /*
+         *    window signal
+         *    calculate output samples
+         */
+
+        pt_V1 = &V[0];
+        pt_V2 = &V[96];
+
+
+        const Int32* pt_C1 = &sbrDecoderFilterbankCoefficients_down_smpl[0];
+        pt_C2 = &sbrDecoderFilterbankCoefficients_down_smpl[16];
+
+        for (Int k = 0; k < 5; k++)
+        {
+            pt_out -= 32;
+            for (i = 0; i < 16; i++)
+            {
+                realAccu1   = fxp_mul_16_by_16bt(*(pt_V1++), *(pt_C1));
+                realAccu2   = fxp_mul_16_by_16bb(*(pt_V1++), *(pt_C1++));
+                realAccu1   = fxp_mac_16_by_16_bt(*(pt_V2++), *(pt_C2), realAccu1);
+                realAccu2   = fxp_mac_16_by_16_bb(*(pt_V2++), *(pt_C2++), realAccu2);
+                *(pt_out++) += realAccu1 >> 5;
+                *(pt_out++) += realAccu2 >> 5;
+            }
+            pt_V1 += 96;
+            pt_V2 += 96;
+            pt_C1 += 16;
+            pt_C2 += 16;
+        }
+        pt_out -= 32;
+
+        for (i = 0; i < 32; i++)
+        {
+            timeSig[2*i] = (Int16)((*(pt_out++) + 512) >> 10);
+        }
+
+    }
+}
+
+
+#endif      /* --- HQ_SBR --- */
+
+
+#endif      /* --- AAC_PLUS --- */
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.h b/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.h
new file mode 100644
index 0000000..28bd6de
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/calc_sbr_synfilterbank.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CALC_SBR_SYNFILTERBANK_H
+#define CALC_SBR_SYNFILTERBANK_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define N  14
+
+#define ROUND_SYNFIL  (32768 + 4096)
+
+    /*----------------------------------------------------------------------------
+    ; 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 calc_sbr_synfilterbank_LC(Int32 * Sr,
+    Int16 * timeSig,
+    Int16   V[1280],
+    bool bDownSampleSBR);
+
+#ifdef HQ_SBR
+
+
+    void calc_sbr_synfilterbank(Int32 * Sr,
+                                Int32 * Si,
+                                Int16 * timeSig,
+                                Int16   V[1280],
+                                bool bDownSampleSBR);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/chans.h b/media/libstagefright/codecs/aacdec/chans.h
new file mode 100644
index 0000000..325b5cd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/chans.h
@@ -0,0 +1,107 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname:   chans.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed file in the correct template format.
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CHANS_H
+#define CHANS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+    /* #define is required in order to use these args in #if () directive */
+#define ICChans 0
+#define DCChans 0
+#define XCChans 0
+#define CChans  0
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    enum
+    {
+        /*
+         * channels for 5.1 main profile configuration
+         * (modify for any desired decoder configuration)
+         */
+        FChans  = 2,    /* front channels: left, center, right */
+        FCenter = 0,    /* 1 if decoder has front center channel */
+        SChans  = 0,    /* side channels: */
+        BChans  = 0,    /* back channels: left surround, right surround */
+        BCenter = 0,    /* 1 if decoder has back center channel */
+        LChans  = 0,    /* LFE channels */
+        XChans  = 0,    /* scratch space for parsing unused channels */
+
+        Chans   = FChans + SChans + BChans + LChans + XChans
+    };
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CHANS_H */
+
diff --git a/media/libstagefright/codecs/aacdec/check_crc.cpp b/media/libstagefright/codecs/aacdec/check_crc.cpp
new file mode 100644
index 0000000..17f3b87
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/check_crc.cpp
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: check_crc.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    INPUT
+
+
+    OUTPUT
+
+    errorCode, noError if successful
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "check_crc.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 check_crc(HANDLE_CRC hCrcBuf, UInt32 bValue, Int32 nBits)
+{
+    Int32 i;
+    UInt32 bMask = (1UL << (nBits - 1));
+
+    for (i = 0; i < nBits; i++, bMask >>= 1)
+    {
+        UInt16 flag  = (UInt16)((hCrcBuf->crcState & hCrcBuf->crcMask) ? 1 : 0);
+        UInt16 flag1 = (UInt16)((bMask & bValue) ? 1 : 0);
+
+        flag ^= flag1;
+        hCrcBuf->crcState <<= 1;
+        if (flag)
+            hCrcBuf->crcState ^= hCrcBuf->crcPoly;
+    }
+
+}
+
diff --git a/media/libstagefright/codecs/aacdec/check_crc.h b/media/libstagefright/codecs/aacdec/check_crc.h
new file mode 100644
index 0000000..9293d47
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/check_crc.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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Filename: check_crc.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef CHECK_CRC_H
+#define CHECK_CRC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_crc_buffer.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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 check_crc(HANDLE_CRC hCrcBuf,
+    UInt32 bValue,
+    Int32 nBits);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/dct16.cpp b/media/libstagefright/codecs/aacdec/dct16.cpp
new file mode 100644
index 0000000..75bd4ba
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dct16.cpp
@@ -0,0 +1,266 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Filename: dct16.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 16
+
+    Int32 flag           1  forward dct16, 0 modified dct-16
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement dct of lenght 16
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include "dct16.h"
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Qfmt_31(a)   (Int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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 dct_16(Int32 vec[], Int flag)
+{
+    Int32 tmp0;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 tmp3;
+    Int32 tmp4;
+    Int32 tmp5;
+    Int32 tmp6;
+    Int32 tmp7;
+    Int32 tmp_o0;
+    Int32 tmp_o1;
+    Int32 tmp_o2;
+    Int32 tmp_o3;
+    Int32 tmp_o4;
+    Int32 tmp_o5;
+    Int32 tmp_o6;
+    Int32 tmp_o7;
+    Int32 itmp_e0;
+    Int32 itmp_e1;
+    Int32 itmp_e2;
+
+    /*  split input vector */
+
+
+    tmp_o0 = fxp_mul32_by_16((vec[ 0] - vec[15]), Qfmt15(0.50241928618816F));
+    tmp0   =  vec[ 0] + vec[15];
+
+    tmp_o7 = fxp_mul32_Q31((vec[ 7] - vec[ 8]) << 3, Qfmt_31(0.63764357733614F));
+    tmp7   =  vec[ 7] + vec[ 8];
+
+    itmp_e0 = (tmp0 + tmp7);
+    tmp7    = fxp_mul32_by_16((tmp0 - tmp7), Qfmt15(0.50979557910416F));
+
+    tmp_o1 = fxp_mul32_by_16((vec[ 1] - vec[14]), Qfmt15(0.52249861493969F));
+    tmp1   =  vec[ 1] + vec[14];
+    tmp_o6 = fxp_mul32_by_16((vec[ 6] - vec[ 9]) << 1, Qfmt15(0.86122354911916F));
+    tmp6   =  vec[ 6] + vec[ 9];
+
+    itmp_e1 = (tmp1 + tmp6);
+    tmp6    = fxp_mul32_by_16((tmp1 - tmp6), Qfmt15(0.60134488693505F));
+
+    tmp_o2 = fxp_mul32_by_16((vec[ 2] - vec[13]), Qfmt15(0.56694403481636F));
+    tmp2   =  vec[ 2] + vec[13];
+    tmp_o5 = fxp_mul32_by_16((vec[ 5] - vec[10]) << 1, Qfmt15(0.53033884299517F));
+    tmp5   =  vec[ 5] + vec[10];
+
+    itmp_e2 = (tmp2 + tmp5);
+    tmp5    = fxp_mul32_by_16((tmp2 - tmp5), Qfmt15(0.89997622313642F));
+
+    tmp_o3 = fxp_mul32_by_16((vec[ 3] - vec[12]), Qfmt15(0.64682178335999F));
+    tmp3   =  vec[ 3] + vec[12];
+    tmp_o4 = fxp_mul32_by_16((vec[ 4] - vec[11]), Qfmt15(0.78815462345125F));
+    tmp4   =  vec[ 4] + vec[11];
+
+    tmp1   = (tmp3 + tmp4);
+    tmp4   =  fxp_mul32_Q31((tmp3 - tmp4) << 2, Qfmt_31(0.64072886193538F));
+
+    /*  split even part of tmp_e */
+
+    tmp0 = (itmp_e0 + tmp1);
+    tmp1 = fxp_mul32_by_16((itmp_e0 - tmp1), Qfmt15(0.54119610014620F));
+
+
+    tmp3 = fxp_mul32_by_16((itmp_e1 - itmp_e2) << 1, Qfmt15(0.65328148243819F));
+    tmp2 = (itmp_e1 + itmp_e2);
+
+    vec[ 0]  = (tmp0 + tmp2) >> 1;
+    vec[ 8]  = fxp_mul32_by_16((tmp0 - tmp2), Qfmt15(0.70710678118655F));
+    vec[12]  = fxp_mul32_by_16((tmp1 - tmp3) << 1, Qfmt15(0.70710678118655F));
+    vec[ 4]  =  tmp1 + tmp3;
+    vec[ 4] +=  vec[12];
+
+    /*  split odd part of tmp_e */
+
+    tmp1 = fxp_mul32_by_16((tmp7 - tmp4) << 1, Qfmt15(0.54119610014620F));
+    tmp7 += tmp4;
+    tmp3 = fxp_mul32_Q31((tmp6 - tmp5) << 2, Qfmt_31(0.65328148243819F));
+
+    tmp6 += tmp5;
+
+    vec[10]  = fxp_mul32_by_16((tmp7 - tmp6) << 1, Qfmt15(0.70710678118655F));
+    vec[ 2]  =  tmp7 + tmp6;
+    vec[14]  = fxp_mul32_by_16((tmp1 - tmp3) << 1, Qfmt15(0.70710678118655F));
+
+    tmp1    +=  tmp3 + vec[14];
+    vec[ 2] +=  tmp1;
+    vec[ 6]  =  tmp1 + vec[10];
+
+    vec[10] += vec[14];
+
+
+    // dct8;
+
+    tmp7 = tmp_o0 + tmp_o7;
+    tmp_o7 = fxp_mul32_by_16((tmp_o0 - tmp_o7) << 1, Qfmt15(0.50979557910416F));
+
+    tmp6 = tmp_o1 + tmp_o6;
+    tmp_o1 = fxp_mul32_by_16((tmp_o1 - tmp_o6) << 1, Qfmt15(0.60134488693505F));
+
+    tmp5 = tmp_o2 + tmp_o5;
+    tmp_o5 = fxp_mul32_by_16((tmp_o2 - tmp_o5) << 1, Qfmt15(0.89997622313642F));
+
+    tmp4 = tmp_o3 + tmp_o4;
+
+    tmp_o3 = fxp_mul32_Q31((tmp_o3 - tmp_o4) << 3, Qfmt_31(0.6407288619354F));
+
+    if (!flag)
+    {
+        tmp7   = -tmp7;
+        tmp_o7 = -tmp_o7;
+        tmp6   = -tmp6;
+        tmp_o1 = -tmp_o1;
+        tmp5   = -tmp5;
+        tmp_o5 = -tmp_o5;
+        tmp4   = -tmp4;
+        tmp_o3 = -tmp_o3;
+    }
+
+    // even part
+
+    tmp1 = fxp_mul32_by_16((tmp7 - tmp4) << 1, Qfmt15(0.54119610014620F));
+    tmp0 =  tmp7 + tmp4;
+    tmp3 = fxp_mul32_Q31((tmp6 - tmp5) << 2, Qfmt_31(0.65328148243819F));
+    tmp2 =  tmp6 + tmp5;
+
+    vec[ 9]  = fxp_mul32_Q31((tmp0 - tmp2) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 1]  =  tmp0 + tmp2;
+    vec[13]  = fxp_mul32_Q31((tmp1 - tmp3) << 1, Qfmt_31(0.70710678118655F));
+
+    vec[ 5]  =  tmp1 + tmp3 + vec[13];
+
+    // odd part
+
+    tmp0 =  tmp_o7 + tmp_o3;
+    tmp1 = fxp_mul32_by_16((tmp_o7 - tmp_o3) << 1, Qfmt15(0.54119610014620F));
+    tmp2 =  tmp_o1 + tmp_o5;
+    tmp3 = fxp_mul32_Q31((tmp_o1 - tmp_o5) << 2, Qfmt_31(0.65328148243819F));
+
+    vec[11]  = fxp_mul32_Q31((tmp0 - tmp2) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 3]  =  tmp0 + tmp2;
+    vec[15]  = fxp_mul32_Q31((tmp1 - tmp3) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 7]  =  tmp1 + tmp3 + vec[15];
+
+
+    vec[ 3] += vec[ 7];
+    vec[ 7] += vec[11];
+    vec[11] += vec[15];
+
+    vec[ 1] += vec[ 3];
+    vec[ 3] += vec[ 5];
+    vec[ 5] += vec[ 7];
+    vec[ 7] += vec[ 9];
+    vec[ 9] += vec[11];
+    vec[11] += vec[13];
+    vec[13] += vec[15];
+
+
+}
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/dct16.h b/media/libstagefright/codecs/aacdec/dct16.h
new file mode 100644
index 0000000..6f8fcb2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dct16.h
@@ -0,0 +1,68 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/dct16.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef DCT16_H
+#define DCT16_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void dct_16(Int32 vec[], Int flag);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* DCT16_H */
diff --git a/media/libstagefright/codecs/aacdec/dct64.cpp b/media/libstagefright/codecs/aacdec/dct64.cpp
new file mode 100644
index 0000000..a21a814
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dct64.cpp
@@ -0,0 +1,569 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: dct64.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 64
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement dct of lenght 64
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "dct16.h"
+#include "dct64.h"
+
+#include "pv_audio_type_defs.h"
+#include "synthesis_sub_band.h"
+
+#include "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Qfmt(a)   (Int32)(a*((Int32)1<<26) + (a>=0?0.5F:-0.5F))
+#define Qfmt31(a)   (Int32)(a*0x7FFFFFFF)
+
+const Int32 CosTable_48[48] =
+{
+    Qfmt31(0.50015063602065F) ,  Qfmt31(0.50135845244641F) ,
+    Qfmt31(0.50378872568104F) ,  Qfmt31(0.50747117207256F) ,
+    Qfmt31(0.51245147940822F) ,  Qfmt31(0.51879271310533F) ,
+    Qfmt31(0.52657731515427F) ,  Qfmt31(0.53590981690799F) ,
+    Qfmt31(0.54692043798551F) ,  Qfmt31(0.55976981294708F) ,
+    Qfmt31(0.57465518403266F) ,  Qfmt31(0.59181853585742F) ,
+    Qfmt31(0.61155734788251F) ,  Qfmt31(0.63423893668840F) ,
+    Qfmt31(0.66031980781371F) ,  Qfmt31(0.69037212820021F) ,
+    Qfmt31(0.72512052237720F) ,  Qfmt31(0.76549416497309F) ,
+    Qfmt31(0.81270209081449F) ,  Qfmt31(0.86834471522335F) ,
+    Qfmt(0.93458359703641F) ,  Qfmt(1.01440826499705F) ,
+    Qfmt(1.11207162057972F) ,  Qfmt(1.23383273797657F) ,
+    Qfmt(1.38929395863283F) ,  Qfmt(1.59397228338563F) ,
+    Qfmt(1.87467598000841F) ,  Qfmt(2.28205006800516F) ,
+    Qfmt(2.92462842815822F) ,  Qfmt(4.08461107812925F) ,
+    Qfmt(6.79675071167363F) ,  Qfmt(20.37387816723145F) , /* 32 */
+    Qfmt(0.50060299823520F) ,  Qfmt(0.50547095989754F) ,
+    Qfmt(0.51544730992262F) ,  Qfmt(0.53104259108978F) ,
+    Qfmt(0.55310389603444F) ,  Qfmt(0.58293496820613F) ,
+    Qfmt(0.62250412303566F) ,  Qfmt(0.67480834145501F) ,
+    Qfmt(0.74453627100230F) ,  Qfmt(0.83934964541553F) ,
+    Qfmt(0.97256823786196F) ,  Qfmt(1.16943993343288F) ,
+    Qfmt(1.48416461631417F) ,  Qfmt(2.05778100995341F) ,
+    Qfmt(3.40760841846872F) ,  Qfmt(10.19000812354803F)
+};
+
+
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; dct_64
+----------------------------------------------------------------------------*/
+
+void pv_split_LC(Int32 *vector,
+                 Int32 *temp_o)
+{
+
+    Int32 i;
+    Int32 *pt_vector     = &vector[0];
+    Int32 *pt_vector_N_1 = &vector[31];
+    const Int32 *pt_cosTerms = &CosTable_48[32];
+    Int32 *pt_temp_o = temp_o;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 tmp3;
+
+
+    tmp1 = *(pt_vector);
+    tmp2 = *(pt_vector_N_1--);
+    for (i = 16; i != 0; i--)
+    {
+        tmp3 = *(pt_cosTerms++);
+        *(pt_vector++) =   tmp1  + tmp2;
+        *(pt_temp_o++) = fxp_mul32_Q26((tmp1 - tmp2), tmp3);
+        tmp1 = *(pt_vector);
+        tmp2 = *(pt_vector_N_1--);
+    }
+
+}
+
+
+#ifdef HQ_SBR
+
+
+void dct_64(Int32 vec[], Int32 *scratch_mem)
+{
+    Int32 *temp_e1;
+    Int32 *temp_o1;
+
+    Int32 *pt_vec;
+
+    Int   i;
+
+    Int32 aux1;
+    Int32 aux2;
+    Int32 aux3;
+    Int32 aux4;
+
+    const Int32 *cosTerms = &CosTable_48[31];
+
+    temp_o1 = &vec[32];
+    temp_e1 = temp_o1 - 1;
+
+
+    for (i = 6; i != 0; i--)
+    {
+        aux1 = *(temp_e1);
+        aux2 = *(temp_o1);
+        aux3 = *(cosTerms--);
+        *(temp_e1--) =   aux1  + aux2;
+        *(temp_o1++) = fxp_mul32_Q26((aux1 - aux2), aux3);
+        aux1 = *(temp_e1);
+        aux2 = *(temp_o1);
+        aux3 = *(cosTerms--);
+        *(temp_e1--) =   aux1  + aux2;
+        *(temp_o1++) = fxp_mul32_Q26((aux1 - aux2), aux3);
+    }
+
+
+    for (i = 10; i != 0; i--)
+    {
+        aux1 = *(temp_e1);
+        aux2 = *(temp_o1);
+        aux3 = *(cosTerms--);
+        *(temp_e1--) =   aux1  + aux2;
+        *(temp_o1++) = fxp_mul32_Q31((aux1 - aux2), aux3) << 1;
+        aux1 = *(temp_e1);
+        aux2 = *(temp_o1);
+        aux3 = *(cosTerms--);
+        *(temp_e1--) =   aux1  + aux2;
+        *(temp_o1++) = fxp_mul32_Q31((aux1 - aux2), aux3) << 1;
+    }
+
+
+    pv_split(&vec[16]);
+
+    dct_16(&vec[16], 0);
+    dct_16(vec,     1);      // Even terms
+
+    pv_merge_in_place_N32(vec);
+
+    pv_split_z(&vec[32]);
+
+    dct_16(&vec[32], 1);     // Even terms
+    dct_16(&vec[48], 0);
+
+    pv_merge_in_place_N32(&vec[32]);
+
+
+
+    aux1   = vec[32];
+    aux3   = vec[33];
+    aux4   = vec[ 1];  /* vec[ 1] */
+
+    /* -----------------------------------*/
+    aux1     = vec[32] + vec[33];
+    vec[ 0] +=  aux1;
+    vec[ 1] +=  aux1;
+
+    aux1        = vec[34];
+    aux2        = vec[ 2];   /* vec[ 2] */
+    aux3        += aux1;
+    vec[ 2] = aux4 + aux3;
+    aux4        = vec[ 3];  /* vec[ 3] */
+    vec[ 3] = aux2 + aux3;
+
+    aux3        = vec[35];
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[32] = vec[ 4];
+    vec[33] = vec[ 5];
+    vec[ 4] = aux2 + aux1;
+    vec[ 5] = aux4 + aux1;
+
+    aux1        = vec[36];
+    aux2        = vec[32];  /* vec[ 4] */
+    aux3        += aux1;
+    vec[34] = vec[ 6];
+    vec[35] = vec[ 7];
+    vec[ 6] = aux4 + aux3;
+    vec[ 7] = aux2 + aux3;
+
+    aux3        = vec[37];
+    aux4        = vec[33];  /* vec[ 5] */
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[32] = vec[ 8];
+    vec[33] = vec[ 9];
+    vec[ 8] = aux2 + aux1;
+    vec[ 9] = aux4 + aux1;
+
+    aux1        = vec[38];
+    aux2        = vec[34];  /* vec[ 6] */
+    aux3        += aux1;
+    vec[34] = vec[10];
+    vec[10] = aux4 + aux3;
+    aux4        = vec[35];  /* vec[ 7] */
+    vec[35] = vec[11];
+    vec[11] = aux2 + aux3;
+
+    aux3        = vec[39];
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[36] = vec[12];
+    vec[37] = vec[13];
+    vec[12] = aux2 + aux1;
+    vec[13] = aux4 + aux1;
+
+    aux1        = vec[40];
+    aux2        = vec[32];  /* vec[ 8] */
+    aux3        += aux1;
+    vec[32] = vec[14];
+    vec[14] = aux4 + aux3;
+    aux4        = vec[33];  /* vec[ 9] */
+    vec[33] = vec[15];
+    vec[15] = aux2 + aux3;
+
+    aux3        = vec[41];
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[38] = vec[16];
+    vec[39] = vec[17];
+    vec[16] = aux2 + aux1;
+    vec[17] = aux4 + aux1;
+
+    aux1        = vec[42];
+    aux2        = vec[34];  /* vec[10] */
+    aux3        += aux1;
+    vec[34] = vec[18];
+    vec[18] = aux4 + aux3;
+    aux4        = vec[35];  /* vec[11] */
+    vec[35] = vec[19];
+    vec[19] = aux2 + aux3;
+
+    aux3        = vec[43];
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[40] = vec[20];
+    vec[41] = vec[21];
+    vec[20] = aux2 + aux1;
+    vec[21] = aux4 + aux1;
+
+    aux1        = vec[44];
+    aux2        = vec[36];  /* vec[12] */
+    aux3        += aux1;
+    vec[42] = vec[22];
+    vec[43] = vec[23];
+    vec[22] = aux4 + aux3;
+    vec[23] = aux2 + aux3;
+
+    aux3        = vec[45];
+    aux4        = vec[37];  /* vec[13] */
+
+    /* -----------------------------------*/
+
+
+    scratch_mem[0] = vec[24];
+    scratch_mem[1] = vec[25];
+    aux1        += aux3;
+    vec[24] = aux2 + aux1;
+    vec[25] = aux4 + aux1;
+
+    aux1        = vec[46];
+    aux2        = vec[32];  /* vec[14] */
+    scratch_mem[2] = vec[26];
+    scratch_mem[3] = vec[27];
+    aux3        += aux1;
+    vec[26] = aux4 + aux3;
+    vec[27] = aux2 + aux3;
+
+    aux3        = vec[47];
+    aux4        = vec[33];  /* vec[15] */
+
+    /* -----------------------------------*/
+    scratch_mem[4] = vec[28];
+    scratch_mem[5] = vec[29];
+    aux1        += aux3;
+    vec[28] = aux2 + aux1;
+    vec[29] = aux4 + aux1;
+
+    aux1        = vec[48];
+    aux2        = vec[38];  /* vec[16] */
+    scratch_mem[6] = vec[30];
+    scratch_mem[7] = vec[31];
+    aux3        += aux1;
+    vec[30] = aux4 + aux3;
+    vec[31] = aux2 + aux3;
+
+    aux3        = vec[49];
+    aux4        = vec[39];  /* vec[17] */
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[32] = aux2 + aux1;
+    vec[33] = aux4 + aux1;
+
+    aux1        = vec[50];
+    aux2        = vec[34];  /* vec[18] */
+    aux3        += aux1;
+    vec[34] = aux4 + aux3;
+    aux4        = vec[35];  /* vec[19] */
+    vec[35] = aux2 + aux3;
+
+    aux3        = vec[51];
+
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[36] = aux2 + aux1;
+    vec[37] = aux4 + aux1;
+
+    aux1        = vec[52];
+    aux2        = vec[40];  /* vec[20] */
+    aux3        += aux1;
+    vec[38] = aux4 + aux3;
+    vec[39] = aux2 + aux3;
+
+    aux3        = vec[53];
+    aux4        = vec[41];  /* vec[21] */
+
+    /* -----------------------------------*/
+    aux1        += aux3;
+    vec[40] = aux2 + aux1;
+    vec[41] = aux4 + aux1;
+
+    aux1        = vec[54];
+    aux2        = vec[42];  /* vec[22] */
+    aux3        += aux1;
+    vec[42] = aux4 + aux3;
+    aux4        = vec[43];  /* vec[23] */
+    vec[43] = aux2 + aux3;
+
+    aux3        = vec[55];
+
+    /* -----------------------------------*/
+
+    pt_vec = &vec[44];
+    temp_o1 = &vec[56];
+    temp_e1 = &scratch_mem[0];
+
+    for (i = 4; i != 0; i--)
+    {
+        aux1        += aux3;
+        *(pt_vec++) = aux2 + aux1;
+        *(pt_vec++) = aux4 + aux1;
+
+        aux1        = *(temp_o1++);
+        aux3        += aux1;
+        aux2        = *(temp_e1++);
+        *(pt_vec++) = aux4 + aux3;
+        *(pt_vec++) = aux2 + aux3;
+
+        aux3        = *(temp_o1++);
+        aux4        = *(temp_e1++);
+    }
+
+    aux1       += aux3;
+    vec[60] = aux2 + aux1;
+    vec[61] = aux4 + aux1;
+    vec[62] = aux4 + aux3;
+
+}
+
+
+#endif
+
+/*----------------------------------------------------------------------------
+; pv_split
+----------------------------------------------------------------------------*/
+
+
+void pv_split(Int32 *temp_o)
+{
+
+    Int32 i;
+    const Int32 *pt_cosTerms = &CosTable_48[47];
+    Int32 *pt_temp_o = temp_o;
+    Int32 *pt_temp_e = pt_temp_o - 1;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 cosx;
+
+    for (i = 8; i != 0; i--)
+    {
+        tmp2 = *(pt_temp_o);
+        tmp1 = *(pt_temp_e);
+        cosx = *(pt_cosTerms--);
+        *(pt_temp_e--) =   tmp1  + tmp2;
+        *(pt_temp_o++) = fxp_mul32_Q26((tmp1 - tmp2), cosx);
+        tmp1 = *(pt_temp_e);
+        tmp2 = *(pt_temp_o);
+        cosx = *(pt_cosTerms--);
+        *(pt_temp_e--) =   tmp1  + tmp2;
+        *(pt_temp_o++) = fxp_mul32_Q26((tmp1 - tmp2), cosx);
+    }
+}
+
+
+
+void pv_split_z(Int32 *vector)
+{
+    Int32 i;
+    Int32 *pt_vector     = &vector[31];
+    const Int32 *pt_cosTerms = &CosTable_48[32];
+    Int32 *pt_temp_e = vector;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 cosx;
+
+    for (i = 8; i != 0; i--)
+    {
+        tmp1 = *(pt_vector);
+        tmp2 = *(pt_temp_e);
+        cosx = *(pt_cosTerms++);
+        *(pt_temp_e++) =   tmp1  + tmp2;
+        *(pt_vector--) = fxp_mul32_Q26((tmp1 - tmp2), cosx);
+        tmp2 = *(pt_temp_e);
+        tmp1 = *(pt_vector);
+        cosx = *(pt_cosTerms++);
+        *(pt_temp_e++) =   tmp1  + tmp2;
+        *(pt_vector--) = fxp_mul32_Q26((tmp1 - tmp2), cosx);
+    }
+}
+
+
+void pv_merge_in_place_N32(Int32 vec[])
+{
+
+    Int32 temp[4];
+
+    temp[0] = vec[14];
+    vec[14] = vec[ 7];
+    temp[1] = vec[12];
+    vec[12] = vec[ 6];
+    temp[2] = vec[10];
+    vec[10] = vec[ 5];
+    temp[3] = vec[ 8];
+    vec[ 8] = vec[ 4];
+    vec[ 6] = vec[ 3];
+    vec[ 4] = vec[ 2];
+    vec[ 2] = vec[ 1];
+
+    vec[ 1] = vec[16] + vec[17];
+    vec[16] = temp[3];
+    vec[ 3] = vec[18] + vec[17];
+    vec[ 5] = vec[19] + vec[18];
+    vec[18] = vec[9];
+    temp[3] = vec[11];
+
+    vec[ 7] = vec[20] + vec[19];
+    vec[ 9] = vec[21] + vec[20];
+    vec[20] = temp[2];
+    temp[2] = vec[13];
+    vec[11] = vec[22] + vec[21];
+    vec[13] = vec[23] + vec[22];
+    vec[22] = temp[3];
+    temp[3] = vec[15];
+    vec[15] = vec[24] + vec[23];
+    vec[17] = vec[25] + vec[24];
+    vec[19] = vec[26] + vec[25];
+    vec[21] = vec[27] + vec[26];
+    vec[23] = vec[28] + vec[27];
+    vec[25] = vec[29] + vec[28];
+    vec[27] = vec[30] + vec[29];
+    vec[29] = vec[30] + vec[31];
+    vec[24] = temp[1];
+    vec[26] = temp[2];
+    vec[28] = temp[0];
+    vec[30] = temp[3];
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/dct64.h b/media/libstagefright/codecs/aacdec/dct64.h
new file mode 100644
index 0000000..3d5e82b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dct64.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/dct64.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef DCT64_H
+#define DCT64_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+    extern const Int32 CosTable_48[48];
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void pv_split_LC(Int32 *vector,
+                     Int32 *temp_o);
+
+
+#ifdef HQ_SBR
+
+    void dct_64(Int32 vec[], Int32 *scratch_mem);
+
+#endif
+
+    void pv_split(Int32 *temp_o);
+
+    void pv_split_z(Int32 *vector);
+
+    void pv_merge_in_place_N32(Int32 vec[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* DCT64_H */
diff --git a/media/libstagefright/codecs/aacdec/decode_huff_cw_binary.cpp b/media/libstagefright/codecs/aacdec/decode_huff_cw_binary.cpp
new file mode 100644
index 0000000..0d1561b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/decode_huff_cw_binary.cpp
@@ -0,0 +1,708 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/decode_huff_cw_binary.c
+ Funtions:
+    decode_huff_cw_tab1
+    decode_huff_cw_tab2
+    decode_huff_cw_tab3
+    decode_huff_cw_tab4
+    decode_huff_cw_tab5
+    decode_huff_cw_tab6
+    decode_huff_cw_tab7
+    decode_huff_cw_tab8
+    decode_huff_cw_tab9
+    decode_huff_cw_tab10
+    decode_huff_cw_tab11
+    decode_huff_cw_scl
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated per review comments
+              (1) make cw sgined and change "if(cw&0x80000000)" to if(cw<0)
+              (2)
+
+ Description: Create specific functions for different huffman tables.
+
+
+ Description: Added ( Int16) castings to eliminate several compiler warnings
+
+
+ Description: Modified huffman tables to allocate int32 variables instead of
+              int16, which lead to data missaligned for some compiler.
+              Eliminated casting and unused variables
+
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    BITS          *pInputStream = pointer to input bit stream
+
+ Local Stores/Buffers/Pointers Needed:
+
+
+ Global Stores/Buffers/Pointers Needed:
+
+
+ Outputs:
+    idx = bit field extracted from a leaf entry of packed Huffman Tables
+
+ Pointers and Buffers Modified:
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   These functions are used to decode huffman codewords from the input
+   bitstream using combined binary search and look-up table approach.
+
+   First the codewords are grouped and the input symbol is determined
+   which group it belongs. Then within that group, a look-up table is
+   used to determine which codeword the symbol is.
+   The table is created by ordering the codeword in the table according to their
+   normalized shifted binary value, i.e., all the codewords are left
+   shifted to meet the maximum codelength. Example, max codelength is
+   10, the codeword with lenth 3 will left shift by 7.
+   The binary values of after the shift are sorted.
+   Then the sorted table is divided into several partition.
+   At the VLC decoding period, input is read in at max codelenght.
+   The partition is decided using if-else logic.
+   Inside each partition, a look-up table is used to map the input value
+   to a correct symbol. Table entries can appear to be repeated according
+   to the humming distance between adjacent codewords.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) Introduction to Algorithms,
+     Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest.
+     The MIT press, 1990
+
+ (3) "Selecting an Optimal Huffman Decoder for AAC",
+     Vladimir Z. Mesarovic, et al.
+     AES 111th Convention, September 21-24, 2001, New York, USA
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE:
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES:
+
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "huffman.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define    MAX_CW_LEN  (19)
+#define    MASK_IDX    (0x1FF)
+#define    MASK_RIGHT  (0xFE00)
+
+#define    UPPER16      (16)
+#define    MASK_LOW16   (0xFFFF)
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int decode_huff_cw_tab1(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              11,
+              pInputStream);
+    if ((cw >> 10) == 0)
+    {
+        pInputStream->usedBits -= (11 - 1);
+        return 40; /* idx is 40 */
+    }
+    else if ((cw >> 6) <= 23)
+    {
+        tab = (cw >> 6) - 16;
+    }
+    else if ((cw >> 4) <= 119)
+    {
+        tab = (cw >> 4) - 96 + 8;
+    }
+    else if ((cw >> 2) <= 503)
+    {
+        tab = (cw >> 2) - 480 + 32;
+    }
+    else
+    {
+        tab = cw - 2016 + 56;
+    }
+
+    tab = *(huff_tab1 + tab);
+
+    pInputStream->usedBits -= (11 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab2(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get9_n_lessbits(
+              9,
+              pInputStream);
+    if ((cw >> 6) == 0)
+    {
+        pInputStream->usedBits -= (9 - 3); /* used 3 bits */
+        return 40; /* idx is 40 */
+    }
+    else if ((cw >> 3) <= 49)
+    {
+        tab = (cw >> 3) - 8;
+    }
+    else if ((cw >> 2) <= 114)
+    {
+        tab = (cw >> 2) - 100 + 42;
+    }
+    else if ((cw >> 1) <= 248)
+    {
+        tab = (cw >> 1) - 230 + 57;
+    }
+    else
+    {
+        tab = cw - 498 + 76;
+    }
+
+    tab = *(huff_tab2 + tab);
+
+    pInputStream->usedBits -= (9 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab3(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              16,
+              pInputStream);
+    if ((cw >> 15) == 0)
+    {
+        pInputStream->usedBits -= (16 - 1); /* used 1 bits */
+        return 0; /* idx is 0 */
+    }
+    else if ((cw >> 10) <= 57)
+    {
+        tab = (cw >> 10) - 32;
+    }
+    else if ((cw >> 7) <= 500)
+    {
+        tab = (cw >> 7) - 464 + 26;
+    }
+    else if ((cw >> 6) <= 1016)
+    {
+        tab = (cw >> 6) - 1002 + 63;
+    }
+    else if ((cw >> 4) <= 4092)
+    {
+        tab = (cw >> 4) - 4068 + 78;
+    }
+    else
+    {
+        tab = cw - 65488 + 103;
+    }
+
+    tab = *(huff_tab3 + tab);
+
+    pInputStream->usedBits -= (16 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab4(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              12,
+              pInputStream);
+
+    if ((cw >> 7) <= 25)
+    {
+        tab = (cw >> 7);
+    }
+    else if ((cw >> 4) <= 246)
+    {
+        tab = (cw >> 4) - 208 + 26;
+    }
+    else if ((cw >> 2) <= 1017)
+    {
+        tab = (cw >> 2) - 988 + 65;
+    }
+    else
+    {
+        tab = cw - 4072 + 95;
+    }
+
+    tab = *(huff_tab4 + tab);
+
+    pInputStream->usedBits -= (12 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+
+Int decode_huff_cw_tab5(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              13,
+              pInputStream);
+
+    if ((cw >> 12) == 0)
+    {
+        pInputStream->usedBits -= (13 - 1); /* used 1 bits */
+        return 40; /* idx is 40 */
+    }
+    else if ((cw >> 8) <= 27)
+    {
+        tab = (cw >> 8) - 16;
+    }
+    else if ((cw >> 5) <= 243)
+    {
+        tab = (cw >> 5) - 224 + 12;
+    }
+    else if ((cw >> 3) <= 1011)
+    {
+        tab = (cw >> 3) - 976 + 32;
+    }
+    else if ((cw >> 2) <= 2041)
+    {
+        tab = (cw >> 2) - 2024 + 68;
+    }
+    else
+    {
+        tab = cw - 8168 + 86;
+    }
+
+    tab = *(huff_tab5 + tab);
+
+    pInputStream->usedBits -= (13 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+
+Int decode_huff_cw_tab6(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              11,
+              pInputStream);
+
+    if ((cw >> 7) <= 8)
+    {
+        tab = (cw >> 7);
+    }
+    else if ((cw >> 4) <= 116)
+    {
+        tab = (cw >> 4) - 72 + 9;
+    }
+    else if ((cw >> 2) <= 506)
+    {
+        tab = (cw >> 2) - 468 + 54;
+    }
+    else
+    {
+        tab = cw - 2028 + 93;
+    }
+
+    tab = *(huff_tab6 + tab);
+
+    pInputStream->usedBits -= (11 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+
+Int decode_huff_cw_tab7(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              12,
+              pInputStream);
+
+    if ((cw >> 11) == 0)
+    {
+        pInputStream->usedBits -= (12 - 1); /* used 1 bits */
+        return 0; /* idx is 0 */
+    }
+    else if ((cw >> 6) <= 55)
+    {
+        tab = (cw >> 6) - 32;
+    }
+    else if ((cw >> 4) <= 243)
+    {
+        tab = (cw >> 4) - 224 + 24;
+    }
+    else if ((cw >> 2) <= 1018)
+    {
+        tab = (cw >> 2) - 976 + 44;
+    }
+    else
+    {
+        tab = cw - 4076 + 87;
+    }
+
+    tab = *(huff_tab7 + tab);
+
+    pInputStream->usedBits -= (12 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+
+Int decode_huff_cw_tab8(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              10,
+              pInputStream);
+
+    if ((cw >> 5) <= 20)
+    {
+        tab = (cw >> 5);
+    }
+    else if ((cw >> 3) <= 117)
+    {
+        tab = (cw >> 3) - 84 + 21;
+    }
+    else if ((cw >> 2) <= 250)
+    {
+        tab = (cw >> 2) - 236 + 55;
+    }
+    else
+    {
+        tab = cw - 1004 + 70;
+    }
+
+    tab = *(huff_tab8 + tab);
+
+    pInputStream->usedBits -= (10 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab9(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              15,
+              pInputStream);
+
+    if ((cw >> 11) <= 12)
+    {
+        tab = (cw >> 11);
+    }
+    else if ((cw >> 8) <= 114)
+    {
+        tab = (cw >> 8) - 104 + 13;
+    }
+    else if ((cw >> 6) <= 486)
+    {
+        tab = (cw >> 6) - 460 + 24;
+    }
+    else if ((cw >> 5) <= 993)
+    {
+        tab = (cw >> 5) - 974 + 51;
+    }
+    else if ((cw >> 4) <= 2018)
+    {
+        tab = (cw >> 4) - 1988 + 71;
+    }
+    else if ((cw >> 3) <= 4075)
+    {
+        tab = (cw >> 3) - 4038 + 102;
+    }
+    else if ((cw >> 2) <= 8183)
+    {
+        tab = (cw >> 2) - 8152 + 140;
+    }
+    else
+    {
+        tab = cw - 32736 + 172;
+    }
+
+    tab = *(huff_tab9 + tab);
+
+    pInputStream->usedBits -= (15 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab10(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              12,
+              pInputStream);
+
+    if ((cw >> 6) <= 41)
+    {
+        tab = (cw >> 6);
+    }
+    else if ((cw >> 5) <= 100)
+    {
+        tab = (cw >> 5) - 84 + 42;
+    }
+    else if ((cw >> 4) <= 226)
+    {
+        tab = (cw >> 4) - 202 + 59;
+    }
+    else if ((cw >> 3) <= 484)
+    {
+        tab = (cw >> 3) - 454 + 84;
+    }
+    else if ((cw >> 2) <= 1010)
+    {
+        tab = (cw >> 2) - 970 + 115;
+    }
+    else if ((cw >> 1) <= 2043)
+    {
+        tab = (cw >> 1) - 2022 + 156;
+    }
+    else
+    {
+        tab = cw - 4088 + 178;
+    }
+
+    tab = *(huff_tab10 + tab);
+
+    pInputStream->usedBits -= (12 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_cw_tab11(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = get17_n_lessbits(
+              12,
+              pInputStream);
+
+    if ((cw >> 6) <= 26)
+    {
+        tab = (cw >> 6);
+    }
+    else if ((cw >> 5) <= 69)
+    {
+        tab = (cw >> 5) - 54 + 27;
+    }
+    else if ((cw >> 4) <= 198)
+    {
+        tab = (cw >> 4) - 140 + 43;
+    }
+    else if ((cw >> 3) <= 452)
+    {
+        tab = (cw >> 3) - 398 + 102;
+    }
+    else if ((cw >> 2) <= 1000)
+    {
+        tab = (cw >> 2) - 906 + 157;
+    }
+    else if ((cw >> 1) <= 2044)
+    {
+        tab = (cw >> 1) - 2002 + 252;
+    }
+    else
+    {
+        tab = cw - 4090 + 295;
+    }
+
+    tab = *(huff_tab11 + tab);
+
+    pInputStream->usedBits -= (12 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
+
+Int decode_huff_scl(
+    BITS          *pInputStream)
+{
+    Int32  tab;
+    Int32  cw;
+
+    cw  = getbits(
+              19,
+              pInputStream);
+
+    if ((cw >> 18) == 0)
+    {
+        pInputStream->usedBits -= (19 - 1); /* used 1 bits */
+        return 60; /* idx is 60 */
+    }
+    else if ((cw >> 13) <= 59)
+    {
+        tab = (cw >> 13) - 32;
+    }
+    else if ((cw >> 10) <= 505)
+    {
+        tab = (cw >> 10) - 480 + 28;
+    }
+    else if ((cw >> 7) <= 4089)
+    {
+        tab = (cw >> 7) - 4048 + 54;
+    }
+    else if ((cw >> 5) <= 16377)
+    {
+        tab = (cw >> 5) - 16360 + 96;
+    }
+    else if ((cw >> 3) <= 65526)
+    {
+        tab = (cw >> 3) - 65512 + 114;
+    }
+    else if ((cw >> 1) <= 262120)
+    {
+        tab = (cw >> 1) - 262108 + 129;
+    }
+    else
+    {
+        tab = cw - 524242 + 142;
+    }
+
+    tab = *(huff_tab_scl + tab);
+
+    pInputStream->usedBits -= (19 - (tab & MASK_LOW16));
+    return ((Int)(tab >> UPPER16));
+}
+
diff --git a/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.cpp b/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.cpp
new file mode 100644
index 0000000..41cd187
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: decode_noise_floorlevels.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#ifdef AAC_PLUS
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "decode_noise_floorlevels.h"
+#include    "sbr_constants.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 decode_noise_floorlevels(SBR_FRAME_DATA * hFrameData)
+
+{
+    Int32 env;
+    Int32 i;
+
+    Int32 * frameInfo           = hFrameData->frameInfo;
+    Int32   nNfb                = hFrameData->nNfb;
+    Int32 * domain_vec          = hFrameData->domain_vec2;
+
+    Int32 * sbrNoiseFloorLevel_man = hFrameData->sbrNoiseFloorLevel_man;
+    Int32 * prevNoiseLevel_man     = hFrameData->prevNoiseLevel_man;
+
+    Int32 nEnv = frameInfo[(frameInfo[0] << 1) + 3];
+
+    for (env = 0; env < nEnv; env++)
+    {
+        if (domain_vec[env] == 0)
+        {
+            prevNoiseLevel_man[0] = *(sbrNoiseFloorLevel_man++);
+
+            for (i = 1; i < nNfb; i++)
+            {
+                *sbrNoiseFloorLevel_man += *(sbrNoiseFloorLevel_man - 1);
+                prevNoiseLevel_man[i] = *(sbrNoiseFloorLevel_man++);
+            }
+        }
+        else
+        {
+            for (i = 0; i < nNfb; i++)
+            {
+                *sbrNoiseFloorLevel_man += prevNoiseLevel_man[i];
+                prevNoiseLevel_man[i] = *(sbrNoiseFloorLevel_man++);
+            }
+        }
+
+    }
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.h b/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.h
new file mode 100644
index 0000000..a9c3551
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/decode_noise_floorlevels.h
@@ -0,0 +1,92 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: decode_noise_floorlevels.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DECODENOISEFLOORLEVELS_H
+#define DECODENOISEFLOORLEVELS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void decode_noise_floorlevels(SBR_FRAME_DATA * hFrameData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/deinterleave.cpp b/media/libstagefright/codecs/aacdec/deinterleave.cpp
new file mode 100644
index 0000000..5298b19
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/deinterleave.cpp
@@ -0,0 +1,287 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/deinterleave.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description: (1) Modified with new template, rename variables
+              (2) Removed for-loop to calculate win_inc, win_inc = SN2 (128)
+              (3) Replaced for-loop with memcpy
+              (4) Converted Int16 -> Int
+
+ Description: Modified per review comments
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    interleaved   = input array that contains interleaved coefficients
+                    Data Type Int
+
+    deinterleaved = output array that will be updated with de-interleaved
+                    coefficients of input array. Data Type Int
+
+    pFrameInfo = pointer to structure that holds information of current
+                 frame. Data Type FrameInfo
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    deinterleaved  contents updated with de-interleaved coefficients from
+                   the input array: interleaved
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the deinterleaving across all short windows in
+ each group
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should replace the contents of pDeinterleaved with the
+ de-interleaved 1024 coefficients of one frame
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4           p78     quant_to_spec
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pInterleaved   = interleaved;
+    pDeinterleaved = deinterleaved;
+
+    pSfbPerWin  = pFrameInfo->sfb_per_win;
+    ngroups     = pFrameInfo->num_groups;
+    pGroupLen   = pFrameInfo->group_len;
+
+    pGroup = pDeinterleaved;
+
+    FOR (group = ngroups; group > 0; group--)
+
+        pSfbWidth   = pFrameInfo->sfb_width_128;
+        sfb_inc = 0;
+        pStart = pInterleaved;
+
+        FOR (sfb = pSfbPerWin[ngroups-group]; sfb > 0; sfb--)
+
+            pWin = pGroup;
+
+            FOR (win = pGroupLen[ngroups-group]; win > 0; win--)
+
+                pDeinterleaved = pWin + sfb_inc;
+
+                pv_memcpy(
+                     pDeinterleaved,
+                     pInterleaved,
+                    *pSfbWidth*sizeof(*pInterleaved));
+
+                pInterleaved += *pSfbWidth;
+
+                pWin += SN2;
+
+            ENDFOR (win)
+
+            sfb_inc += *pSfbWidth++;
+
+        ENDFOR (sfb)
+
+    pGroup += (pInterleaved - pStart);
+
+    ENDFOR (group)
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "huffman.h"
+#include    "aac_mem_funcs.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 deinterleave(
+    Int16        interleaved[],
+    Int16        deinterleaved[],
+    FrameInfo   *pFrameInfo)
+{
+
+    Int      group;  /* group index */
+    Int      sfb;    /* scalefactor band index */
+    Int      win;    /* window index */
+    Int16    *pGroup;
+    Int16    *pWin;
+    Int16    *pStart;
+    Int16    *pInterleaved;
+    Int16    *pDeinterleaved;
+    Int      sfb_inc;
+
+    Int      ngroups;
+    Int     *pGroupLen;
+    Int     *pSfbPerWin;
+    Int     *pSfbWidth;
+
+    pInterleaved   = interleaved;
+    pDeinterleaved = deinterleaved;
+
+    pSfbPerWin  = pFrameInfo->sfb_per_win;
+    ngroups     = pFrameInfo->num_groups;
+    pGroupLen   = pFrameInfo->group_len;
+
+    pGroup = pDeinterleaved;
+
+    for (group = ngroups; group > 0; group--)
+    {
+        pSfbWidth   = pFrameInfo->sfb_width_128;
+        sfb_inc = 0;
+        pStart = pInterleaved;
+
+        /* Perform the deinterleaving across all windows in a group */
+
+        for (sfb = pSfbPerWin[ngroups-group]; sfb > 0; sfb--)
+        {
+            pWin = pGroup;
+
+            for (win = pGroupLen[ngroups-group]; win > 0; win--)
+            {
+                pDeinterleaved = pWin + sfb_inc;
+
+                pv_memcpy(
+                    pDeinterleaved,
+                    pInterleaved,
+                    *pSfbWidth*sizeof(*pInterleaved));
+
+                pInterleaved += *pSfbWidth;
+
+                pWin += SN2;
+
+            } /* for (win) */
+
+            sfb_inc += *pSfbWidth++;
+
+        } /* for (sfb) */
+
+        pGroup += (pInterleaved - pStart);
+
+    } /* for (group) */
+
+} /* deinterleave */
diff --git a/media/libstagefright/codecs/aacdec/digit_reversal_tables.cpp b/media/libstagefright/codecs/aacdec/digit_reversal_tables.cpp
new file mode 100644
index 0000000..ffa980d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/digit_reversal_tables.cpp
@@ -0,0 +1,279 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/digit_reversal_tables.c
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+  ------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+  Tables for digit reverse operation
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "digit_reversal_tables.h"
+#include "imdct_fxp.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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ Digit Reverse tables
+------------------------------------------------------------------------------
+*/
+
+const Int16 digit_reverse_64[ 64] =
+{
+    + 0,  + 32,  + 64,  + 96,
+    + 8,  + 40,  + 72, + 104,
+    + 16,  + 48,  + 80, + 112,
+    + 24,  + 56,  + 88, + 120,
+    + 2,  + 34,  + 66,  + 98,
+    + 10,  + 42,  + 74, + 106,
+    + 18,  + 50,  + 82, + 114,
+    + 26,  + 58,  + 90, + 122,
+    + 4,  + 36,  + 68, + 100,
+    + 12,  + 44,  + 76, + 108,
+    + 20,  + 52,  + 84, + 116,
+    + 28,  + 60,  + 92, + 124,
+    + 6,  + 38,  + 70, + 102,
+    + 14,  + 46,  + 78, + 110,
+    + 22,  + 54,  + 86, + 118,
+    + 30,  + 62,  + 94, + 126
+};
+
+
+const Int16 digit_reverse_256[ 256] =
+{
+    + 0, + 128, + 256, + 384,
+    + 32, + 160, + 288, + 416,
+    + 64, + 192, + 320, + 448,
+    + 96, + 224, + 352, + 480,
+    + 8, + 136, + 264, + 392,
+    + 40, + 168, + 296, + 424,
+    + 72, + 200, + 328, + 456,
+    + 104, + 232, + 360, + 488,
+    + 16, + 144, + 272, + 400,
+    + 48, + 176, + 304, + 432,
+    + 80, + 208, + 336, + 464,
+    + 112, + 240, + 368, + 496,
+    + 24, + 152, + 280, + 408,
+    + 56, + 184, + 312, + 440,
+    + 88, + 216, + 344, + 472,
+    + 120, + 248, + 376, + 504,
+    + 2, + 130, + 258, + 386,
+    + 34, + 162, + 290, + 418,
+    + 66, + 194, + 322, + 450,
+    + 98, + 226, + 354, + 482,
+    + 10, + 138, + 266, + 394,
+    + 42, + 170, + 298, + 426,
+    + 74, + 202, + 330, + 458,
+    + 106, + 234, + 362, + 490,
+    + 18, + 146, + 274, + 402,
+    + 50, + 178, + 306, + 434,
+    + 82, + 210, + 338, + 466,
+    + 114, + 242, + 370, + 498,
+    + 26, + 154, + 282, + 410,
+    + 58, + 186, + 314, + 442,
+    + 90, + 218, + 346, + 474,
+    + 122, + 250, + 378, + 506,
+    + 4, + 132, + 260, + 388,
+    + 36, + 164, + 292, + 420,
+    + 68, + 196, + 324, + 452,
+    + 100, + 228, + 356, + 484,
+    + 12, + 140, + 268, + 396,
+    + 44, + 172, + 300, + 428,
+    + 76, + 204, + 332, + 460,
+    + 108, + 236, + 364, + 492,
+    + 20, + 148, + 276, + 404,
+    + 52, + 180, + 308, + 436,
+    + 84, + 212, + 340, + 468,
+    + 116, + 244, + 372, + 500,
+    + 28, + 156, + 284, + 412,
+    + 60, + 188, + 316, + 444,
+    + 92, + 220, + 348, + 476,
+    + 124, + 252, + 380, + 508,
+    + 6, + 134, + 262, + 390,
+    + 38, + 166, + 294, + 422,
+    + 70, + 198, + 326, + 454,
+    + 102, + 230, + 358, + 486,
+    + 14, + 142, + 270, + 398,
+    + 46, + 174, + 302, + 430,
+    + 78, + 206, + 334, + 462,
+    + 110, + 238, + 366, + 494,
+    + 22, + 150, + 278, + 406,
+    + 54, + 182, + 310, + 438,
+    + 86, + 214, + 342, + 470,
+    + 118, + 246, + 374, + 502,
+    + 30, + 158, + 286, + 414,
+    + 62, + 190, + 318, + 446,
+    + 94, + 222, + 350, + 478,
+    + 126, + 254, + 382, + 510
+};
+
+
+
+
+const Int16 digit_reverse_swap_256[ 241] =
+{
+    + 2, + 128,   + 4, + 256,
+    + 6, + 384,   + 8,  + 32,
+    + 10, + 160,  + 12, + 288,
+    + 14, + 416,  + 16,  + 64,
+    + 18, + 192,  + 20, + 320,
+    + 22, + 448,  + 24,  + 96,
+    + 26, + 224,  + 28, + 352,
+    + 30, + 480,  + 34, + 136,
+    + 36, + 264,  + 38, + 392,
+    + 42, + 168,  + 44, + 296,
+    + 46, + 424,  + 48,  + 72,
+    + 50, + 200,  + 52, + 328,
+    + 54, + 456,  + 56, + 104,
+    + 58, + 232,  + 60, + 360,
+    + 62, + 488,  + 66, + 144,
+    + 68, + 272,  + 70, + 400,
+    + 74, + 176,  + 76, + 304,
+    + 78, + 432,  + 82, + 208,
+    + 84, + 336,  + 86, + 464,
+    + 88, + 112,  + 90, + 240,
+    + 92, + 368,  + 94, + 496,
+    + 98, + 152, + 100, + 280,
+    + 102, + 408, + 106, + 184,
+    + 108, + 312, + 110, + 440,
+    + 114, + 216, + 116, + 344,
+    + 118, + 472, + 122, + 248,
+    + 124, + 376, + 126, + 504,
+    + 132, + 258, + 134, + 386,
+    + 138, + 162, + 140, + 290,
+    + 142, + 418, + 146, + 194,
+    + 148, + 322, + 150, + 450,
+    + 154, + 226, + 156, + 354,
+    + 158, + 482, + 164, + 266,
+    + 166, + 394, + 172, + 298,
+    + 174, + 426, + 178, + 202,
+    + 180, + 330, + 182, + 458,
+    + 186, + 234, + 188, + 362,
+    + 190, + 490, + 196, + 274,
+    + 198, + 402, + 204, + 306,
+    + 206, + 434, + 212, + 338,
+    + 214, + 466, + 218, + 242,
+    + 220, + 370, + 222, + 498,
+    + 228, + 282, + 230, + 410,
+    + 236, + 314, + 238, + 442,
+    + 244, + 346, + 246, + 474,
+    + 252, + 378, + 254, + 506,
+    + 262, + 388, + 268, + 292,
+    + 270, + 420, + 276, + 324,
+    + 278, + 452, + 284, + 356,
+    + 286, + 484, + 294, + 396,
+    + 302, + 428, + 308, + 332,
+    + 310, + 460, + 316, + 364,
+    + 318, + 492, + 326, + 404,
+    + 334, + 436, + 342, + 468,
+    + 348, + 372, + 350, + 500,
+    + 358, + 412, + 366, + 444,
+    + 374, + 476, + 382, + 508,
+    + 398, + 422, + 406, + 454,
+    + 414, + 486, + 438, + 462,
+    + 446, + 494, + 478, + 502
+};
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void digit_reversal_swapping(Int32 *y, Int32 *x);
+
+#ifdef __cplusplus
+}
+#endif
+
+void digit_reversal_swapping(Int32 *y, Int32 *x)
+{
+    Int16 i, j;
+    Int32 tmp[2];
+    const Int16 *pTable;
+
+    pTable = digit_reverse_swap_256;
+
+    for (Int k = 120; k != 0; k--)
+    {
+        i = *pTable++;
+        j = *pTable++;
+        tmp[0] = y[i];
+        tmp[1] = y[i+1];
+        y[i]   = y[j];
+        y[i+1] = y[j+1];
+        y[j]   = tmp[0];
+        y[j+1] = tmp[1];
+
+        tmp[0] = x[j];
+        tmp[1] = x[j+1];
+        x[j]   = x[i];
+        x[j+1] = x[i+1];
+        x[i]   = tmp[0];
+        x[i+1] = tmp[1];
+
+    }
+
+}
diff --git a/media/libstagefright/codecs/aacdec/digit_reversal_tables.h b/media/libstagefright/codecs/aacdec/digit_reversal_tables.h
new file mode 100644
index 0000000..7fdaaf7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/digit_reversal_tables.h
@@ -0,0 +1,86 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/DIGIT_REVERSAL_TABLES.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions digit_reversal_tables
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DIGIT_REVERSAL_TABLES_H
+#define DIGIT_REVERSAL_TABLES_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 Int16 digit_reverse_64[];
+extern const Int16 digit_reverse_256[];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* DIGIT_REVERSAL_TABLES_H */
diff --git a/media/libstagefright/codecs/aacdec/dst16.cpp b/media/libstagefright/codecs/aacdec/dst16.cpp
new file mode 100644
index 0000000..41c9259
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst16.cpp
@@ -0,0 +1,172 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: dst16.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 16
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement discrete sine transform of lenght 16
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include "dst16.h"
+#include "dst8.h"
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+#define R_SHIFT     28
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+const Int32 CosTable_8[8] =
+{
+    Qfmt(0.50241928618816F),   Qfmt(0.52249861493969F),
+    Qfmt(0.56694403481636F),   Qfmt(0.64682178335999F),
+    Qfmt(0.78815462345125F),   Qfmt(1.06067768599035F),
+    Qfmt(1.72244709823833F),   Qfmt(5.10114861868916F)
+};
+
+/*----------------------------------------------------------------------------
+; 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 dst_16(Int32 vec[], Int32 scratch_mem[])     /* scratch_mem size 8 */
+{
+    Int32 *temp_even = scratch_mem;
+
+    Int i;
+    const Int32 *pt_cos = &CosTable_8[7];
+    Int32 tmp0 = vec[15] >> 1;
+    Int32 tmp1, tmp2;
+    Int32 *pt_even = temp_even;
+    Int32 *pt_odd  = vec;
+    Int32 *pt_vec  = vec;
+    Int32 *pt_vecN_1;
+    Int32 tmp3;
+
+
+    *(pt_even++) = *(pt_vec++);
+    tmp1         = *(pt_vec++);
+    *(pt_odd++) = tmp1;
+
+    for (i = 3; i != 0; i--)
+    {
+        *(pt_even++) = *(pt_vec++);
+        tmp2         = *(pt_vec++);
+        *(pt_even++) = *(pt_vec++);
+        tmp3         = *(pt_vec++);
+        *(pt_odd++) = tmp2 + tmp1;
+        *(pt_odd++) = tmp3 + tmp2;
+        tmp1         = tmp3;
+
+    }
+
+    *(pt_even)   = *(pt_vec++);
+    *(pt_odd++) = *(pt_vec) + tmp1;
+
+
+    dst_8(temp_even);
+    dst_8(vec);
+
+    pt_vec  = &vec[7];
+
+    pt_even = &temp_even[7];
+    pt_vecN_1  = &vec[8];
+
+    tmp1 = *(pt_even--);
+
+    for (i = 4; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q28((*(pt_vec) - tmp0), *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vec--)     = tmp3 + tmp1;
+        *(pt_vecN_1++)  = tmp3 - tmp1;
+        tmp3  = fxp_mul32_Q28((*(pt_vec) + tmp0), *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp3 - tmp2;
+        *(pt_vec--)     = tmp3 + tmp2;
+    }
+
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/dst16.h b/media/libstagefright/codecs/aacdec/dst16.h
new file mode 100644
index 0000000..bce73ba
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst16.h
@@ -0,0 +1,68 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/dst16.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef DST16_H
+#define DST16_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void dst_16(Int32 vec[], Int32 scratch_mem[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* DST16_H */
diff --git a/media/libstagefright/codecs/aacdec/dst32.cpp b/media/libstagefright/codecs/aacdec/dst32.cpp
new file mode 100644
index 0000000..5edecf1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst32.cpp
@@ -0,0 +1,200 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: dst32.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 32
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement discrete sine transform of lenght 32
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "dst32.h"
+#include "dst16.h"
+
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+#define R_SHIFT1     29
+#define Qfmt29(x)   (Int32)(x*((Int32)1<<R_SHIFT1) + (x>=0?0.5F:-0.5F))
+#define Qfmt31(a)   (Int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+const Int32 CosTable_16[14] =
+{
+    Qfmt31(0.50060299823520F),   Qfmt31(0.50547095989754F),
+    Qfmt31(0.51544730992262F),   Qfmt31(0.53104259108978F),
+    Qfmt31(0.55310389603444F),   Qfmt31(0.58293496820613F),
+    Qfmt31(0.62250412303566F),   Qfmt31(0.67480834145501F),
+    Qfmt31(0.74453627100230F),   Qfmt31(0.83934964541553F),
+    Qfmt29(0.97256823786196F),   Qfmt29(1.16943993343288F),
+    Qfmt29(1.48416461631417F),   Qfmt29(2.05778100995341F)
+};
+
+/*----------------------------------------------------------------------------
+; 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 dst_32(Int32 vec[], Int32 scratch_mem[])   /* scratch_mem size 32 */
+{
+    Int32 *temp_even = scratch_mem;
+
+    Int32 i;
+    const Int32 *pt_cos = &CosTable_16[13];
+    Int32 tmp0 = vec[31] >> 1;
+    Int32 tmp1, tmp2;
+    Int32 *pt_even = temp_even;
+    Int32 *pt_odd  = vec;
+    Int32 *pt_vec  = vec;
+    Int32 *pt_vecN_1  = vec;
+    Int32 tmp3;
+
+
+    tmp1 = 0;
+
+    for (i = 5; i != 0; i--)
+    {
+        *(pt_even++) = *(pt_vec++);
+        tmp2         = *(pt_vec++);
+        *(pt_even++) = *(pt_vec++);
+        tmp3         = *(pt_vec++);
+        *(pt_even++) = *(pt_vec++);
+        *(pt_odd++) = tmp2 + tmp1;
+        *(pt_odd++) = tmp3 + tmp2;
+        tmp1         = *(pt_vec++);
+        *(pt_odd++) = tmp1 + tmp3;
+    }
+
+    *(pt_even) = *(pt_vec++);
+    *(pt_odd)  = *(pt_vec) + tmp1;
+
+
+    dst_16(temp_even, &scratch_mem[16]);
+    dst_16(vec, &scratch_mem[24]);
+
+
+    pt_vecN_1  = &vec[16];
+
+    tmp1 = temp_even[15];
+
+    tmp3  = fxp_mul32_Q31((vec[15] - tmp0) << 3, Qfmt31(0.63687550772175F)) << 2;
+    tmp2  = temp_even[14];
+    *(pt_vecN_1++)  = tmp3 - tmp1;
+    vec[15]         = tmp3 + tmp1;
+    tmp1  = temp_even[13];
+    tmp3  = fxp_mul32_Q31((vec[14] + tmp0) << 3, Qfmt31(0.85190210461718F));
+    *(pt_vecN_1++)  = tmp3 - tmp2;
+    vec[14]         = tmp3 + tmp2;
+
+    pt_even = &temp_even[12];
+    pt_vec  = &vec[13];
+
+    for (i = 2; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q29((*(pt_vec) - tmp0), *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vec--)     = tmp3 + tmp1;
+        *(pt_vecN_1++)  = tmp3 - tmp1;
+        tmp3  = fxp_mul32_Q29((*(pt_vec) + tmp0), *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vec--)     = tmp3 + tmp2;
+        *(pt_vecN_1++)  = tmp3 - tmp2;
+    }
+
+    for (i = 5; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q31((*(pt_vec) - tmp0) << 1, *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vec--)     = tmp3 + tmp1;
+        *(pt_vecN_1++)  = tmp3 - tmp1;
+        tmp3  = fxp_mul32_Q31((*(pt_vec) + tmp0) << 1, *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vec--)     = tmp3 + tmp2;
+        *(pt_vecN_1++)  = tmp3 - tmp2;
+    }
+
+
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/dst32.h b/media/libstagefright/codecs/aacdec/dst32.h
new file mode 100644
index 0000000..c2bf1d2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst32.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/dst32.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef DST32_H
+#define DST32_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+    extern const Int32 CosTable_16[];
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void dst_32(Int32 vec[], Int32 scratch_mem[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* DST32_H */
diff --git a/media/libstagefright/codecs/aacdec/dst8.cpp b/media/libstagefright/codecs/aacdec/dst8.cpp
new file mode 100644
index 0000000..eaf8280
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst8.cpp
@@ -0,0 +1,179 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: dst8.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 8
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement discrete sine transform of lenght 8
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "dst8.h"
+
+#include "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+#define R_SHIFT     29
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt31(x)   (Int32)(x*0x7FFFFFFF + (x>=0?0.5F:-0.5F))
+
+
+void dst_8(Int32 vec[])
+{
+
+    Int32 temp1;
+    Int32 temp2;
+    Int32 temp3;
+    Int32 temp4;
+    Int32 temp5;
+    Int32 temp6;
+    Int32 temp7;
+    Int32 tmp_a;
+    Int32 tmp_aa;
+    Int32 tmp_b;
+    Int32 tmp_bb;
+    Int32 tmp_c;
+    Int32 tmp_cc;
+    Int32 tmp_d;
+    Int32 tmp_dd;
+
+    temp1 = fxp_mul32_by_16(vec[1], Qfmt15(0.50979557910416F));         /* (1/(2*cos(  phi)));*/
+    temp2 = fxp_mul32_by_16(vec[2], Qfmt15(0.54119610014620F));         /* (1/(2*cos(2*phi)));*/
+    temp3 = fxp_mul32_by_16(vec[3], Qfmt15(0.60134488693505F));         /* (1/(2*cos(3*phi)));*/
+    temp5 = fxp_mul32_by_16(vec[5], Qfmt15(0.89997622313642F));         /* (1/(2*cos(5*phi)));*/
+    temp6 = fxp_mul32_by_16(vec[6] << 1, Qfmt15(0.65328148243819F));        /* (1/(2*cos(6*phi)));*/
+    temp7 = vec[7] + fxp_mul32_Q31(vec[7], Qfmt31(0.56291544774152F));          /* (1/(2*cos(7*phi)));*/
+
+    /*  even  */
+    tmp_a = fxp_mul32_Q31((temp2 + temp6) << 1, Qfmt31(0.70710678118655F));
+    tmp_b = (temp2 - temp6) + tmp_a;
+
+    temp4 = fxp_mul32_by_16(vec[4], Qfmt15(0.70710678118655F));
+    vec[0] =   tmp_a + temp4;
+    vec[1] =   tmp_b + temp4;
+    vec[2] =   tmp_b - temp4;
+    vec[3] =   tmp_a - temp4;
+
+
+    /* odd */
+
+    tmp_a  = fxp_mul32_by_16((temp1 + temp7) << 1, Qfmt15(0.54119610014620F));  /* (1/(2*cos(2*phi)));  */
+    tmp_aa = (temp1 - temp7);
+    tmp_bb = (temp5 - temp3);
+    temp5  = fxp_mul32_Q29((temp5 + temp3), Qfmt(1.30656296487638F));   /* (1/(2*cos(6*phi)));  */
+
+
+    tmp_c  = fxp_mul32_by_16((tmp_a + temp5) << 1, Qfmt15(0.70710678118655F));
+    tmp_cc =  tmp_a - temp5;
+
+    tmp_d  = fxp_mac32_by_16((tmp_aa - tmp_bb) << 1, Qfmt15(0.70710678118655F), tmp_c);
+    tmp_dd = (tmp_aa + tmp_bb);
+
+    tmp_dd +=  tmp_c;
+    tmp_a   =  tmp_d  + tmp_cc;
+    vec[5]  =  tmp_a  - vec[2];
+    vec[2] +=  tmp_a;
+
+    temp5   =  tmp_dd + tmp_cc;
+
+    vec[4]  =  temp5  - vec[3];
+    vec[3] +=  temp5;
+    vec[7]  =  tmp_c  - vec[0];
+    vec[0] +=  tmp_c;
+    vec[6]  =  tmp_d  - vec[1];
+    vec[1] +=  tmp_d;
+
+}
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/dst8.h b/media/libstagefright/codecs/aacdec/dst8.h
new file mode 100644
index 0000000..2738e80
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/dst8.h
@@ -0,0 +1,68 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/dst8.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef DST8_H
+#define DST8_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void dst_8(Int32 vec[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* DST8_H */
diff --git a/media/libstagefright/codecs/aacdec/e_adif_const.h b/media/libstagefright/codecs/aacdec/e_adif_const.h
new file mode 100644
index 0000000..08b5415
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_adif_const.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_ADIF_Const.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for ADIF header related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_ADIF_CONST_H
+#define E_ADIF_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /*
+     * audio data interchange format header
+     */
+    LEN_ADIF_ID     = (32 / 8),
+    LEN_COPYRT_PRES = 1,
+    LEN_COPYRT_ID   = (72 / 8),
+    LEN_ORIG        = 1,
+    LEN_HOME        = 1,
+    LEN_BS_TYPE     = 1,
+    LEN_BIT_RATE    = 23,
+    LEN_NUM_PCE     = 4,
+    LEN_ADIF_BF     = 20
+
+} eADIF_Const;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_blockswitching.h b/media/libstagefright/codecs/aacdec/e_blockswitching.h
new file mode 100644
index 0000000..bf6ad15
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_blockswitching.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_BlockSwitching.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for BlockSwitching related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_BLOCK_SWITCHING_H
+#define E_BLOCK_SWITCHING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /*
+     * block switching
+     */
+    LN          = 2048,
+    SN          = 256,
+    LN2         = LN / 2,
+    SN2         = SN / 2,
+    LN4         = LN / 4,
+    SN4         = SN / 4,
+    NSHORT      = LN / SN,
+    MAX_SBK     = NSHORT,
+    MAX_WIN     = MAX_SBK,
+
+    ONLY_LONG_WINDOW    = 0,
+    LONG_START_WINDOW,
+    EIGHT_SHORT_WINDOW,
+    LONG_STOP_WINDOW,
+    NUM_WIN_SEQ,
+
+    WLONG       = ONLY_LONG_WINDOW,
+    WSTART,
+    WSHORT,
+    WSTOP,
+
+    MAXBANDS        = 16 * NSHORT,  /* max number of scale factor bands */
+    MAXFAC      = 121,      /* maximum scale factor */
+    MIDFAC      = (MAXFAC - 1) / 2,
+    SF_OFFSET       = 100       /* global gain must be positive */
+} eBlockSwitching;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_coupling_mode.h b/media/libstagefright/codecs/aacdec/e_coupling_mode.h
new file mode 100644
index 0000000..68244bb
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_coupling_mode.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_coupling_mode.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_COUPLING_MODE_H
+#define E_COUPLING_MODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    COUPLING_OFF,
+    COUPLING_LEVEL,
+    COUPLING_BAL
+}
+COUPLING_MODE;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_elementid.h b/media/libstagefright/codecs/aacdec/e_elementid.h
new file mode 100644
index 0000000..5f84643
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_elementid.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Pathname: ./include/e_BLOCKTYPE.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for BlockType related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_ELEMENTID_H
+#define E_ELEMENTID_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /* sfb 40, coef 672, pred bw of 15.75 kHz at 48 kHz
+     * this is also the highest number of bins used
+     * by predictor for any sampling rate
+     */
+    MAX_PRED_SFB    = 40,   /* 48 kHz only, now obsolete */
+    MAX_PRED_BINS   = 672,
+
+    ID_SCE      = 0,
+    ID_CPE,
+    ID_CCE,
+    ID_LFE,
+    ID_DSE,
+    ID_PCE,
+    ID_FIL,
+    ID_END
+}
+ElementId;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_huffmanconst.h b/media/libstagefright/codecs/aacdec/e_huffmanconst.h
new file mode 100644
index 0000000..5d0e628
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_huffmanconst.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_HuffmanConst.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for Huffman related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_HUFFMAN_CONST_H
+#define E_HUFFMAN_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /*
+     * specify huffman tables as signed (1) or unsigned (0)
+     */
+    HUF1SGN     = 1,
+    HUF2SGN     = 1,
+    HUF3SGN     = 0,
+    HUF4SGN     = 0,
+    HUF5SGN     = 1,
+    HUF6SGN     = 1,
+    HUF7SGN     = 0,
+    HUF8SGN     = 0,
+    HUF9SGN     = 0,
+    HUF10SGN        = 0,
+    HUF11SGN        = 0,
+
+    ZERO_HCB        = 0,
+    BY4BOOKS        = 4,
+    ESCBOOK     = 11,
+    NSPECBOOKS      = ESCBOOK + 1,
+    BOOKSCL     = NSPECBOOKS,
+    NBOOKS      = NSPECBOOKS + 1,
+    INTENSITY_HCB2  = 14,
+    INTENSITY_HCB   = 15,
+    NOISE_HCB       = 13,
+    NOISE_HCB2      = 113,
+
+    NOISE_PCM_BITS      = 9,
+    NOISE_PCM_OFFSET    = (1 << (NOISE_PCM_BITS - 1)),
+
+    NOISE_OFFSET        = 90,
+
+    LONG_SECT_BITS  = 5,
+    SHORT_SECT_BITS = 3
+} eHuffmanConst;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_infoinitconst.h b/media/libstagefright/codecs/aacdec/e_infoinitconst.h
new file mode 100644
index 0000000..788b5e9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_infoinitconst.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_infoinitConst.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for Infoinit related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_INFOINIT_CONST_H
+#define E_INFOINIT_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "chans.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /* block switch windows for single channels or channel pairs */
+    Winds   = Chans,
+
+    /* average channel block length, bytes */
+    Avjframe    = 341,
+
+    TEXP    = 128,      /* size of exp cache table */
+    MAX_IQ_TBL  = 128,      /* size of inv quant table */
+    MAXFFT  = LN4
+
+} infoinitConst;
+
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_invf_mode.h b/media/libstagefright/codecs/aacdec/e_invf_mode.h
new file mode 100644
index 0000000..57b3281
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_invf_mode.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_invf_mode.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_INVF_MODE_H
+#define E_INVF_MODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    INVF_OFF,
+    INVF_LOW_LEVEL,
+    INVF_MID_LEVEL,
+    INVF_HIGH_LEVEL,
+
+    INVF_NO_OVERRIDE
+}
+INVF_MODE;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_maskstatus.h b/media/libstagefright/codecs/aacdec/e_maskstatus.h
new file mode 100644
index 0000000..010b6f8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_maskstatus.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+   Pathname: ./include/e_MaskStatus.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file gives the enum of mask_present value used in getmask.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_MASKSTATUS_H
+#define E_MASKSTATUS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+enum
+{
+    MASK_NOT_PRESENT,
+    MASK_FROM_BITSTREAM,
+    MASK_ALL_FRAME,
+    MASK_ERROR
+};
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_mp4ff_const.h b/media/libstagefright/codecs/aacdec/e_mp4ff_const.h
new file mode 100644
index 0000000..1006406
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_mp4ff_const.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: e_MP4FF_const.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file enums the constants used by MP4FF header
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_MP4FF_CONST_H
+#define E_MP4FF_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    LEN_OBJ_TYPE = 5,
+    LEN_SAMP_RATE_IDX = 4,
+    LEN_SAMP_RATE   = 24,
+    LEN_CHAN_CONFIG = 4,
+    LEN_SYNC_EXTENSION_TYPE = 11,
+    LEN_FRAME_LEN_FLAG = 1,
+    LEN_DEPEND_ON_CORE = 1,
+    LEN_CORE_DELAY = 14,
+    LEN_EXT_FLAG = 1,
+    LEN_EP_CONFIG = 2,
+    LEN_LAYER_NUM = 3,
+    LEN_SUB_FRAME = 5,
+    LEN_LAYER_LEN = 11,
+    LEN_SECT_RES_FLAG = 1,
+    LEN_SCF_RES_FLAG = 1,
+    LEN_SPEC_RES_FLAG = 1,
+    LEN_EXT_FLAG3 = 1
+} eMP4FF_const;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_progconfigconst.h b/media/libstagefright/codecs/aacdec/e_progconfigconst.h
new file mode 100644
index 0000000..b5fdc08
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_progconfigconst.h
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: e_ProgConfigConst.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for ProgConfig related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_PROG_CONFIG_CONST_H
+#define E_PROG_CONFIG_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    /*
+     * Program Configuration
+     */
+    Main_Profile    = 0,
+    LC_Profile      = 1,
+
+    Fs_48       = 3,
+    Fs_44       = 4,
+    Fs_32       = 5,
+
+    LEN_PROFILE     = 2,
+    LEN_SAMP_IDX    = 4,
+    LEN_NUM_ELE     = 4,
+    LEN_NUM_LFE     = 2,
+    LEN_NUM_DAT     = 3,
+    LEN_NUM_CCE     = 4,
+    LEN_MIX_PRES    = 1,
+    LEN_MMIX_IDX    = 2,
+    LEN_PSUR_ENAB   = 1,
+    LEN_ELE_IS_CPE  = 1,
+    LEN_IND_SW_CCE  = 1,
+    LEN_COMMENT_BYTES   = 8
+
+} eProgConfigConst;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_rawbitstreamconst.h b/media/libstagefright/codecs/aacdec/e_rawbitstreamconst.h
new file mode 100644
index 0000000..a460d13
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_rawbitstreamconst.h
@@ -0,0 +1,130 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+   Pathname: e_RawBitstreamConst.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for the Raw Bitstream related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_RAW_BITSTREAM_CONST_H
+#define E_RAW_BITSTREAM_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    LEN_SE_ID       = 3,
+    LEN_TAG     = 4,
+    LEN_COM_WIN     = 1,
+    LEN_ICS_RESERV  = 1,
+    LEN_WIN_SEQ     = 2,
+    LEN_WIN_SH      = 1,
+    LEN_MAX_SFBL    = 6,
+    LEN_MAX_SFBS    = 4,
+    LEN_CB          = 4,
+    LEN_SCL_PCM     = 8,
+    LEN_PRED_PRES   = 1,
+    LEN_PRED_RST    = 1,
+    LEN_PRED_RSTGRP = 5,
+    LEN_PRED_ENAB   = 1,
+    LEN_MASK_PRES   = 2,
+    LEN_MASK        = 1,
+    LEN_PULSE_PRES  = 1,
+    LEN_TNS_PRES    = 1,
+    LEN_GAIN_PRES   = 1,
+
+    LEN_PULSE_NPULSE    = 2,
+    LEN_PULSE_ST_SFB    = 6,
+    LEN_PULSE_POFF      = 5,
+    LEN_PULSE_PAMP      = 4,
+    NUM_PULSE_LINES     = 4,
+    PULSE_OFFSET_AMP    = 4,
+
+    LEN_IND_CCE_FLG = 1,
+    LEN_NCC         = 3,
+    LEN_IS_CPE      = 1,
+    LEN_CC_LR       = 1,
+    LEN_CC_DOM      = 1,
+    LEN_CC_SGN      = 1,
+    LEN_CCH_GES     = 2,
+    LEN_CCH_CGP     = 1,
+
+    LEN_D_ALIGN     = 1,
+    LEN_D_CNT       = 8,
+    LEN_D_ESC       = 8,
+    LEN_F_CNT       = 4,
+    LEN_F_ESC       = 8,
+    LEN_BYTE        = 8,
+    LEN_PAD_DATA    = 8,
+
+    LEN_PC_COMM     = 9
+
+} eRawBitstreamConst;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_sbr_element_id.h b/media/libstagefright/codecs/aacdec/e_sbr_element_id.h
new file mode 100644
index 0000000..1b021ff
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sbr_element_id.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sbr_element_id.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SBR_ELEMENT_ID_H
+#define E_SBR_ELEMENT_ID_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    SBR_ID_SCE = 0,
+    SBR_ID_CPE
+}
+SBR_ELEMENT_ID;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_sbr_error.h b/media/libstagefright/codecs/aacdec/e_sbr_error.h
new file mode 100644
index 0000000..b6c8a90
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sbr_error.h
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sbr_error.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SBR_ERROR_H
+#define E_SBR_ERROR_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define HANDLE_ERROR_INFO Int32
+#define noError 0
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+typedef enum
+{
+    SBRDEC_OK = 0,
+    SBRDEC_NOSYNCH,
+    SBRDEC_ILLEGAL_PROGRAM,
+    SBRDEC_ILLEGAL_TAG,
+    SBRDEC_ILLEGAL_CHN_CONFIG,
+    SBRDEC_ILLEGAL_SECTION,
+    SBRDEC_ILLEGAL_SCFACTORS,
+    SBRDEC_ILLEGAL_PULSE_DATA,
+    SBRDEC_MAIN_PROFILE_NOT_IMPLEMENTED,
+    SBRDEC_GC_NOT_IMPLEMENTED,
+    SBRDEC_ILLEGAL_PLUS_ELE_ID,
+    SBRDEC_CREATE_ERROR,
+    SBRDEC_NOT_INITIALIZED,
+    SBRDEC_TOO_MANY_SBR_ENVELOPES,
+    SBRDEC_INVALID_BITSTREAM
+}
+SBR_ERROR;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_sbr_header_status.h b/media/libstagefright/codecs/aacdec/e_sbr_header_status.h
new file mode 100644
index 0000000..5b2a43f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sbr_header_status.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sbr_header_status.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SBR_HEADER_STATUS_H
+#define E_SBR_HEADER_STATUS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    HEADER_OK,
+    HEADER_RESET,
+    HEADER_NOT_INITIALIZED
+}
+SBR_HEADER_STATUS;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_sbr_master_status.h b/media/libstagefright/codecs/aacdec/e_sbr_master_status.h
new file mode 100644
index 0000000..16e43a4
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sbr_master_status.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sbr_master_status.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SBR_MASTER_STATUS_H
+#define E_SBR_MASTER_STATUS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    MASTER_OK,
+    MASTER_RESET
+}
+SBR_MASTER_STATUS;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_sbr_sync_state.h b/media/libstagefright/codecs/aacdec/e_sbr_sync_state.h
new file mode 100644
index 0000000..d9f8669
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sbr_sync_state.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sbr_sync_state.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SBR_SYNC_STATE_H
+#define E_SBR_SYNC_STATE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    SBR_NOT_INITIALIZED,
+    UPSAMPLING,
+    SBR_ACTIVE
+}
+SBR_SYNC_STATE;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_sr_mode.h b/media/libstagefright/codecs/aacdec/e_sr_mode.h
new file mode 100644
index 0000000..eff00dd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_sr_mode.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: e_sr_mode.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_SR_MODE_H
+#define E_SR_MODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    SINGLE_RATE = 1,
+    UP_BY_2
+}
+SR_MODE;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_tmp4audioobjecttype.h b/media/libstagefright/codecs/aacdec/e_tmp4audioobjecttype.h
new file mode 100644
index 0000000..83cccce
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_tmp4audioobjecttype.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_tMP4AudioObjectType.h
+
+ This file contains enumerated types for MP4 Audio Object Types, as defined
+ in ISO/IEC 14496-3, AMMENDMENT 1 Dated 2000-09-15
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_TMP4AUDIOOBJECTTYPE_H
+#define E_TMP4AUDIOOBJECTTYPE_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+    typedef enum eMP4AudioObjectType
+    {
+        MP4AUDIO_NULL            =  0, /*                                       */
+        MP4AUDIO_AAC_MAIN        =  1, /*                                       */
+        MP4AUDIO_AAC_LC          =  2, /* LC = Low Complexity                   */
+        MP4AUDIO_AAC_SSR         =  3, /* SSR = Scalable Sampling Rate          */
+        MP4AUDIO_LTP             =  4, /* LTP = Long Term Prediction            */
+        MP4AUDIO_SBR             =  5, /* SBR = Spectral Band Replication       */
+        MP4AUDIO_AAC_SCALABLE    =  6, /* scales both bitrate and sampling rate */
+        MP4AUDIO_TWINVQ          =  7, /* low bit rate                          */
+        MP4AUDIO_CELP            =  8,
+        MP4AUDIO_HVXC            =  9,
+        /* 10 is reserved                        */
+        /* 11 is reserved                        */
+        MP4AUDIO_TTSI            = 12,
+        /* 13-16 are synthesis and MIDI types    */
+        MP4AUDIO_ER_AAC_LC       = 17, /*                                       */
+        /* 18 is reserved                        */
+        MP4AUDIO_ER_AAC_LTP      = 19, /*                                       */
+        MP4AUDIO_ER_AAC_SCALABLE = 20, /*                                       */
+        MP4AUDIO_ER_TWINVQ       = 21, /*                                       */
+        MP4AUDIO_ER_BSAC         = 22, /*                                       */
+        MP4AUDIO_ER_AAC_LD       = 23, /*                                       */
+        MP4AUDIO_ER_CELP         = 24, /*                                       */
+        MP4AUDIO_ER_HVXC         = 25, /*                                       */
+        MP4AUDIO_ER_HILN         = 26, /*                                       */
+        MP4AUDIO_PARAMETRIC      = 27, /*                                       */
+        MP4AUDIO_PS              = 29  /*  Explicit Parametric Stereo           */
+
+    } tMP4AudioObjectType;
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /* Should not be any function declarations in this file */
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* E_TMP4AUDIOOBJECTTYPE_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/e_tns_const.h b/media/libstagefright/codecs/aacdec/e_tns_const.h
new file mode 100644
index 0000000..157d471
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_tns_const.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Pathname: ./include/e_TNS_Const.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for TNS related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_TNS_CONST_H
+#define E_TNS_CONST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    TNS_MAX_BANDS = 49,
+    TNS_MAX_ORDER = 20,
+    TNS_MAX_WIN   =  8,
+    TNS_MAX_FILT  =  3,
+    Q_SPEC        = 11,
+    Q_LPC         = 19
+
+} eTNS_Const;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_window_sequence.h b/media/libstagefright/codecs/aacdec/e_window_sequence.h
new file mode 100644
index 0000000..c4b933e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_window_sequence.h
@@ -0,0 +1,90 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/e_WINDOW_SEQUENCE.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for Window Sequence related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_WINDOW_SEQUENCE_H
+#define E_WINDOW_SEQUENCE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    ONLY_LONG_SEQUENCE,
+    LONG_START_SEQUENCE,
+    EIGHT_SHORT_SEQUENCE,
+    LONG_STOP_SEQUENCE,
+    NUM_WINDOW_SEQUENCE,
+    ENSURE_WINDOW_SEQUENCE_INT_SIZE = 0x7FFFFF
+}
+WINDOW_SEQUENCE;
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/e_window_shape.h b/media/libstagefright/codecs/aacdec/e_window_shape.h
new file mode 100644
index 0000000..3eca438
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/e_window_shape.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: e_Window_shape.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ enum for Window Sequence related constants
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_WINDOW_SHAPE_H
+#define E_WINDOW_SHAPE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef enum
+{
+    SINE_WINDOW = 0,
+    KAISER_BESSEL_WINDOW,
+    NUM_WINDOW_SHAPES,
+    ENSURE_WINDOW_SHAPE_INT_SIZE = 0x7FFFFF
+}
+WINDOW_SHAPE;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/esc_iquant_scaling.cpp b/media/libstagefright/codecs/aacdec/esc_iquant_scaling.cpp
new file mode 100644
index 0000000..778c88c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/esc_iquant_scaling.cpp
@@ -0,0 +1,789 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/esc_iquant_scaling.c
+ Funtions:  esc_iquant_scaling
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from esc_iquant_fxp.c code
+
+ Description:  Eliminated unused variables to avoid warnings, changed header
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    quantSpec[] = array of quantized compressed spectral coefficients, of
+                  data type Int and length sfbWidth.
+
+    sfbWidth    = number of array elements in quantSpec and the output array
+                  coef, data type Int.
+
+    coef[]      = output array of uncompressed coefficients, stored in a
+                  variable Q format, depending on the maximum value found
+                  for the group, array of Int32, length sfbWdith to be
+                  overwritten.
+
+    QFormat     = the output Q format for the array coef[].
+
+
+    scale       = scaling factor after separating power of 2 factor out from
+                  0.25*(sfb_scale - 100), i.e., 0.25*sfb_scale.
+
+    maxInput    = maximum absolute value of quantSpec.
+
+ Local Stores/Buffers/Pointers Needed: None.
+
+ Global Stores/Buffers/Pointers Needed:
+    inverseQuantTable = lookup table of const integer values to the one third
+                power stored in Q27 format, in file iquant_table.c, const
+                array of UInt32, of size 1025.
+
+ Outputs: None
+
+ Pointers and Buffers Modified:
+    coef[] contents are overwritten with the uncompressed values from
+    quantSpec[]
+
+
+
+
+ Local Stores Modified: None.
+
+ Global Stores Modified: None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the inverse quantization of the spectral coeficients
+ read from huffman decoding. It takes each input array value to the four
+ thirds power, then scales it according to the scaling factor input argument
+ ,and stores the result in the output array in a variable Q format
+ depending upon the maximum input value found.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall not have static or global variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+   of moving pictures and associated audio information - Part 7: Advanced
+   Audio Coding (AAC)", Section 10.3, "Decoding process", page 43.
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    maxInput = 0;
+
+    FOR (i = sfbWidth - 1; i >= 0; i--)
+        x = quantSpec[i];
+
+        IF ( x >= 0)
+            absX = x;
+        ELSE
+            absX = -x;
+        ENDIF
+
+        coef[i] = absX;
+
+        IF (absX > maxInput)
+            maxInput = absX;
+        ENDIF
+    ENDFOR
+
+    IF (maxInput == 0)
+        *pQFormat = QTABLE;
+    ELSE
+        temp = inverseQuantTable[(maxInput >> ORDER) + 1];
+
+        temp += ((1 << (QTABLE))-1);
+
+        temp >>= (QTABLE-1);
+
+        temp *= maxInput;
+
+        binaryDigits = 0;
+        WHILE( temp != 0)
+            temp >>= 1;
+            binaryDigits++;
+        WEND
+
+        IF (binaryDigits < (SIGNED32BITS - QTABLE))
+            binaryDigits = SIGNED32BITS - QTABLE;
+        ENDIF
+
+        *pQFormat = SIGNED32BITS - binaryDigits;
+        shift = QTABLE - *pQFormat;
+
+        IF (maxInput < TABLESIZE)
+            FOR (i = sfbWidth - 1; i >= 0; i--)
+                x = quantSpec[i];
+
+                absX = coef[i];
+
+                tmp_coef = x * (inverseQuantTable[absX] >> shift);
+
+                b_low  = (tmp_coef & 0xFFFF);
+                b_high = (tmp_coef >> 16);
+
+                mult_low  = ( (UInt32) b_low * scale );
+                mult_high = ( (Int32) b_high * scale );
+
+                mult_low >>= 16;
+
+                coef[i]  = (Int32) (mult_high + mult_low);
+
+            ENDFOR
+        ELSE
+            FOR (i = sfbWidth; i >= 0 ; i--)
+                x    = quantSpec[i];
+                absX = coef[i];
+
+                IF (absX < TABLESIZE)
+                    tmp_coef = x * (inverseQuantTable[absX] >> shift);
+                ELSE
+                    index = absX >> ORDER;
+                    w1 = inverseQuantTable[index];
+
+                    approxOneThird = (w1 * FACTOR) >> shift;
+
+
+                    x1 = index * SPACING;
+                    w2 = inverseQuantTable[index+1];
+
+                    deltaOneThird = (w2 - w1) * (absX - x1);
+
+                    deltaOneThird >>= (shift + ORDER - 1);
+
+                    tmp_coef = x * (approxOneThird + deltaOneThird);
+
+                ENDIF
+
+                b_low  = (mult_high & 0xFFFF);
+                b_high = (mult_high >> 16);
+
+                mult_low  = ( (UInt32) b_low * scale );
+                mult_high = ( (Int32) b_high * scale );
+
+                mult_low >>= 16;
+
+                coef[i]  = (Int32) (mult_high + mult_low);
+
+            ENDFOR
+        ENDIF
+    ENDIF
+
+    RETURN
+
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "iquant_table.h"
+#include "esc_iquant_scaling.h"
+#include "aac_mem_funcs.h"         /* For pv_memset                         */
+
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+/*
+ * Read further on what order is.
+ * Note: If ORDER is not a multiple of 3, FACTOR is not an integer.
+ * Note: Portions of this function assume ORDER is 3, and so does the table
+ *       in iquant_table.c
+ */
+#define ORDER        (3)
+/*
+ * For input values > TABLESIZE, multiply by FACTOR to get x ^ (1/3)
+ * FACTOR = 2 ^ (ORDER/3)
+ */
+#define FACTOR       (2)
+
+/*
+ * This is one more than the range of expected inputs.
+ */
+#define INPUTRANGE   (8192)
+
+/*
+ * SPACING is 2 ^ ORDER, and is the spacing between points when in the
+ * interpolation range.
+ */
+#define SPACING      (1<<ORDER)
+
+/*
+ * The actual table size is one more than TABLESIZE, to allow for
+ * interpolation for numbers near 8191
+ */
+#define TABLESIZE    (INPUTRANGE/SPACING)
+
+/*
+ * Format the table is stored in.
+ */
+#define QTABLE       (27)
+
+/*
+ * Number of bits for data in a signed 32 bit integer.
+ */
+#define SIGNED32BITS  (31)
+
+/*
+ * Round up value for intermediate values obtained from the table
+ */
+#define ROUND_UP (( ((UInt32) 1) << (QTABLE) )-1)
+
+#define     MASK_LOW16  0xffff
+#define     UPPER16     16
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+ * Processing in this function is performed in these steps:
+ *
+ * 1) Find the overall Q format for the entire group of inputs. This consists
+ *    of:
+ *    a) Finding the maximum input
+ *    b) estimate the maximum output
+ *    c) Using the table, get max ^ (4/3), taking into account the table is
+ *       in q format.
+ * 2) For each array element, see if the value is directly inside the table.
+ *    a) If yes, just multiply by table value by itself, then shift as
+ *       appropriate.
+ *    b) If no, get an approximation (described below) for x ^ (1/3) by linearly
+ *       interpolating using lower values in the table, then multiply by a
+ *       correction factor, then multiply by x (see below).
+ *
+ * It more accurate to interpolate x ^ (1/3) then x ^ (4/3), so that is stored
+ * in the lookup table. For values not in the table, interpolation is used:
+ *
+ *  We want y = x ^ (4/3) = x * (x ^ (1/3))
+ *
+ *  Let     x = w * (2 ^ m)  where m is a constant, = ORDER
+ *
+ *  then     x ^ (1/3) = w ^ (1/3) * (2 ^ (m/3))
+ *
+ *  w is most likely not an integer, so an interpolation with floor(w) and
+ *  ceil(w) can be performed to approximate w ^ (1/3) by getting values out of
+ *  the table. Then to get x ^ (1/3), multiply by FACTOR. If m = 0, 3, 6,
+ *  then FACTOR is a simple power of 2, so a shift can do the job.
+ *
+ *  The actual code employs some more tricks to speed things up, and because
+ *  the table is stored in Q format.
+ *
+ *  Rather than saving the sign of each input, the unsigned value of
+ *  abs(x) ^ (1/3) is multiplied by the signed input value.
+ */
+
+
+
+#if ( defined(_ARM) || defined(_ARM_V4))
+
+/*
+ *  Absolute value for 16 bit-numbers
+ */
+__inline Int32 abs2(Int32 x)
+{
+    Int32 z;
+    /*
+        z = x - (x<0);
+        x = z ^ sign(z)
+     */
+    __asm
+    {
+        sub  z, x, x, lsr #31
+        eor  x, z, z, asr #31
+    }
+    return (x);
+}
+
+
+#define pv_abs(x)   abs2(x)
+
+
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+/*
+ *  Absolute value for 16 bit-numbers
+ */
+__inline Int32 abs2(Int32 x)
+{
+    register Int32 z;
+    register Int32 y;
+    register Int32 ra = x;
+    asm volatile(
+        "sub  %0, %2, %2, lsr #31\n\t"
+        "eor  %1, %0, %0, asr #31"
+    : "=&r*i"(z),
+        "=&r*i"(y)
+                : "r"(ra));
+
+    return (y);
+}
+
+#define pv_abs(x)   abs2(x)
+
+
+#else
+
+#define pv_abs(x)   ((x) > 0)? (x) : (-x)
+
+#endif
+
+
+
+
+
+void esc_iquant_scaling(
+    const Int16     quantSpec[],
+    Int32         coef[],
+    const Int     sfbWidth,
+    Int const      QFormat,
+    UInt16        scale,
+    Int           maxInput)
+{
+    Int    i;
+    Int    x;
+    Int    y;
+    Int    index;
+    Int    shift;
+    UInt   absX;
+    UInt32 w1, w2;
+    UInt32 deltaOneThird;
+    UInt32 x1;
+    UInt32 approxOneThird;
+    Int32   mult_high;
+
+
+#if ( defined(_ARM) || defined(_ARM_V4))
+
+    {
+        Int32   *temp;
+        Int32   R12, R11, R10, R9;
+
+        deltaOneThird = sizeof(Int32) * sfbWidth;
+        temp = coef;
+
+        // from standard library call for __rt_memset
+        __asm
+        {
+            MOV     R12, #0x0
+            MOV     R11, #0x0
+            MOV     R10, #0x0
+            MOV     R9, #0x0
+            SUBS    deltaOneThird, deltaOneThird, #0x20
+loop:
+            STMCSIA temp!, {R12, R11, R10, R9}
+            STMCSIA temp!, {R12, R11, R10, R9}
+            SUBCSS  deltaOneThird, deltaOneThird, #0x20
+            BCS     loop
+
+            MOVS    deltaOneThird, deltaOneThird, LSL #28
+            STMCSIA temp!, {R12, R11, R10, R9}
+            STMMIIA temp!, {R12, R11}
+        }
+    }
+
+#else
+    pv_memset(coef, 0, sizeof(Int32) * sfbWidth);
+#endif
+
+    if (maxInput > 0)
+    {
+
+        shift = QTABLE - QFormat;
+
+        if (scale != 0)
+        {
+            if (maxInput < TABLESIZE)
+            {
+
+                for (i = sfbWidth - 1; i >= 0; i -= 4)
+                {
+                    x = quantSpec[i];
+                    y = quantSpec[i-1];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        mult_high = (x * (inverseQuantTable[absX] >> shift));
+                        coef[i] = fxp_mul32_by_16(mult_high, scale) << 1;
+                    }
+
+                    if (y)
+                    {
+                        absX = pv_abs(y);
+                        mult_high = y * (inverseQuantTable[absX] >> shift);
+                        coef[i-1] = fxp_mul32_by_16(mult_high, scale) << 1;
+                    }
+
+                    x = quantSpec[i-2];
+                    y = quantSpec[i-3];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        mult_high = x * (inverseQuantTable[absX] >> shift);
+                        coef[i-2] = fxp_mul32_by_16(mult_high, scale) << 1;
+                    }
+
+                    if (y)
+                    {
+                        absX = pv_abs(y);
+                        mult_high = y * (inverseQuantTable[absX] >> shift);
+                        coef[i-3] = fxp_mul32_by_16(mult_high, scale) << 1;
+                    }
+                } /* end for (i = sfbWidth - 1; i >= 0; i--) */
+
+            } /* end if (maxInput < TABLESIZE)*/
+
+            else /* maxInput >= TABLESIZE) */
+            {
+                for (i = sfbWidth - 1; i >= 0; i -= 4)
+                {
+                    x    = quantSpec[i];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i] = fxp_mul32_by_16(mult_high, scale) << 1;
+
+                        }
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i] = fxp_mul32_by_16(mult_high, scale) << 1;
+
+                        }
+                    } /* if(x) */
+
+
+                    x    = quantSpec[i-1];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = (x * (inverseQuantTable[absX] >> shift));
+                            coef[i-1] = fxp_mul32_by_16(mult_high, scale) << 1;
+
+                        }
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-1] = fxp_mul32_by_16(mult_high, scale) << 1;
+                        }
+                    } /* if(x) */
+
+                    x    = quantSpec[i-2];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i-2] = fxp_mul32_by_16(mult_high, scale) << 1;
+                        }
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-2] = fxp_mul32_by_16(mult_high, scale) << 1;
+                        }
+                    } /* if(x) */
+
+                    x    = quantSpec[i-3];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i-3] = fxp_mul32_by_16(mult_high, scale) << 1;
+
+                        }
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-3] = fxp_mul32_by_16(mult_high, scale) << 1;
+
+                        }
+                    } /* if(x) */
+
+                }  /* end for (i = sfbWidth - 1; i >= 0; i--) */
+            } /* end else for if (maxInput < TABLESIZE)*/
+        }
+        else /* scale == 0 */
+        {
+            if (maxInput < TABLESIZE)
+            {
+                for (i = sfbWidth - 1; i >= 0; i -= 4)
+                {
+                    x = quantSpec[i];
+                    y = quantSpec[i-1];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        mult_high = x * (inverseQuantTable[absX] >> shift);
+                        coef[i] = mult_high >> 1;
+                    }
+
+                    if (y)
+                    {
+                        absX = pv_abs(y);
+                        mult_high = y * (inverseQuantTable[absX] >> shift);
+                        coef[i-1] = mult_high >> 1;
+                    }
+
+                    x = quantSpec[i-2];
+                    y = quantSpec[i-3];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        mult_high = x * (inverseQuantTable[absX] >> shift);
+                        coef[i-2] = mult_high >> 1;
+                    }
+
+                    if (y)
+                    {
+                        absX = pv_abs(y);
+                        mult_high = y * (inverseQuantTable[absX] >> shift);
+                        coef[i-3] = mult_high >> 1;
+                    }
+                }
+
+            } /* end if (maxInput < TABLESIZE)*/
+
+            else /* maxInput >= TABLESIZE) */
+            {
+                for (i = sfbWidth - 1; i >= 0; i -= 4)
+                {
+                    x    = quantSpec[i];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i] = (mult_high >> 1);
+                        } /* end if (absX < TABLESIZE) */
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i] = (mult_high >> 1);
+                        }
+                    } /* if(x) */
+
+                    x    = quantSpec[i-1];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i-1] = (mult_high >> 1);
+                        } /* end if (absX < TABLESIZE) */
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-1] = (mult_high >> 1);
+                        }
+                    } /* if(x) */
+
+                    x    = quantSpec[i-2];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i-2] = (mult_high >> 1);
+                        } /* end if (absX < TABLESIZE) */
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-2] = (mult_high >> 1);
+                        }
+                    } /* if(x) */
+
+                    x    = quantSpec[i-3];
+                    if (x)
+                    {
+                        absX = pv_abs(x);
+                        if (absX < TABLESIZE)
+                        {
+                            mult_high = x * (inverseQuantTable[absX] >> shift);
+                            coef[i-3] = (mult_high >> 1);
+                        } /* end if (absX < TABLESIZE) */
+                        else
+                        {
+                            index = absX >> ORDER;
+                            w1 = inverseQuantTable[index];
+                            w2 = inverseQuantTable[index+1];
+                            approxOneThird = (w1 * FACTOR) >> shift;
+                            x1 = index << ORDER;
+                            deltaOneThird = (w2 - w1) * (absX - x1);
+                            deltaOneThird >>= (shift + 2);
+                            mult_high = x * (approxOneThird + deltaOneThird);
+                            coef[i-3] = (mult_high >> 1);
+                        }
+
+                    } /* if(x) */
+
+                }  /* end for (i = sfbWidth - 1; i >= 0; i--) */
+
+            } /* end else for if (maxInput < TABLESIZE)*/
+
+        } /* end else for if(scale!=0) */
+
+    }  /* end else for if(maxInput == 0) */
+
+} /* end esc_iquant_fxp */
+
+
diff --git a/media/libstagefright/codecs/aacdec/esc_iquant_scaling.h b/media/libstagefright/codecs/aacdec/esc_iquant_scaling.h
new file mode 100644
index 0000000..a846b9f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/esc_iquant_scaling.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/esc_iquant_scaling.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for esc_iquant_scaling.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ESC_IQUANT_SCALING_H
+#define ESC_IQUANT_SCALING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void esc_iquant_scaling(
+        const Int16   quantSpec[],
+        Int32       coef[],
+        const Int   sfbWidth,
+        Int  const pQFormat,
+        UInt16      scale,
+        Int           maxInput);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif /* ESC_IQUANT_SCALING_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/extractframeinfo.cpp b/media/libstagefright/codecs/aacdec/extractframeinfo.cpp
new file mode 100644
index 0000000..571cc98
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/extractframeinfo.cpp
@@ -0,0 +1,487 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Filename: extractframeInfo.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:   hBitBuf      - bitbuffer handle
+              v_frame_info - pointer to memorylocation where the frame-info will
+                             be stored.
+
+ Return:     none.
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+Extracts a frame_info vector from control data read from the bitstream.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "extractframeinfo.h"
+#include    "buf_getbits.h"
+#include    "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+
+/*
+ *  (int) ceil (log (bs_num_env + 1) / log (2))
+ *  ceil(log([0:5]+1)/log(2))
+ */
+
+const Int32 bs_pointer_bits_tbl[MAX_ENVELOPES + 1] = { 0, 1, 2, 2, 3, 3};
+
+/*
+ *  (int)((float)numTimeSlots/bs_num_env + 0.5f)
+ *  floor(16./[0:5] + 0.5)
+ */
+
+const Int32 T_16_ov_bs_num_env_tbl[MAX_ENVELOPES + 1] = { 2147483647, 16, 8,
+        5,  4, 3
+                                                        };
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+SBR_ERROR extractFrameInfo(BIT_BUFFER     * hBitBuf,
+                           SBR_FRAME_DATA * h_frame_data)
+{
+
+    Int32 absBordLead = 0;
+    Int32 nRelLead = 0;
+    Int32 nRelTrail = 0;
+    Int32 bs_num_env = 0;
+    Int32 bs_num_rel = 0;
+    Int32 bs_var_bord = 0;
+    Int32 bs_var_bord_0 = 0;
+    Int32 bs_var_bord_1 = 0;
+    Int32 bs_pointer = 0;
+    Int32 bs_pointer_bits;
+    Int32 frameClass;
+    Int32 temp;
+    Int32 env;
+    Int32 k;
+    Int32 bs_num_rel_0 = 0;
+    Int32 bs_num_rel_1 = 0;
+    Int32 absBordTrail = 0;
+    Int32 middleBorder = 0;
+    Int32 bs_num_noise;
+    Int32 lA = 0;
+
+    Int32 tE[MAX_ENVELOPES + 1];
+    Int32 tQ[2 + 1];
+    Int32 f[MAX_ENVELOPES + 1];
+    Int32 bs_rel_bord[3];
+    Int32 bs_rel_bord_0[3];
+    Int32 bs_rel_bord_1[3];
+    Int32 relBordLead[3];
+    Int32 relBordTrail[3];
+
+
+    Int32 *v_frame_info = h_frame_data->frameInfo;
+
+    SBR_ERROR err =  SBRDEC_OK;
+
+
+    /*
+     * First read from the bitstream.
+     */
+
+    /* Read frame class */
+    h_frame_data->frameClass = frameClass = buf_getbits(hBitBuf, SBR_CLA_BITS);
+
+
+    switch (frameClass)
+    {
+
+        case FIXFIX:
+            temp = buf_getbits(hBitBuf, SBR_ENV_BITS);   /* 2 bits */
+
+            bs_num_env = 1 << temp;
+
+
+            f[0] = buf_getbits(hBitBuf, SBR_RES_BITS);   /* 1 bit */
+
+            for (env = 1; env < bs_num_env; env++)
+            {
+                f[env] = f[0];
+            }
+
+            nRelLead     = bs_num_env - 1;
+            absBordTrail  = 16;
+
+
+            break;
+
+        case FIXVAR:
+            bs_var_bord = buf_getbits(hBitBuf, SBR_ABS_BITS);   /* 2 bits */
+            bs_num_rel  = buf_getbits(hBitBuf, SBR_NUM_BITS);   /* 2 bits */
+            bs_num_env  = bs_num_rel + 1;
+
+            for (k = 0; k < bs_num_env - 1; k++)
+            {
+                bs_rel_bord[k] = (buf_getbits(hBitBuf, SBR_REL_BITS) + 1) << 1;
+            }
+
+            bs_pointer_bits = bs_pointer_bits_tbl[bs_num_env];
+
+            bs_pointer = buf_getbits(hBitBuf, bs_pointer_bits);
+
+            for (env = 0; env < bs_num_env; env++)
+            {                                                    /* 1 bit */
+                f[bs_num_env - 1 - env] = buf_getbits(hBitBuf, SBR_RES_BITS);
+            }
+
+            absBordTrail  = 16 + bs_var_bord;
+            nRelTrail     = bs_num_rel;
+
+            break;
+
+        case VARFIX:
+            bs_var_bord = buf_getbits(hBitBuf, SBR_ABS_BITS);   /* 2 bits */
+            bs_num_rel  = buf_getbits(hBitBuf, SBR_NUM_BITS);   /* 2 bits */
+            bs_num_env  = bs_num_rel + 1;
+
+            for (k = 0; k < bs_num_env - 1; k++)
+            {
+                bs_rel_bord[k] = (buf_getbits(hBitBuf, SBR_REL_BITS) + 1) << 1;
+            }
+
+            bs_pointer_bits = bs_pointer_bits_tbl[bs_num_env];
+
+            bs_pointer = buf_getbits(hBitBuf, bs_pointer_bits);
+
+            for (env = 0; env < bs_num_env; env++)
+            {                                  /* 1 bit */
+                f[env] = buf_getbits(hBitBuf, SBR_RES_BITS);
+            }
+
+            absBordTrail = 16;
+            absBordLead  = bs_var_bord;
+            nRelLead     = bs_num_rel;
+
+            break;
+
+        case VARVAR:
+            bs_var_bord_0 = buf_getbits(hBitBuf, SBR_ABS_BITS);   /* 2 bits */
+            bs_var_bord_1 = buf_getbits(hBitBuf, SBR_ABS_BITS);
+            bs_num_rel_0  = buf_getbits(hBitBuf, SBR_NUM_BITS);   /* 2 bits */
+            bs_num_rel_1  = buf_getbits(hBitBuf, SBR_NUM_BITS);
+
+            bs_num_env = bs_num_rel_0 + bs_num_rel_1 + 1;
+
+            for (k = 0; k < bs_num_rel_0; k++)
+            {                                                 /* 2 bits */
+                bs_rel_bord_0[k] = (buf_getbits(hBitBuf, SBR_REL_BITS) + 1) << 1;
+            }
+
+            for (k = 0; k < bs_num_rel_1; k++)
+            {                                                 /* 2 bits */
+                bs_rel_bord_1[k] = (buf_getbits(hBitBuf, SBR_REL_BITS) + 1) << 1;
+            }
+
+
+            bs_pointer_bits = bs_pointer_bits_tbl[bs_num_env];
+
+            bs_pointer = buf_getbits(hBitBuf, bs_pointer_bits);
+
+            for (env = 0; env < bs_num_env; env++)
+            {                                  /* 1 bit */
+                f[env] = buf_getbits(hBitBuf, SBR_RES_BITS);
+            }
+
+            absBordLead   = bs_var_bord_0;
+            absBordTrail  = 16 + bs_var_bord_1;
+            nRelLead      = bs_num_rel_0;
+            nRelTrail     = bs_num_rel_1;
+
+            break;
+
+    };
+
+
+    /*
+     * Calculate the framing.
+     */
+
+
+    switch (frameClass)
+    {
+        case FIXFIX:
+            for (k = 0; k < nRelLead; k++)
+            {
+                relBordLead[k] = T_16_ov_bs_num_env_tbl[bs_num_env];
+            }
+            break;
+        case VARFIX:
+            for (k = 0; k < nRelLead; k++)
+            {
+                relBordLead[k] = bs_rel_bord[k];
+            }
+            break;
+        case VARVAR:
+            for (k = 0; k < nRelLead; k++)
+            {
+                relBordLead[k] = bs_rel_bord_0[k];
+            }
+            for (k = 0; k < nRelTrail; k++)
+            {
+                relBordTrail[k] = bs_rel_bord_1[k];
+            }
+            break;
+        case FIXVAR:
+            for (k = 0; k < nRelTrail; k++)
+            {
+                relBordTrail[k] = bs_rel_bord[k];
+            }
+            break;
+    }
+
+
+    tE[0]          = absBordLead;
+    tE[bs_num_env] = absBordTrail;
+
+    for (env = 1; env <= nRelLead; env++)
+    {
+        tE[env] = absBordLead;
+        for (k = 0; k <= env - 1; k++)
+        {
+            tE[env] += relBordLead[k];
+        }
+    }
+
+    for (env = nRelLead + 1; env < bs_num_env; env++)
+    {
+        tE[env] = absBordTrail;
+        for (k = 0; k <= bs_num_env - env - 1; k++)
+        {
+            tE[env] -= relBordTrail[k];
+        }
+    }
+
+
+
+    switch (frameClass)
+    {
+        case  FIXFIX:
+            middleBorder = bs_num_env >> 1;
+            break;
+        case VARFIX:
+            switch (bs_pointer)
+            {
+                case 0:
+                    middleBorder = 1;
+                    break;
+                case 1:
+                    middleBorder = bs_num_env - 1;
+                    break;
+                default:
+                    middleBorder = bs_pointer - 1;
+                    break;
+            };
+            break;
+        case FIXVAR:
+        case VARVAR:
+            switch (bs_pointer)
+            {
+                case 0:
+                case 1:
+                    middleBorder = bs_num_env - 1;
+                    break;
+                default:
+                    middleBorder = bs_num_env + 1 - bs_pointer;
+                    break;
+            };
+            break;
+    };
+
+
+    tQ[0] = tE[0];
+    if (bs_num_env > 1)
+    {
+        tQ[1] = tE[middleBorder];
+        tQ[2] = tE[bs_num_env];
+        bs_num_noise = 2;
+    }
+    else
+    {
+        tQ[1] = tE[bs_num_env];
+        bs_num_noise = 1;
+    }
+
+    /*
+     *  Check consistency on freq bands
+     */
+
+    if ((tE[bs_num_env] < tE[0]) || (tE[0] < 0))
+    {
+        err = SBRDEC_INVALID_BITSTREAM;
+    }
+
+
+    switch (frameClass)
+    {
+        case  FIXFIX:
+            lA = -1;
+            break;
+        case VARFIX:
+            switch (bs_pointer)
+            {
+                case 0:
+                case 1:
+                    lA = -1;
+                    break;
+                default:
+                    lA = bs_pointer - 1;
+                    break;
+            };
+            break;
+        case FIXVAR:
+        case VARVAR:
+            switch (bs_pointer)
+            {
+                case 0:
+                    lA = - 1;
+                    break;
+                default:
+                    lA = bs_num_env + 1 - bs_pointer;
+                    break;
+            };
+            break;
+    };
+
+    /*
+     * Build the frameInfo vector...
+     */
+
+    v_frame_info[0] = bs_num_env;   /* Number of envelopes*/
+    pv_memcpy(v_frame_info + 1, tE, (bs_num_env + 1)*sizeof(Int32));    /* time borders*/
+    /* frequency resolution */
+    pv_memcpy(v_frame_info + 1 + bs_num_env + 1, f, bs_num_env*sizeof(Int32));
+
+    temp = (1 + bs_num_env) << 1;
+    v_frame_info[temp] = lA;                     /* transient envelope*/
+    v_frame_info[temp + 1] = bs_num_noise;       /* Number of noise envelopes */
+    /* noise borders */
+    pv_memcpy(v_frame_info + temp + 2, tQ, (bs_num_noise + 1)*sizeof(Int32));
+
+
+    return (err);
+
+}
+
+
+
+
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/extractframeinfo.h b/media/libstagefright/codecs/aacdec/extractframeinfo.h
new file mode 100644
index 0000000..2fcfe37
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/extractframeinfo.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: extractFrameInfo.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef EXTRACTFRAMEINFO_H
+#define EXTRACTFRAMEINFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+#include    "e_sbr_error.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+typedef Int32 FRAME_INFO[LENGTH_FRAME_INFO];
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    SBR_ERROR extractFrameInfo(BIT_BUFFER     * hBitBuf,
+    SBR_FRAME_DATA * h_frame_data);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/fft_rx4.h b/media/libstagefright/codecs/aacdec/fft_rx4.h
new file mode 100644
index 0000000..8e7acb3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fft_rx4.h
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/fft_rx4.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+        (1) modified definition of w_64rx4 from Int to Int16
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions fft_rx4()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef FFT_RX4_H
+#define FFT_RX4_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define     FFT_RX4_LONG                256
+#define     ONE_FOURTH_FFT_RX4_LONG     ((FFT_RX4_LONG)>>2)
+#define     FFT_RX4_SHORT               64
+#define     ONE_FOURTH_FFT_RX4_SHORT    ((FFT_RX4_SHORT)>>2)
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+extern const Int16 w_64rx4[];
+extern const Int32 W_64rx4[];
+extern const Int32 W_256rx4[];
+extern const Int32 w_512rx2[];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void fft_rx4_long(
+        Int32      Data[],
+        Int32      *peak_value);
+
+    Int fft_rx4_short(
+        Int32      Data[],
+        Int32      *peak_value);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* FFT_RX4_H */
diff --git a/media/libstagefright/codecs/aacdec/fft_rx4_long.cpp b/media/libstagefright/codecs/aacdec/fft_rx4_long.cpp
new file mode 100644
index 0000000..c517e7e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fft_rx4_long.cpp
@@ -0,0 +1,428 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/fft_rx4_long.c
+ Funtions: fft_rx4_long
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+            (1) Eliminated search for max in the main loop.
+            (2) Reduced precision on w_256rx4 from Q15 to Q10
+
+ Description:
+            (1) Created function fft_rx4_long_no_max to overcome LTP problem.
+
+ Description:
+            (1) Modified shift so the accumulation growths faster than the
+                downshift, so now the input can be as high as 1.0 and saturation
+                will not occurre. The accumulation times the Q10 format will
+                never exceed 31 bits. This increases precision
+            (2) Eliminated unneeded data moves, used before for max search.
+            (3) Eliminated function fft_rx4_long_no_max.
+
+ Description:
+            (1) Added comment to explain max search elimination and
+                Q format during multiplications
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Data       =  Input complex vector, arranged in the following order:
+                  real, imag, real, imag...
+                  This is a complex vector whose elements (real and Imag) are
+                  Int32.
+                  type Int32 *
+
+    peak_value =  Input,  peak value of the input vector
+                  Output,  peak value of the resulting vector
+                  type Int32 *
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    calculation are done in-place and returned in Data
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Fast Fourier Transform, radix 4 with Decimation in Frequency and block
+    floating point arithmetic.
+    The radix-4 FFT  simply divides the FFT into four smaller FFTs. Each of
+    the smaller FFTs is then further divided into smaller ones and so on.
+    It consists of log 4 N stages and each stage consists of N/4 dragonflies.
+
+    An FFT is nothing but a bundle of multiplications and summations which
+    may overflow during calculations.
+
+
+    This routine uses a scheme to test and scale the result output from
+    each FFT stage in order to fix the accumulation overflow.
+
+    The Input Data should be in Q13 format to get the highest precision.
+    At the end of each dragonfly calculation, a test for possible bit growth
+    is made, if bit growth is possible the Data is scale down back to Q13.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should provide a fixed point FFT for an input array
+    of size 256.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] Advance Digital Signal Processing, J. Proakis, C. Rader, F. Ling,
+        C. Nikias, Macmillan Pub. Co.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+   MODIFY( x[] )
+   RETURN( exponent )
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "fft_rx4.h"
+
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void fft_rx4_long(
+    Int32      Data[],
+    Int32      *peak_value)
+
+{
+    Int     n1;
+    Int     n2;
+    Int     j;
+    Int     k;
+    Int     i;
+
+    Int32   t1;
+    Int32   t2;
+    Int32   r1;
+    Int32   r2;
+    Int32   r3;
+    Int32   r4;
+    Int32   s1;
+    Int32   s2;
+    Int32   s3;
+    Int32   *pData1;
+    Int32   *pData2;
+    Int32   *pData3;
+    Int32   *pData4;
+    Int32   temp1;
+    Int32   temp2;
+    Int32   temp3;
+    Int32   temp4;
+    Int32   max;
+
+    Int32   exp_jw1;
+    Int32   exp_jw2;
+    Int32   exp_jw3;
+
+
+
+    const Int32  *pw = W_256rx4;
+
+    n2 = FFT_RX4_LONG;
+
+    for (k = FFT_RX4_LONG; k > 4; k >>= 2)
+    {
+
+        n1 = n2;
+        n2 >>= 2;
+
+        for (i = 0; i < FFT_RX4_LONG; i += n1)
+        {
+            pData1 = &Data[ i<<1];
+            pData2 = pData1 + n1;
+
+            temp1   = *pData1;
+            temp2   = *pData2;
+
+            r1      = temp1 + temp2;
+            r2      = temp1 - temp2;
+
+            pData3 = pData1 + (n1 >> 1);
+            pData4 = pData3 + n1;
+            temp3   = *pData3++;
+            temp4   = *pData4++;
+
+            t1      = temp3 + temp4;
+
+            *(pData1++) = (r1 + t1);
+            t2      = temp3 - temp4;
+            *(pData2++) = (r1 - t1);
+
+            temp1   = *pData1;
+            temp2   = *pData2;
+
+            s1      = temp1 + temp2;
+            temp3   = *pData3;
+            s2      = temp1 - temp2;
+            temp4   = *pData4;
+            *pData3--  = (s2 - t2);
+            *pData4--  = (s2 + t2);
+
+            t1      = temp3 + temp4;
+
+            *pData1    = (s1 + t1);
+            *pData2    = (s1 - t1);
+
+            r1      = temp3 - temp4;
+
+            *pData4    = (r2 - r1);
+            *pData3    = (r2 + r1);
+
+        }  /* i */
+
+
+
+        for (j = 1; j < n2; j++)
+        {
+
+            exp_jw1 = (*pw++);
+            exp_jw2 = (*pw++);
+            exp_jw3 = (*pw++);
+
+
+            for (i = j; i < FFT_RX4_LONG; i += n1)
+            {
+                pData1 = &Data[ i<<1];
+                pData2 = pData1 + n1;
+
+                temp1   = *pData1;
+                temp2   = *pData2++;
+
+                r1      = temp1 + temp2;
+                r2      = temp1 - temp2;
+
+                pData3 = pData1 + (n1 >> 1);
+                pData4 = pData3 + n1;
+                temp3   = *pData3++;
+                temp4   = *pData4++;
+
+                r3      = temp3 + temp4;
+                r4      = temp3 - temp4;
+
+                *(pData1++) = (r1 + r3);
+                r1          = (r1 - r3) << 1;
+
+                temp2   = *pData2;
+                temp1   = *pData1;
+
+                s1      = temp1 + temp2;
+                s2      = temp1 - temp2;
+                s3      = (s2 + r4) << 1;
+                s2      = (s2 - r4) << 1;
+
+                temp3   = *pData3;
+                temp4   = *pData4;
+
+                t1      = temp3 + temp4;
+                t2      = temp3 - temp4;
+
+                *pData1  = (s1 + t1);
+                s1       = (s1 - t1) << 1;
+
+                *pData2--  = cmplx_mul32_by_16(s1, -r1, exp_jw2);
+                r3      = (r2 - t2) << 1;
+                *pData2    = cmplx_mul32_by_16(r1,  s1, exp_jw2);
+
+                r2      = (r2 + t2) << 1;
+
+                *pData3--  = cmplx_mul32_by_16(s2, -r2, exp_jw1);
+                *pData3    = cmplx_mul32_by_16(r2,  s2, exp_jw1);
+
+                *pData4--  = cmplx_mul32_by_16(s3, -r3, exp_jw3);
+                *pData4    = cmplx_mul32_by_16(r3,  s3, exp_jw3);
+
+            }  /* i */
+
+        }  /*  j */
+
+    } /* k */
+
+
+    max = 0;
+
+    pData1 = Data - 7;
+
+
+    for (i = ONE_FOURTH_FFT_RX4_LONG; i != 0 ; i--)
+    {
+        pData1 += 7;
+        pData2 = pData1 + 4;
+
+
+        temp1   = *pData1;
+        temp2   = *pData2++;
+
+        r1      = temp1 + temp2;
+        r2      = temp1 - temp2;
+
+        pData3 = pData1 + 2;
+        pData4 = pData1 + 6;
+        temp1   = *pData3++;
+        temp2   = *pData4++;
+
+        t1      = temp1 + temp2;
+        t2      = temp1 - temp2;
+
+        temp1       = (r1 + t1);
+        r1          = (r1 - t1);
+        *(pData1++) = temp1;
+        max        |= (temp1 >> 31) ^ temp1;
+
+
+
+        temp2   = *pData2;
+        temp1   = *pData1;
+
+        s1      = temp1 + temp2;
+        s2      = temp1 - temp2;
+
+
+        temp1   = *pData3;
+        temp2   = *pData4;
+
+        s3      = (s2 + t2);
+        s2      = (s2 - t2);
+
+        t1      = temp1 + temp2;
+        t2      = temp1 - temp2;
+
+        temp1      = (s1 + t1);
+        *pData1    = temp1;
+        temp2      = (s1 - t1);
+
+        max       |= (temp1 >> 31) ^ temp1;
+        *pData2--  = temp2;
+        max       |= (temp2 >> 31) ^ temp2;
+
+        *pData2    = r1;
+        max       |= (r1 >> 31) ^ r1;
+        *pData3--  = s2;
+        max       |= (s2 >> 31) ^ s2;
+        *pData4--  = s3;
+        max       |= (s3 >> 31) ^ s3;
+
+        temp1      = (r2 - t2);
+        *pData4    = temp1;
+        temp2      = (r2 + t2);
+        *pData3    = temp2;
+        max       |= (temp1 >> 31) ^ temp1;
+        max       |= (temp2 >> 31) ^ temp2;
+
+    }  /* i */
+
+    *peak_value = max;
+
+    return ;
+
+}
+
diff --git a/media/libstagefright/codecs/aacdec/fft_rx4_short.cpp b/media/libstagefright/codecs/aacdec/fft_rx4_short.cpp
new file mode 100644
index 0000000..4a8a0d6
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fft_rx4_short.cpp
@@ -0,0 +1,468 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/fft_rx4_short.c
+ Funtions: fft_rx4_short
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+            (1) Eliminated search for max in the main loop.
+            (2) Simplified the function by eliminating different conditions
+                for exp.
+            (3) Reduced precision on w_64rx4 from Q15 to Q12, so now the
+                input can be as high as 1.0 and saturation will not occurre
+                because the accumulation times the new Q12 format will never
+                exceed 31 bits.
+
+ Description:
+            (1) Added comment to explain max search elimination and
+                Q format during multiplications
+            (2) Increased down shift from 1 to 2, to ensure that 32-bit
+                numbers will not overflow when 2 consecutive adds are done
+                This was found during code review.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Data       =  Input complex vector, arranged in the following order:
+                  real, imag, real, imag...
+                  This is a complex vector whose elements (real and Imag) are
+                  Int32.
+                  type Int32 *
+
+    peak_value =  Input,  peak value of the input vector
+                  Output,  peak value of the resulting vector
+                  type Int32 *
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exponent returns a shift to compensate the scaling introduced by
+    overflow protection
+
+ Pointers and Buffers Modified:
+    calculation are done in-place and returned in Data
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Fast Fourier Transform, radix 4 with Decimation in Frequency and block
+    floating point arithmetic.
+    The radix-4 FFT  simply divides the FFT into four smaller FFTs. Each of
+    the smaller FFTs is then further divided into smaller ones and so on.
+    It consists of log 4 N stages and each stage consists of N/4 dragonflies.
+
+    An FFT is nothing but a bundle of multiplications and summations which
+    may overflow during calculations.
+
+
+    This routine uses a scheme to test and scale the result output from
+    each FFT stage in order to fix the accumulation overflow.
+
+    The Input Data should be in Q13 format to get the highest precision.
+    At the end of each dragonfly calculation, a test for possible bit growth
+    is made, if bit growth is possible the Data is scale down back to Q13.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should provide a fixed point FFT for an input array
+    of size 64.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] Advance Digital Signal Processing, J. Proakis, C. Rader, F. Ling,
+        C. Nikias, Macmillan Pub. Co.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+   MODIFY( x[] )
+   RETURN( exponent )
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "fft_rx4.h"
+#include "pv_normalize.h"
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Int fft_rx4_short(
+    Int32      Data[],
+    Int32      *peak_value)
+
+{
+    Int     n1;
+    Int     n2;
+    Int     n3;
+    Int     j;
+    Int     k;
+    Int     i;
+    Int32   exp_jw1;
+    Int32   exp_jw2;
+    Int32   exp_jw3;
+
+
+    Int32   t1;
+    Int32   t2;
+    Int32   r1;
+    Int32   r2;
+    Int32   r3;
+    Int32   s1;
+    Int32   s2;
+    Int32   s3;
+
+    Int32   *pData1;
+    Int32   *pData2;
+    Int32   *pData3;
+    Int32   *pData4;
+    const Int32  *pw;
+    Int32   temp1;
+    Int32   temp2;
+    Int32   temp3;
+    Int32   temp4;
+    Int32   max;
+    Int     exp;
+    Int     exponent = 0;
+    Int     shift;
+
+
+    max = *peak_value;
+    exp = 0;
+
+    if (max > 0x008000)
+    {
+        exp = 8 - pv_normalize(max);   /* use 24 bits  */
+
+        exponent = exp;        /* keeps track of # of shifts */
+
+    }
+
+    n2 = FFT_RX4_SHORT;
+
+    pw = W_64rx4;
+
+
+    /* shift down to avoid possible overflow in first pass of the loop */
+    shift = 2;
+
+    for (k = FFT_RX4_SHORT; k > 4; k >>= 2)
+    {
+
+        n1 = n2;
+        n2 >>= 2;
+        n3 = n1 >> 1;
+
+        exp -= 2;
+
+        for (i = 0; i < FFT_RX4_SHORT; i += n1)
+        {
+            pData1 = &Data[ i<<1];
+            pData3 = pData1 + n3;
+            pData2 = pData1 + n1;
+            pData4 = pData3 + n1;
+
+            temp1   = *(pData1);
+            temp2   = *(pData2);
+            temp1   >>= shift;
+            temp2   >>= shift;
+
+            r1      = temp1 + temp2;
+            r2      = temp1 - temp2;
+
+            temp3   = *(pData3++);
+            temp4   = *(pData4++);
+            temp3   >>= shift;
+            temp4   >>= shift;
+
+            t1      = temp3 + temp4;
+            t2      = temp3 - temp4;
+
+            *(pData1++) = (r1 + t1) >> exp;
+            *(pData2++) = (r1 - t1) >> exp;
+
+            temp1   = *pData1;
+            temp2   = *pData2;
+            temp1   >>= shift;
+            temp2   >>= shift;
+
+            s1      = temp1 + temp2;
+            s2      = temp1 - temp2;
+
+            temp3   = *pData3;
+            temp4   = *pData4;
+            temp3   >>= shift;
+            temp4   >>= shift;
+
+            t1      = temp3 + temp4;
+            r1      = temp3 - temp4;
+
+            *pData1   = (s1 + t1) >> exp;
+            *pData2   = (s1 - t1) >> exp;
+
+            *pData4--    = (s2 + t2) >> exp;
+            *pData4      = (r2 - r1) >> exp;
+
+            *pData3--    = (s2 - t2) >> exp;
+            *pData3      = (r2 + r1) >> exp;
+
+
+        }  /* i */
+
+        for (j = 1; j < n2; j++)
+        {
+            exp_jw1 = *pw++;
+            exp_jw2 = *pw++;
+            exp_jw3 = *pw++;
+
+
+            for (i = j; i < FFT_RX4_SHORT; i += n1)
+            {
+                pData1 = &Data[ i<<1];
+                pData3 = pData1 + n3;
+                pData2 = pData1 + n1;
+                pData4 = pData3 + n1;
+
+                temp1   = *(pData1);
+                temp2   = *(pData2++);
+                temp1   >>= shift;
+                temp2   >>= shift;
+
+                r1      = temp1 + temp2;
+                r2      = temp1 - temp2;
+                temp3   = *(pData3++);
+                temp4   = *(pData4++);
+                temp3   >>= shift;
+                temp4   >>= shift;
+
+                t1      = temp3 + temp4;
+                t2      = temp3 - temp4;
+
+                *(pData1++) = (r1 + t1) >> exp;
+                r1          = (r1 - t1) >> exp;
+
+                temp1   = *pData1;
+                temp2   = *pData2;
+                temp1   >>= shift;
+                temp2   >>= shift;
+
+                s1      = temp1 + temp2;
+                s2      = temp1 - temp2;
+
+                s3      = (s2 + t2) >> exp;
+                s2      = (s2 - t2) >> exp;
+
+                temp3   = *pData3;
+                temp4   = *pData4 ;
+                temp3   >>= shift;
+                temp4   >>= shift;
+
+                t1      = temp3 + temp4;
+                t2      = temp3 - temp4;
+
+                *pData1  = (s1 + t1) >> exp;
+                s1       = (s1 - t1) >> exp;
+
+
+                *pData2--  = cmplx_mul32_by_16(s1, -r1, exp_jw2) << 1;
+                *pData2    = cmplx_mul32_by_16(r1,  s1, exp_jw2) << 1;
+
+                r3       = ((r2 - t2) >> exp);
+                r2       = ((r2 + t2) >> exp);
+
+                *pData3--  = cmplx_mul32_by_16(s2, -r2, exp_jw1) << 1;
+                *pData3    = cmplx_mul32_by_16(r2,  s2, exp_jw1) << 1;
+
+                *pData4--  = cmplx_mul32_by_16(s3, -r3, exp_jw3) << 1;
+                *pData4    = cmplx_mul32_by_16(r3,  s3, exp_jw3) << 1;
+
+            }  /* i */
+
+        }  /*  j */
+
+        /*
+         *  this will reset exp and shift to zero for the second pass of the
+         *  loop
+         */
+        exp   = 2;
+        shift = 0;
+
+    } /* k */
+
+
+    max = 0;
+
+    pData1 = Data - 7;
+
+    for (i = ONE_FOURTH_FFT_RX4_SHORT; i != 0 ; i--)
+    {
+        pData1 += 7;
+
+        pData3 = pData1 + 2;
+        pData2 = pData1 + 4;
+        pData4 = pData1 + 6;
+
+        temp1   = *pData1;
+        temp2   = *pData2++;
+
+        r1      = temp1 + temp2;
+        r2      = temp1 - temp2;
+
+        temp1   = *pData3++;
+        temp2   = *pData4++;
+
+        t1      = temp1 + temp2;
+        t2      = temp1 - temp2;
+
+        temp1       = (r1 + t1);
+        r1          = (r1 - t1);
+        *(pData1++) = temp1;
+        max        |= (temp1 >> 31) ^ temp1;
+
+
+
+        temp1   = *pData1;
+        temp2   = *pData2;
+
+        s1      = temp1 + temp2;
+        s2      = temp1 - temp2;
+
+        s3      = (s2 + t2);
+        s2      = (s2 - t2);
+
+        temp1   = *pData3;
+        temp2   = *pData4;
+
+        t1      = temp1 + temp2;
+        t2      = temp1 - temp2;
+
+        temp1      = (s1 + t1);
+        temp2      = (s1 - t1);
+        *pData1    = temp1;
+        *pData2--  = temp2;
+        max       |= (temp1 >> 31) ^ temp1;
+        max       |= (temp2 >> 31) ^ temp2;
+
+        *pData2    = r1;
+        *pData3--  = s2;
+        *pData4--  = s3;
+        max       |= (r1 >> 31) ^ r1;
+        max       |= (s2 >> 31) ^ s2;
+        max       |= (s3 >> 31) ^ s3;
+
+        temp1      = (r2 - t2);
+        temp2      = (r2 + t2);
+        *pData4    = temp1;
+        *pData3    = temp2;
+        max       |= (temp1 >> 31) ^ temp1;
+        max       |= (temp2 >> 31) ^ temp2;
+
+    }  /* i */
+
+    *peak_value = max;
+
+
+    return (exponent);
+
+}
diff --git a/media/libstagefright/codecs/aacdec/fft_rx4_tables_fxp.cpp b/media/libstagefright/codecs/aacdec/fft_rx4_tables_fxp.cpp
new file mode 100644
index 0000000..2476b87
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fft_rx4_tables_fxp.cpp
@@ -0,0 +1,269 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/fft_rx4_tables_fxp.c
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Reduce the accuracy of w_256rx4 and w_512rx2 to Q10 format.
+            Try to to pack sin and cos into one 32-bit number to reduce the
+            memory access, but doesn't help in speed, so commented out for now.
+
+ Description:
+        (1) Reduced precision of w_64rx4 from Q15 to Q12.
+        (2) Increased precision of w_512rx2 from Q10 to Q13, Both changes
+            increase overall decoder precision
+
+ Description:
+        (1) per code review comment, added description for table generation
+        (2) modified definition of w_64rx4 from Int to Int16
+
+
+ Who:                           Date:
+ Description:
+
+  ----------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+  Table generation
+
+ n = 256  or  64;
+ M = precision; 2^10, 2^12, 2^13
+
+ for j=1; j<log4(n); j *= 4
+
+    for i=0; i<n/4; i +=j
+
+        phi_1 = 2*pi*i/n;
+        phi_2 = 4*pi*i/n;
+        phi_3 = 6*pi*i/n;
+        M*[cos(phi_1) sin(phi_1) cos(phi_2) sin(phi_2) cos(phi_3) sin(phi_4)];
+
+    end
+
+ end
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "fft_rx4.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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ Forward FFT radix-4 tables
+------------------------------------------------------------------------------
+*/
+
+
+const Int32 W_64rx4[60] =            /* 2 Q15  */
+{
+
+    0x7F610C8C,  0x7D8918F9,  0x7A7C2528,
+    0x7D8918F9,  0x764130FB,  0x6A6D471C,
+    0x7A7C2528,  0x6A6D471C,  0x513362F1,
+    0x764130FB,  0x5A825A82,  0x30FB7641,
+    0x70E23C56,  0x471C6A6D,  0x0C8C7F61,
+    0x6A6D471C,  0x30FB7641,  0xE7057D89,
+    0x62F15133,  0x18F97D89,  0xC3A870E2,
+    0x5A825A82,  0x00007FFF,  0xA57C5A82,
+    0x513362F1,  0xE7057D89,  0x8F1C3C56,
+    0x471C6A6D,  0xCF037641,  0x827518F9,
+    0x3C5670E2,  0xB8E26A6D,  0x809DF372,
+    0x30FB7641,  0xA57C5A82,  0x89BDCF03,
+    0x25287A7C,  0x9591471C,  0x9D0DAECB,
+    0x18F97D89,  0x89BD30FB,  0xB8E29591,
+    0x0C8C7F61,  0x827518F9,  0xDAD68582,
+    0x764130FB,  0x5A825A82,  0x30FB7641,
+    0x5A825A82,  0x00007FFF,  0xA57C5A82,
+    0x30FB7641,  0xA57C5A82,  0x89BDCF03,
+};
+
+
+
+const Int32 W_256rx4[495] =            /* 2 Q15  */
+{
+
+    0x7FF50324,  0x7FD80648,  0x7FA6096A,
+    0x7FD80648,  0x7F610C8C,  0x7E9C12C8,
+    0x7FA6096A,  0x7E9C12C8,  0x7CE31C0B,
+    0x7F610C8C,  0x7D8918F9,  0x7A7C2528,
+    0x7F090FAB,  0x7C291F1A,  0x776B2E11,
+    0x7E9C12C8,  0x7A7C2528,  0x73B536BA,
+    0x7E1D15E2,  0x78842B1F,  0x6F5E3F17,
+    0x7D8918F9,  0x764130FB,  0x6A6D471C,
+    0x7CE31C0B,  0x73B536BA,  0x64E84EBF,
+    0x7C291F1A,  0x70E23C56,  0x5ED755F5,
+    0x7B5C2223,  0x6DC941CE,  0x58425CB3,
+    0x7A7C2528,  0x6A6D471C,  0x513362F1,
+    0x79892826,  0x66CF4C3F,  0x49B468A6,
+    0x78842B1F,  0x62F15133,  0x41CE6DC9,
+    0x776B2E11,  0x5ED755F5,  0x398C7254,
+    0x764130FB,  0x5A825A82,  0x30FB7641,
+    0x750433DF,  0x55F55ED7,  0x28267989,
+    0x73B536BA,  0x513362F1,  0x1F1A7C29,
+    0x7254398C,  0x4C3F66CF,  0x15E27E1D,
+    0x70E23C56,  0x471C6A6D,  0x0C8C7F61,
+    0x6F5E3F17,  0x41CE6DC9,  0x03247FF5,
+    0x6DC941CE,  0x3C5670E2,  0xF9B67FD8,
+    0x6C23447A,  0x36BA73B5,  0xF0537F09,
+    0x6A6D471C,  0x30FB7641,  0xE7057D89,
+    0x68A649B4,  0x2B1F7884,  0xDDDB7B5C,
+    0x66CF4C3F,  0x25287A7C,  0xD4DF7884,
+    0x64E84EBF,  0x1F1A7C29,  0xCC1F7504,
+    0x62F15133,  0x18F97D89,  0xC3A870E2,
+    0x60EB539B,  0x12C87E9C,  0xBB846C23,
+    0x5ED755F5,  0x0C8C7F61,  0xB3BF66CF,
+    0x5CB35842,  0x06487FD8,  0xAC6360EB,
+    0x5A825A82,  0x00007FFF,  0xA57C5A82,
+    0x58425CB3,  0xF9B67FD8,  0x9F13539B,
+    0x55F55ED7,  0xF3727F61,  0x992F4C3F,
+    0x539B60EB,  0xED367E9C,  0x93DB447A,
+    0x513362F1,  0xE7057D89,  0x8F1C3C56,
+    0x4EBF64E8,  0xE0E47C29,  0x8AFA33DF,
+    0x4C3F66CF,  0xDAD67A7C,  0x877A2B1F,
+    0x49B468A6,  0xD4DF7884,  0x84A22223,
+    0x471C6A6D,  0xCF037641,  0x827518F9,
+    0x447A6C23,  0xC94473B5,  0x80F50FAB,
+    0x41CE6DC9,  0xC3A870E2,  0x80260648,
+    0x3F176F5E,  0xBE306DC9,  0x8009FCDA,
+    0x3C5670E2,  0xB8E26A6D,  0x809DF372,
+    0x398C7254,  0xB3BF66CF,  0x81E1EA1C,
+    0x36BA73B5,  0xAECB62F1,  0x83D5E0E4,
+    0x33DF7504,  0xAA095ED7,  0x8675D7D8,
+    0x30FB7641,  0xA57C5A82,  0x89BDCF03,
+    0x2E11776B,  0xA12755F5,  0x8DAAC672,
+    0x2B1F7884,  0x9D0D5133,  0x9235BE30,
+    0x28267989,  0x992F4C3F,  0x9758B64A,
+    0x25287A7C,  0x9591471C,  0x9D0DAECB,
+    0x22237B5C,  0x923541CE,  0xA34BA7BC,
+    0x1F1A7C29,  0x8F1C3C56,  0xAA09A127,
+    0x1C0B7CE3,  0x8C4936BA,  0xB13F9B16,
+    0x18F97D89,  0x89BD30FB,  0xB8E29591,
+    0x15E27E1D,  0x877A2B1F,  0xC0E790A0,
+    0x12C87E9C,  0x85822528,  0xC9448C49,
+    0x0FAB7F09,  0x83D51F1A,  0xD1ED8893,
+    0x0C8C7F61,  0x827518F9,  0xDAD68582,
+    0x096A7FA6,  0x816212C8,  0xE3F3831B,
+    0x06487FD8,  0x809D0C8C,  0xED368162,
+    0x03247FF5,  0x80260648,  0xF6948058,
+    0x7F610C8C,  0x7D8918F9,  0x7A7C2528,
+    0x7D8918F9,  0x764130FB,  0x6A6D471C,
+    0x7A7C2528,  0x6A6D471C,  0x513362F1,
+    0x764130FB,  0x5A825A82,  0x30FB7641,
+    0x70E23C56,  0x471C6A6D,  0x0C8C7F61,
+    0x6A6D471C,  0x30FB7641,  0xE7057D89,
+    0x62F15133,  0x18F97D89,  0xC3A870E2,
+    0x5A825A82,  0x00007FFF,  0xA57C5A82,
+    0x513362F1,  0xE7057D89,  0x8F1C3C56,
+    0x471C6A6D,  0xCF037641,  0x827518F9,
+    0x3C5670E2,  0xB8E26A6D,  0x809DF372,
+    0x30FB7641,  0xA57C5A82,  0x89BDCF03,
+    0x25287A7C,  0x9591471C,  0x9D0DAECB,
+    0x18F97D89,  0x89BD30FB,  0xB8E29591,
+    0x0C8C7F61,  0x827518F9,  0xDAD68582,
+    0x764130FB,  0x5A825A82,  0x30FB7641,
+    0x5A825A82,  0x00007FFF,  0xA57C5A82,
+    0x30FB7641,  0xA57C5A82,  0x89BDCF03
+};
+
+
+
+/*
+------------------------------------------------------------------------------
+ Forward FFT radix-2 table
+------------------------------------------------------------------------------
+*/
+
+
+const Int32 w_512rx2[127] =
+{
+    /* Q15  */
+    0x7FFE0192, 0x7FF60324, 0x7FEA04B6,
+    0x7FD90648,  0x7FC207D9, 0x7FA7096B, 0x7F870AFB,
+    0x7F620C8C,  0x7F380E1C, 0x7F0A0FAB, 0x7ED6113A,
+    0x7E9D12C8,  0x7E601455, 0x7E1E15E2, 0x7DD6176E,
+    0x7D8A18F9,  0x7D3A1A83, 0x7CE41C0C, 0x7C891D93,
+    0x7C2A1F1A,  0x7BC6209F, 0x7B5D2224, 0x7AEF23A7,
+    0x7A7D2528,  0x7A0626A8, 0x798A2827, 0x790A29A4,
+    0x78852B1F,  0x77FB2C99, 0x776C2E11, 0x76D92F87,
+    0x764230FC,  0x75A6326E, 0x750533DF, 0x7460354E,
+    0x73B636BA,  0x73083825, 0x7255398D, 0x719E3AF3,
+    0x70E33C57,  0x70233DB8, 0x6F5F3F17, 0x6E974074,
+    0x6DCA41CE,  0x6CF94326, 0x6C24447B, 0x6B4B45CD,
+    0x6A6E471D,  0x698C486A, 0x68A749B4, 0x67BD4AFB,
+    0x66D04C40,  0x65DE4D81, 0x64E94EC0, 0x63EF4FFB,
+    0x62F25134,  0x61F15269, 0x60EC539B, 0x5FE454CA,
+    0x5ED755F6,  0x5DC8571E, 0x5CB45843, 0x5B9D5964,
+    0x5A825A82,  0x59645B9D, 0x58435CB4, 0x571E5DC8,
+    0x55F65ED7,  0x54CA5FE4, 0x539B60EC, 0x526961F1,
+    0x513462F2,  0x4FFB63EF, 0x4EC064E9, 0x4D8165DE,
+    0x4C4066D0,  0x4AFB67BD, 0x49B468A7, 0x486A698C,
+    0x471D6A6E,  0x45CD6B4B, 0x447B6C24, 0x43266CF9,
+    0x41CE6DCA,  0x40746E97, 0x3F176F5F, 0x3DB87023,
+    0x3C5770E3,  0x3AF3719E, 0x398D7255, 0x38257308,
+    0x36BA73B6,  0x354E7460, 0x33DF7505, 0x326E75A6,
+    0x30FC7642,  0x2F8776D9, 0x2E11776C, 0x2C9977FB,
+    0x2B1F7885,  0x29A4790A, 0x2827798A, 0x26A87A06,
+    0x25287A7D,  0x23A77AEF, 0x22247B5D, 0x209F7BC6,
+    0x1F1A7C2A,  0x1D937C89, 0x1C0C7CE4, 0x1A837D3A,
+    0x18F97D8A,  0x176E7DD6, 0x15E27E1E, 0x14557E60,
+    0x12C87E9D,  0x113A7ED6, 0x0FAB7F0A, 0x0E1C7F38,
+    0x0C8C7F62,  0x0AFB7F87, 0x096B7FA7, 0x07D97FC2,
+    0x06487FD9,  0x04B67FEA, 0x03247FF6, 0x01927FFE
+};
+
diff --git a/media/libstagefright/codecs/aacdec/find_adts_syncword.cpp b/media/libstagefright/codecs/aacdec/find_adts_syncword.cpp
new file mode 100644
index 0000000..535f177
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/find_adts_syncword.cpp
@@ -0,0 +1,305 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/find_adts_syncword.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Fixed error in logic that determines whether there are enough
+ bits available to conduct a search for the syncword.  The plus sign in
+ the following condition should be a minus.
+
+    if (pInputStream->usedBits <
+            (pInputStream->availableBits + syncword_length)
+
+ The length of the syncword should subtract from the number of available
+ bits, not add.
+
+ Description:  Fixed condition when the end of file was found, unsigned
+   comparison produced a undesired search. Fixed by casting comparison
+     if ((Int)pInputStream->usedBits <
+            ((Int)pInputStream->availableBits - syncword_length) )
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pSyncword     = Pointer to variable containing the syncword that the
+                    function should be scanning for in the buffer. [ UInt32 * ]
+
+    pInputStream  = Pointer to a BITS structure, used by the function getbits
+                    to retrieve data from the bitstream.  [ BITS * ]
+
+    syncword_length = The length of the syncword. [ Int ]
+
+    syncword_mask   = A mask to be applied to the bitstream before comparison
+                      with the value pointed to by pSyncword. [ UInt32 ]
+
+ 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
+
+ This module scans the bitstream for a syncword of any length between 1 and 32.
+ If certain bits in the syncword are to be ignored, that bit position should
+ be set to 0 in both parameters *(pSyncword) and syncword_mask.  This allows
+ for a syncword to be constructed out of non-contiguous bits.
+
+ Upon finding the syncword's position in the bitstream, a value denoting the
+ syncword's degree of deviance from being byte-aligned (byte_align_offset)
+ is set in the structure pointed to by pInputStream.
+ This is a value between 0 and 7.
+
+ If no syncword is found, the function returns status == ERROR.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ "Don't care" bits must be set to '0' in both *(pSyncword) and syncword_mask.
+
+ This function should not be called if there are less than
+ (8 + syncword_length) bits in the buffer.
+
+------------------------------------------------------------------------------
+ REFERENCES
+ (1) ISO/IEC 13818-7:1997(E)
+     Part 7
+        Subpart 6.2 (Audio_Data_Transport_Stream frame, ADTS)
+
+ (2) ISO/IEC 11172-3:1993(E)
+     Part 3
+        Subpart 2.4.3 The audio decoding process
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF (pInputStream->usedBits <
+            (pInputStream->availableBits + syncword_length) )
+
+        max_search_length = (pInputStream->availableBits - pInputStream->usedBits);
+
+        max_search_length = max_search_length - syncword_length;
+
+        search_length = 0;
+
+        adts_header =
+        CALL getbits(syncword_length, pInputStream);
+            MODIFYING pInputStream->usedBits
+            RETURNING bits from bitstream of length (syncword_length)
+
+        test_for_syncword = adts_header AND syncword_mask;
+        test_for_syncword = test_for_syncword XOR syncword;
+
+        WHILE ( (test_for_syncword != 0) && (search_length > 0) )
+
+            search_length = search_length - 1;
+
+            adts_header = adts_header << 1;
+            adts_header = adts_header OR ...
+
+            CALL getbits(syncword_length, pInputStream);
+                MODIFYING pInputStream->usedBits
+                RETURNING 1 bit from the bitstream
+
+            test_for_syncword = adts_header AND syncword_mask;
+            test_for_syncword = test_for_syncword XOR syncword;
+
+        ENDWHILE
+
+        IF (search_length == 0)
+            status = ERROR;
+        ENDIF
+
+        *(pSyncword) = adts_header;
+
+         pInputStream->byteAlignOffset =
+             (pInputStream->usedBits - syncwordlength) AND 0x7;
+
+    ELSE
+        status = ERROR;
+    ENDIF
+
+    return (status);
+
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_bits.h"
+#include "ibstream.h"
+#include "find_adts_syncword.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define FIND_ADTS_ERROR -1
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int find_adts_syncword(
+    UInt32 *pSyncword,
+    BITS   *pInputStream,
+    Int     syncword_length,
+    UInt32  syncword_mask)
+{
+
+    Int    status = SUCCESS;
+    UInt   search_length;
+    UInt32 adts_header = 0;
+    UInt32 test_for_syncword;
+    UInt32 syncword = *(pSyncword);
+
+    /*
+     * Determine the maximum number of bits available to this function for
+     * the syncword search.
+     */
+    if ((Int)pInputStream->usedBits <
+            ((Int)pInputStream->availableBits - syncword_length))
+    {
+        search_length = (pInputStream->availableBits - pInputStream->usedBits);
+
+        search_length -= syncword_length;
+
+        adts_header  = getbits(syncword_length, pInputStream);
+
+        /*
+         * Mask the result in adts_header with the syncword_mask, so only the
+         * bits relevant to syncword detection are compared to *(pSyncword).
+         */
+        test_for_syncword  = adts_header & syncword_mask;
+        test_for_syncword ^= syncword;
+
+        /*
+         * Scan bit-by-bit through the bitstream, until the function either
+         * runs out of bits, or finds the syncword.
+         */
+
+        while ((test_for_syncword != 0) && (search_length > 0))
+        {
+            search_length--;
+
+            adts_header <<= 1;
+            adts_header |= getbits(1, pInputStream);
+
+            test_for_syncword  = adts_header & syncword_mask;
+            test_for_syncword ^= syncword;
+        }
+
+        if (search_length == 0)
+        {
+            status = FIND_ADTS_ERROR;
+        }
+
+        /*
+         * Return the syncword's position in the bitstream.  Correct placement
+         * of the syncword will result in byte_align_offset == 0.
+         * If the syncword is found not to be byte-aligned, then return
+         * the degree of disalignment, so further decoding can
+         * be shifted as necessary.
+         *
+         */
+        pInputStream->byteAlignOffset =
+            (pInputStream->usedBits - syncword_length) & 0x7;
+
+    } /* END if (pInputStream->usedBits < ...) */
+
+    else
+    {
+        status = FIND_ADTS_ERROR;
+    }
+
+    *(pSyncword) = adts_header;
+
+    return (status);
+
+} /* find_adts_syncword() */
diff --git a/media/libstagefright/codecs/aacdec/find_adts_syncword.h b/media/libstagefright/codecs/aacdec/find_adts_syncword.h
new file mode 100644
index 0000000..d147bc5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/find_adts_syncword.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/find_adts_syncword.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This function includes the function declaration for find_adts_syncword()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef FIND_ADTS_SYNCWORD_H
+#define FIND_ADTS_SYNCWORD_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int find_adts_syncword(
+    UInt32 *pSyncword,
+    BITS   *pInputStream,
+    Int     syncword_length,
+    UInt32  syncword_mask);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.cpp b/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.cpp
new file mode 100644
index 0000000..b85c7df
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.cpp
@@ -0,0 +1,284 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/fwd_long_complex_rot.c
+ Funtions: fwd_long_complex_rot
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Date: 10/18/2002
+ Description:
+            (1) Change the input arguments, no shifts information from
+                long_fft_rx4 is passed, only a single max is passed.
+            (2) Eliminate search for max, a fixed shift has replaced the
+                search for max with minimal loss of precision.
+            (3) Eliminated unused variables
+
+ Date: 10/28/2002
+ Description:
+            (1) Added comments per code review
+            (2) Eliminated hardly used condition on if-else (exp==0)
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    Data_in   = Input vector (sized for long windows
+                TWICE_FWD_LONG_CX_ROT_LENGTH), with time domain samples
+                type Int32 *
+
+    Data_out  = Output vector with a post-rotation by exp(-j(2pi/N)(k+1/8)),
+                (sized for long windows TWICE_FWD_LONG_CX_ROT_LENGTH)
+                type Int32 *
+
+    max       = Input, carries the maximum value of the input vector
+                "Data_in"
+                type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exp = shift factor to reflect signal scaling
+
+ Pointers and Buffers Modified:
+    Results are return in "Data_out"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    fwd_long_complex_rot() performs the pre complex rotation for the MDCT
+    for the case of long windows. It also performs digit reverse ordering of
+    the first and second halves of the input vector "Data_in", as well as
+    reordering of the two half vectors (following radix-2 decomposition)
+    Word normalization is also done to ensure 16 by 16 bit multiplications.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    fwd_long_complex_rot() should execute a pre-rotation by
+    exp(-j(2pi/N)(k+1/8)), digit reverse ordering and normalization
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ 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 "fwd_long_complex_rot.h"
+#include "digit_reversal_tables.h"
+#include "imdct_fxp.h"
+#include "pv_normalize.h"
+
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+Int fwd_long_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max)
+{
+    Int     i;
+    const   Int32 *p_rotate;
+    Int32   temp_re;
+    Int32   temp_im;
+    Int32   *pData_in_ref1;
+    Int32   *pData_in_ref2;
+    Int32   exp_jw;
+    Int32   temp_re_32;
+    Int32   temp_im_32;
+
+    Int32   *pData_out_1;
+    Int32   *pData_out_2;
+    Int32   *pData_out_3;
+    Int32   *pData_out_4;
+
+    Int32 *pData_in_1;
+    Int32 *pData_in_2;
+
+    Int     exp;
+
+    p_rotate       =  exp_rotation_N_2048;
+
+    pData_in_ref1  =  Data_in;
+    pData_in_ref2  = &Data_in[TWICE_FWD_LONG_CX_ROT_LENGTH];
+
+    pData_out_1 = Data_out;
+    pData_out_2 = &Data_out[LONG_WINDOW_LENGTH_m_1];
+    pData_out_3 = &Data_out[LONG_WINDOW_LENGTH];
+    pData_out_4 = &Data_out[TWICE_LONG_WINDOW_LENGTH_m_1];
+
+    /*
+     *  Data_out
+     *                                   >>>>                   <<<<
+     *                                pData_out_3             pData_out_4
+     *      |             |             |             |             |
+     * pData_out_1               pData_out_2
+     *      >>>>                     <<<<
+     */
+
+
+    exp = 16 - pv_normalize(max);
+
+    if (exp < 0)
+    {
+        exp = 0;
+    }
+
+    /*
+     *  Apply  A/2^(diff) + B
+     */
+
+
+    pData_in_1 = pData_in_ref1;
+    pData_in_2 = pData_in_ref2;
+
+    for (i = FWD_LONG_CX_ROT_LENGTH; i != 0; i--)
+    {
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+
+        exp_jw = *p_rotate++;
+
+        /*
+         *  Use auxiliary variables to avoid double accesses to memory.
+         *  Data in is scaled to use only lower 16 bits.
+         */
+
+        temp_re =  *(pData_in_1++) >> exp;
+        temp_im =  *(pData_in_1++) >> exp;
+
+        /*
+         *   Pre-rotation
+         */
+
+        temp_re_32  = (cmplx_mul32_by_16(temp_re,   temp_im,  exp_jw));
+        temp_im_32  = (cmplx_mul32_by_16(temp_im,  -temp_re,  exp_jw));
+
+        *(pData_out_1++) = - temp_re_32;
+        *(pData_out_2--) =   temp_im_32;
+        *(pData_out_3++) = - temp_im_32;
+        *(pData_out_4--) =   temp_re_32;
+
+        /*
+         *   Pointer increment to jump over imag (1 & 4) or real parts
+         *   (2 & 3)
+         */
+        pData_out_1++;
+        pData_out_2--;
+        pData_out_3++;
+        pData_out_4--;
+
+        /*
+         *   Repeat procedure for odd index at the output
+         */
+
+        exp_jw = *p_rotate++;
+
+        temp_re =  *(pData_in_2++) >> exp;
+        temp_im =  *(pData_in_2++) >> exp;
+
+        temp_re_32  = (cmplx_mul32_by_16(temp_re,   temp_im,  exp_jw));
+        temp_im_32  = (cmplx_mul32_by_16(temp_im,  -temp_re,  exp_jw));
+
+        *(pData_out_1++) = - temp_re_32;
+        *(pData_out_2--) =   temp_im_32;
+        *(pData_out_3++) = - temp_im_32;
+        *(pData_out_4--) =   temp_re_32;
+
+        pData_out_1++;
+        pData_out_2--;
+        pData_out_3++;
+        pData_out_4--;
+
+    }
+
+    return (exp + 1);
+}
diff --git a/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.h b/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.h
new file mode 100644
index 0000000..5978906
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fwd_long_complex_rot.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/fwd_long_complex_rot.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions fwd_long_complex_rot
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef FWD_LONG_COMPLEX_ROT_H
+#define FWD_LONG_COMPLEX_ROT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define FWD_LONG_CX_ROT_LENGTH              256
+#define TWICE_FWD_LONG_CX_ROT_LENGTH        (FWD_LONG_CX_ROT_LENGTH<<1)
+#define LONG_WINDOW_LENGTH                  1024
+#define LONG_WINDOW_LENGTH_m_1              (LONG_WINDOW_LENGTH - 1)
+#define TWICE_LONG_WINDOW_LENGTH_m_1        ((LONG_WINDOW_LENGTH<<1) - 1)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+
+Int fwd_long_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* FWD_LONG_COMPLEX_ROT_H */
diff --git a/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.cpp b/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.cpp
new file mode 100644
index 0000000..964f766
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.cpp
@@ -0,0 +1,261 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Pathname: ./src/fwd_short_complex_rot.c
+ Funtions:  fwd_short_complex_rot
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Date: 10/18/2002
+ Description:
+            (1) Change the input argument, only a single max is passed.
+            (2) Eliminate search for max, a fixed shift has replaced the
+                search for max with minimal loss of precision.
+            (3) Eliminated unused variables
+
+ Date: 10/28/2002
+ Description:
+            (1) Added comments per code review
+            (2) Eliminated hardly used condition on if-else (exp==0)
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    Data_in   = Input vector (sized for short windows
+                2*FWD_SHORT_CX_ROT_LENGTH elements), with freq. domain samples
+                type Int32 *
+
+    Data_out  = Output vector with a post-rotation by exp(-j(2pi/N)(k+1/8)),
+                (sized for short windows 2*FWD_SHORT_CX_ROT_LENGTH)
+                type Int32 *
+
+    max       = Input, carries the maximum value of the input vector
+                "Data_in"
+                type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exp = shift factor to reflect signal scaling
+
+ Pointers and Buffers Modified:
+    Results are return in "Data_out"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    fwd_short_complex_rot() performs the complex rotation for the MDCT
+    for the case of short windows. It performs digit reverse ordering as well
+    word normalization to ensure 16 by 16 bit multiplications.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    fwd_short_complex_rot() should execute a pre-rotation by
+    exp(-j(2pi/N)(k+1/8)), digit reverse ordering and word normalization
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ 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 "fwd_short_complex_rot.h"
+#include "digit_reversal_tables.h"
+#include "imdct_fxp.h"
+#include "pv_normalize.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+Int fwd_short_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max)
+
+{
+    Int     i;
+    Int16     I;
+    const   Int16 *pTable;
+    const   Int32 *p_rotate;
+
+    Int32   *pData_in_1;
+    Int     exp;
+    Int32   temp_re;
+    Int32   temp_im;
+
+    Int32   cos_n;
+    Int32   sin_n;
+    Int32   temp_re_32;
+    Int32   temp_im_32;
+
+    Int32   *pData_in_ref;
+
+    Int32   *pData_out_1;
+    Int32   *pData_out_2;
+    Int32   *pData_out_3;
+    Int32   *pData_out_4;
+
+    pTable    =  digit_reverse_64;
+    p_rotate  =  exp_rotation_N_256;
+
+    pData_in_ref  =  Data_in;
+
+    exp = 16 - pv_normalize(max);
+
+    if (exp < 0)
+    {
+        exp = 0;
+    }
+
+    pData_out_1 = Data_out;
+    pData_out_2 = &Data_out[TWICE_FWD_SHORT_CX_ROT_LENGTH_m_1];
+    pData_out_3 = &Data_out[TWICE_FWD_SHORT_CX_ROT_LENGTH];
+    pData_out_4 = &Data_out[FOUR_FWD_SHORT_CX_ROT_LENGTH_m_1];
+
+    /*
+     *  Data_out
+     *                                   >>>>                   <<<<
+     *                                pData_out_3             pData_out_4
+     *      |             |             |             |             |
+     * pData_out_1               pData_out_2
+     *      >>>>                     <<<<
+     */
+
+
+    for (i = FWD_SHORT_CX_ROT_LENGTH; i != 0; i--)
+    {
+        /*
+         *   Perform digit reversal by accessing index I from table
+         */
+
+        I = *pTable++;
+        pData_in_1 = pData_in_ref + I;
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+
+        sin_n = *p_rotate++;
+        cos_n = sin_n >> 16;
+        sin_n = sin_n & 0xFFFF;
+
+        /*
+         *  Use auxiliary variables to avoid double accesses to memory.
+         *  Data in is scaled to use only lower 16 bits.
+         */
+
+        temp_re =  *(pData_in_1++) >> exp;
+        temp_im =  *(pData_in_1) >> exp;
+
+        /*
+         *   Pre-rotation
+         */
+
+        temp_re_32 = (temp_re * cos_n + temp_im * sin_n) >> 16;
+        temp_im_32 = (temp_im * cos_n - temp_re * sin_n) >> 16;
+
+        *(pData_out_1++) = - temp_re_32;
+        *(pData_out_2--) =   temp_im_32;
+        *(pData_out_3++) = - temp_im_32;
+        *(pData_out_4--) =   temp_re_32;
+
+        /*
+         *   Pointer increment to jump over imag (1 & 4) or real parts
+         *   (2 & 3)
+         */
+
+        pData_out_1++;
+        pData_out_2--;
+        pData_out_3++;
+        pData_out_4--;
+
+    } /* for(i) */
+
+    return (exp);
+}
diff --git a/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.h b/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.h
new file mode 100644
index 0000000..3d1e1f1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fwd_short_complex_rot.h
@@ -0,0 +1,92 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: .fwd_short_complex_rot.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions fwd_short_complex_rot
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef FWD_SHORT_COMPLEX_ROT_H
+#define FWD_SHORT_COMPLEX_ROT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define FWD_SHORT_CX_ROT_LENGTH             64
+#define TWICE_FWD_SHORT_CX_ROT_LENGTH       (FWD_SHORT_CX_ROT_LENGTH<<1)
+#define TWICE_FWD_SHORT_CX_ROT_LENGTH_m_1   ((FWD_SHORT_CX_ROT_LENGTH<<1) - 1)
+#define FOUR_FWD_SHORT_CX_ROT_LENGTH_m_1    ((FWD_SHORT_CX_ROT_LENGTH<<2) - 1)
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int fwd_short_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* FWD_SHORT_COMPLEX_ROT_H */
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32.h b/media/libstagefright/codecs/aacdec/fxp_mul32.h
new file mode 100644
index 0000000..230cef5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32.h
@@ -0,0 +1,72 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/fxp_mul32.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32
+#define FXP_MUL32
+
+#if   defined(PV_ARM_V5)
+
+#include "fxp_mul32_arm_v5.h"
+
+#elif defined(PV_ARM_V4)
+
+#include "fxp_mul32_arm_v4.h"
+
+#elif defined(PV_ARM_MSC_EVC_V4)
+
+#include "fxp_mul32_c_msc_evc.h"
+
+#elif defined(PV_ARM_MSC_EVC_V5)
+
+#include "fxp_mul32_c_msc_evc_armv5.h"
+
+#elif defined(PV_ARM_GCC_V5)
+
+#include "fxp_mul32_arm_gcc.h"
+
+#elif defined(PV_ARM_GCC_V4)
+
+#include "fxp_mul32_arm_v4_gcc.h"
+
+#else
+
+#ifndef C_EQUIVALENT
+#define C_EQUIVALENT
+#endif
+
+#include "fxp_mul32_c_equivalent.h"
+
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_arm_gcc.h b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_gcc.h
new file mode 100644
index 0000000..dc58976
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_gcc.h
@@ -0,0 +1,547 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/fxp_mul32_arm_gcc.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_ARM_GCC
+#define FXP_MUL32_ARM_GCC
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+
+#if (defined (PV_ARM_GCC_V4) || defined(PV_ARM_GCC_V5)) /* ARM GNU COMPILER  */
+
+
+
+#define preload_cache( a)
+
+
+    static inline Int32 shft_lft_1(Int32 y)
+    {
+        register Int32 x;
+        register Int32 ra = y;
+
+
+        asm volatile(
+            "qadd %0, %1, %1\n\t"
+    : "=&r*i"(x)
+                    : "r"(ra));
+
+        return (x);
+    }
+
+    static inline Int32 fxp_mul_16_by_16bb(Int32 L_var1, const Int32 L_var2)
+    {
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smulbb %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+
+    static inline Int32 fxp_mul_16_by_16tb(Int32 L_var1, const Int32 L_var2)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smultb %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+    static inline Int32 fxp_mul_16_by_16bt(Int32 L_var1, const Int32 L_var2)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smulbt %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+    static inline Int32 fxp_mul_16_by_16tt(Int32 L_var1, const Int32 L_var2)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smultt %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+    static inline Int32 fxp_mac_16_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+{
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "smlabb %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp);
+    }
+
+
+
+    static inline Int32 fxp_mac_16_by_16_bb(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+{
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "smlabb %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp);
+    }
+
+
+    static inline Int32 fxp_mac_16_by_16_bt(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+{
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "smlabt %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp);
+    }
+
+
+
+    static inline Int32 cmplx_mul32_by_16(Int32 x, const Int32 y, Int32 exp_jw)
+{
+        register Int32 cx_sum;
+        register Int32 rx = (Int32)x;
+        register Int32 ry = (Int32)y;
+        register Int32 rexp = (Int32)exp_jw;
+        asm volatile(
+            "smulwt %0, %1, %3\n\t"
+            "smlawb %0, %2, %3, %0"
+    : "=&r*i"(cx_sum)
+                    : "r"(rx),
+                    "r"(ry),
+                    "r"(rexp));
+
+        return (cx_sum);
+    }
+
+
+    static inline Int32 fxp_mul32_by_16(Int32 L_var1, const Int32 L_var2)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smulwb %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+    static inline Int32 fxp_mul32_by_16t(Int32 L_var1, const Int32 L_var2)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "smulwt %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp);
+    }
+
+
+
+    static inline Int32 fxp_mac32_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+{
+
+        register Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "smlawb %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp);
+    }
+
+
+    __inline  int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+{
+        sum += (int64)L_var1 * L_var2;
+        return (sum);
+    }
+
+
+
+
+    static inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %4, %4, %0, asl #2\n\t"
+                     "add %0, %4, %1, lsr #30"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mac32_Q31(Int32 L_add, const Int32 a, const Int32 b)
+{
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %0, %0, %4"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_msu32_Q31(Int32 L_sub, const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_sub;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "sub %0, %4, %0"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q31(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile(
+            "smull %1, %0, %2, %3"
+    : "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #2\n\t"
+                     "orr   %0, %0, %1, lsr #30"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mac32_Q29(const Int32 a, const Int32 b, Int32 L_add)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add   %4, %4, %0, lsl #3\n\t"
+                     "add   %0, %4, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_msu32_Q29(const Int32 a, const Int32 b, Int32 L_sub)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_sub;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "sub   %4, %4, %0, lsl #3\n\t"
+                     "sub   %0, %4, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+    static inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #3\n\t"
+                     "orr   %0, %0, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #4\n\t"
+                     "orr   %0, %0, %1, lsr #28"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+    static inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #5\n\t"
+                     "orr   %0, %0, %1, lsr #27"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #6\n\t"
+                     "orr   %0, %0, %1, lsr #26"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q20(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #12\n\t"
+                     "orr   %0, %0, %1, lsr #20"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q15(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #17\n\t"
+                     "orr   %0, %0, %1, lsr #15"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mul32_Q14(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2,  %3\n\t"
+                     "mov   %0, %0, lsl #18\n\t"
+                     "orr   %0, %0, %1, lsr #14"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4.h b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4.h
new file mode 100644
index 0000000..6869c54
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4.h
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: fxp_mul32_c_equivalent.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_ARM_V4
+#define FXP_MUL32_ARM_V4
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+
+#if defined(PV_ARM_V4)
+
+#define preload_cache( a)
+
+
+    __inline  Int32 shft_lft_1(Int32 L_var1)
+    {
+        Int32 x;
+        Int32 z = 1; /* rvct compiler problem */
+        __asm
+        {
+            mov x, L_var1, asl 1
+            teq L_var1, x, asr z
+            eorne  x, INT32_MAX, L_var1, asr #31
+        }
+
+        return(x);
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16bb(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+
+            mov L_var2, L_var2, asl #16
+            mov L_var2, L_var2, asr #16
+            mov L_var1, L_var1, asl #16
+            mov L_var1, L_var1, asr #16
+
+
+            mul L_var1, L_var2, L_var1
+        }
+
+        return L_var1;
+
+    }
+
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+
+    __inline  Int32 fxp_mul_16_by_16tb(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            mov L_var2, L_var2, asl #16
+            mov L_var2, L_var2, asr #16
+            mov L_var1, L_var1, asr #16
+
+            mul L_var1, L_var2, L_var1
+        }
+        return L_var1;
+    }
+
+    __inline  Int32 fxp_mul_16_by_16bt(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            mov L_var2, L_var2, asr #16
+            mov L_var1, L_var1, asl #16
+            mov L_var1, L_var1, asr #16
+
+            mul L_var1, L_var2, L_var1
+        }
+
+        return L_var1;
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16tt(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            mov L_var2, L_var2, asr #16
+            mov L_var1, L_var1, asr #16
+
+            mul L_var1, L_var2, L_var1
+        }
+
+        return L_var1;
+
+    }
+
+    __inline  Int32 fxp_mac_16_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            mla L_add, L_var1, L_var2, L_add
+        }
+        return (L_add);
+    }
+
+
+    __inline  Int32 fxp_mac_16_by_16_bb(const Int32 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            mov L_var2, L_var2, asl #16
+            mov L_var2, L_var2, asr #16
+            mla L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_mac_16_by_16_bt(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            mov L_var2, L_var2, asr #16
+            mla L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+
+    __inline  Int32 cmplx_mul32_by_16(Int32 x, const Int32 y, Int32 exp_jw)
+    {
+
+        Int32 result64_hi;
+        Int32 rTmp0;
+        Int32 iTmp0;
+        __asm
+        {
+            mov rTmp0, exp_jw, asr #16
+            mov rTmp0, rTmp0, asl #16
+            mov iTmp0, exp_jw, asl #16
+            smull rTmp0, result64_hi, x, rTmp0
+            smlal iTmp0, result64_hi, y, iTmp0
+        }
+
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mul32_by_16(Int32 L_var1, Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            mov L_var2, L_var2, asl #16
+            smull L_var1, result64_hi, L_var2, L_var1
+        }
+        return (result64_hi);
+    }
+
+
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+
+    __inline  Int32 fxp_mul32_by_16t(Int32 L_var1, Int32 L_var2)
+    {
+
+        Int32 result64_hi;
+        __asm
+        {
+            mov L_var2, L_var2, asr #16
+            mov L_var2, L_var2, asl #16
+            smull L_var1, result64_hi, L_var2, L_var1
+        }
+        return (result64_hi);
+
+    }
+
+    __inline  Int32 fxp_mac32_by_16(Int32 L_var1, Int32 L_var2, Int32 L_add)
+    {
+
+        __asm
+        {
+            mov L_var2, L_var2, asl #16
+            smlal L_var1, L_add, L_var2, L_var1
+        }
+
+        return (L_add);
+    }
+
+
+    __inline  int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+    {
+        uint32 b = (UInt32)(sum);
+        int32 c = Int32(sum >> 32);
+        __asm
+        {
+            smlal b, c, L_var1, L_var2
+        }
+        return (((int64(c)) << 32) | b);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q31(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            smull L_var1, result64_hi, L_var2, L_var1
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mac32_Q31(Int32 L_add,  Int32 L_var1, const Int32 L_var2)
+    {
+        __asm
+        {
+            smlal L_var1, L_add, L_var2, L_var1
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_msu32_Q31(Int32 L_sub,  Int32 L_var1, const Int32 L_var2)
+    {
+        __asm
+        {
+            rsb   L_var1, L_var1, #0
+            smlal L_var1, L_sub, L_var2, L_var1
+        }
+        return L_sub;
+    }
+
+
+    __inline  Int32 fxp_mul32_Q30(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #2
+            orr  result64_hi, result64_hi, result64_lo, lsr #30
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mac32_Q30(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            add L_add, L_add, result64_hi, asl  #2
+            add L_add, L_add, result64_lo, lsr  #30
+        }
+        return (L_add);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q29(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #3
+            orr  result64_hi, result64_hi, result64_lo, lsr #29
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mac32_Q29(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            add L_add, L_add, result64_hi, asl  #3
+            add L_add, L_add, result64_lo, lsr  #29
+        }
+        return (L_add);
+    }
+
+    __inline  Int32 fxp_msu32_Q29(const Int32 L_var1, const Int32 L_var2, Int32 L_sub)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            sub L_sub, L_sub, result64_hi, asl  #3
+            sub L_sub, L_sub, result64_lo, lsr  #29
+        }
+        return (L_sub);
+    }
+
+    __inline  Int32 fxp_mul32_Q28(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #4
+            orr  result64_hi, result64_hi, result64_lo, lsr #28
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q27(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #5
+            orr  result64_hi, result64_hi, result64_lo, lsr #27
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q26(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #6
+            orr  result64_hi, result64_hi, result64_lo, lsr #26
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q20(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #12
+            orr  result64_hi, result64_hi, result64_lo, lsr #20
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q15(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #17
+            orr  result64_hi, result64_hi, result64_lo, lsr #15
+        }
+        return (result64_hi);
+    }
+
+
+
+
+    __inline  Int32 fxp_mul32_Q14(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #18
+            orr  result64_hi, result64_hi, result64_lo, lsr #14
+        }
+        return (result64_hi);
+    }
+
+
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4_gcc.h b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4_gcc.h
new file mode 100755
index 0000000..f4ab2f7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v4_gcc.h
@@ -0,0 +1,630 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: fxp_mul32_arm_v4_gcc.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+
+
+#ifndef FXP_MUL32_V4_ARM_GCC
+#define FXP_MUL32_V4_ARM_GCC
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+
+#if defined (_ARM_V4_GCC) /* ARM_V4 GNU COMPILER  */
+
+
+#define preload_cache( a)
+
+
+    static inline  Int32 shft_lft_1(Int32 L_var1)
+    {
+        Int32 x;
+        register Int32 ra = L_var1;
+        Int32 z = INT32_MAX;
+
+        asm volatile(
+            "mov %0, %1, asl #1\n\t"
+            "teq %1, %0, asr #1\n\t"
+            "eorne   %0, %2, %1, asr #31"
+    : "=&r*i"(x)
+                    : "r"(ra),
+                    "r"(z));
+
+        return(x);
+    }
+
+    static inline Int32 fxp_mul_16_by_16bb(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %3, asl #16\n\t"
+            "mov %0, %0, asr #16\n\t"
+            "mov %1, %2, asl #16\n\t"
+            "mov %1, %1, asr #16\n\t"
+            "mul %0, %1, %0"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp1);
+
+    }
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+
+    static inline Int32 fxp_mul_16_by_16tb(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %3, asl #16\n\t"
+            "mov %0, %0, asr #16\n\t"
+            "mov %1, %2, asr #16\n\t"
+            "mul %0, %1, %0"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp1);
+
+    }
+
+
+    static inline Int32 fxp_mul_16_by_16bt(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %3, asr #16\n\t"
+            "mov %1, %2, asl #16\n\t"
+            "mov %1, %1, asr #16\n\t"
+            "mul %0, %1, %0"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp1);
+
+    }
+
+
+    static inline Int32 fxp_mul_16_by_16tt(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %3, asr #16\n\t"
+            "mov %1, %2, asr #16\n\t"
+            "mul %0, %1, %0"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (tmp1);
+
+    }
+
+
+
+    static inline  Int32 fxp_mac_16_by_16(Int16 L_var1,  Int16 L_var2, Int32 L_add)
+{
+
+        Int32 tmp;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "mla %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp);
+    }
+
+
+
+    static inline Int32 fxp_mac_16_by_16_bb(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "mov %0, %3, asl #16\n\t"
+            "mov %0, %0, asr #16\n\t"
+            "mla %1, %0, %2, %4"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp2);
+    }
+
+
+
+    static inline  Int32 fxp_mac_16_by_16_bt(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+{
+
+        Int32 tmp1;
+        Int32 tmp2;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "mov %0, %3, asr #16\n\t"
+            "mla %1, %0, %2, %4"
+    : "=&r*i"(tmp1),
+            "=&r*i"(tmp2)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (tmp2);
+
+    }
+
+
+
+    static inline  Int32 cmplx_mul32_by_16(Int32 x, Int32 y, Int32 exp_jw)
+{
+
+        Int32 rTmp0;
+        Int32 iTmp0;
+        Int32 result64_hi;
+        register Int32 ra = (Int32)x;
+        register Int32 rb = (Int32)y;
+        register Int32 rc = (Int32)exp_jw;
+
+
+
+        asm volatile(
+            "mov %0, %5, asr #16\n\t"
+            "mov %1, %5, asl #16\n\t"
+            "mov %0, %0, asl #16\n\t"
+    : "=&r*i"(rTmp0),
+            "=&r*i"(iTmp0),
+            "=&r*i"(result64_hi)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+
+        asm volatile(
+            "smull %0, %2, %3, %0\n\t"
+            "smlal %1, %2, %4, %1"
+    : "=&r*i"(rTmp0),
+            "=&r*i"(iTmp0),
+            "=&r*i"(result64_hi)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (result64_hi);
+
+
+    }
+
+
+    static inline  Int32 fxp_mul32_by_16(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 rTmp0;
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %4, asl #16\n\t"
+            "smull %2, %1, %0, %3"
+    : "=&r*i"(rTmp0),
+            "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+
+    static inline  Int32 fxp_mul32_by_16t(Int32 L_var1, Int32 L_var2)
+{
+
+        Int32 rTmp0;
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+
+        asm volatile(
+            "mov %0, %4, asr #16\n\t"
+            "mov %0, %0, asl #16\n\t"
+            "smull %2, %1, %0, %3"
+    : "=&r*i"(rTmp0),
+            "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline  Int32 fxp_mac32_by_16(Int32 L_var1, Int32 L_var2, Int32 L_add)
+{
+
+        Int32 rTmp0;
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)L_var1;
+        register Int32 rb = (Int32)L_var2;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile(
+            "mov %0, %4, asl #16\n\t"
+            "mov %1, %5\n\t"
+            "smlal %2, %1, %0, %3"
+    : "=&r*i"(rTmp0),
+            "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+    static inline int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+{
+        sum += (int64)L_var1 * L_var2;
+        return (sum);
+    }
+
+
+    static inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %4, %4, %0, asl #2\n\t"
+                     "add %0, %4, %1, lsr #30"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mac32_Q31(Int32 L_add, const Int32 a, const Int32 b)
+{
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %0, %0, %4"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_msu32_Q31(Int32 L_sub, const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_sub;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "sub %0, %4, %0"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q31(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile(
+            "smull %1, %0, %2, %3"
+    : "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #2\n\t"
+                     "orr   %0, %0, %1, lsr #30"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mac32_Q29(const Int32 a, const Int32 b, Int32 L_add)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add   %4, %4, %0, lsl #3\n\t"
+                     "add   %0, %4, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_msu32_Q29(const Int32 a, const Int32 b, Int32 L_sub)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        register Int32 rc = (Int32)L_sub;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "sub   %4, %4, %0, lsl #3\n\t"
+                     "sub   %0, %4, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+    static inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #3\n\t"
+                     "orr   %0, %0, %1, lsr #29"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #4\n\t"
+                     "orr   %0, %0, %1, lsr #28"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+    static inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #5\n\t"
+                     "orr   %0, %0, %1, lsr #27"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #6\n\t"
+                     "orr   %0, %0, %1, lsr #26"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q20(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #12\n\t"
+                     "orr   %0, %0, %1, lsr #20"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline Int32 fxp_mul32_Q15(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov %0, %0, lsl #17\n\t"
+                     "orr   %0, %0, %1, lsr #15"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline Int32 fxp_mul32_Q14(const Int32 a, const Int32 b)
+{
+        Int32 result64_hi;
+        Int32 result64_lo;
+        register Int32 ra = (Int32)a;
+        register Int32 rb = (Int32)b;
+        asm volatile("smull %1, %0, %2,  %3\n\t"
+                     "mov   %0, %0, lsl #18\n\t"
+                     "orr   %0, %0, %1, lsr #14"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+
+        return (result64_hi);
+    }
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32_V4_ARM_GCC  */
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v5.h b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v5.h
new file mode 100644
index 0000000..8ab108f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_arm_v5.h
@@ -0,0 +1,450 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/fxp_mul32_arm_v5.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_ARM_V5
+#define FXP_MUL32_ARM_V5
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "pv_audio_type_defs.h"
+
+
+#if defined(PV_ARM_V5)
+
+//#undef EXTENDED_ASM
+#define EXTENDED_ASM
+#define _ARM_V5_
+
+
+    __inline  Int32 shft_lft_1(Int32 L_var1)
+    {
+        __asm
+        {
+            qadd L_var1, L_var1, L_var1
+        }
+
+        return L_var1;
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            smulbb L_var1, L_var1, L_var2
+        }
+        return L_var1;
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16bb(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            smulbb L_var1, L_var1, L_var2
+        }
+        return L_var1;
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16tb(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            smultb L_var1, L_var1, L_var2
+        }
+        return L_var1;
+    }
+
+    __inline  Int32 fxp_mul_16_by_16tt(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            smultt L_var1, L_var1, L_var2
+        }
+        return L_var1;
+    }
+
+    __inline  Int32 fxp_mul_16_by_16bt(Int32 L_var1,  Int32 L_var2)
+    {
+        __asm
+        {
+            smulbt L_var1, L_var1, L_var2
+        }
+        return L_var1;
+    }
+
+
+
+    __inline  Int32 fxp_mac_16_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlabb L_add, L_var1, L_var2, L_add
+        }
+        return (L_add);
+    }
+
+    __inline  Int32 fxp_mac_16_by_16_bb(const Int32 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlabb L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_mac_16_by_16_bt(const Int32 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlabt L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+
+    __inline  Int32 fxp_mac_16_by_16_tb(const Int32 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlatb L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_mac_16_by_16_tt(const Int32 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlatt L_add, L_var1, L_var2, L_add
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_mac32_by_16(Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        __asm
+        {
+            smlawb L_add, L_var1, L_var2, L_add
+        }
+        return (L_add);
+    }
+
+
+    __inline  int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+    {
+        uint32 b = (UInt32)(sum);
+        int32 c = Int32(sum >> 32);
+        __asm
+        {
+            smlal b, c, L_var1, L_var2
+        }
+        return (((int64(c)) << 32) | b);
+    }
+
+
+    __inline  Int32 fxp_mac32_Q31(Int32 L_add,  Int32 L_var1, const Int32 L_var2)
+    {
+        __asm
+        {
+            smlal L_var1, L_add, L_var2, L_var1
+        }
+        return L_add;
+    }
+
+    __inline  Int32 fxp_msu32_Q31(Int32 L_sub,  Int32 L_var1, const Int32 L_var2)
+    {
+        __asm
+        {
+            rsb   L_var1, L_var1, #0
+            smlal L_var1, L_sub, L_var2, L_var1
+        }
+        return L_sub;
+    }
+
+    __inline  Int32 fxp_mul32_Q31(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            smull L_var1, result64_hi, L_var2, L_var1
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q30(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #2
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #30
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #30
+#endif
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mac32_Q30(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            add L_add, L_add, result64_hi, asl  #2
+            add L_add, L_add, result64_lo, lsr  #30
+        }
+        return (L_add);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q29(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #3
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #29
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #29
+#endif
+        }
+        return (result64_hi);
+    }
+
+
+
+    __inline  Int32 fxp_mac32_Q29(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            add L_add, L_add, result64_hi, asl  #3
+            add L_add, L_add, result64_lo, lsr  #29
+        }
+        return (L_add);
+    }
+
+
+    __inline  Int32 fxp_msu32_Q29(const Int32 L_var1, const Int32 L_var2, Int32 L_sub)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            sub L_sub, L_sub, result64_hi, asl  #3
+            sub L_sub, L_sub, result64_lo, lsr  #29
+        }
+        return (L_sub);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q28(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #4
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #28
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #28
+#endif
+
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q27(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #5
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #27
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #27
+#endif
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q26(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #6
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #26
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #26
+#endif
+
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q20(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #12
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #20
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #20
+#endif
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_by_16(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            smulwb result64_hi, L_var1, L_var2
+        }
+        return (result64_hi);
+    }
+
+#define fxp_mul32_by_16b( a, b)         fxp_mul32_by_16(a, b)
+
+    __inline  Int32 fxp_mul32_by_16t(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            smulwt result64_hi, L_var1, L_var2
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q15(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #17
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #15
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #15
+#endif
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 cmplx_mul32_by_16(Int32 L_var1, const Int32 L_var2, const Int32 cmplx)
+    {
+        Int32 result64_hi;
+
+        __asm
+        {
+            smulwt result64_hi, L_var1, cmplx
+            smlawb result64_hi, L_var2, cmplx, result64_hi
+        }
+        return (result64_hi);
+
+    }
+
+    __inline  Int32 fxp_mul32_Q14(const Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov result64_hi, result64_hi, asl  #18
+#ifdef EXTENDED_ASM
+            mov result64_lo, result64_lo, lsr  #14
+            orr  result64_hi, result64_lo, result64_hi
+#else
+            orr  result64_hi, result64_hi, result64_lo, lsr #14
+#endif
+        }
+        return (result64_hi);
+    }
+
+
+#define preload_cache( a)
+
+
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_c_equivalent.h b/media/libstagefright/codecs/aacdec/fxp_mul32_c_equivalent.h
new file mode 100644
index 0000000..5bcbe53
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_c_equivalent.h
@@ -0,0 +1,285 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./c/include/fxp_mul32_c_equivalent.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_C_EQUIVALENT
+#define FXP_MUL32_C_EQUIVALENT
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+
+#if defined(C_EQUIVALENT)
+
+#define preload_cache( a)
+
+    __inline  Int32 shft_lft_1(Int32 L_var1)
+    {
+        if (((L_var1 << 1) >> 1) == L_var1)
+            L_var1 <<= 1;
+        else
+            L_var1 = ((L_var1 >> 31) ^ INT32_MAX);
+
+        return (L_var1);
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16bb(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+        L_var1 = (L_var1 << 16) >> 16;
+
+        L_var1 *= L_var2;
+
+        return L_var1;
+
+    }
+
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+
+    __inline  Int32 fxp_mul_16_by_16tb(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+        L_var1 =  L_var1 >> 16;
+
+        L_var1 *= L_var2;
+
+        return L_var1;
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16bt(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = L_var2 >> 16;
+        L_var1 = (L_var1 << 16) >> 16;
+
+        L_var1 *= L_var2;
+
+        return L_var1;
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16tt(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = L_var2 >> 16;
+        L_var1 = L_var1 >> 16;
+
+        L_var1 *= L_var2;
+
+        return L_var1;
+
+    }
+
+    __inline  Int32 fxp_mac_16_by_16(Int16 L_var1,  Int16 L_var2, Int32 L_add)
+    {
+
+        L_add += L_var1 * L_var2;
+
+        return L_add;
+
+    }
+
+
+
+
+
+    __inline  Int32 fxp_mac_16_by_16_bb(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+
+        L_add += L_var1 * L_var2;
+
+        return L_add;
+
+    }
+
+
+    __inline  Int32 fxp_mac_16_by_16_bt(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        L_var2 = L_var2 >> 16;
+
+        L_add += L_var1 * L_var2;
+
+        return L_add;
+
+    }
+
+
+
+
+
+    __inline  Int32 cmplx_mul32_by_16(Int32 x, const Int32 y, Int32 exp_jw)
+    {
+        Int32  rTmp0 = (Int16)(exp_jw >> 16);
+        Int32  iTmp0 = exp_jw;
+        Int32  z;
+
+        z  = (Int32)(((int64_t)x * (rTmp0 << 16)) >> 32);
+        z += (Int32)(((int64_t)y * (iTmp0 << 16)) >> 32);
+
+        return (z);
+    }
+
+
+    __inline  Int32 fxp_mul32_by_16(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32  z;
+
+        z = (Int32)(((int64_t) L_var1 * (L_var2 << 16)) >> 32);
+        return(z);
+    }
+
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+    __inline  Int32 fxp_mul32_by_16t(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32  rTmp0 = (Int16)(L_var2 >> 16);
+        Int32  z;
+
+        z = (Int32)(((int64_t) L_var1 * (rTmp0 << 16)) >> 32);
+
+        return(z);
+    }
+
+
+    __inline  Int32 fxp_mac32_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32  rTmp0 = L_var2 << 16;
+
+        L_add += (Int32)(((int64_t) L_var1 * rTmp0) >> 32);
+
+        return(L_add);
+    }
+
+    __inline  int64_t fxp_mac64_Q31(int64_t sum, const Int32 L_var1, const Int32 L_var2)
+    {
+        sum += (int64_t)L_var1 * L_var2;
+        return (sum);
+    }
+
+    __inline Int32 fxp_mul32_Q31(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 32);
+    }
+
+    __inline Int32 fxp_mac32_Q31(Int32 L_add, const Int32 a, const Int32 b)
+    {
+        return (L_add + (Int32)(((int64_t)(a) * b) >> 32));
+    }
+
+    __inline Int32 fxp_msu32_Q31(Int32 L_sub, const Int32 a, const Int32 b)
+    {
+        return (L_sub - (Int32)(((int64_t)(a) * b) >> 32));
+    }
+
+
+    __inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 30);
+    }
+
+    __inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64_t)(a) * b) >> 30));
+    }
+
+
+    __inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 29);
+    }
+
+    __inline Int32 fxp_mac32_Q29(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64_t)(a) * b) >> 29));
+    }
+
+    __inline Int32 fxp_msu32_Q29(const Int32 a, const Int32 b, Int32 L_sub)
+    {
+        return (L_sub - (Int32)(((int64_t)(a) * b) >> 29));
+    }
+
+
+    __inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 28);
+    }
+
+    __inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 27);
+    }
+
+    __inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 26);
+    }
+
+    __inline Int32 fxp_mul32_Q20(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 20);
+    }
+
+    __inline Int32 fxp_mul32_Q15(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 15);
+    }
+
+    __inline Int32 fxp_mul32_Q14(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64_t)(a) * b) >> 14);
+    }
+
+
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc.h b/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc.h
new file mode 100644
index 0000000..64397cf
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc.h
@@ -0,0 +1,254 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: fxp_mul32_msc_evc.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+
+#ifndef FXP_MUL32_MSC_EVC
+#define FXP_MUL32_MSC_EVC
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+#if defined(PV_ARM_MSC_EVC_V4)
+
+#include "cmnintrin.h"
+
+#define preload_cache( a)
+
+    __inline  Int32 shft_lft_1(Int32 L_var1)
+    {
+        if (((L_var1 << 1) >> 1) == L_var1)
+            L_var1 <<= 1;
+        else
+            L_var1 = ((L_var1 >> 31) ^ INT32_MAX);
+
+        return L_var1;
+
+    }
+
+    __inline  Int32 fxp_mul_16_by_16bb(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+        L_var1 = (L_var1 << 16) >> 16;
+
+        return (L_var1*L_var2);
+
+    }
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+    __inline  Int32 fxp_mul_16_by_16tb(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+        L_var1 =  L_var1 >> 16;
+
+        return (L_var1*L_var2);
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16bt(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = L_var2 >> 16;
+        L_var1 = (L_var1 << 16) >> 16;
+
+        return (L_var1*L_var2);
+
+    }
+
+
+    __inline  Int32 fxp_mul_16_by_16tt(Int32 L_var1,  Int32 L_var2)
+    {
+        L_var2 = L_var2 >> 16;
+        L_var1 = L_var1 >> 16;
+
+        return (L_var1*L_var2);
+
+    }
+
+    __inline  Int32 fxp_mac_16_by_16(Int16 L_var1,  Int16 L_var2, Int32 L_add)
+    {
+        return (L_add + (L_var1*L_var2));
+    }
+
+
+
+    __inline  Int32 fxp_mac_16_by_16_bb(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        L_var2 = (L_var2 << 16) >> 16;
+
+        return (L_add + (L_var1*L_var2));
+
+    }
+
+
+    __inline  Int32 fxp_mac_16_by_16_bt(Int16 L_var1,  Int32 L_var2, Int32 L_add)
+    {
+        L_var2 = L_var2 >> 16;
+
+        return (L_add + (L_var1*L_var2));
+
+    }
+
+
+    __inline  Int32 cmplx_mul32_by_16(Int32 x, const Int32 y, Int32 exp_jw)
+    {
+        Int32  rTmp0 = (exp_jw >> 16) << 16;
+        Int32  iTmp0 = exp_jw << 16;
+        Int32  z;
+
+
+        z  = _MulHigh(rTmp0, x);
+        z += _MulHigh(iTmp0, y);
+
+        return (z);
+    }
+
+
+    __inline  Int32 fxp_mul32_by_16(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32  rTmp0 = L_var2 << 16;
+
+        return(_MulHigh(rTmp0, L_var1));
+    }
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+    __inline  Int32 fxp_mul32_by_16t(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32  rTmp0 = (Int16)(L_var2 >> 16);
+
+        return(_MulHigh((rTmp0 << 16), L_var1));
+    }
+
+
+    __inline  Int32 fxp_mac32_by_16(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+
+        Int32  rTmp0 = (L_var2 << 16);
+
+        return(L_add + _MulHigh(rTmp0, L_var1));
+    }
+
+    __inline  int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+    {
+        sum += (int64)L_var1 * L_var2;
+        return (sum);
+    }
+
+#define fxp_mul32_Q31( a,  b)   _MulHigh( b, a)
+
+    __inline Int32 fxp_mac32_Q31(Int32 L_add, const Int32 a, const Int32 b)
+    {
+        return (L_add + _MulHigh(b, a));
+    }
+
+    __inline Int32 fxp_msu32_Q31(Int32 L_sub, const Int32 a, const Int32 b)
+    {
+        return (L_sub - _MulHigh(b, a));
+    }
+
+
+    __inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 30);
+    }
+
+    __inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 30));
+    }
+
+
+    __inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 29);
+    }
+
+    __inline Int32 fxp_mac32_Q29(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 29));
+    }
+
+    __inline Int32 fxp_msu32_Q29(const Int32 a, const Int32 b, Int32 L_sub)
+    {
+        return (L_sub - (Int32)(((int64)(a) * b) >> 29));
+    }
+
+
+    __inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 28);
+    }
+
+    __inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 27);
+    }
+
+    __inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 26);
+    }
+
+    __inline Int32 fxp_mul32_Q20(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 20);
+    }
+
+    __inline Int32 fxp_mul32_Q15(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 15);
+    }
+
+    __inline Int32 fxp_mul32_Q14(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 14);
+    }
+
+
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc_armv5.h b/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc_armv5.h
new file mode 100644
index 0000000..04cbf49
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_c_msc_evc_armv5.h
@@ -0,0 +1,178 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: .fxp_mul32_msc_evc_armv5.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_MSC_EVC_ARMV5
+#define FXP_MUL32_MSC_EVC_ARMV5
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+#if defined(PV_ARM_MSC_EVC_V5)
+
+#include "armintr.h"
+#include "cmnintrin.h"
+
+#define preload_cache( a)
+
+#define shft_lft_1( L_var1)  _AddSatInt( L_var1, L_var1)
+
+#define fxp_mul_16_by_16bb( L_var1, L_var2)  _SmulLo_SW_SL( L_var1, L_var2)
+
+#define fxp_mul_16_by_16(a, b)  fxp_mul_16_by_16bb(  a, b)
+
+#define fxp_mul_16_by_16tb( L_var1, L_var2)  _SmulHiLo_SW_SL( L_var1, L_var2)
+
+#define fxp_mul_16_by_16bt( L_var1, L_var2)  _SmulLoHi_SW_SL( L_var1, L_var2)
+
+#define fxp_mul_16_by_16tt( L_var1, L_var2)  _SmulHi_SW_SL( L_var1, L_var2)
+
+#define fxp_mac_16_by_16( L_var1, L_var2, L_add)  _SmulAddLo_SW_SL( L_add, L_var1, L_var2)
+
+#define fxp_mac_16_by_16_bb(a, b, c)  fxp_mac_16_by_16(  a, b, c)
+
+#define fxp_mac_16_by_16_bt( L_var1, L_var2, L_add)  _SmulAddLoHi_SW_SL( L_add, L_var1, L_var2)
+
+
+    __inline  Int32 cmplx_mul32_by_16(Int32 L_var1, const Int32 L_var2, const Int32 cmplx)
+    {
+        Int32 result64_hi;
+
+        result64_hi = _SmulWHi_SW_SL(L_var1, cmplx);
+        result64_hi = _SmulAddWLo_SW_SL(result64_hi, L_var2, cmplx);
+
+        return (result64_hi);
+    }
+
+#define fxp_mul32_by_16( L_var1, L_var2)  _SmulWLo_SW_SL( L_var1, L_var2)
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+#define fxp_mul32_by_16t( L_var1, L_var2)  _SmulWHi_SW_SL( L_var1, L_var2)
+
+#define fxp_mac32_by_16( L_var1, L_var2, L_add)  _SmulAddWLo_SW_SL( L_add, L_var1, L_var2)
+
+
+    __inline  int64 fxp_mac64_Q31(int64 sum, const Int32 L_var1, const Int32 L_var2)
+    {
+        sum += (int64)L_var1 * L_var2;
+        return (sum);
+    }
+
+#define fxp_mul32_Q31( a,  b)   _MulHigh( b, a)
+
+
+    __inline Int32 fxp_mac32_Q31(Int32 L_add, const Int32 a, const Int32 b)
+    {
+        return (L_add + _MulHigh(b, a));
+    }
+
+
+    __inline Int32 fxp_msu32_Q31(Int32 L_sub, const Int32 a, const Int32 b)
+    {
+        return (L_sub - _MulHigh(b, a));
+    }
+
+
+    __inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 30);
+    }
+
+    __inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 30));
+    }
+
+
+    __inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 29);
+    }
+
+    __inline Int32 fxp_mac32_Q29(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 29));
+    }
+
+    __inline Int32 fxp_msu32_Q29(const Int32 a, const Int32 b, Int32 L_sub)
+    {
+        return (L_sub - (Int32)(((int64)(a) * b) >> 29));
+    }
+
+
+    __inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 28);
+    }
+
+    __inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 27);
+    }
+
+    __inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 26);
+    }
+
+    __inline Int32 fxp_mul32_Q20(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 20);
+    }
+
+    __inline Int32 fxp_mul32_Q15(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 15);
+    }
+
+    __inline Int32 fxp_mul32_Q14(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 14);
+    }
+
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/fxp_mul32_pentium.h b/media/libstagefright/codecs/aacdec/fxp_mul32_pentium.h
new file mode 100644
index 0000000..72862e7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/fxp_mul32_pentium.h
@@ -0,0 +1,55 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: .fxp_mul32_pentium.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FXP_MUL32_PENTIUM
+#define FXP_MUL32_PENTIUM
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "pv_audio_type_defs.h"
+
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  FXP_MUL32  */
+
diff --git a/media/libstagefright/codecs/aacdec/gen_rand_vector.cpp b/media/libstagefright/codecs/aacdec/gen_rand_vector.cpp
new file mode 100644
index 0000000..08ccc4a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/gen_rand_vector.cpp
@@ -0,0 +1,512 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to remove instances of pow() and sqrt(), and
+ optimized for inclusion in fixed-point version of decoder.
+
+ Description:  Modified to include comments/optimizations from code review.
+ Also, declared appropriate variables as type "const"
+
+ Description:  Adopted strategy of "one q-format per sfb" strategy, which
+ eliminated the array q-format from this function.  The q-format the
+ random vector is stored in is now returned from the function.
+
+ Description:  Completely redesigned the routine to allow a simplified
+        calculation of the adjusted noise, by eliminating the dependency
+        on the band_length. Added polynomial approximation for the
+        function 1/sqrt(power). Updated comments and pseudo-code
+
+ Description:  Modified function description, pseudocode, etc.
+
+ Description:
+    Modified casting to ensure proper operations for different platforms
+
+ Description:
+    Eliminiated access to memory for noise seed. Now a local variable is
+    used. Also unrolled loops to speed up code.
+
+ Description:
+    Modified pointer decrement to a pointer increment, to ensure proper
+    compiler behavior
+
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:    random_array[] = Array for storage of the power-scaled
+                             random values of length "band_length"
+            Int32
+
+            band_length    = Length of random_array[]
+            const Int
+
+            pSeed          = seed for random number generator
+            Int32*
+
+            power_scale    = scale factor for this particular band
+            const Int
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:   Function returns the q-format the random vector is stored in.
+
+ Pointers and Buffers Modified:
+            random_array[] = filled with random numbers scaled
+            to the correct power as defined by the input value power_scale.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function generates a vector of uniformly distributed random numbers for
+ the PNS block.  The random numbers are each scaled by a scale_factor,
+ defined in Ref(2) as
+
+ 2^(scale_factor/4)
+ ------------------
+  sqrt(N*MEAN_NRG)
+
+ where N == band_length, and MEAN_NRG is defined as...
+
+         N-1
+         ___
+     1   \
+    ---   >    x(i)^2
+     N   /__
+         i=0
+
+ And x is the unscaled vector from the random number generator.
+
+ This function takes advantage of the fact that the portion of the
+ scale_factor that is divisible by 4 can be simply accounted for by varying
+ the q-format.
+
+ The scaling of the random numbers is thus broken into the
+ equivalent equation below.
+
+ 2^(scale_factor%4)   2^(floor(scale_factor/4))
+ ------------------ *
+  sqrt(N*MEAN_NRG)
+
+
+ 2^(scale_factor%4) is stored in a simple 4-element table.
+ 2^(floor(scale_factor/4) is accounted for by adjusting the q-format.
+ sqrt(N*MEAN_NRG) is calculated and implemented via a polynomial approximation.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall produce uniformly distributed random 32-bit integers,
+ with signed random values of average energy equal to the results of the ISO
+ code's multiplying factor discussed in the FUNCTION DESCRIPTION section.
+
+ Please see Ref (2) for a detailed description of the requirements.
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) Numerical Recipes in C     Second Edition
+        William H. Press        Saul A. Teukolsky
+        William T. Vetterling   Brian P. Flannery
+        Page 284
+
+ (2) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.12 (Perceptual Noise Substitution)
+
+ (3) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    power_adj = scale_mod_4[power_scale & 3];
+
+    power = 0;
+
+    FOR (k=band_length; k > 0; k--)
+
+        *(pSeed) = *(pSeed) * 1664525L;
+        *(pSeed) = *(pSeed) + 1013904223L;
+
+        temp = (Int)(*(pSeed) >> 16);
+
+        power = power + ((temp*temp) >> 6);
+
+        *(pArray) = (Int32)temp;
+
+        pArray = pArray + 1;
+
+    ENDFOR
+
+    k = 0;
+    q_adjust = 30;
+
+    IF (power)
+    THEN
+
+        WHILE ( power > 32767)
+
+            power = power >> 1;
+            k = k + 1;
+
+        ENDWHILE
+
+        k = k - 13;
+
+        IF (k < 0)
+        THEN
+            k = -k;
+            IF ( k & 1 )
+            THEN
+                power_adj = (power_adj*SQRT_OF_2)>>14;
+            ENDIF
+            q_adjust = q_adjust - ( k >> 1);
+
+        ELSE IF (k > 0)
+        THEN
+            IF ( k & 1  )
+            THEN
+                power_adj = (power_adj*INV_SQRT_OF_2)>>14;
+            ENDIF
+            q_adjust = q_adjust + ( k >> 1);
+        ENDIF
+
+        pInvSqrtCoeff = inv_sqrt_coeff;
+
+        inv_sqrt_power  = (*(pInvSqrtCoeff)* power) >>15;
+
+        pInvSqrtCoeff = pInvSqrtCoeff + 1;
+
+        inv_sqrt_power = inv_sqrt_power + *(pInvSqrtCoeff);
+
+        pInvSqrtCoeff = pInvSqrtCoeff + 1;
+
+        FOR ( k=INV_SQRT_POLY_ORDER - 1; k>0; k--)
+
+            inv_sqrt_power  =  ( inv_sqrt_power * power)>>15;
+
+            inv_sqrt_power = inv_sqrt_power + *(pInvSqrtCoeff);
+
+            pInvSqrtCoeff = pInvSqrtCoeff + 1;
+
+        ENDFOR
+
+        inv_sqrt_power = (inv_sqrt_power*power_adj)>>13;
+
+        FOR (k=band_length; k > 0; k--)
+
+            pArray = pArray - 1;
+
+            *(pArray) = *(pArray)*inv_sqrt_power;
+
+        ENDFOR
+
+    ENDIF
+
+    q_adjust = q_adjust - (power_scale >> 2);
+
+    return q_adjust;
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor
+     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    "pv_audio_type_defs.h"
+#include    "gen_rand_vector.h"
+#include    "window_block_fxp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define     SQRT_OF_2       23170       /*    sqrt(2) in Q14  */
+#define     INV_SQRT_OF_2   11585       /*  1/sqrt(2) in Q14  */
+#define     INV_SQRT_POLY_ORDER     4
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+
+/*
+ *  2^([0:3]/4) = 1.0000    1.1892    1.4142    1.6818
+ */
+const UInt scale_mod_4[4] = { 16384, 19484, 23170, 27554};
+
+/*
+ *  polynomial approx. in Q12 (type Int)
+ */
+
+const Int  inv_sqrt_coeff[INV_SQRT_POLY_ORDER+1] =
+    { 4680, -17935, 27697, -22326, 11980};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int gen_rand_vector(
+    Int32     random_array[],
+    const Int band_length,
+    Int32*   pSeed,
+    const Int power_scale)
+{
+
+    Int      k;
+    UInt     power_adj;
+    Int      q_adjust = 30;
+
+    Int32    temp;
+    Int32    seed;
+    Int32    power;
+
+    Int32*   pArray = &random_array[0];
+
+    Int32    inv_sqrt_power;
+    const Int  *pInvSqrtCoeff;
+
+    /*
+     *  The out of the random number generator is scaled is such a way
+     *  that is independent of the band length.
+     *  The output is computed as:
+     *
+     *                  x(i)
+     *  output = ------------------ * 2^(power_scale%4) 2^(floor(power_scale/4))
+     *                   bl
+     *           sqrt(  SUM x(i)^2 )
+     *                   0
+     *
+     *  bl == band length
+     */
+
+
+    /*
+     *  get 2^(power_scale%4)
+     */
+
+
+    power = 0;
+
+    seed = *pSeed;
+
+    /*
+     *  band_length is always an even number (check tables in pg.66 IS0 14496-3)
+     */
+    if (band_length < 0 || band_length > LONG_WINDOW)
+    {
+        return  q_adjust;     /*  avoid any processing on error condition */
+    }
+
+    for (k = (band_length >> 1); k != 0; k--)
+    {
+        /*------------------------------------------------
+           Numerical Recipes in C
+                    Page 284
+        ------------------------------------------------*/
+        seed *= 1664525L;
+        seed += 1013904223L;
+
+        temp =  seed >> 16;
+
+        seed *= 1664525L;
+        seed += 1013904223L;
+
+        /* shift by 6 make room for band length accumulation  */
+        power  += ((temp * temp) >> 6);
+        *pArray++ = temp;
+
+        temp    = seed >> 16;
+        power  += ((temp * temp) >> 6);
+        *pArray++ = temp;
+
+    } /* END for (k=half_band_length; k > 0; k--) */
+
+
+    *pSeed = seed;
+
+    /*
+     *  If the distribution is uniform, the power is expected to use between
+     *  28 and 27 bits, by shifting down by 13 bits the power will be a
+     *  Q15 number.
+     *  For different band lengths, the power uses between 20 and 29 bits
+     */
+
+
+    k = 0;
+
+    if (power)
+    {
+        /*
+         *    approximation requires power  between 0.5 < power < 1 in Q15.
+         */
+
+        while (power > 32767)
+        {
+            power >>= 1;
+            k++;
+        }
+
+        /*
+         *  expected power bit usage == 27 bits
+         */
+
+        k -= 13;
+
+        power_adj = scale_mod_4[power_scale & 3];
+
+        if (k < 0)
+        {
+            k = -k;
+            if (k & 1)
+            {                               /* multiply by sqrt(2)  */
+                power_adj = (UInt)(((UInt32) power_adj * SQRT_OF_2) >> 14);
+            }
+            q_adjust -= (k >> 1);    /* adjust Q instead of shifting up */
+        }
+        else if (k > 0)
+        {
+            if (k & 1)
+            {                               /* multiply by 1/sqrt(2)  */
+                power_adj = (UInt)(((UInt32) power_adj * INV_SQRT_OF_2) >> 14);
+            }
+            q_adjust += (k >> 1);   /* adjust Q instead of shifting down */
+        }
+
+        /*
+         *    Compute 1/sqrt(power), where 0.5 < power < 1.0 is approximated
+         *    using a polynomial order INV_SQRT_POLY_ORDER
+         */
+
+        pInvSqrtCoeff = inv_sqrt_coeff;
+
+        inv_sqrt_power  = (*(pInvSqrtCoeff++) * power) >> 15;
+        inv_sqrt_power += *(pInvSqrtCoeff++);
+        inv_sqrt_power  = (inv_sqrt_power * power) >> 15;
+        inv_sqrt_power += *(pInvSqrtCoeff++);
+        inv_sqrt_power  = (inv_sqrt_power * power) >> 15;
+        inv_sqrt_power += *(pInvSqrtCoeff++);
+        inv_sqrt_power  = (inv_sqrt_power * power) >> 15;
+        inv_sqrt_power += *(pInvSqrtCoeff);
+
+        inv_sqrt_power  = (inv_sqrt_power * power_adj) >> 13;
+
+        pArray = &random_array[0];
+
+        for (k = (band_length >> 1); k != 0; k--)
+        {
+            temp        = *(pArray) * inv_sqrt_power;
+            *(pArray++) = temp;
+            temp        = *(pArray) * inv_sqrt_power;
+            *(pArray++) = temp;
+        } /* END for (k=half_band_length; k > 0; k--) */
+
+    }   /* if(power) */
+
+    /*
+     *      Adjust Q with the value corresponding to 2^(floor(power_scale/4))
+     */
+
+    q_adjust  -= (power_scale >> 2);
+
+    return (q_adjust);
+
+} /* gen_rand_vector */
diff --git a/media/libstagefright/codecs/aacdec/gen_rand_vector.h b/media/libstagefright/codecs/aacdec/gen_rand_vector.h
new file mode 100644
index 0000000..17b5490
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/gen_rand_vector.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: gen_rand_vector.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added include of pv_audio_type_defs.h
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the function declaration for gen_rand_vector.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef gen_rand_vector_H
+#define gen_rand_vector_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int gen_rand_vector(
+    Int32  random_array[],
+    const Int    band_length,
+    Int32 *pSeed,
+    const Int    power_scale);
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/get_adif_header.cpp b/media/libstagefright/codecs/aacdec/get_adif_header.cpp
new file mode 100644
index 0000000..8a1e74b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_adif_header.cpp
@@ -0,0 +1,443 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_adif_header.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Change to PV template, remove default config parameter,
+               move some functionality into get_prog_config().
+
+ Description: Update per code review
+              1) Add parameter pScratchPCE
+              2) Change way ADIF_ID is read in.
+              3) Fix comments
+              4) ADD a test for status != SUCCESS in loop.
+
+ Description: The ADIF_Header has now been delegated to the "scratch memory"
+ union.  This change inside s_tDec_Int_File.h had to be reflected here also.
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pVars        = pointer to the structure that contains the current state
+                   of this instance of the library, of data type pointer to
+                   tDec_Int_File
+
+    pScratchPCE  = pointer to a ProgConfig structure used as scratch in the
+                   the function get_prog_config. of data type pointer to
+                   ProgConfig
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+    The function returns 0 if no error occurred, non-zero otherwise.
+
+ Pointers and Buffers Modified:
+    pVars->adif_header contents are updated with the some of the ADIF header
+           contents
+    pVars->tempProgConfig contents are overwritten with last PCE found,
+           which is most likely the first one found.
+    pVars->prog_config contents are updated with the first PCE found.
+    pVars->inputStream contents are modify in such a way that the
+           stream is moved further along in the buffer.
+    pVars->SFBWidth128 contents may be updated.
+    pVars->winSeqInfo  contents may be updated.
+    pScratchPCE        contents may be updated.
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads in the ADIF Header found at the front of ADIF streams.
+ If the header is not found an error is returned. An ADIF header can contain
+ from zero to sixteen program configuration elements (PCE). This function, and
+ the rest of the library, saves and uses the first PCE found.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ Function shall not use static or global variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+   of moving pictures and associated audio information - Part 7: Advanced
+   Audio Coding (AAC)", Table 6.21 - Syntax of program_config_element(),
+   page 16, and section 8.5 "Program Config Element (PCE)", page 30.
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+     CALL getbits(
+        neededBits = 2 * LEN_BYTE,
+        pInputStream = pInputStream)
+     MODIFYING( pInputStream )
+     RETURNING( theIDFromFile )
+
+     CALL getbits(
+        neededBits = 2 * LEN_BYTE,
+        pInputStream = pInputStream)
+     MODIFYING( pInputStream )
+     RETURNING( temp )
+
+    theIDFromFile = (theIDFromFile << (2*LEN_BYTE)) | temp;
+
+    IF (theIDFromFile != ADIF_ID)
+    THEN
+
+        pInputStream->usedBits -= (4 * LEN_BYTE);
+
+        status = -1;
+    ELSE
+        CALL getbits(
+            neededBits = LEN_COPYRT_PRES,
+            pInputStream = pInputStream)
+        MODIFYING( pInputStream )
+        RETURNING( temp )
+
+        IF (temp != FALSE) THEN
+            FOR (i = LEN_COPYRT_ID; i > 0; i--)
+               CALL getbits(
+                   neededBits = LEN_BYTE,
+                   pInputStream = pInputStream)
+               MODIFYING( pInputStream )
+
+            END FOR
+        END IF
+
+        CALL getbits(
+            neededBits = LEN_ORIG + LEN_HOME,
+            pInputStream = pInputStream)
+        MODIFYING( pInputStream )
+
+        CALL getbits(
+            neededBits = LEN_BS_TYPE,
+            pInputStream = pInputStream)
+        MODIFYING( pInputStream )
+        RETURNING( bitStreamType )
+
+        CALL getbits(
+            neededBits = LEN_BIT_RATE,
+            pInputStream = pInputStream)
+        MODIFYING( pInputStream )
+        RETURNING( pHeader->bitrate )
+
+        CALL getbits(
+            neededBits = LEN_NUM_PCE,
+            pInputStream = pInputStream)
+        MODIFYING( pInputStream )
+        RETURNING( numConfigElementsMinus1 )
+
+        FOR (  i = numConfigElementsMinus1;
+              (i >= 0) && (status == SUCCESS);
+               i--)
+
+            IF (bitStreamType == CONSTANT_RATE_BITSTREAM) THEN
+               CALL getbits(
+                   neededBits = LEN_ADIF_BF,
+                   pInputStream = pInputStream)
+               MODIFYING( pInputStream )
+            END IF
+
+            CALL get_prog_config(
+                pVars = pVars)
+            MODIFYING( pVars->prog_config )
+            RETURNING( status )
+
+        END FOR
+    END IF
+
+    RETURN (status)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "e_adif_const.h"
+
+#include "s_progconfig.h"
+#include "s_adif_header.h"
+#include "s_bits.h"
+#include "s_mc_info.h"
+#include "s_frameinfo.h"
+#include "s_tdec_int_file.h"
+
+#include "get_prog_config.h"
+#include "ibstream.h"
+
+#include "get_adif_header.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*
+ * This constant is simply the characters 'A' 'D' 'I' 'F' compressed into
+ * a UInt32. Any possible endian problems that exist must be solved by
+ * the function that fills the buffer and getbits(), or this constant and
+ * the rest of the bit stream will not work.
+ */
+#define ADIF_ID (0x41444946)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+Int get_adif_header(
+    tDec_Int_File *pVars,
+    ProgConfig    *pScratchPCE)
+{
+    Int          i;
+    UInt32       temp;
+    Int          numConfigElementsMinus1;
+    Int          bitStreamType;
+    UInt32       theIDFromFile;
+
+    BITS        *pInputStream = &pVars->inputStream;
+    ADIF_Header *pHeader = &pVars->scratch.adif_header;
+    Int          status  = SUCCESS;
+
+    /*
+     * The ADIF_ID field is 32 bits long, one more than what getbits() can
+     * do, so read the field in two parts. There is no point in saving the
+     * string - it either matches or it does not. If it matches, it must
+     * have been 'ADIF'
+     */
+
+    theIDFromFile = get17_n_lessbits((2 * LEN_BYTE), pInputStream);
+
+    temp          = get17_n_lessbits((2 * LEN_BYTE), pInputStream);
+
+    theIDFromFile = (theIDFromFile << (2 * LEN_BYTE)) | temp;
+
+
+    if (theIDFromFile != ADIF_ID)
+    {
+        /*
+         * Rewind the bit stream pointer so a search for ADTS header
+         * can start at the beginning.
+         */
+
+        pInputStream->usedBits -= (4 * LEN_BYTE);
+
+        /*
+         * The constant in the next line needs to be updated when
+         * error handling method is determined.
+         */
+        status = -1;
+    }
+    else
+    {
+        /*
+         * To save space, the unused fields are read in, but not saved.
+         */
+
+        /* copyright string */
+        temp =
+            get1bits(/*                LEN_COPYRT_PRES,*/
+                pInputStream);
+
+        if (temp != FALSE)
+        {
+            /*
+             * Read in and ignore the copyright string. If restoring
+             * watch out for count down loop.
+             */
+
+            for (i = LEN_COPYRT_ID; i > 0; i--)
+            {
+                get9_n_lessbits(LEN_BYTE,
+                                pInputStream);
+            } /* end for */
+
+            /*
+             * Make sure to terminate the string with '\0' if restoring
+             * the the copyright string.
+             */
+
+        } /* end if */
+
+        /* Combine the original/copy and fields into one call */
+        get9_n_lessbits(
+            LEN_ORIG + LEN_HOME,
+            pInputStream);
+
+        bitStreamType =
+            get1bits(/*                LEN_BS_TYPE,*/
+                pInputStream);
+
+        pHeader->bitrate =
+            getbits(
+                LEN_BIT_RATE,
+                pInputStream);
+
+        /*
+         * Read in all the Program Configuration Elements.
+         * For this library, only one of the up to 16 possible PCE's will be
+         * saved. Since each PCE must be read, a temporary PCE structure is
+         * used, and if that PCE is the one to use, it is copied into the
+         * single PCE. This is done inside of get_prog_config()
+         */
+
+        numConfigElementsMinus1 =  get9_n_lessbits(LEN_NUM_PCE,
+                                   pInputStream);
+
+        for (i = numConfigElementsMinus1;
+                (i >= 0) && (status == SUCCESS);
+                i--)
+        {
+            /*
+             * For ADIF contant bit rate streams, the _encoder_ buffer
+             * fullness is transmitted. This version of an AAC decoder has
+             * no use for this variable; yet it must be read in to move
+             * the bitstream pointers.
+             */
+
+            if (bitStreamType == CONSTANT_RATE_BITSTREAM)
+            {
+                getbits(
+                    LEN_ADIF_BF,
+                    pInputStream);
+            } /* end if */
+
+            pVars->adif_test = 1;
+            /* Get one program configuration element */
+            status =
+                get_prog_config(
+                    pVars,
+                    pScratchPCE);
+
+#ifdef AAC_PLUS
+
+            /*
+             *  For implicit signalling, no hint that sbr or ps is used, so we need to
+             *  check the sampling frequency of the aac content, if lesser or equal to
+             *  24 KHz, by defualt upsample, otherwise, do nothing
+             */
+            if ((pVars->prog_config.sampling_rate_idx >= 6) && (pVars->aacPlusEnabled == true) &&
+                    pVars->mc_info.audioObjectType == MP4AUDIO_AAC_LC)
+            {
+                pVars->mc_info.upsamplingFactor = 2;
+                pVars->prog_config.sampling_rate_idx -= 3;
+                pVars->mc_info.sbrPresentFlag = 1;
+                pVars->sbrDecoderData.SbrChannel[0].syncState = UPSAMPLING;
+                pVars->sbrDecoderData.SbrChannel[1].syncState = UPSAMPLING;
+            }
+#endif
+
+
+
+        } /* end for */
+
+
+    } /* end 'else' of --> if (theIDFromFile != ADIF_ID) */
+
+    return status;
+
+} /* end get_adif_header */
diff --git a/media/libstagefright/codecs/aacdec/get_adif_header.h b/media/libstagefright/codecs/aacdec/get_adif_header.h
new file mode 100644
index 0000000..8bc3411
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_adif_header.h
@@ -0,0 +1,95 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_adif_header.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Add parameter to get_adif_header() function.
+
+ Who:                                      Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for get_adif_header.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_ADIF_HEADER_H
+#define GET_ADIF_HEADER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define CONSTANT_RATE_BITSTREAM  (0)
+#define VARIABLE_RATE_BITSTREAM  (1)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int get_adif_header(
+    tDec_Int_File *pVars,
+    ProgConfig    *pScratchPCE);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_adts_header.cpp b/media/libstagefright/codecs/aacdec/get_adts_header.cpp
new file mode 100644
index 0000000..3ac2756
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_adts_header.cpp
@@ -0,0 +1,672 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_adts_header.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Remove default_config variable
+
+ Description: change enter_mc_info to set_mc_info
+
+ Description: (1) add error checking for channel_config > 2
+              (2) eliminated call to check_mc_info
+              (3) use (profile + 1) when calling set_mc_info
+              (4) use winmap when calling set_mc_info
+
+ Who:                                          Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pVars           =   Pointer to structure that holds file-scope variables.
+                        [ tDec_Int_File * ]
+
+    pSyncword       =   Pointer to variable that holds the 28-bit fixed
+                        header upon the exit of this function. [ UInt32 * ]
+
+    pInvoke         =   Pointer to variable that keeps track of how many
+                        "short" (14 bit) headers have been successfully
+                        parsed from the bitstream. [ Int * ]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    Status = SUCCESS or ERROR CODE
+
+ Pointers and Buffers Modified:
+    pVars->prog_config   Updated with program information data as read from
+                         the ADTS header.
+
+    pSyncword            Value pointed to is updated with the contents of
+                         the 28-bit fixed header.
+
+    pInvoke              Value pointed to is updated to reflect the number
+                         of successful "short" (14 bit) headers that have
+                         been successfully parsed from the bitstream.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Acronym Definitions
+ ADTS  Audio Data Transport Stream
+ CRC   Cyclic Redundancy Code
+
+ This function calls find_adts_syncword to find the next ADTS header.  Until
+ three consistent headers have been read, the syncword used for detection
+ consists of the 12-bit syncword and the 2-bit Layer.  After three consistent
+ headers are read, the entire fixed header is used for a robust 28-bit
+ syncword.
+
+ Configuration information is then extracted from the bitstream.
+
+ The bitstream information is packed as follows.
+ Comments about the correct interpretation of these bits are contained within
+ the code.
+
+                                      CRC_absent    sampling_rate_idx
+                                           \               / \
+                                            \             /   \
+                                             \  Profile  /     \  UNUSED
+                                              \   / \   /       \   /
+|00|01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|
+ \         _______________         / |   \  /                         \      /
+  \-------|0xFFF syncword |-------/  |   Layer == '00' for AAC         \    /
+           \-------------/           |                                  \  /
+                                     |                                   \/
+                                     ID == '1' for MPEG-2 AAC    channel_config
+       copyright_id_bit                 == '0' for MPEG-4 AAC
+          /
+    home /
+     /  /
+|26|27|28|29|30|31|32|33|34|35|36|37|38|39|40|41|42|
+  |        \  \          _____________           /
+  |         \  \--------|frame length |---------/
+  orig_copy  \           \-----------/
+              \                                  ______________________________
+        copyright_id_start                      | TOTAL HEADER LENGTH: 56 bits|
+                                                |-----------------------------|
+|43|44|45|46|47|48|49|50|51|52|53|54|55|        | FIXED    HEADER BITS 00-27  |
+  \       _______________      /  |   |         | VARIABLE HEADER BITS 28-55  |
+   \-----|buffer_fullness|----/    \ /          |_____________________________|
+          \-------------/           |
+                              headerless_frames
+
+ In addition to the bits displayed above, if the value CRC_absent is '0' an
+ additional 16 bits corresponding to a CRC word are read from the bitstream,
+ following the header.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ After the ADTS syncword is detected, this function shall parse the
+ information residing behind the syncword in the bitstream.
+------------------------------------------------------------------------------
+ REFERENCES
+ (1) ISO/IEC 13818-7:1997(E)
+     Part 7
+        Subpart 6.2 (Audio_Data_Transport_Stream frame, ADTS)
+
+ (2) ISO/IEC 11172-3:1993(E)
+     Part 3
+        Subpart 2.4.3 The audio decoding process
+
+ (3) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those UIntending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF (*(pInvoke) > 3)
+
+         CALL find_adts_syncword(
+                    pSyncword,
+                   &(pVars->inputStream),
+                    LENGTH_FIXED_HEADER,
+                    MASK_28BITS);
+           RETURNING  status
+    ELSE
+
+        *(pSyncword) = SYNCWORD_15BITS;
+
+        CALL find_adts_syncword(
+                   pSyncword,
+                  &(pVars->inputStream),
+                   LENGTH_SYNCWORD,
+                   ID_BIT_FILTER);
+
+          MODIFYING  *(pSyncword) = 28-bit fixed header (long syncword)
+          RETURNING  status
+
+        CALL getbits(
+                (LENGTH_FIXED_HEADER - LENGTH_SYNCWORD),
+               &(pVars->inputStream));
+
+          MODIFYING pVars->inputStream
+          RETURNING adts_header = remaining bits in the fixed header
+
+        *(pSyncword) <<= 13;
+        *(pSyncword) = *(pSyncword) OR adts_header;
+
+        pVars->prog_config.CRC_absent  = ((UInt)(adts_header >> 12)) AND 0x0001;
+
+        lower_16 = (UInt)adts_header;
+
+        pVars->prog_config.profile = (lower_16 >> 10) AND 0x3;
+
+        pVars->prog_config.sampling_rate_idx = (lower_16 >> 6) AND 0xF;
+
+        channel_configuration = (lower_16 >> 2) AND 0x7;
+
+        channel_configuration = channel_configuration - 1;
+        pVars->prog_config.front.ele_is_cpe[0] = channel_configuration;
+
+        pVars->prog_config.front.num_ele    = 1;
+
+        pVars->prog_config.front.ele_tag[0] = 0;
+
+        pVars->prog_config.mono_mix.present = 0;
+        pVars->prog_config.stereo_mix.present = 0;
+        pVars->prog_config.matrix_mix.present = 0;
+
+        CALL set_mc_info(
+                &(pVars->mc_info),
+                &(pVars->savedMCInfo),
+                &(pVars->prog_config),
+                  pVars->pWinSeqInfo,
+                  pVars->SFBWidth128);
+          MODIFYING pVars->mc_info = multi-channel configuration information
+          RETURNING status         = SUCCESS/FAILURE
+
+        IF ( (*pInvoke) != 0)
+            CALL check_mc_info(
+                    &(pVars->mc_info),
+                    &(pVars->savedMCInfo),
+                     FALSE);
+              RETURNING status = SUCCESS/FAILURE
+        ELSE
+            CALL check_mc_info(
+                    &(pVars->mc_info),
+                    &(pVars->savedMCInfo),
+                     TRUE);
+              MODIFYING pVars->savedMCInfo = pVars->mc_info
+              RETURNING status = SUCCESS/FAILURE
+        ENDIF
+
+        IF (status == SUCCESS)
+            (*pInvoke) = (*pInvoke) + 1;
+        ELSE
+            (*pInvoke) = 0;
+        ENDIF
+
+    ENDIF
+
+    CALL getbits(
+            LENGTH_VARIABLE_HEADER,
+           &(pVars->inputStream));
+      RETURNING adts_header = 28-bits (the contents of the variable header.)
+
+    pVars->prog_config.frame_length  = ((UInt)(adts_header >> 13)) AND 0x1FFF;
+
+    lower_16 = (UInt)adts_header;
+
+    pVars->prog_config.buffer_fullness = (lower_16 >> 2) AND 0x7FF;
+
+    pVars->prog_config.headerless_frames = (lower_16 AND 0x0003);
+
+    IF (pVars->prog_config.CRC_absent == 0)
+
+        CALL getbits(
+                LENGTH_CRC,
+               &(pVars->inputStream) );
+          RETURNING pVars->prog_config.CRC_check = 16-bit CRC
+
+    ENDIF
+
+    pVars->default_config = 0;
+
+    IF (byte_align_offset > 7)
+        status = 1;
+    ENDIF
+
+    return (status);
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_bits.h"
+#include "s_tdec_int_file.h"
+#include "ibstream.h"
+#include "set_mc_info.h"
+#include "find_adts_syncword.h"
+#include "get_adts_header.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LENGTH_VARIABLE_HEADER  28
+#define LENGTH_FIXED_HEADER     28
+#define LENGTH_SYNCWORD         15
+#define LENGTH_CRC              16
+
+#define ID_BIT_FILTER           0x7FFB
+#define SYNCWORD_15BITS         0x7FF8
+#define MASK_28BITS             0x0FFFFFFFL
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_adts_header(
+    tDec_Int_File *pVars,
+    UInt32        *pSyncword,
+    Int           *pInvoke,
+    Int            CorrectlyReadFramesCount)
+{
+    UInt32 adts_header;
+    UInt   lower_16;
+    Int    status = SUCCESS;
+    UInt   channel_configuration;
+
+    /*
+     * Search for the LONG ADTS syncword (comprised of the entire fixed header)
+     * if the number of CorrectlyReadFrames is > CorrectlyReadFramesCount
+     *
+     * Otherwise, search for just the short syncword.
+     */
+    if (*(pInvoke) > CorrectlyReadFramesCount)
+    {
+        /*
+         * Find the long ADTS syncword
+         * (comprised of the entire ADTS fixed header)
+         */
+
+        status = find_adts_syncword(pSyncword,
+                                    &(pVars->inputStream),
+                                    LENGTH_FIXED_HEADER,
+                                    MASK_28BITS);
+    }
+    else
+    {
+
+        *(pSyncword) = SYNCWORD_15BITS;
+
+        status = find_adts_syncword(pSyncword,
+                                    &(pVars->inputStream),
+                                    LENGTH_SYNCWORD,
+                                    ID_BIT_FILTER);
+
+        /*
+         *  Extract the data from the header following the syncword
+         */
+        adts_header = getbits((LENGTH_FIXED_HEADER - LENGTH_SYNCWORD),
+                              &(pVars->inputStream));
+
+        *(pSyncword) <<= (LENGTH_FIXED_HEADER - LENGTH_SYNCWORD);
+        *(pSyncword)  |= adts_header;
+
+        /* Denotes whether a CRC check should be performed */
+        pVars->prog_config.CRC_absent  = ((UInt)(adts_header >> 12)) & 0x0001;
+
+        /*
+         * All the unread bits in adts_header reside in the lower
+         * 16-bits at this point.  Perform a typecast for faster
+         * execution on 16-bit processors.
+         */
+        lower_16 = (UInt)adts_header;
+
+        /*
+         * Profile consists of 2 bits, which indicate
+         * the profile used.
+         *
+         * '00' AAC_MAIN profile
+         * '01' AAC_LC (Low Complexity) profile
+         * '10' AAC_SSR (Scaleable Sampling Rate) profile
+         * '11' AAC_LTP (Long Term Prediction) profile
+         */
+        pVars->prog_config.profile = (lower_16 >> 10) & 0x3;
+
+        if (pVars->prog_config.profile == MP4AUDIO_AAC_SSR)
+        {
+            status = 1;     /* Not supported */
+        }
+
+        /*
+         * Sampling_rate_idx consists of 4 bits
+         * see Ref #1 for their interpretation.
+         */
+        pVars->prog_config.sampling_rate_idx = (lower_16 >> 6) & 0xF;
+
+        /*
+         * private_bit is a bit for private use.  ISO/IEC will not make
+         * use of this bit in the future.
+         *
+         * We currently make no use of it, but parsing the information
+         * from the bitstream could be easily implemented with the
+         * following instruction...
+         *
+         * private_bit = (lower_16 & 0x0400) >> 10;
+         */
+
+        /*
+         * These 3 bits indicate the channel configuration used.
+         *
+         * If '0' then the channel configuration is unspecified here,
+         * and must be given by a program configuration element in
+         * the raw data block.
+         *
+         * If '1' then the channel configuration is MONO.
+         * If '2' then the channel configuration is STEREO
+         *
+         * 3-7 represent channel configurations which this library
+         * will not support in the forseeable future.
+         */
+        channel_configuration = (lower_16 >> 2) & 0x7;
+        /* do not support more than 2 channels */
+        if (channel_configuration > 2)
+        {
+            status = 1;
+        }
+
+        /*
+         * The following 2 bits encode copyright information.
+         * original_copy is '0' if there is no copyright in the bitstream.
+         *                  '1' if the bitstream is copyright protected.
+         *
+         * home is '0' for a copy, '1' for an original.
+         *
+         * PacketVideo currently does nothing with this information,
+         * however, parsing the data from the bitstream could be easily
+         * implemented with the following instructions...
+         *
+         * original_copy = (lower_16 >> 1) & 0x1;
+         *
+         * home = (lower_16 & 0x1);
+         *
+         */
+
+        /* Set up based on information extracted from the ADTS FIXED header */
+
+        /* This equals 1 for STEREO, 0 for MONO */
+        if (channel_configuration)
+        {
+            channel_configuration--;
+        }
+        pVars->prog_config.front.ele_is_cpe[0] = channel_configuration;
+
+        /* This value is constant for both MONO and STEREO */
+        pVars->prog_config.front.num_ele    = 1;
+
+        /* ADTS does not specify this tag value - do we even use it? */
+        pVars->prog_config.front.ele_tag[0] = 0;
+
+        /* Disable all mix related variables */
+        pVars->prog_config.mono_mix.present = 0;
+        pVars->prog_config.stereo_mix.present = 0;
+        pVars->prog_config.matrix_mix.present = 0;
+
+        /* enter configuration into MC_Info structure */
+        if (status == SUCCESS)
+        {
+            /* profile + 1 == audioObjectType */
+            status =
+                set_mc_info(
+                    &(pVars->mc_info),
+                    (tMP4AudioObjectType)(pVars->prog_config.profile + 1),
+                    pVars->prog_config.sampling_rate_idx,
+                    pVars->prog_config.front.ele_tag[0],
+                    pVars->prog_config.front.ele_is_cpe[0],
+                    pVars->winmap, /* changed from pVars->pWinSeqInfo, */
+                    pVars->SFBWidth128);
+
+        } /* if (status == SUCCESS) */
+
+
+#ifdef AAC_PLUS
+
+        /*
+         *  For implicit signalling, no hint that sbr or ps is used, so we need to
+         *  check the sampling frequency of the aac content, if lesser or equal to
+         *  24 KHz, by defualt upsample, otherwise, do nothing
+         */
+        if ((pVars->prog_config.sampling_rate_idx >= 6) && (pVars->aacPlusEnabled == TRUE))
+        {
+            pVars->mc_info.upsamplingFactor = 2;
+            pVars->prog_config.sampling_rate_idx -= 3;
+            pVars->mc_info.sbrPresentFlag = 1;
+            pVars->sbrDecoderData.SbrChannel[0].syncState = SBR_ACTIVE;
+            pVars->sbrDecoderData.SbrChannel[1].syncState = SBR_ACTIVE;
+        }
+#endif
+
+
+        /*
+         * The tag and is_cpe will be checked in huffdecode,
+         * remove this check routine.
+         */
+        /*if (status == SUCCESS)
+         *{
+         *   if ( (*pInvoke) != 0)
+         *   {
+         *       status =
+         *           check_mc_info(
+         *               &(pVars->mc_info),
+         *               &(pVars->savedMCInfo),
+         *               FALSE);
+         *   }
+         *   else
+         *   {
+         *       status =
+         *           check_mc_info(
+         *               &(pVars->mc_info),
+         *               &(pVars->savedMCInfo),
+         *               TRUE);
+         *   }
+         *
+         *}*/ /* if (status == SUCCESS) */
+
+        /*
+         * This keeps track of how many headers have been read in the file.
+         * After the three successful headers with the same configuration
+         * are read in, the entire ADTS fixed header is used as the syncword
+         * for a more robust 28-bit long syncword
+         */
+
+        if (status == SUCCESS)
+        {
+            (*pInvoke)++;
+        }
+        else
+        {
+            (*pInvoke) = 0;
+        }
+
+    } /* END if (*(pInvoke) > 3) */
+
+    /* Grab the bits in the ADTS variable header */
+    adts_header = getbits(
+                      LENGTH_VARIABLE_HEADER,
+                      &(pVars->inputStream));
+    /*
+     * copyright_identification bit is a single bit of the 72-bit
+     * copyright_id field.  This consists of a 8-bit copyright identifier
+     * and a 64-bit copyright_number.  72 headers must be decoded
+     * to reconstruct the entire copyright_id field.
+     *
+     * copyright_identification_start is a single bit flagging
+     * the beginning bit of the copyright_id field.  '1' for start of
+     * copyright_id, '0' otherwise.
+     *
+     *
+     * PacketVideo currently does nothing with this information,
+     * however, parsing the data from the bitstream could be easily
+     * implemented with the following instructions...
+     *
+     * copyright_id_bit = ((UInt)(adts_header >> 27)) & 0x1;
+     *
+     * copyright_id_start = ((UInt)(adts_header >> 26)) & 0x1;
+     */
+
+    /*
+     * frame_length is a 13-bit field which indicates the length,
+     * in bytes, of the frame including error_check and headers.
+     * This information can theoretically be used to help verify syncwords.
+     */
+    pVars->prog_config.frame_length  = ((UInt)(adts_header >> 13)) & 0x1FFF;
+
+    /*
+     * All the unread bits in adts_header reside in the lower
+     * 16-bits at this point.  Perform a typecast for faster
+     * execution on 16-bit processors.
+     */
+    lower_16 = (UInt)adts_header;
+
+    /*
+     * Indicates the number of 32-bit words remaining in the
+     * encoder buffer after the encoding of the first raw
+     * data block.  This value is 0x7ff for variable bit
+     * rate encoders, since buffer fullness does not apply
+     * to Variable Bit Rate (VBR) encoders.
+     */
+    pVars->prog_config.buffer_fullness = (lower_16 >> 2) & 0x7FF;
+
+    /*
+     * headerless_frames indicates the number of
+     * frames with no headers to be processed before the reading
+     * in of the next header.
+     *
+     * In ADTS, up to 4 "no header frames" can exist between
+     * syncwords.
+     *
+     * EXAMPLES:
+     *
+     * Legend: (Sync words denoted by X, frames
+     * deonted by FRAME_#)
+     *
+     * Example(1): The ADTS sequence below packs 5
+     * frames per header.
+     * Here, headerless_frames would always be read in as "4"
+     *
+     * |X||FRAME_0||FRAME_1||FRAME_2||FRAME_3||FRAME_4||X||FRAME_0|
+     *
+     * Example(2): The ADTS sequence below packs 1 frame per header.
+     * Here, headerless_frames would always be read in as "0"
+     *
+     * |X||FRAME_0||X||FRAME_1||X||FRAME_2|
+     *
+     */
+    pVars->prog_config.headerless_frames = (lower_16 & 0x0003);
+
+    if (pVars->prog_config.CRC_absent == 0)
+    {
+        pVars->prog_config.CRC_check = (UInt)getbits(
+                                           LENGTH_CRC,
+                                           &(pVars->inputStream));
+    }
+
+    /* pVars->current_program = 0; */ /* shall be set after PCE is read */
+
+    return (status);
+
+} /* END get_adts_header */
diff --git a/media/libstagefright/codecs/aacdec/get_adts_header.h b/media/libstagefright/codecs/aacdec/get_adts_header.h
new file mode 100644
index 0000000..13afa05
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_adts_header.h
@@ -0,0 +1,90 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/get_adts_header.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file has the function declaration for get_adts_header().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_ADTS_HEADER_H
+#define GET_ADTS_HEADER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_adts_header(
+    tDec_Int_File *pVars,
+    UInt32        *pSyncword,
+    Int           *pInvoke,
+    Int            CorrectlyReadFramesCount);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_audio_specific_config.cpp b/media/libstagefright/codecs/aacdec/get_audio_specific_config.cpp
new file mode 100644
index 0000000..092f397
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_audio_specific_config.cpp
@@ -0,0 +1,691 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/get_audio_specific_config.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified per review comments
+
+ Description: Modified per second review comments
+              (1) change audioObjectType to Int
+              (2) do not set pVars->prog_config.profile
+              (3) clean up status flag, default to SUCCESS
+              (4) fix multiple lines comments
+
+ Description: Change getbits.h to ibstream.h
+
+ Description: Modified per review comments
+              (1) updated revision history
+              (2) declare audioObjectType as enum type
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less.
+
+ Description: Added support for backward and non-backward (explicit)
+              mode for Parametric Stereo (PS) used in enhanced AAC+
+
+ Who:                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pVars = pointer to the structure that holds all information for
+            this instance of the library. pVars->prog_config is directly
+            used, and pVars->mc_info, pVars->prog_config,
+            pVars->pWinSeqInfo, pVars->SFBWidth128 are needed indirectly
+            for calling set_mc_info. Data type pointer to tDec_Int_File
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    status = 0 if successfully decoded AudioSpecificConfig
+             1 if un-supported config is used for this release
+
+ Pointers and Buffers Modified:
+    pVars->prog_config contents are updated with the information read in.
+    pVars->mc_info contents are updated with channel information.
+    pVars->pWinSeqInfo contents are updated with window information.
+    pVars->SFBWidth128 contents are updated with scale factor band width data.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads the bitstream for the structure "AudioSpecificConfig",
+ and sets the decoder configuration that is needed by the decoder to be able
+ to decode the media properly.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall not use global variables
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3: 1999(E)
+ Part 3
+ Subpart 1  p18     1.6   Interface to MPEG-4 Systems
+ Subpart 4  p13     4.4.1 GA Specific Configuration
+ Amendment  p10     6.2.1 AudioSpecificInfo
+ Amendment  p78     8.2   Decoder configuration (GASpecificConfig)
+
+ (2) AAC DecoderSpecificInfo Information
+   PacketVideo descriptions - San Diego
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    status = SUCCESS;
+
+    pInputStream = &(pVars->inputStream);
+
+    temp = CALL getbits(
+                    neededBits = LEN_OBJ_TYPE + LEN_SAMP_RATE_IDX,
+                    pInputStream = pInputStream)
+           MODIFYING (pInputStream)
+           RETURNING (temp)
+
+    audioObjectType = (temp & 0x1f0) >> 4;
+
+    pVars->prog_config.profile = audioObjectType;
+
+    pVars->prog_config.sampling_rate_idx = temp & 0xf;
+
+    IF (pVars->prog_config.sampling_rate_idx == 0xf)
+    THEN
+        sampling_rate = CALL getbits(
+                            neededBits = LEN_SAMP_RATE,
+                            pInputStream = pInputStream);
+                        MODIFYING (pInputStream)
+                        RETURNING (sampling_rate)
+    ENDIF
+
+    channel_config = CALL getbits(
+                            neededBits = LEN_CHAN_CONFIG,
+                            pInputStream = pInputStream);
+                        MODIFYING (pInputStream)
+                        RETURNING (channel_config)
+
+    IF (channel_config > 2)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (((audioObjectType == MP4AUDIO_AAC_MAIN)     OR
+        (audioObjectType == MP4AUDIO_AAC_LC)        OR
+        (audioObjectType == MP4AUDIO_AAC_SSR)       OR
+        (audioObjectType == MP4AUDIO_LTP)           OR
+        (audioObjectType == MP4AUDIO_AAC_SCALABLE)  OR
+        (audioObjectType == MP4AUDIO_TWINVQ)) AND (status == -1))
+    THEN
+        status = CALL get_GA_specific_config(
+                            pVars = pVars,
+                            channel_config = channel_config,
+                            audioObjectType = audioObjectType,
+                            pInputStream = pInputStream);
+                      MODIFYING (pVars->mc_info,channel_config,pInputStream)
+                      RETURNING (status)
+
+    ENDIF
+
+    IF (audioObjectType == MP4AUDIO_CELP)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (audioObjectType == MP4AUDIO_HVXC)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (audioObjectType == MP4AUDIO_TTSI)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF ((audioObjectType == 13) OR (audioObjectType == 14) OR
+        (audioObjectType == 15) OR (audioObjectType == 16))
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (((audioObjectType == MP4AUDIO_ER_AAC_LC)       OR
+         (audioObjectType == MP4AUDIO_ER_AAC_LTP)      OR
+         (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE) OR
+         (audioObjectType == MP4AUDIO_ER_TWINVQ)       OR
+         (audioObjectType == MP4AUDIO_ER_BSAC)         OR
+         (audioObjectType == MP4AUDIO_ER_AAC_LD)) AND (status == -1))
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (audioObjectType == MP4AUDIO_ER_CELP)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF (audioObjectType == MP4AUDIO_ER_HVXC)
+    THEN
+        status = 1;
+    ENDIF
+
+    IF ((audioObjectType == MP4AUDIO_ER_HILN) OR
+        (audioObjectType == MP4AUDIO_PARAMETRIC))
+    THEN
+        status = 1;
+    ENDIF
+
+    IF ((audioObjectType == MP4AUDIO_ER_AAC_LC)       OR
+        (audioObjectType == MP4AUDIO_ER_AAC_LTP)      OR
+        (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE) OR
+        (audioObjectType == MP4AUDIO_ER_TWINVQ)       OR
+        (audioObjectType == MP4AUDIO_ER_BSAC)         OR
+        (audioObjectType == MP4AUDIO_ER_AAC_LD)       OR
+        (audioObjectType == MP4AUDIO_ER_CELP)         OR
+        (audioObjectType == MP4AUDIO_ER_HVXC)         OR
+        (audioObjectType == MP4AUDIO_ER_HILN)         OR
+        (audioObjectType == MP4AUDIO_PARAMETRIC))
+    THEN
+        epConfig = CALL getbits(
+                            neededBits = LEN_EP_CONFIG,
+                            pInputStream = pInputStream);
+                      MODIFYING (pInputStream)
+                      RETURNING (epConfig)
+
+        IF (epConfig == 2)
+        THEN
+            status = 1;
+        ENDIF
+
+    ENDIF
+
+    RETURN status;
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "e_mp4ff_const.h"
+#include    "e_tmp4audioobjecttype.h"
+#include    "get_audio_specific_config.h"
+#include    "get_ga_specific_config.h"
+#include    "ibstream.h"
+#include    "sfb.h"                   /* Where samp_rate_info[] is declared */
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_audio_specific_config(tDec_Int_File   * const pVars)
+{
+
+    UInt    temp;
+    tMP4AudioObjectType     audioObjectType;
+    //UInt32  sampling_rate;
+    UInt    channel_config;
+    UInt    syncExtensionType;
+    UInt    extensionAudioObjectType = 0;
+    UInt    extensionSamplingFrequencyIndex = 0;
+    BITS   *pInputStream;
+    Int     status;
+
+    status = SUCCESS;
+
+    pInputStream = &(pVars->inputStream);
+
+    pVars->mc_info.upsamplingFactor = 1;   /*  default to regular AAC */
+
+    temp =  get9_n_lessbits(LEN_OBJ_TYPE + LEN_SAMP_RATE_IDX,
+                            pInputStream);
+
+    /*
+     * The following code can directly set the values of elements in
+     * MC_Info, rather than first setting the values in pVars->prog_config
+     * and then copy these values to MC_Info by calling set_mc_info.
+     * In order to keep consistent with get_prog_config (ADIF) and
+     * get_adts_header (ADTS), the code here is still copying
+     * the info, and set the pVars->current_program = 0
+     */
+
+    /* AudioObjectType */
+    audioObjectType = (tMP4AudioObjectType)((temp & 0x1f0) >> 4);
+
+    pVars->mc_info.ExtendedAudioObjectType =  audioObjectType;   /* default */
+    /* saving an audioObjectType into a profile field */
+    /* pVars->prog_config.profile = audioObjectType; */
+
+    /* sampling rate index */
+    pVars->prog_config.sampling_rate_idx = temp & 0xf;
+
+    if (pVars->prog_config.sampling_rate_idx > 0xb)
+    {
+        /*
+         *  Only support 12 sampling frequencies from array samp_rate_info ( see sfb.cpp)
+         *  7350 Hz (index 0xc) is not supported, the other indexes are reserved or escape
+         */
+        if (pVars->prog_config.sampling_rate_idx == 0xf) /* escape sequence */
+        {
+            /*
+             * sampling rate not listed in Table 1.6.2,
+             * this release does not support this
+             */
+            /*sampling_rate =  getbits( LEN_SAMP_RATE,
+                                      pInputStream);*/
+            getbits(LEN_SAMP_RATE, pInputStream); /* future use */
+        }
+
+        status = 1;
+    }
+
+    channel_config =  get9_n_lessbits(LEN_CHAN_CONFIG,
+                                      pInputStream);
+
+    if ((channel_config > 2) && (!pVars->aacConfigUtilityEnabled))
+    {
+        /*
+         * AAC lib does not support more than two channels
+         * signal error when in decoder mode
+         * do not test when in utility mode
+         */
+        status = 1;
+
+    }
+
+    if (audioObjectType == MP4AUDIO_SBR || audioObjectType == MP4AUDIO_PS)
+    {
+        /* to disable explicit backward compatiblity check */
+        pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_SBR;
+        pVars->mc_info.sbrPresentFlag = 1;
+
+        if (audioObjectType == MP4AUDIO_PS)
+        {
+            pVars->mc_info.psPresentFlag = 1;
+            pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_PS;
+        }
+
+        extensionSamplingFrequencyIndex = /* extensionSamplingFrequencyIndex */
+            get9_n_lessbits(LEN_SAMP_RATE_IDX,
+                            pInputStream);
+        if (extensionSamplingFrequencyIndex == 0x0f)
+        {
+            /*
+             * sampling rate not listed in Table 1.6.2,
+             * this release does not support this
+                */
+            /*sampling_rate = getbits( LEN_SAMP_RATE,
+                                     pInputStream);*/
+            getbits(LEN_SAMP_RATE, pInputStream);
+        }
+
+        audioObjectType = (tMP4AudioObjectType) get9_n_lessbits(LEN_OBJ_TYPE ,
+                          pInputStream);
+    }
+
+
+    if ((/*(audioObjectType == MP4AUDIO_AAC_MAIN)     ||*/
+                (audioObjectType == MP4AUDIO_AAC_LC)        ||
+                /*(audioObjectType == MP4AUDIO_AAC_SSR)       ||*/
+                (audioObjectType == MP4AUDIO_LTP)           /*||*/
+                /*(audioObjectType == MP4AUDIO_AAC_SCALABLE)  ||*/
+                /*(audioObjectType == MP4AUDIO_TWINVQ)*/) && (status == SUCCESS))
+    {
+        status = get_GA_specific_config(pVars,
+                                        pInputStream,
+                                        channel_config,
+                                        audioObjectType);
+
+        /*
+         *  verify that Program config returned a supported audio object type
+         */
+
+        if ((pVars->mc_info.audioObjectType != MP4AUDIO_AAC_LC) &&
+                (pVars->mc_info.audioObjectType != MP4AUDIO_LTP))
+        {
+            return 1;   /* status != SUCCESS invalid aot */
+        }
+    }
+    else
+    {
+        return 1;   /* status != SUCCESS invalid aot or invalid parameter */
+    }
+
+    /*
+     *  SBR tool explicit signaling ( backward compatible )
+     */
+    if (extensionAudioObjectType != MP4AUDIO_SBR)
+    {
+        syncExtensionType = (UInt)get17_n_lessbits(LEN_SYNC_EXTENSION_TYPE,
+                            pInputStream);
+
+        if (syncExtensionType == 0x2b7)
+        {
+            extensionAudioObjectType = get9_n_lessbits( /* extensionAudioObjectType */
+                                           LEN_OBJ_TYPE,
+                                           pInputStream);
+
+            if (extensionAudioObjectType == MP4AUDIO_SBR)
+            {
+                pVars->mc_info.sbrPresentFlag = get1bits(pInputStream);  /* sbrPresentFlag */
+                if (pVars->mc_info.sbrPresentFlag == 1)
+                {
+                    extensionSamplingFrequencyIndex =
+                        get9_n_lessbits( /* extensionSamplingFrequencyIndex */
+                            LEN_SAMP_RATE_IDX,
+                            pInputStream);
+                    if (pVars->aacPlusEnabled == true)
+                    {
+#ifdef AAC_PLUS
+                        pVars->mc_info.upsamplingFactor = (samp_rate_info[extensionSamplingFrequencyIndex].samp_rate >> 1) ==
+                                                          samp_rate_info[pVars->prog_config.sampling_rate_idx].samp_rate ? 2 : 1;
+
+                        if ((Int)extensionSamplingFrequencyIndex == pVars->prog_config.sampling_rate_idx)
+                        {
+                            /*
+                             *  Disable SBR decoding for any sbr-downsampled file whose SF is >= 24 KHz
+                             */
+                            if (pVars->prog_config.sampling_rate_idx < 6)
+                            {
+                                pVars->aacPlusEnabled = false;
+                            }
+
+                            pVars->mc_info.bDownSampledSbr = true;
+                        }
+                        pVars->prog_config.sampling_rate_idx = extensionSamplingFrequencyIndex;
+
+#endif
+                    }
+
+                    if (extensionSamplingFrequencyIndex == 0x0f)
+                    {
+                        /*
+                         * sampling rate not listed in Table 1.6.2,
+                         * this release does not support this
+                         */
+                        /*sampling_rate = getbits( LEN_SAMP_RATE,
+                                                 pInputStream);*/
+                        getbits(LEN_SAMP_RATE, pInputStream);
+                    }
+                    /* syncExtensionType */
+                    syncExtensionType = (UInt)get17_n_lessbits(LEN_SYNC_EXTENSION_TYPE,
+                                        pInputStream);
+                    if (syncExtensionType == 0x548)
+                    {
+                        pVars->mc_info.psPresentFlag = get1bits(pInputStream);  /* psPresentFlag */
+                        if (pVars->mc_info.psPresentFlag)
+                        {
+                            extensionAudioObjectType = MP4AUDIO_PS;
+                        }
+                    }
+                    else
+                    {
+                        /*
+                        * Rewind bitstream pointer so that the syncExtensionType reading has no
+                        * effect when decoding raw bitstream
+                            */
+                        pVars->inputStream.usedBits -= LEN_SYNC_EXTENSION_TYPE;
+                    }
+
+                    pVars->mc_info.ExtendedAudioObjectType = (eMP4AudioObjectType)extensionAudioObjectType;
+                }
+            }
+        }
+        else if (!status)
+        {
+            /*
+             * Rewind bitstream pointer so that the syncExtensionType reading has no
+             * effect when decoding raw bitstream
+             */
+            pVars->inputStream.usedBits -= LEN_SYNC_EXTENSION_TYPE;
+
+#ifdef AAC_PLUS
+
+            /*
+             *  For implicit signalling, no hint that sbr or ps is used, so we need to
+             *  check the sampling frequency of the aac content, if lesser or equal to
+             *  24 KHz, by defualt upsample, otherwise, do nothing
+             */
+            if ((pVars->prog_config.sampling_rate_idx >= 6) && (pVars->aacPlusEnabled == true) &&
+                    audioObjectType == MP4AUDIO_AAC_LC)
+            {
+                pVars->mc_info.upsamplingFactor = 2;
+                pVars->prog_config.sampling_rate_idx -= 3;
+                pVars->mc_info.sbrPresentFlag = 1;
+                pVars->sbrDecoderData.SbrChannel[0].syncState = SBR_NOT_INITIALIZED;
+                pVars->sbrDecoderData.SbrChannel[1].syncState = SBR_NOT_INITIALIZED;
+
+            }
+#endif
+
+        }
+    }
+    else    /*  MP4AUDIO_SBR was detected  */
+    {
+        /*
+         *  Set the real output frequency use by the SBR tool, define tentative upsample ratio
+         */
+        if (pVars->aacPlusEnabled == true)
+        {
+#ifdef AAC_PLUS
+            pVars->mc_info.upsamplingFactor = (samp_rate_info[extensionSamplingFrequencyIndex].samp_rate >> 1) ==
+                                              samp_rate_info[pVars->prog_config.sampling_rate_idx].samp_rate ? 2 : 1;
+
+            if ((Int)extensionSamplingFrequencyIndex == pVars->prog_config.sampling_rate_idx)
+            {
+                /*
+                 *  Disable SBR decoding for any sbr-downsampled file whose SF is >= 24 KHz
+                 */
+                if (pVars->prog_config.sampling_rate_idx < 6)
+                {
+                    pVars->aacPlusEnabled = false;
+                }
+                pVars->mc_info.bDownSampledSbr = true;
+            }
+            pVars->prog_config.sampling_rate_idx = extensionSamplingFrequencyIndex;
+
+
+
+#endif
+
+
+
+
+        }
+
+    }  /*  if ( extensionAudioObjectType != MP4AUDIO_SBR ) */
+
+    /*
+     * The following object types are not supported in this release,
+     * however, keep these interfaces for future implementation
+     */
+
+    /*
+     *if (audioObjectType == MP4AUDIO_CELP)
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if (audioObjectType == MP4AUDIO_HVXC)
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if (audioObjectType == MP4AUDIO_TTSI)
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if ((audioObjectType == 13) || (audioObjectType == 14) ||
+     *   (audioObjectType == 15) || (audioObjectType == 16))
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /* The following objects are Amendment 1 objects */
+    /*
+     *if (((audioObjectType == MP4AUDIO_ER_AAC_LC)       ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_LTP)      ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE) ||
+     *    (audioObjectType == MP4AUDIO_ER_TWINVQ)       ||
+     *    (audioObjectType == MP4AUDIO_ER_BSAC)         ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_LD)) && (status == -1))
+     *{
+     */
+    /*
+     * should call get_GA_specific_config
+     * for this release, do not support Error Resilience
+     * temporary solution is set status flag and exit decoding
+     */
+    /*    status = 1;
+    *}
+    */
+
+    /*
+     *if (audioObjectType == MP4AUDIO_ER_CELP)
+     * {
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if (audioObjectType == MP4AUDIO_ER_HVXC)
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if ((audioObjectType == MP4AUDIO_ER_HILN) ||
+     *    (audioObjectType == MP4AUDIO_PARAMETRIC))
+     *{
+     *    status = 1;
+     *}
+     */
+
+    /*
+     *if ((audioObjectType == MP4AUDIO_ER_AAC_LC)       ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_LTP)      ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE) ||
+     *    (audioObjectType == MP4AUDIO_ER_TWINVQ)       ||
+     *    (audioObjectType == MP4AUDIO_ER_BSAC)         ||
+     *    (audioObjectType == MP4AUDIO_ER_AAC_LD)       ||
+     *    (audioObjectType == MP4AUDIO_ER_CELP)         ||
+     *    (audioObjectType == MP4AUDIO_ER_HVXC)         ||
+     *    (audioObjectType == MP4AUDIO_ER_HILN)         ||
+     *    (audioObjectType == MP4AUDIO_PARAMETRIC))
+     *{
+     */
+    /* error protection config */
+    /*
+     *     epConfig =
+     *       getbits(
+     *           LEN_EP_CONFIG,
+     *           pInputStream);
+     *
+     *   if (epConfig == 2)
+     *   {
+     */
+    /* should call ErrorProtectionSpecificConfig() */
+    /*
+     *       status = 1;
+     *   }
+     *
+     *}
+     */
+
+    return status;
+
+}
diff --git a/media/libstagefright/codecs/aacdec/get_audio_specific_config.h b/media/libstagefright/codecs/aacdec/get_audio_specific_config.h
new file mode 100644
index 0000000..b7cfcf5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_audio_specific_config.h
@@ -0,0 +1,86 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/get_audio_specific_config.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes function declaration for get_audio_specific_config
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_AUDIO_SPECIFIC_CONFIG_H
+#define GET_AUDIO_SPECIFIC_CONFIG_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_tdec_int_file.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_audio_specific_config(
+    tDec_Int_File   * const pVars
+);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/get_dse.cpp b/media/libstagefright/codecs/aacdec/get_dse.cpp
new file mode 100644
index 0000000..d64087f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_dse.cpp
@@ -0,0 +1,215 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pInputStream = pointer to a BITS structure that holds information
+                   regarding the input stream.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pInputStream->usedBits is rounded up to a number that represents the next
+    byte boundary.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Adquire Data Stream element (DSE) from raw bitstream
+    At this time this function just drops the information.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+  This function shall not use global or static variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void byte_align(
+    BITS  *pInputStream)
+
+    MODIFYING(pInputStream->usedBits = pInputStream->usedBits +
+                (pInputStream->usedBits + 7) % 8)
+
+    RETURN(nothing)
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+
+ STACK USAGE:
+
+     where:
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+#include "get_dse.h"
+#include "ibstream.h"
+#include "getbits.h"
+#include "s_bits.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void get_dse(
+    Char    *DataStreamBytes,
+    BITS    *pInputStream)
+{
+    Int i;
+    Int data_byte_align_flag;
+    UInt count;
+    Int esc_count;
+    Char    *pDataStreamBytes;
+
+    pDataStreamBytes = DataStreamBytes;
+
+    /*
+     *  Get element instance tag  ( 4 bits)
+     *  ( max of 16 per raw data block)
+     */
+    get9_n_lessbits(LEN_TAG, pInputStream);
+
+    /*
+     *  get data_byte_align_flag ( 1 bit0 to see if byte alignment is
+     *  performed within the DSE
+     */
+    data_byte_align_flag = get1bits(pInputStream);
+
+    /*
+     *  get count ( 8 bits)
+     */
+    count =  get9_n_lessbits(LEN_D_CNT, pInputStream);
+
+    /*
+     *  if count == 255, its value it is incremented  by a
+     *  second 8 bit value, esc_count. This final value represents
+     *  the number of bytes in the DSE
+     */
+    if (count == (1 << LEN_D_CNT) - 1)
+    {
+        esc_count = (Int)get9_n_lessbits(LEN_D_ESC, pInputStream);  /* 8 bits */
+        count +=  esc_count;
+    }
+
+    /*
+     *  Align if flag is set
+     */
+    if (data_byte_align_flag)
+    {
+        byte_align(pInputStream);
+    }
+
+    for (i = count; i != 0; i--)
+    {
+        *(pDataStreamBytes++) = (Char) get9_n_lessbits(
+                                    LEN_BYTE,
+                                    pInputStream);
+    }
+
+    return;
+
+} /* end get_dse */
+
diff --git a/media/libstagefright/codecs/aacdec/get_dse.h b/media/libstagefright/codecs/aacdec/get_dse.h
new file mode 100644
index 0000000..3563f71
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_dse.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_dse.h
+ Funtions:
+    get_dse
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_DSE_H
+#define GET_DSE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_elelist.h"
+#include "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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 get_dse(
+    Char    *DataStreamBytes,
+    BITS    *pInputStream);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/get_ele_list.cpp b/media/libstagefright/codecs/aacdec/get_ele_list.cpp
new file mode 100644
index 0000000..0534c13
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ele_list.cpp
@@ -0,0 +1,243 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_ele_list.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description: Change to PacketVideo standard, rename variables.
+
+ Description: Add own header file, make pInputStream second param for speed.
+
+ Description: Changes per code review:
+              1) Include header file
+              2) Convert to count down
+              3) Add return (not in review)
+
+ Description:
+ (1) Updated copyright header
+ (2) Replaced include of "interface.h" with "e_ProgConfig.h"
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Who:                                 Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pElementList = pointer to an EleList structure - only the field num_ele
+                   needs to be set. Data type pointer to EleList.
+
+   pInputStream = pointer to a BITS structure, used by the function getbits
+                   to provide data. Data type pointer to BITS
+
+    enableCPE = boolean value indicating the area to be read contains
+                a channel pair element field. Data type Bool
+
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs: None
+
+ Pointers and Buffers Modified:
+    pElementList contents are updated with information pertaining to channel
+        configuration.
+
+    pInputBuffer contents are updated to the next location to be read from
+        the input stream.
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is called several times by get_prog_config() to read in part of
+ the program configuration data related to channel setup.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall not have static or global variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+   of moving pictures and associated audio information - Part 7: Advanced
+   Audio Coding (AAC)", Table 6.21 - Syntax of program_config_element(),
+   page 16, and section 8.5 "Program Config Element (PCE)", page 30.
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    elementCount = pElementList->num_ele;
+
+    FOR (index = 0; index < elementCount; index++)
+        IF (enableCPE != FALSE) THEN
+            pElementList->ele_is_cpe[index] =
+                getbits(LEN_ELE_IS_CPE, pInputStream);
+        ELSE
+            pElementList->ele_is_cpe[index] = 0;
+        END IF
+
+        pElementList->ele_tag[index] = getbits(LEN_TAG, pInputStream);
+
+    END FOR
+
+    RETURNS nothing
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_elelist.h"
+#include "s_bits.h"
+#include "e_progconfigconst.h"
+#include "ibstream.h"
+#include "get_ele_list.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 get_ele_list(
+    EleList     *pElementList,
+    BITS        *pInputStream,
+    const Bool   enableCPE)
+{
+    Int index;
+    Int *pEleIsCPE;
+    Int *pEleTag;
+
+    pEleIsCPE = &pElementList->ele_is_cpe[0];
+    pEleTag   = &pElementList->ele_tag[0];
+
+    for (index = pElementList->num_ele; index > 0; index--)
+    {
+        if (enableCPE != FALSE)
+        {
+            *pEleIsCPE++ = get1bits(/*LEN_ELE_IS_CPE, */pInputStream);
+        }
+        else
+        {
+            *pEleIsCPE++ = FALSE;
+        }
+
+        *pEleTag++ = get9_n_lessbits(LEN_TAG, pInputStream);
+
+    } /* end for (index) */
+
+    return;
+
+} /* end get_ele_list */
+
diff --git a/media/libstagefright/codecs/aacdec/get_ele_list.h b/media/libstagefright/codecs/aacdec/get_ele_list.h
new file mode 100644
index 0000000..82f140b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ele_list.h
@@ -0,0 +1,90 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/get_ele_list.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for get_ele_list.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_ELE_LIST_H
+#define GET_ELE_LIST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_elelist.h"
+#include "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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 get_ele_list(
+    EleList     *pElementList,
+    BITS        *pInputStream,
+    const Bool   enableCPE);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_ga_specific_config.cpp b/media/libstagefright/codecs/aacdec/get_ga_specific_config.cpp
new file mode 100644
index 0000000..65c00ea
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ga_specific_config.cpp
@@ -0,0 +1,473 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_GA_specific_config.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified per review comments
+
+ Description: Change getbits.h to ibstream.h
+
+ Description: (1) use enum type for audioObjectType (2) update revision history
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Description: Updated to use scratch memory for the temporary prog config.
+
+ Description: Replace some instances of getbits to get1bits
+              when only 1 bit is read.
+
+ Who:                               Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+        pVars   = pointer to the structure that holds all information for
+                  this instance of the library. pVars->prog_config
+                  pVars->mc_info, pVars->pWinSeqInfo, pVars->SFBWidth128
+                  are needed for calling set_mc_info.
+                  Data type pointer to tDec_Int_File
+
+        channel_config = variable that indicates the channel configuration
+                         information, in this decoder library, only values
+                         0, 1, and 2 are allowed.
+                         Data type UInt
+
+        audioObjectType = variable that indicates the Audio Object Type.
+                          Data type UInt.
+
+        pInputStream = pointer to a BITS structure that holds information
+                       regarding the input stream.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    status = 0 if success
+             1 otherwise
+
+ Pointers and Buffers Modified:
+    pVars->mc_info contents are updated with channel information.
+    if infoinit is called within set_mc_info, then
+    pVars->pWinSeqInfo contents are updated with window information.
+    pVars->SFBWidth128 contents are updated with scale factor band width data.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function takes the sampling_rate_idx, channel_config, and
+ audioObjectType from AudioSpecificConfig() and set the decoder configuration
+ necessary for the decoder to decode properly.
+ It also reads the bitstream for frame length, scalable bitstream information
+ and extension information to General Audio defined in MPEG-4 phase 1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+  This function shall not use global variables
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3: 1999(E)
+ Part 3
+ Subpart 1  p18     1.6 Interface to MPEG-4 Systems
+ Subpart 4  p13     4.4.1 GA Specific Configuration
+ Amendment  p10     6.2.1 AudioSpecificInfo
+ Amendment  p78     8.2 Decoder configuration (GASpecificConfig)
+
+ (2) AAC DecoderSpecificInfo Information
+   PacketVideo descriptions - San Diego
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    frameLenFlag = CALL getbits(
+                            neededBits = LEN_FRAME_LEN_FLAG,
+                            pInputStream = pInputStream);
+                        MODIFYING (pInputStream)
+                        RETURNING (frameLenFlag)
+
+    dependsOnCoreCoder = CALL getbits(
+                               neededBits = LEN_DEPEND_ON_CORE,
+                               pInputStream = pInputStream);
+                        MODIFYING (pInputStream)
+                        RETURNING (dependsOnCoreCoder)
+
+    IF (dependsOnCoreCoder != FALSE)
+    THEN
+        coreCoderDelay = CALL getbits(
+                                neededBits = LEN_CORE_DELAY,
+                                pInputStream = pInputStream);
+                            MODIFYING (pInputStream)
+                            RETURNING (coreCoderDelay)
+    ENDIF
+
+    extFlag = CALL getbits(
+                      neededBits = LEN_EXT_FLAG,
+                      pInputStream = pInputStream);
+                   MODIFYING (pInputStream)
+                   RETURNING (extFlag)
+
+    IF (channel_config == 0)
+    THEN
+        status = CALL get_prog_config(
+                        pVars = pVars,
+                        pScratchPCE = &pVars->scratch_prog_config);
+                   MODIFYING (pVars, pScratchPCE)
+                   RETURNING (status)
+
+    ELSE
+        channel_config--;
+        pVars->prog_config.front.ele_is_cpe[0] = channel_config;
+        pVars->prog_config.front.ele_tag[0] = 0;
+
+        status = CALL set_mc_info(
+                        pMC_Info =  &(pVars->mc_info),
+                        audioObjectType = audioObjectType,
+                        sampling_rate_idx = pVars->prog_config.sampling_rate_idx,
+                        tag = pVars->prog_config.front.ele_tag[0],
+                        is_cpe = pVars->prog_config.front.ele_is_cpe[0],
+                        pWinSeqInfo = pVars->pWinSeqInfo,
+                        sfbwidth128 = pVars->SFBWidth128);
+                    MODIFYING (pMC_Info, pWinSeqInfo, sfbwidth128)
+                    RETURNING (SUCCESS)
+    ENDIF
+
+    IF ((audioObjectType == MP4AUDIO_AAC_SCALABLE) OR
+        (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE))
+    THEN
+        layer_num = CALL getbits(
+                            neededBits = LEN_LAYER_NUM,
+                            pInputStream = pInputStream);
+                        MODIFYING (pInputStream)
+                        RETURNING (layer_num)
+
+        status = 1;
+    ENDIF
+
+    IF (extFlag != FALSE)
+    THEN
+         IF (audioObjectType == MP4AUDIO_ER_BSAC)
+         THEN
+              numOfSubFrame = CALL getbits(
+                                     neededBits = LEN_SUB_FRAME,
+                                     pInputStream = pInputStream);
+                                MODIFYING (pInputStream)
+                                RETURNING (numOfSubFrame)
+
+              layer_len = CALL getbits(
+                                neededBits = LEN_LAYER_LEN,
+                                pInputStream = pInputStream);
+                               MODIFYING (pInputStream)
+                               RETURNING (layer_len)
+
+         ENDIF
+
+         IF (((audioObjectType > 16) AND (audioObjectType < 22)) OR
+             (audioObjectType == 23))
+         THEN
+             aacSectionDataResilienceFlag =
+                            CALL getbits(
+                                    neededBits = LEN_SECT_RES_FLAG,
+                                    pInputStream = pInputStream);
+                                MODIFYING (pInputStream)
+                                RETURNING (aacSectionDataResilienceFlag)
+
+             aacScalefactorDataResilienceFlag =
+                            CALL getbits(
+                                    neededBits = LEN_SFB_RES_FLAG,
+                                    pInputStream = pInputStream);
+                                MODIFYING (pInputStream)
+                                RETURNING (aacScalefactorDataResilienceFlag)
+
+             aacSpectralDataResilienceFlag =
+                            CALL getbits(
+                                    neededBits = LEN_SPEC_RES_FLAG,
+                                    pInputStream = pInputStream);
+                                MODIFYING (pInputStream)
+                                RETURNING (aacSpectralDataResilienceFlag)
+         ENDIF
+
+        status = 1;
+
+    ENDIF
+
+    RETURN status;
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "e_mp4ff_const.h"
+#include    "e_tmp4audioobjecttype.h"
+#include    "s_tdec_int_file.h"
+#include    "get_ga_specific_config.h"
+#include    "set_mc_info.h"
+#include    "get_prog_config.h"
+#include    "ibstream.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
+----------------------------------------------------------------------------*/
+Int get_GA_specific_config(
+    tDec_Int_File * const pVars,
+    BITS    *pInputStream,
+    UInt     channel_config,
+    const tMP4AudioObjectType audioObjectType
+)
+{
+
+    Int status = SUCCESS;
+    UInt dependsOnCoreCoder;
+    /* Int coreCoderDelay; */
+    UInt extFlag;
+
+    /* These variables are left for future implementation */
+    /* UInt layer_num; */
+    /* UInt numOfSubFrame; */
+    /* UInt layer_len; */
+    /* UInt aacSectionDataResilienceFlag; */
+    /* UInt aacScalefactorDataResilienceFlag; */
+    /* UInt aacSpectralDataResilienceFlag; */
+    Int  extFlag3;
+
+    /*
+     * frame length flag == 0, 1024 samples/frame
+     * frame length flag == 1,  960 samples/frame
+     */
+    get1bits(/*            LEN_FRAME_LEN_FLAG,*/
+        pInputStream);
+
+    /*
+     * dependsOnCoreCoder == 1, core coder has different sampling rate
+     * in a scalable bitstream
+     */
+    dependsOnCoreCoder =
+        get1bits(/*            LEN_DEPEND_ON_CORE,*/
+            pInputStream);
+
+    if (dependsOnCoreCoder != FALSE)
+    {
+        /*coreCoderDelay =
+         *    getbits(
+         *        LEN_CORE_DELAY,
+         *        pInputStream);
+         */
+
+        status = 1; /* do not support scalable coding in this release */
+    }
+
+    /*
+     * extension flag indicates if Amendment 1 objects are used or not
+     * extension flag == 0 objects = 1, 2, 3, 4, 6, 7
+     * extension flag == 1 objects = 17, 19, 20, 21, 22, 23
+     */
+    extFlag = get1bits(pInputStream);       /*  LEN_EXT_FLAG,*/
+
+
+    /* Force checks for implicit channel configuration */
+    pVars->mc_info.implicit_channeling = 1;
+
+    if (status == SUCCESS)
+    {
+
+        if (channel_config == 0)
+        {
+            status = get_prog_config(pVars,
+                                     &pVars->scratch.scratch_prog_config);
+
+            if (status != SUCCESS)
+            {
+                pVars->prog_config.front.ele_is_cpe[0] = 0; /* default to mono  */
+                pVars->mc_info.nch = 1;
+                pVars->prog_config.front.ele_tag[0] = 0;
+
+                status = SUCCESS;
+            }
+        }
+        else
+        {
+            /*
+             * dummy tag = 0 and
+             * set up decoding configurations
+             */
+            channel_config--;
+            pVars->prog_config.front.ele_is_cpe[0] = channel_config;
+            pVars->prog_config.front.ele_tag[0] = 0;
+
+            status =
+                set_mc_info(
+                    &(pVars->mc_info),
+                    audioObjectType, /* previously profile */
+                    pVars->prog_config.sampling_rate_idx,
+                    pVars->prog_config.front.ele_tag[0],
+                    pVars->prog_config.front.ele_is_cpe[0],
+                    pVars->winmap, /*pVars->pWinSeqInfo,*/
+                    pVars->SFBWidth128);
+
+        } /* if (channel_config) */
+
+    } /* if(status) */
+
+    /*
+     * This layer_num is not found in ISO/IEC specs,
+     * but it is defined in San Diego spec for scalable bitstream
+     */
+    if ((audioObjectType == MP4AUDIO_AAC_SCALABLE) ||
+            (audioObjectType == MP4AUDIO_ER_AAC_SCALABLE))
+    {
+        /*layer_num =
+         *    getbits(
+         *        LEN_LAYER_NUM,
+         *        pInputStream);
+         */
+
+        status = 1; /* for this release only */
+    }
+
+    if (extFlag)
+    {
+        /*
+         * currently do not implement these functionalities
+         * defined in Amendment 1
+         * keep it here for future release
+         */
+        if (audioObjectType == MP4AUDIO_ER_BSAC)
+        {
+            status = 1;     /* NOT SUPPORTED */
+            /*
+            numOfSubFrame = getbits( LEN_SUB_FRAME, pInputStream);
+
+            layer_len = getbits( LEN_LAYER_LEN, pInputStream);
+            */
+        }
+
+        /*
+         * The following code is equivalent to
+         * if ((audioObjectType == 17) || (audioObjectType == 18) ||
+         *     (audioObjectType == 19) || (audioObjectType == 20) ||
+         *     (audioObjectType == 21) || (audioObjectType == 23))
+         */
+
+        if (((audioObjectType > 16) && (audioObjectType < 22)) ||
+                (audioObjectType == 23))
+        {
+            status = 1;     /* NOT SUPPORTED */
+            /*
+            aacSectionDataResilienceFlag = getbits( LEN_SECT_RES_FLAG,
+                                                    pInputStream);
+
+            aacScalefactorDataResilienceFlag = getbits( LEN_SCF_RES_FLAG,
+                                                        pInputStream);
+
+            aacSpectralDataResilienceFlag = getbits( LEN_SPEC_RES_FLAG,
+                                                     pInputStream);
+            */
+        }
+        /*
+         * this flag is tbd in version 3 of ISO/IEC spec
+         * if the encoder generates this bit, then it has to be read
+         * current adif2mp4ff does not write this bit. If this bit is to
+         * be read, it can be done by the following code:
+         */
+
+        extFlag3 = get1bits(pInputStream);       /*  LEN_EXT_FLAG3 */
+
+        if (extFlag3)
+        {
+            status = 1;     /* NOT SUPPORTED */
+        }
+
+    }
+
+    return status;
+}
diff --git a/media/libstagefright/codecs/aacdec/get_ga_specific_config.h b/media/libstagefright/codecs/aacdec/get_ga_specific_config.h
new file mode 100644
index 0000000..7c77da5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ga_specific_config.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_GA_specific_config.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) use enum type for audioObjectType
+              (2) update revision history
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes the function declaration for get_GA_specific_config.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_GA_SPECIFIC_CONFIG_H
+#define GET_GA_SPECIFIC_CONFIG_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_tdec_int_file.h"
+#include    "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_GA_specific_config(
+    tDec_Int_File * const pVars,
+    BITS    *pInputStream,
+    UInt     channel_config,
+    const tMP4AudioObjectType audioObjectType
+);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_ics_info.cpp b/media/libstagefright/codecs/aacdec/get_ics_info.cpp
new file mode 100644
index 0000000..17204cc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ics_info.cpp
@@ -0,0 +1,608 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/get_ics_info.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Clean up code.
+
+ Description:  Fix comments before review, remove lpflag[]
+
+ Description:  Update per review comments, and match ISO/IEC 14496-3
+
+ Description:  Update per peer review comments.
+
+ Description:  Remove "rollback" of used bits, since lt_decode is to change.
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    audioObjectType = MP4 Audio Object Type for the current song. Only if
+                    this is set to LTP (MP4AUDIO_LTP) will long term
+                    prediction bits be retrieved. Data type
+                    tMP4AudioObjectType, which is an enumeration, which in
+                    turn is an Int.
+
+    pInputStream  = pointer to a BITS structure, used by the function getbits
+                    to provide data. This is the second parameter to this
+                    function to match its position in getbits().
+                    Data type pointer to BITS structure
+
+    common_window = field read in huffdecode, which tells whether information
+                    is shared between the left and right channel. Long term
+                    prediction (LTP) data is NOT shared even if its a common
+                    window, so this flag is needed to see if another set of
+                    LTP possibly needs to be read. If this flag is false,
+                    pSecondLTPStatus is not touched, it could be NULL if
+                    need be. Data type Bool, which is Int.
+
+    pWindowSequence = pointer to where the the window type of the current
+                    frame and channel should be placed, of data type
+                    WINDOW_SEQUENCE, which is Int. It can take on one
+                    of four values: ONLY_LONG_SEQUENCE, LONG_START_SEQUENCE,
+                    EIGHT_SHORT_SEQUENCE, LONG_STOP_SEQUENCE,
+
+    pWindowShape =  pointer to where the window shape for the current frame
+                    and channel should be placed, of data type WINDOW_SHAPE,
+                    which is Int. It can take on the one of these two values:
+                    SINE_WINDOW, KAISER_BESSEL_WINDOW. It is used in the
+                    "filterbank" section of decoding.
+
+    group         = array that holds the index of the first window in each
+                    group. Data type array of Int, eight elements.
+
+    p_max_sfb     = pointer to where the maximum number of scale factor bands
+                    for the current frame and channel will be placed. Data
+                    type of pointer to Int.
+
+    p_winmap      = array of pointers to all of the possible four window
+                    configurations. This parameter did not need to be pointers,
+                    and could be changed in the future. Data type array of pointers
+                    to FrameInfo structures, length 4.
+
+    pFirstLTPStatus = pointer to a structure where the first LTP
+                    information will be stored. It would be confusing and wrong
+                    to call this left LTP status since if common_window = FALSE,
+                    this function will be called twice - once for the left, once
+                    for the right. It could be done, but extra conditional code
+                    would need to be done.
+                    Data type pointer to LT_PRED_STATUS structure.
+
+    pSecondLTPStatus = pointer to where the right channel of LTP
+                    information will be stored only if common_window is non-zero.
+                    Data type pointer to LT_PRED_STATUS structure.
+
+ Local Stores/Buffers/Pointers Needed: None.
+
+ Global Stores/Buffers/Pointers Needed: None.
+
+ Outputs:
+    status  = 0 implies no error occurred, non-zero otherwise.
+
+ Pointers and Buffers Modified:
+    pInputStream contents are modified in such a way that the number of bits
+        read increases.
+    pWindowSequence contents are updated with the current window for this
+        frame and channel
+    group[] contents will be modified to grouping information. See getgroup
+        source code for a better description of what this is.
+    p_max_sfb contents will be updated with the maximum scale factor bands
+        for this frame and channel.
+    pFirstLTPStatus contents may be updated if the stream has long term
+        prediction information.
+    pSecondLTPStatus contents may be updated if common_window != 0 and LTP data
+        is present.
+
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function retrieves the individual channel stream (ICS) information
+ from the bitstream. The information read for the current
+ frame and channel is:
+ - window sequence
+ - window shape for use in the filter bank
+ - number of scale factor bands
+ - long term predication (LTP) information
+ - grouping information
+
+ This function does NOT support MPEG2 style AAC Frequency Domain Predictor,
+ not to be confused with LTP (Long Term Prediction). If such data is found
+ to be on the file an error is generated.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function is not to use static or global data.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (1) ISO/IEC 14496-3:1999(E) Titled "Information technology - Coding
+      of audio-visual objects Part 3: Audio Subpart 4:"
+      Table 4.4.6 - Syntax of ics_info(), page 16.
+
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    status = 0;
+    first_ltp_data_present = FALSE;
+    second_ltp_data_present = FALSE;
+
+
+    CALL getbits(
+        neededBits = LEN_ICS_RESERV + LEN_WIN_SEQ + LEN_WIN_SH,
+        pInputStream = pInputStream)
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    windowSequence = (temp >> LEN_WIN_SH) & ((0x1<<LEN_WIN_SEQ)-1);
+
+    *pWindowShape = (temp) & ((0x1<<LEN_WIN_SH)-1);
+
+    IF (windowSequence == EIGHT_SHORT_SEQUENCE)
+    THEN
+        CALL getbits(
+            neededBits = LEN_MAX_SFBS,
+            pInputStream = pInputStream)
+        MODIFYING(pInputStream)
+        RETURNING(local_max_sfb = returnValue)
+
+        CALL getgroup(
+            group = group,
+            pInputStream = pInputStream)
+        MODIFYING(group)
+        MODIFYING(pInputStream)
+        RETURNING(nothing)
+
+
+    ELSE
+
+        group[0] = 1;
+
+        CALL getbits(
+            neededBits = LEN_MAX_SFBL + LEN_PREDICTOR_DATA_PRESENT,
+            pInputStream = pInputStream)
+        MODIFYING(pInputStream)
+        RETURNING(temp = returnValue)
+
+        predictor_data_present =
+            (Bool) getbits(
+                LEN_BOOLEAN,
+                pInputStream);
+
+        local_max_sfb = (Int)(temp >> LEN_PREDICTOR_DATA_PRESENT);
+
+        predictor_data_present =
+            (Bool) (temp & ((0x1 << LEN_PREDICTOR_DATA_PRESENT)-1));
+
+        IF (local_max_sfb > allowed_max_sfb)
+        THEN
+            status = 1
+        ELSEIF (audioObjectType == MP4AUDIO_LTP)
+        THEN
+            IF (predictor_data_present != FALSE)
+            THEN
+                CALL getbits(
+                    neededBits = LEN_LTP_DATA_PRESENT,
+                    pInputStream = pInputStream)
+                MODIFYING(pInputStream)
+                RETURNING(first_ltp_data_present = returnValue)
+
+                IF (ltp_data_present != FALSE)
+                THEN
+
+                    CALL lt_decode(
+                        win_type = windowSequence,
+                        pInputStream  = pInputStream,
+                        max_sfb = local_max_sfb,
+                        pLt_pred = pFirstLTPStatus)
+                    MODIFYING(pInputStream)
+                    MODIFYING(pFirstLTPStatus)
+                    RETURNING(nothing)
+
+                ENDIF
+
+                IF (common_window != FALSE)
+                THEN
+                    CALL getbits(
+                        neededBits = LEN_LTP_DATA_PRESENT,
+                        pInputStream = pInputStream)
+                    MODIFYING(pInputStream)
+                    RETURNING(second_ltp_data_present = returnValue)
+
+                    IF (second_ltp_data_present != FALSE)
+                    THEN
+
+                        CALL lt_decode(
+                            win_type = windowSequence,
+                            pInputStream  = pInputStream,
+                            max_sfb = local_max_sfb,
+                            pLt_pred = pSecondLTPStatus)
+                        MODIFYING(pInputStream)
+                        MODIFYING(pSecondLTPStatus)
+                        RETURNING(nothing)
+                    ENDIF
+                ENDIF
+            ENDIF
+        ELSE
+            IF  (predictor_data_present != FALSE)
+            THEN
+                status = 1
+            ENDIF
+        END IF
+    ENDIF
+
+    pFirstLTPStatus->ltp_data_present = first_ltp_data_present;
+
+    IF (common_window != FALSE)
+    THEN
+        pSecondLTPStatus->ltp_data_present = second_ltp_data_present;
+    ENDIF
+
+    pFrameInfo = p_winmap[*p_wnd];
+    IF (local_max_sfb > pFrameInfo->sfb_per_frame)
+    THEN
+        status = 1;
+    ENDIF
+
+    *(p_max_sfb) = local_max_sfb;
+
+    MODIFY(*(pWindowSequence))
+    MODIFY(*(pWinShape))
+    MODIFY(*(p_max_sfb))
+    MODIFY(group[])
+    MODIFY(*pInputStream)
+    MODIFY(*pFirstLTPStatus)
+    MODIFY(*pSecondLTPStatus)
+    RETURN (status);
+
+
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+
+#include "e_rawbitstreamconst.h"
+#include "e_tmp4audioobjecttype.h"
+
+#include "s_bits.h"
+#include "s_frameinfo.h"
+#include "s_lt_pred_status.h"
+
+#include "ibstream.h"
+#include "lt_decode.h"
+#include "ltp_common_internal.h" /* For LEN_LTP_DATA_PRESENT constant */
+
+#include "get_ics_info.h"
+#include "huffman.h"        /* For the declaration of getgroup */
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define LEN_PREDICTOR_DATA_PRESENT (1)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Int get_ics_info(
+    const tMP4AudioObjectType  audioObjectType,
+    BITS                      *pInputStream,
+    const Bool                 common_window,
+    WINDOW_SEQUENCE           *pWindowSequence,
+    WINDOW_SHAPE              *pWindowShape,
+    Int                        group[],
+    Int                       *p_max_sfb,
+    FrameInfo                 *p_winmap[],
+    LT_PRED_STATUS            *pFirstLTPStatus,
+    LT_PRED_STATUS            *pSecondLTPStatus)
+{
+    WINDOW_SEQUENCE       windowSequence;
+    UInt                  temp;
+    Bool                  predictor_data_present;
+    UInt                   local_max_sfb;
+    UInt                   allowed_max_sfb;
+    Int                   status = SUCCESS;
+    Bool                  first_ltp_data_present = FALSE;
+    Bool                  second_ltp_data_present = FALSE;
+
+    /*
+     * The following three calls to getbits have been replaced with one
+     * call for speed:
+     *
+     *                  getbits(LEN_ICS_RESERV, pInputStream);
+     * windowSequence = getbits(LEN_WIN_SEQ, pInputStream);
+     * *pWindowShape  = getbits(LEN_WIN_SH, pInputStream);
+     *
+     */
+
+    temp =
+        get9_n_lessbits(
+            LEN_ICS_RESERV + LEN_WIN_SEQ + LEN_WIN_SH,
+            pInputStream);
+
+
+    windowSequence = (WINDOW_SEQUENCE)((temp >> LEN_WIN_SH) & ((0x1 << LEN_WIN_SEQ) - 1));
+
+    *pWindowShape = (WINDOW_SHAPE)((temp) & ((0x1 << LEN_WIN_SH) - 1));
+
+    /*
+     * This pointer should not be NULL as long as the initialization code
+     * has been run, so the test for NULL has been removed.
+     */
+    allowed_max_sfb = p_winmap[windowSequence]->sfb_per_win[0];
+
+    if (windowSequence == EIGHT_SHORT_SEQUENCE)
+    {
+        local_max_sfb =  get9_n_lessbits(LEN_MAX_SFBS,
+                                         pInputStream);
+
+        getgroup(
+            group,
+            pInputStream);
+
+        if (local_max_sfb > allowed_max_sfb)
+        {
+            status = 1;  /* ERROR CODE - needs to be updated */
+        }
+
+    } /* end of TRUE of if (windowSequence == EIGHT_SHORT_SEQUENCE) */
+    else
+    {
+        /* There is only one group for long windows. */
+        group[0] = 1;
+
+        /*
+         * The window is long, get the maximum scale factor bands,
+         * and get long term prediction info.
+         *
+         * Reference [1] states that the audioObjectType is first tested,
+         * then the predictor_data_present is read on either branch of the
+         * if (audioObjectType == MP4AUDIO_LTP). Instead, this code combines
+         * the two calls on both branches into one before the
+         * if, and then in turn combines with another call to getbits, all
+         * in the name of speed.
+         *
+         * This would be the individual calls, without checking the number
+         * of scale factor bands:
+         *
+         *   local_max_sfb =
+         *      (Int) getbits(
+         *          LEN_MAX_SFBL,
+         *           pInputStream);
+         *
+         *  if (audioObjectType == MP4AUDIO_LTP)
+         *  {
+         *        predictor_data_present =
+         *           (Bool) getbits(
+         *              LEN_PREDICTOR_DATA_PRESENT,
+         *              pInputStream);
+         *
+         *     .....   (read LTP data)
+         *
+         *    }
+         *    else
+         *    {
+         *
+         *        predictor_data_present =
+         *           (Bool) getbits(
+         *              LEN_PREDICTOR_DATA_PRESENT,
+         *              pInputStream);
+         *
+         *     .....   (its an error for this library)
+         *     }
+         */
+        temp =
+            get9_n_lessbits(
+                LEN_MAX_SFBL + LEN_PREDICTOR_DATA_PRESENT,
+                pInputStream);
+
+        local_max_sfb = (Int)(temp >> LEN_PREDICTOR_DATA_PRESENT);
+
+        predictor_data_present =
+            (Bool)(temp & ((0x1 << LEN_PREDICTOR_DATA_PRESENT) - 1));
+
+        if (local_max_sfb > allowed_max_sfb)
+        {
+            status = 1;  /* ERROR CODE - needs to be updated */
+        }
+        else if (audioObjectType == MP4AUDIO_LTP)
+        {
+            /*
+             * Note that the predictor data bit has already been
+             * read.
+             */
+
+            /*
+             * If the object type is LTP, the predictor data is
+             * LTP. If the object type is not LTP, the predictor data
+             * is so called "frequency predictor data", which is not
+             * supported by this implementation. Refer to (1)
+             */
+            if (predictor_data_present != FALSE)
+            {
+                first_ltp_data_present =
+                    (Bool) get1bits(/*                        LEN_LTP_DATA_PRESENT,*/
+                        pInputStream);
+
+                if (first_ltp_data_present != FALSE)
+                {
+                    lt_decode(
+                        windowSequence,
+                        pInputStream,
+                        local_max_sfb,
+                        pFirstLTPStatus);
+                }
+                if (common_window != FALSE)
+                {
+                    second_ltp_data_present =
+                        (Bool) get1bits(/*                            LEN_LTP_DATA_PRESENT,*/
+                            pInputStream);
+
+                    if (second_ltp_data_present != FALSE)
+                    {
+                        lt_decode(
+                            windowSequence,
+                            pInputStream,
+                            local_max_sfb,
+                            pSecondLTPStatus);
+                    }
+                } /* if (common_window != FALSE) */
+
+            } /* if (predictor_data_present != FALSE) */
+
+        } /* else if (audioObjectType == MP4AUDIO_LTP) */
+        else
+        {
+            /*
+             * Note that the predictor data bit has already been
+             * read.
+             */
+
+            /*
+             * The object type is not LTP. If there is data, its
+             * frequency predictor data, not supported by this
+             * implementation.
+             */
+            if (predictor_data_present != FALSE)
+            {
+                status = 1; /* ERROR CODE UPDATE LATER */
+            } /* if (predictor_data_present != FALSE) */
+
+        } /* end of "else" clause of if (audioObjectType == MP4AUDIO_LTP) */
+
+    } /*  if (windowSequence == EIGHT_SHORT_SEQUENCE) [FALSE branch] */
+
+
+    /*
+     * Save all local copies.
+     */
+    pFirstLTPStatus->ltp_data_present = first_ltp_data_present;
+    if (common_window != FALSE)
+    {
+        pSecondLTPStatus->ltp_data_present = second_ltp_data_present;
+    }
+
+    *p_max_sfb = local_max_sfb;
+
+    *pWindowSequence = windowSequence;
+
+    return (status);
+
+}  /* get_ics_info */
+
diff --git a/media/libstagefright/codecs/aacdec/get_ics_info.h b/media/libstagefright/codecs/aacdec/get_ics_info.h
new file mode 100644
index 0000000..b94ef8e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_ics_info.h
@@ -0,0 +1,111 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/get_ics_info.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Contains the declaration for the function get_ics_info()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_ICS_INFO_H
+#define GET_ICS_INFO_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_tmp4audioobjecttype.h"
+#include "s_bits.h"
+#include "e_window_sequence.h"
+#include "e_window_shape.h"
+#include "s_frameinfo.h"
+#include "s_lt_pred_status.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    Int get_ics_info(
+        const tMP4AudioObjectType  audioObjectType,
+        BITS                      *pInputStream,
+        const Bool                 common_window,
+        WINDOW_SEQUENCE           *p_wnd,
+        WINDOW_SHAPE              *pWindowShape,
+        Int                        group[],
+        Int                       *p_max_sfb,
+        FrameInfo                 *p_winmap[],
+        LT_PRED_STATUS            *pFirstLTPStatus,
+        LT_PRED_STATUS            *pSecondLTPStatus);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif /* GET_ICS_INFO_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_prog_config.cpp b/media/libstagefright/codecs/aacdec/get_prog_config.cpp
new file mode 100644
index 0000000..6bddd57
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_prog_config.cpp
@@ -0,0 +1,739 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_prog_config.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Move functionality from get_adif_header for when to change
+               the current program configuration, add a temporary config
+               to read into, clean up code, change function prototype.
+
+ Description:  Clean up
+
+ Description:  Update per review comments
+
+ Description:  Fix double 'could'
+
+ Description:  change enter_mc_info to set_mc_info
+
+ Description:  update comments
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pVars      = pointer to the structure that holds all information for
+                 this instance of the library. pVars->prog_config is directly
+                 used, and pVars->mc_info, pVars->prog_config, pVars->winmap,
+                 pVars->SFBWidth128 are needed indirectly for calling
+                 set_mc_info. Data type  pointer to tDec_Int_File structure.
+
+    pScratchPCE = pointer to a temporary ProgConfig structure to be used
+                  to read in the program configuration element.
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+    status     = zero if no error was found, non-zero otherwise.
+
+ Pointers and Buffers Modified:
+    pVars->prog_config contents are updated with the PCE read in.
+    pVars->mc_info contents are updated with channel information.
+    pVars->winmap contents are updated with window information.
+    pVars->SFBWidth128 contents are updated with scale factor band width data.
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads from the input stream to memory for a temporary
+ program configuration element (PCE). If the PCE read is the first
+ encountered it is saved. Or, if the tag of the PCE read matches the tag of
+ the first PCE encounted, it is saved as well. This is a mechanism for
+ changing the sampling rate.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall not use static or global variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+   of moving pictures and associated audio information - Part 7: Advanced
+   Audio Coding (AAC)", Table 6.21 - Syntax of program_config_element(),
+   page 16, and section 8.5 "Program Config Element (PCE)", page 30.
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    status          = SUCCESS;
+    pInputStream   = &(pVars->inputStream);
+
+
+    CALL getbits(
+        neededBits = LEN_TAG,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( tag = returnValue )
+
+    CALL getbits(
+        neededBits = LEN_PROFILE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( pScratchPCE->profile = returnValue )
+
+    CALL getbits(
+        neededBits = LEN_PROFILE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( pScratchPCE->sampling_rate_idx = returnValue )
+
+    CALL getbits(
+        neededBits = LEN_NUM_ELE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->front.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_NUM_ELE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->side.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_NUM_ELE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->back.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_NUM_LFE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->lfe.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_NUM_DAT,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->data.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_NUM_CCE,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( temp = returnValue )
+
+    pScratchPCE->coupling.num_ele = temp;
+
+    CALL getbits(
+        neededBits = LEN_MIX_PRES,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( flag = returnValue )
+
+    pScratchPCE->mono_mix.present = flag;
+
+    IF (flag != FALSE)
+    THEN
+        CALL getbits(
+            neededBits = LEN_TAG,
+            pInputStream = pInputStream )
+        MODIFYING( pInputStream )
+        RETURNING( temp = returnValue )
+
+        pScratchPCE->mono_mix.ele_tag = temp;
+
+    ENDIF
+
+    CALL getbits(
+        neededBits = LEN_MIX_PRES,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( flag = returnValue )
+
+    pScratchPCE->stereo_mix.present = flag;
+
+    IF (flag != FALSE)
+    THEN
+
+        CALL getbits(
+            neededBits = LEN_TAG,
+            pInputStream = pInputStream )
+        MODIFYING( pInputStream )
+        RETURNING( temp = returnValue )
+
+        pScratchPCE->stereo_mix.ele_tag = temp;
+
+    ENDIF
+
+    CALL getbits(
+        neededBits = LEN_MIX_PRES,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( flag = returnValue )
+
+    flag =
+        getbits(
+            LEN_MIX_PRES,
+            pInputStream);
+
+    pScratchPCE->matrix_mix.present = flag;
+
+    IF (flag != FALSE)
+    THEN
+        CALL getbits(
+            neededBits = LEN_MMIX_IDX,
+            pInputStream = pInputStream )
+        MODIFYING( pInputStream )
+        RETURNING( temp = returnValue )
+
+        pScratchPCE->matrix_mix.ele_tag = temp;
+
+        CALL getbits(
+            neededBits = LEN_PSUR_ENAB,
+            pInputStream = pInputStream )
+        MODIFYING( pInputStream )
+        RETURNING( temp = returnValue )
+
+        pScratchPCE->matrix_mix.pseudo_enab = temp;
+
+    ENDIF
+
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->front,
+        pInputStream = pInputStream,
+        enableCPE    = TRUE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->front )
+    RETURNING( nothing )
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->side,
+        pInputStream = pInputStream,
+        enableCPE    = TRUE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->side )
+    RETURNING( nothing )
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->back,
+        pInputStream = pInputStream,
+        enableCPE    = TRUE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->back )
+    RETURNING( nothing )
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->lfe,
+        pInputStream = pInputStream,
+        enableCPE    = FALSE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->lfe )
+    RETURNING( nothing )
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->data,
+        pInputStream = pInputStream,
+        enableCPE    = FALSE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->data )
+    RETURNING( nothing )
+
+    CALL get_ele_list(
+        pElementList = &pScratchPCE->coupling,
+        pInputStream = pInputStream,
+        enableCPE    = TRUE )
+    MODIFYING( pInputStream )
+    MODIFYING( pScratchPCE->coupling )
+    RETURNING( nothing )
+
+
+    CALL byte_align(
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( nothing )
+
+    CALL getbits(
+        neededBits = LEN_COMMENT_BYTES,
+        pInputStream = pInputStream )
+    MODIFYING( pInputStream )
+    RETURNING( numChars = returnValue )
+
+    FOR (i = numChars; i > 0; i--)
+
+        CALL getbits(
+            neededBits = LEN_COMMENT_BYTES,
+            pInputStream = pInputStream )
+        MODIFYING( pInputStream )
+        RETURNING( nothing )
+
+    ENDFOR
+
+    IF (pVars->current_program < 0)
+    THEN
+        pVars->current_program = tag;
+    ENDIF
+
+
+    IF (tag == pVars->current_program)
+    THEN
+
+        CALL pv_memcpy(
+            to = &pVars->prog_config,
+            from = pScratchPCE,
+            n = sizeof(ProgConfig))
+        MODIFYING( pVars->prog_config )
+        RETURNING( nothing )
+
+        CALL set_mc_info(
+            pMC_Info = &pVars->mc_info,
+            objectType = pVars->prog_config.profile + 1,
+            samplin_rate_idx = pVars->prog_config.sampling_rate_idx,
+            tag = pVars->prog_config.front.ele_tag[0],
+            is_cpe = pVars->prog_config.front.ele_is_cpe[0],
+            pWinSeqInfo = pVars->winmap,
+            pSfbwidth128 = pVars->SFBWidth128)
+        MODIFYING( pVars->mc_info )
+        MODIFYING( pVars->winmap )
+        MODIFYING( pVars->SFBWidth128 )
+        RETURN( status = return_value )
+
+    ENDIF
+
+    MODIFY( pVars->mc_info )
+    MODIFY( pVars->winmap )
+    MODIFY( pVars->SFBWidth128 )
+    RETURN (status)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_bits.h"
+#include "s_elelist.h"
+#include "s_tdec_int_file.h"
+#include "s_tdec_int_chan.h"
+#include "e_progconfigconst.h"
+#include "ibstream.h"
+#include "get_ele_list.h"
+#include "aac_mem_funcs.h"
+#include "set_mc_info.h"
+#include "get_prog_config.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+Int get_prog_config(
+    tDec_Int_File *pVars,
+    ProgConfig    *pScratchPCE)
+{
+    Int    i;
+    UInt    tag;
+    Int    numChars;
+    UInt    temp;
+    Bool   flag;
+    Int    status          = SUCCESS;
+    BITS  *pInputStream   = &(pVars->inputStream);
+
+
+    /*
+     * The tag is used at the very end to see if this PCE is
+     * the one to be used. Otherwise it does not need to be saved for the
+     * the simple configurations to be used in this version of an AAC
+     * decoder.
+     *
+     * All of the bits of this PCE must be read even if this PCE will not
+     * be used. They are read into a temporary PCE, then later it is decided
+     * whether to keep this PCE.
+     *
+     * To allow quick removal of the fields from the ProgConfig structure
+     * that will probably not be used at a later date,
+     * while still advancing the bitstream pointer,the return value of
+     * getbits is saved into a temporary variable, then transfered to
+     * the structure item.
+     */
+    tag =
+        get9_n_lessbits(
+            LEN_TAG,
+            pInputStream);
+
+    pScratchPCE->profile =
+        get9_n_lessbits(
+            LEN_PROFILE,
+            pInputStream);
+
+    pScratchPCE->sampling_rate_idx =
+        get9_n_lessbits(
+            LEN_SAMP_IDX,
+            pInputStream);
+
+    if (!pVars->adif_test && pScratchPCE->sampling_rate_idx != pVars->prog_config.sampling_rate_idx)
+    {
+        /* rewind the pointer as implicit channel configuration maybe the case */
+        pInputStream->usedBits -= (LEN_TAG + LEN_PROFILE + LEN_SAMP_IDX);
+
+        return (1); /*  mismatch cannot happen */
+    }
+
+
+    /*
+     * Retrieve the number of element lists for each of
+     * front, side, back, lfe, data, and coupling.
+     *
+     * For two-channel stereo or mono, only the data in the front needs
+     * to be saved. However, ALL fields need to be skipped over in some
+     * fashion. Also, the number of elements needs to be temporarily saved
+     * to call get_ele_list(). If that function was changed to pass in
+     * the number of points to be read, the memory set aside inside the
+     * ProgConfig structure could be removed.
+     */
+
+    /*
+     * The next six function calls could be combined into one, then use
+     * shifts and masks to retrieve the individual fields.
+     */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_ELE,
+            pInputStream);
+
+    pScratchPCE->front.num_ele = temp;
+
+    /* Needed only to read in the element list. */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_ELE,
+            pInputStream);
+
+    pScratchPCE->side.num_ele = temp;
+
+    /* Needed only to read in the element list. */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_ELE,
+            pInputStream);
+
+    pScratchPCE->back.num_ele = temp;
+
+    /* Needed only to read in the element list. */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_LFE,
+            pInputStream);
+
+    pScratchPCE->lfe.num_ele = temp;
+
+    /* Needed only to read in the element list. */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_DAT,
+            pInputStream);
+    pScratchPCE->data.num_ele = temp;
+
+    /* Needed only to read in the element list. */
+    temp =
+        get9_n_lessbits(
+            LEN_NUM_CCE,
+            pInputStream);
+
+    pScratchPCE->coupling.num_ele = temp;
+
+    /*
+     * Read in mix down data.
+     *
+     * Whether these fields can be removed and have proper operation
+     * will be determined at a later date.
+     */
+
+    /* Read presence of mono_mix */
+    flag =
+        get1bits(/*            LEN_MIX_PRES,*/
+            pInputStream);
+
+    pScratchPCE->mono_mix.present = flag;
+
+    if (flag != FALSE)
+    {
+        temp =
+            get9_n_lessbits(
+                LEN_TAG,
+                pInputStream);
+
+        pScratchPCE->mono_mix.ele_tag = temp;
+
+    } /* end if (flag != FALSE) */
+
+    /* Read presence of stereo mix */
+    flag =
+        get1bits(/*            LEN_MIX_PRES,*/
+            pInputStream);
+
+    pScratchPCE->stereo_mix.present = flag;
+
+    if (flag != FALSE)
+    {
+        temp =
+            get9_n_lessbits(
+                LEN_TAG,
+                pInputStream);
+
+        pScratchPCE->stereo_mix.ele_tag = temp;
+
+    } /* end if (flag != FALSE) */
+
+    /* Read presence of matrix mix */
+    flag =
+        get1bits(/*            LEN_MIX_PRES,*/
+            pInputStream);
+
+    pScratchPCE->matrix_mix.present = flag;
+
+    if (flag != FALSE)
+    {
+        temp =
+            get9_n_lessbits(
+                LEN_MMIX_IDX,
+                pInputStream);
+
+        pScratchPCE->matrix_mix.ele_tag = temp;
+
+        temp =
+            get1bits(/*                LEN_PSUR_ENAB,*/
+                pInputStream);
+
+        pScratchPCE->matrix_mix.pseudo_enab = temp;
+
+    } /* end if (flag != FALSE) */
+
+    /*
+     * Get each of the element lists. Only the front information will be
+     * used for the PV decoder, but the usedBits field of pInputStream must
+     * be advanced appropriately.
+     *
+     * This could be optimized by advancing the bit stream for the
+     * elements that do not need to be read.
+     */
+    get_ele_list(
+        &pScratchPCE->front,
+        pInputStream,
+        TRUE);
+
+    get_ele_list(
+        &pScratchPCE->side,
+        pInputStream,
+        TRUE);
+
+    get_ele_list(
+        &pScratchPCE->back,
+        pInputStream,
+        TRUE);
+
+    get_ele_list(
+        &pScratchPCE->lfe,
+        pInputStream,
+        FALSE);
+
+    get_ele_list(
+        &pScratchPCE->data,
+        pInputStream,
+        FALSE);
+
+    get_ele_list(
+        &pScratchPCE->coupling,
+        pInputStream,
+        TRUE);
+
+    /*
+     * The standard requests a byte alignment before reading in the
+     * comment. This can be done because LEN_COMMENT_BYTES == 8.
+     */
+    byte_align(pInputStream);
+
+    numChars =
+        get9_n_lessbits(
+            LEN_COMMENT_BYTES, pInputStream);
+
+    /*
+     * Ignore the comment - it requires 65 bytes to store (or worse on DSP).
+     * If this field is restored, make sure to append a trailing '\0'
+     */
+    for (i = numChars; i > 0; i--)
+    {
+        pScratchPCE->comments[i] = (Char) get9_n_lessbits(LEN_BYTE,
+                                   pInputStream);
+
+    } /* end for */
+
+    if (pVars->current_program < 0)
+    {
+        /*
+         * If this is the first PCE, it becomes the current, regardless of
+         * its tag number.
+         */
+        pVars->current_program = tag;
+
+    } /* end if (pVars->current_program < 0) */
+
+
+    if (tag == (UInt)pVars->current_program)
+    {
+        /*
+         * This branch is reached under two conditions:
+         * 1) This is the first PCE found, it was selected in the above if
+         *    block. In all encoders found thus far, the tag value has been
+         *    zero.
+         * 2) A PCE has been sent by the encoder with a tag that matches the
+         *    the first one sent. It will then be re-read. No encoder found
+         *    thus far re-sends a PCE, when looking at ADIF files.
+         *
+         * Regardless, the temporary PCE will now be copied into the
+         * the one official program configuration.
+         */
+        pv_memcpy(
+            &pVars->prog_config,
+            pScratchPCE,
+            sizeof(ProgConfig));
+
+        /* enter configuration into MC_Info structure */
+        status =
+            set_mc_info(
+                &pVars->mc_info,
+                (tMP4AudioObjectType)(pVars->prog_config.profile + 1),
+                pVars->prog_config.sampling_rate_idx,
+                pVars->prog_config.front.ele_tag[0],
+                pVars->prog_config.front.ele_is_cpe[0],
+                pVars->winmap,
+                pVars->SFBWidth128);
+
+    } /* end if (tag == pVars->current_program) */
+
+    return (status);
+}
+
diff --git a/media/libstagefright/codecs/aacdec/get_prog_config.h b/media/libstagefright/codecs/aacdec/get_prog_config.h
new file mode 100644
index 0000000..646ba46
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_prog_config.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_prog_config.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                      Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for get_prog_config.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_PROG_CONFIG_H
+#define GET_PROG_CONFIG_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_progconfig.h"
+#include "s_tdec_int_file.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int get_prog_config(
+    tDec_Int_File *pVars,
+    ProgConfig    *pTempPCE);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_pulse_data.cpp b/media/libstagefright/codecs/aacdec/get_pulse_data.cpp
new file mode 100644
index 0000000..f9c24f4
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_pulse_data.cpp
@@ -0,0 +1,286 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_pulse_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description: Put into PV format
+
+ Description: 1) Change loop to use pointers.
+              2) Rename to from get_nec_nc to get_pulse_data
+
+ Description: Changes per code review
+              1) Fix pathname
+              2) Read in two fields to save call to getbits
+              3) Change how pPulseInfo->number_pulse is stored.
+
+ Description: Placed typecast to Int in places where UInt->Int
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9.
+
+ Who:                                  Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+     pInputStream = pointer to a BITS structure, used by the function getbits
+                   to provide data. Data type pointer to BITS structure
+
+     pPulseInfo   = pointer to pulse data structure to be filled with data
+                    concerning pulses in the frequency domain.
+                    Data type pointer to PulseInfo
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+     status       = return value, zero signifies success, non-zero otherwise.
+                    Presently this function only returns a success, error
+                    checking may be added later.
+                    Data type Int.
+
+ Pointers and Buffers Modified:
+
+    pPulseInfo contents are updated with pulse information. Specifically,
+    pPulseInfo->number_pulse with the number of pulses found, and
+    pPulseInfo->pulse_start_sfb is set to the first scale factor band.
+    Then pPulseInfo->pulse_offset and pPulseInfo->pulse_amp are filled
+    with data. For these array, only the number of pulses defined will be
+    set, those values beyond the number of pulses will retain their previous
+    value and should not be read from.
+    Note: The value in pPulseInfo->number_pulse is different by a value of
+          one from the original ISO code.
+
+    pInputBuffer contents are updated to the next location to be read from
+        the input stream.
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function fills in the pulse data structure with information to be used
+ later for restoring pulses in the spectrum.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall not use global or static variables.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+      of moving pictures and associated audio information - Part 7: Advanced
+      Audio Coding (AAC)", Table 6.17 - Syntax of pulse_data(),
+      page 15, and section 9.3 "Decoding process", starting on page 41.
+
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    status = SUCCESS;
+
+    CALL getbits(neededBits = LEN_PULSE_NPULSE + LEN_PULSE_ST_SFB,
+                 pInputStream = pInputStream)
+    MODIFYING(*pInputStream)
+    RETURNING(temp)
+
+    pPulseInfo->number_pulse = 1 + (temp >> LEN_PULSE_ST_SFB);
+    pPulseInfo->pulse_start_sfb = temp & ((1 << LEN_PULSE_ST_SFB) - 1);
+
+    pPulseOffset = &pPulseInfo->pulse_offset[0];
+    pPulseAmp    = &pPulseInfo->pulse_amp[0];
+
+    FOR (i = PulseInfo->number_pulse; i > 0; i--)
+        CALL getbits(neededBits = LEN_PULSE_POFF + LEN_PULSE_PAMP,
+                     pInputStream = pInputStream)
+        MODIFYING(*pInputStream)
+        RETURNING(temp)
+
+        *pPulseOffset++ = temp >> LEN_PULSE_PAMP;
+        *pPulseAmp++    = temp & ((1 << LEN_PULSE_PAMP) - 1);
+    END FOR
+
+    MODIFYING (*pInputStream)
+    MODIFYING (*pPulseInfo)
+
+    RETURN status
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "ibstream.h"
+#include "s_pulseinfo.h"
+#include "s_bits.h"
+#include "e_rawbitstreamconst.h"
+#include "get_pulse_data.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+Int get_pulse_data(
+    PulseInfo   *pPulseInfo,
+    BITS        *pInputStream)
+{
+    Int   i;
+    Int  *pPulseOffset;
+    Int  *pPulseAmp;
+    Int   status = SUCCESS;
+    UInt  temp;
+
+    /*
+     * Read in both field fields at once to save cycles. These are the
+     * original lines of code:
+     * pPulseInfo->number_pulse = getbits(LEN_PULSE_NPULSE, pInputStream);
+     * pPulseInfo->pulse_start_sfb = getbits(LEN_PULSE_ST_SFB, pInputStream);
+     */
+
+    temp =
+        get9_n_lessbits(
+            LEN_PULSE_NPULSE + LEN_PULSE_ST_SFB,
+            pInputStream);
+
+    pPulseInfo->number_pulse = (Int)(1 + (temp >> LEN_PULSE_ST_SFB));
+    pPulseInfo->pulse_start_sfb = (Int)(temp & ((1 << LEN_PULSE_ST_SFB) - 1));
+
+    pPulseOffset = &pPulseInfo->pulse_offset[0];
+    pPulseAmp    = &pPulseInfo->pulse_amp[0];
+
+    /*
+     * This loop needs to count one more than the number read in from
+     * the bitstream - look at reference [1].
+     */
+
+    for (i = pPulseInfo->number_pulse; i > 0; i--)
+    {
+        /*
+         * Read in both fields. Original lines:
+         *  *pPulseOffset++ = getbits(LEN_PULSE_POFF, pInputStream);
+         *  *pPulseAmp++    = getbits(LEN_PULSE_PAMP, pInputStream);
+         */
+
+        temp =
+            get9_n_lessbits(
+                LEN_PULSE_POFF + LEN_PULSE_PAMP,
+                pInputStream);
+
+        *pPulseOffset++ = (Int)(temp >> LEN_PULSE_PAMP);
+
+        *pPulseAmp++    = (Int)(temp & ((1 << LEN_PULSE_PAMP) - 1));
+    }
+
+    return (status);
+}
+
diff --git a/media/libstagefright/codecs/aacdec/get_pulse_data.h b/media/libstagefright/codecs/aacdec/get_pulse_data.h
new file mode 100644
index 0000000..267f534
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_pulse_data.h
@@ -0,0 +1,100 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_pulse_data.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change structure name.
+
+ Who:                                      Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for get_pulse_data.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_PULSE_DATA_H
+#define GET_PULSE_DATA_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_pulseinfo.h"
+#include "s_bits.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    Int get_pulse_data(
+        PulseInfo   *pPulseInfo,
+        BITS        *pInputStream);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /*  GET_PULSE_DATA_H  */
+
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_bitstream.cpp b/media/libstagefright/codecs/aacdec/get_sbr_bitstream.cpp
new file mode 100644
index 0000000..b6ec365
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_bitstream.cpp
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_bitstream.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    INPUT
+
+    SBRDECODER self,
+    SBRBITSTREAM * stream,
+    float *timeData,
+    int numChannels
+
+    OUTPUT
+
+    errorCode, noError if successful
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        sbr decoder processing, set up SBR decoder phase 2 in case of
+        different cotrol data
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+#include "get_sbr_bitstream.h"
+#include "pv_audio_type_defs.h"
+#include    "sbr_crc_check.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 get_sbr_bitstream(SBRBITSTREAM *sbrBitStream, BITS *pInputStream)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    Int32 count;
+    Int32 esc_count;
+    Int32 Extention_Type;
+    Int32 i;
+
+    count = get9_n_lessbits(LEN_F_CNT, pInputStream);
+    if (count == 15)
+    {
+        esc_count = get9_n_lessbits(LEN_F_ESC, pInputStream);
+        count = esc_count + 14;
+    }
+
+
+
+    Extention_Type = get9_n_lessbits(LEN_F_CNT, pInputStream);
+
+
+    if (((Extention_Type == SBR_EXTENSION) || (Extention_Type == SBR_EXTENSION_CRC))
+            && (count < MAXSBRBYTES) && (count) && (sbrBitStream->NrElements < MAXNRELEMENTS))
+    {
+
+        sbrBitStream->sbrElement[sbrBitStream->NrElements].ExtensionType = Extention_Type;
+        sbrBitStream->sbrElement[sbrBitStream->NrElements].Payload       = count;
+        sbrBitStream->sbrElement[sbrBitStream->NrElements].Data[0]       = (UChar) get9_n_lessbits(LEN_F_CNT, pInputStream);
+        for (i = 1 ; i < count ; i++)
+        {
+            sbrBitStream->sbrElement[sbrBitStream->NrElements].Data[i] = (UChar) get9_n_lessbits(8, pInputStream);
+        }
+
+        sbrBitStream->NrElements += 1;
+
+    }
+    else
+    {
+        pInputStream->usedBits += (count - 1) * LEN_BYTE;
+        pInputStream->usedBits += 4;        /* compenste for LEN_F_CNT (=4) bits read for Extention_Type */
+
+    }
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_bitstream.h b/media/libstagefright/codecs/aacdec/get_sbr_bitstream.h
new file mode 100644
index 0000000..8094b1a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_bitstream.h
@@ -0,0 +1,126 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_bitstream.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_SBR_BITSTREAM_H
+#define GET_SBR_BITSTREAM_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_bits.h"
+#include "ibstream.h"
+#include "e_rawbitstreamconst.h"
+#include "s_sbrbitstream.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void get_sbr_bitstream(SBRBITSTREAM *sbrBitStream,
+    BITS *pInputStream);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_startfreq.cpp b/media/libstagefright/codecs/aacdec/get_sbr_startfreq.cpp
new file mode 100644
index 0000000..38ddc0b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_startfreq.cpp
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_startfreq.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "get_sbr_startfreq.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
+----------------------------------------------------------------------------*/
+const Int v_offset[7][16] =
+{
+    { -8, -7, -6, -5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7},
+    { -5, -4, -3, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13},
+    { -5, -3, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13, 16},
+    { -6, -4, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13, 16},
+    { -4, -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13, 16, 20},
+    { -2, -1,  0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13, 16, 20, 24},
+    { 0,  1,  2,  3,  4,  5,  6,  7,  9, 11, 13, 16, 20, 24, 28, 33}
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int get_sbr_startfreq(const Int32 fs,
+                      const Int32 start_freq)
+{
+    Int k0_min = 0;
+    Int32 index;
+
+
+    switch (fs)
+    {
+        case 16000:
+            index = 0;
+            k0_min = 24;
+            break;
+        case 22050:
+            index = 1;
+            k0_min = 17;
+            break;
+        case 24000:
+            index = 2;
+            k0_min = 16;
+            break;
+        case 32000:
+            index = 3;
+            k0_min = 16;
+            break;
+        case 44100:
+            index = 4;
+            k0_min = 12;
+            break;
+        case 48000:
+            index = 4;
+            k0_min = 11;
+            break;
+        case 64000:
+            index = 4;
+            k0_min = 10;
+            break;
+        case 88200:
+        case 96000:
+            index = 5;
+            k0_min = 7;
+            break;
+
+        default:
+            index = 6;
+    }
+    return (k0_min + v_offset[index][start_freq]);
+
+}
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_startfreq.h b/media/libstagefright/codecs/aacdec/get_sbr_startfreq.h
new file mode 100644
index 0000000..10fa160
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_startfreq.h
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_startfreq.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_SBR_STARTFREQ_H
+#define GET_SBR_STARTFREQ_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int get_sbr_startfreq(const Int32 fs,
+                      const Int32 start_freq);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.cpp b/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.cpp
new file mode 100644
index 0000000..e32c61d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.cpp
@@ -0,0 +1,190 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_stopfreq.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+     if(fs < 32000)
+     {
+         k1_min = (Int) ( ( (float) (6000 * 2 * 64) / fs ) + 0.5 );
+     }
+     else
+     {
+         if (fs < 64000)
+         {
+             k1_min = (Int) ( ( (float) (8000 * 2 * 64) / fs ) + 0.5 );
+         }
+         else
+         {
+             k1_min = (Int) ( ((float) (10000 * 2 * 64) / fs ) + 0.5);
+         }
+     }
+
+     return((Int)( k1_min * pow( 64.0 / k1_min,(stop_freq)/13.0) + 0.5));
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include    "get_sbr_stopfreq.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
+----------------------------------------------------------------------------*/
+
+const UChar sbr_stopfreq_tbl[6][13] =
+{
+
+    { 21, 23, 25, 27, 29, 32, 35, 38, 41, 45, 49, 54, 59},  /* 48000  */
+    { 23, 25, 27, 29, 31, 34, 37, 40, 43, 47, 51, 55, 59},  /* 44100  */
+    { 32, 34, 36, 38, 40, 42, 44, 46, 49, 52, 55, 58, 61},  /* 32000  and 24000 */
+    { 35, 36, 38, 40, 42, 44, 46, 48, 50, 52, 55, 58, 61},  /* 22050  */
+    { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 62}   /* 16000  */
+
+};
+
+Int get_sbr_stopfreq(const Int32 fs,
+                     const Int32 stop_freq)
+{
+
+    Int i;
+
+    switch (fs)
+    {
+        case 48000:
+            i = 0;
+            break;
+
+        case 32000:
+        case 24000:
+            i = 2;
+            break;
+
+        case 22050:
+            i = 3;
+            break;
+
+        case 16000:
+            i = 4;
+            break;
+
+        case 44100:
+        default:
+            i = 1;
+            break;
+    }
+
+    return((Int)sbr_stopfreq_tbl[i][stop_freq]);
+
+}
+
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.h b/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.h
new file mode 100644
index 0000000..341a3d4
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sbr_stopfreq.h
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: get_sbr_stopfreq.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_SBR_STOPFREQ_H
+#define GET_SBR_STOPFREQ_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int get_sbr_stopfreq(const Int32 fs,
+                     const Int32 stop_freq);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_sign_bits.h b/media/libstagefright/codecs/aacdec/get_sign_bits.h
new file mode 100644
index 0000000..445d2f2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_sign_bits.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_sign_bits.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Update comments for the structure
+
+ Description: Change include file. Above description probably from another
+              header file.
+
+ Description: Fix pathname above
+
+ Who:                                               Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for the function get_sign_bits()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_SIGN_BITS_H
+#define GET_SIGN_BITS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "ibstream.h"
+
+/*----------------------------------------------------------------------------
+; 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 get_sign_bits(
+    Int          q[],
+    BITS        *pInputStream,
+    const Int    q_len
+);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif /* GET_SIGN_BITS_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/get_tns.cpp b/media/libstagefright/codecs/aacdec/get_tns.cpp
new file mode 100644
index 0000000..e0b021b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_tns.cpp
@@ -0,0 +1,573 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_tns.c
+
+     Date: 10/25/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Brought code in-line with PV standards.  Some minor
+               optimizations (count-down for loops, etc.) were made.
+
+ Description:  Made cosmetic changes as suggested during review.  Also,
+ changed calculation of s_mask and n_mask from table-based to being
+ calculated based on res_index.  Also, the flag coef_res was changed
+ from having a range of [3,4] to having a range of [0,1], which corresponds
+ exactly with the true value that is passed via the bitstream.
+
+ Description:  Modified to use more efficient TNS memory structure.
+
+ Description: Updated to reflect more efficient usage of memory by the TNS
+ filters.
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Description: Moved pInputStream to be the 2nd parameter, for a slight
+ optimization on some platforms.
+
+ Description: Moved pSfbTop outside of the loops, since its value does
+ not change.
+
+ Description: Replace some instances of getbits to get1bits
+              when only 1 bit is read.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    FrameInfo *pFrameInfo
+        Pointer to structure that holds information about each block.
+        (long block flag,
+         number of subblocks,
+         scalefactor bands per subblock, etc.)
+
+    BITS *pInputStream
+        Pointer to a BITS structure that is
+        passed on to function getbits to pull information from the bitstream.
+
+    TNS_Frame_info *pTnsFrameInfo
+        Pointer to filter data structure - to be populated by this function.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    TNS_frame_info *pTnsFrameInfo
+
+    pTnsFrameInfo->n_filt = Number of tns filters to be applied to the data.
+
+    pTnsFrameInfo->filt[]->order = The order of each individual TNS filter.
+
+    pTnsFrameInfo->filt[]->coef_res = The resolution of the filter coefficients
+
+    pTnsFrameInfo->filt[]->start_band = start of spectral band
+
+    pTnsFrameInfo->filt[]->stop_band = end of spectral band
+
+    pTnsFrameInfo->filt[]->coef[] = Each filter's coefficients are filled with
+    data read from the input bitstream.
+
+    pTnsFrameInfo->filt[]->direction = A flag is set for each TNS filter.
+
+    If the direction flag (on the bitstream) = 0, then the filter
+    is applied to the block of spectral data in normal (upward) fashion.
+
+    If the direction flag (on the bitstream) = 1, then the filter
+    is applied in a reverse (downward) fashion.
+    (Starting with the last element in the block of data.)
+
+    The value stored in filt[]->direction maps the values [0,1] to [1,-1] for
+    a more intuitive storage of this flag's meaning.
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads the TNS filter information from the bitstream, and stores
+ the filter order, LPC coefficients, and the number of TNS filters to
+ be applied in the structure TNS_frame_info.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This code should match the ISO code in functionality, with the exception
+ that coef_res has range of [0,1] (PV code) instead of [3,4] (ISO code)
+
+ coef_res is only used by tns_decode_coef.
+
+------------------------------------------------------------------------------
+ REFERENCES
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.8 (Temporal Noise Shaping)
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor
+     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 "pv_audio_type_defs.h"
+#include "get_tns.h"
+#include "s_mc_info.h"
+#include "s_frameinfo.h"
+#include "s_tnsfilt.h"
+#include "s_tns_frame_info.h"
+#include "s_bits.h"
+#include "ibstream.h"
+#include "e_window_sequence.h"
+#include "e_progconfigconst.h"
+
+#include "tns_decode_coef.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#define SCALE_FACTOR_BAND_OFFSET(x) ( ((x) > 0) ? pSFB_top[(x)-1] : 0 )
+#define MINIMUM(x,y) ( ((x) < (y)) ? (x) : (y) )
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+/*
+ * The entries in the ensuing tables provide the maximum permissable
+ * number of scalefactor bands for each TNS filter.  This value is effected
+ * by the sampling rate, and window type.
+ */
+
+const Int tns_max_bands_tbl_long_wndw[(1<<LEN_SAMP_IDX)] =
+    {31,       /* 96000 Hz */
+     31,       /* 88200 Hz */
+     34,       /* 64000 Hz */
+     40,       /* 48000 Hz */
+     42,       /* 44100 Hz */
+     51,       /* 32000 Hz */
+     46,       /* 24000 Hz */
+     46,       /* 22050 Hz */
+     42,       /* 16000 Hz */
+     42,       /* 12000 Hz */
+     42,       /* 11025 Hz */
+     39,       /* 8000  Hz */
+     0,
+     0,
+     0,
+     0
+    };
+
+const Int tns_max_bands_tbl_short_wndw[(1<<LEN_SAMP_IDX)] =
+    {9,       /* 96000 Hz */
+     9,       /* 88200 Hz */
+     10,       /* 64000 Hz */
+     14,       /* 48000 Hz */
+     14,       /* 44100 Hz */
+     14,       /* 32000 Hz */
+     14,       /* 24000 Hz */
+     14,       /* 22050 Hz */
+     14,       /* 16000 Hz */
+     14,       /* 12000 Hz */
+     14,       /* 11025 Hz */
+     14,       /* 8000  Hz */
+     0,
+     0,
+     0,
+     0
+    };
+
+/*
+ * For completeness, here are the table entries for object types that make
+ * use of PQF filter bank.  We do not currently support this; these are
+ * given here only to ease future implementation.
+ *
+ *  const Int tns_max_bands_tbl_long_wndw_PQF[(1<<LEN_SAMP_IDX)] =
+ *         {28,       ; 96000
+ *          28,       ; 88200
+ *          27,       ; 64000
+ *          26,       ; 48000
+ *          26,       ; 44100
+ *          26,       ; 32000
+ *          29,       ; 24000
+ *          29,       ; 22050
+ *          23,       ; 16000
+ *          23,       ; 12000
+ *          23,       ; 11025
+ *          19,       ; 8000
+ *           0,
+ *           0,
+ *           0,
+ *           0};
+ *
+ *  const Int tns_max_bands_tbl_short_wndw_PQF[(1<<LEN_SAMP_IDX)] =
+ *         {7,       ; 96000
+ *          7,       ; 88200
+ *          7,       ; 64000
+ *          6,       ; 48000
+ *          6,       ; 44100
+ *          6,       ; 32000
+ *          7,       ; 24000
+ *          7,       ; 22050
+ *          8,       ; 16000
+ *          8,       ; 12000
+ *          8,       ; 11025
+ *          7,       ; 8000
+ *          0,
+ *          0,
+ *          0,
+ *          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
+----------------------------------------------------------------------------*/
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void get_tns(
+    const Int               max_bands,
+    BITS            * const pInputStream,
+    const WINDOW_SEQUENCE   wnd_seq,
+    const FrameInfo * const pFrameInfo,
+    const MC_Info   * const pMC_Info,
+    TNS_frame_info  * const pTnsFrameInfo,
+    Int32                   scratchTnsDecCoefMem[])
+{
+
+    const Int16 * const pSFB_top = pFrameInfo->win_sfb_top[0];
+
+    Int f;
+    Int t;
+    Int win;
+    UInt tempInt;
+
+    Int num_filt_bits;
+    Int num_order_bits;
+    Int num_start_band_bits;
+
+    Int top;
+    Int res;
+    Int res_index;
+    Int compress;
+
+    Int sfb_per_win;
+
+    Int32 *pLpcCoef;
+    Int32 *pStartLpcCoef;
+    Int s_mask;
+    Int n_mask;
+
+    Int tns_bands;
+    UInt max_order;
+    Int coef_res;
+
+
+    TNSfilt *pFilt;
+
+    if (wnd_seq != EIGHT_SHORT_SEQUENCE)
+    {
+        num_filt_bits  = 2;
+        num_order_bits = 5;
+        num_start_band_bits = 6;
+
+        tns_bands = tns_max_bands_tbl_long_wndw[pMC_Info->sampling_rate_idx];
+
+        /*
+         *  Definition from 14496-3:1999 doc. Our first encoder follows this rule,
+         *  later encoders don't
+         */
+
+        if (pMC_Info->sampling_rate_idx > 4)  /* if (sampling_rate <= 32000 */
+        {
+            max_order = 20;
+        }
+        else
+        {
+            max_order = 12;
+        }
+    }
+    else
+    {
+        num_filt_bits  = 1;
+        num_order_bits = 3;
+        num_start_band_bits = 4;
+
+        tns_bands = tns_max_bands_tbl_short_wndw[pMC_Info->sampling_rate_idx];
+
+        max_order = 7;
+    }
+
+    /*
+     * After this branch, tns_bands will be equal to the minimum of
+     * the passed in variable, nbands, and the result from the
+     * tns_max_bands_tbl
+     */
+
+    if (max_bands < tns_bands)
+    {
+        tns_bands = max_bands;
+    }
+
+    sfb_per_win = pFrameInfo->sfb_per_win[0];
+
+    win = 0;
+
+    pLpcCoef = pTnsFrameInfo->lpc_coef;
+
+    pFilt = pTnsFrameInfo->filt;
+
+    do
+    {
+        tempInt = get9_n_lessbits(num_filt_bits,
+                                  pInputStream);
+
+        pTnsFrameInfo->n_filt[win] = tempInt;
+
+        if (tempInt != 0)
+        {
+            /*
+             * coef_res = [0, 1]
+             * Switch between a resolution of 3 and 4 bits respectively
+             *
+             * if coef_res = 0, the coefficients have a range of
+             *
+             *                 -4  -3  -2  -1  0   1   2   3
+             *
+             * if coef_res = 1, the coefficients have a range of
+             *
+             * -8  -7  -6  -5  -4  -3  -2  -1  0   1   2   3   4   5   6   7
+             *
+             * The arrays in ./src/tns_tab.c are completely based on
+             * the value of coef_res.
+             */
+            res = get1bits(
+                      pInputStream);
+
+            /* res is post-incremented for correct calculation of res_index */
+            coef_res = res++;
+
+            top = sfb_per_win;
+
+            for (f = pTnsFrameInfo->n_filt[win]; f > 0; f--)
+            {
+                tempInt = MINIMUM(top, tns_bands);
+
+                pFilt->stop_coef = SCALE_FACTOR_BAND_OFFSET(tempInt);
+
+                pFilt->stop_band = tempInt;
+
+                top -= get9_n_lessbits(num_start_band_bits,
+                                       pInputStream);
+
+                tempInt = MINIMUM(top, tns_bands);
+
+                pFilt->start_coef = SCALE_FACTOR_BAND_OFFSET(tempInt);
+
+                pFilt->start_band = tempInt;
+
+                tempInt = get9_n_lessbits(num_order_bits,
+                                          pInputStream);
+
+                pFilt->order = tempInt;
+
+                if (tempInt != 0)
+                {
+                    if (tempInt > max_order)
+                    {
+                        pFilt->order = max_order;
+                    }
+
+                    /*
+                     * This maps the bitstream's [0,1] to
+                     * pFilt->direction = [1,-1]
+                     */
+
+                    tempInt = get1bits(pInputStream);
+
+                    pFilt->direction = (-(Int)tempInt) | 0x1;
+
+                    /*
+                     * compress = [0,1]
+                     * If compress is true, the MSB has
+                     * been omitted from transmission (Ref. 1)
+                     *
+                     * For coef_res = 0, this limits the range of
+                     * transmitted coefficients to...
+                     *
+                     *         -2  -1  0   1
+                     *
+                     * For coef_res = 1, the coefficients have
+                     * a range of...
+                     *
+                     * -4  -3  -2  -1  0   1   2   3
+                     */
+                    compress = get1bits(pInputStream);
+
+                    /*
+                     * res has a range of [1,2]
+                     * compress has a range of [0,1]
+                     * So (res - compress) has range [0,2];
+                     */
+                    res_index = res - compress;
+
+                    s_mask =  2 << res_index;
+
+                    /*
+                     * If res_index = 0, grab 2 bits of data
+                     * If res_index = 1, grab 3 bits of data
+                     * If res_index = 2, grab 4 bits of data
+                     */
+                    res_index += 2;
+
+                    pStartLpcCoef = pLpcCoef;
+
+                    for (t = pFilt->order; t > 0; t--)
+                    {
+                        /*
+                         * These are the encoded coefficients, which will
+                         * later be decoded into LPC coefficients by
+                         * the function tns_decode_coef()
+                         */
+                        tempInt = get9_n_lessbits(res_index,
+                                                  pInputStream);
+
+                        n_mask  = -((Int)tempInt & s_mask);
+
+                        /*
+                         * n_mask is used to sign_extend the
+                         * value, if it is negative.
+                         *
+                         */
+                        *(pLpcCoef++) = tempInt | n_mask;
+                    }
+
+                    /* Decode the TNS coefficients */
+
+                    tempInt = pFilt->stop_coef - pFilt->start_coef;
+
+                    if (tempInt > 0)
+                    {
+                        pFilt->q_lpc =
+                            tns_decode_coef(
+                                pFilt->order,
+                                coef_res,
+                                pStartLpcCoef,
+                                scratchTnsDecCoefMem);
+                    }
+
+                } /* if (pTnsFilt->order != 0) */
+
+                pFilt++;
+
+            } /* END for (f=pTnsInfo->n_filt; f>0; f--, pTnsFilt++) */
+
+        } /* if (pTnsInfo->n_filt != 0) */
+
+        win++;
+
+    }
+    while (win < pFrameInfo->num_win);
+
+    return;
+
+} /* get_tns */
diff --git a/media/libstagefright/codecs/aacdec/get_tns.h b/media/libstagefright/codecs/aacdec/get_tns.h
new file mode 100644
index 0000000..731484f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/get_tns.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: get_tns.h
+
+   Author:
+     Date: 03/08/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description: Modified to include updated function declaration, which reflects
+ the combination of the get_tns and tns_setup_filter routines.  Also, moved
+ pInputStream to be the 2nd parameter, for a slight optimization.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+  This file includes the function definition for get_tns.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GET_TNS_H
+#define GET_TNS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+#include "s_mc_info.h"
+#include "s_tns_frame_info.h"
+#include "s_bits.h"
+#include "e_window_sequence.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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 get_tns(
+        const Int               max_bands,
+        BITS            * const pInputStream,
+        const WINDOW_SEQUENCE   wnd_seq,
+        const FrameInfo * const pFrameInfo,
+        const MC_Info   * const pMC_Info,
+        TNS_frame_info  * const pTnsFrameInfo,
+        Int32                   scratchTnsDecCoefMem[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GET_TNS_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/getbits.h b/media/libstagefright/codecs/aacdec/getbits.h
new file mode 100644
index 0000000..e854be5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getbits.h
@@ -0,0 +1,346 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getbits.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Update comments for the structure
+
+ Description: Move structur to another file
+
+ Who:                                            Date: MM/DD/YYYY
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for the function getbits().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GETBITS_H
+#define GETBITS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "ibstream.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+#define INBUF_ARRAY_INDEX_SHIFT  (3)
+#define INBUF_BIT_WIDTH         (1<<(INBUF_ARRAY_INDEX_SHIFT))
+#define INBUF_BIT_MODULO_MASK   ((INBUF_BIT_WIDTH)-1)
+
+#define MAX_GETBITS             (25)
+
+#define  CHECK_INPUT_BUFFER_LIMITS  1
+
+    __inline UInt32 getbits(
+        const UInt  neededBits,
+        BITS       *pInputStream)
+    {
+        UInt32   returnValue = 0;
+        UInt     offset;
+        UInt     bitIndex;
+        UChar    *pElem;        /* Needs to be same type as pInput->pBuffer */
+
+        offset = (pInputStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+        pElem = pInputStream->pBuffer + offset;
+
+#if CHECK_INPUT_BUFFER_LIMITS
+
+        offset =  pInputStream->inputBufferCurrentLength - offset;
+        /*  check if access to input buffer does not go beyond boundaries */
+        if (offset > 3)
+        {
+            returnValue = (((UInt32) * (pElem)) << 24) |
+                          (((UInt32) * (pElem + 1)) << 16) |
+                          (((UInt32) * (pElem + 2)) << 8) |
+                          ((UInt32) * (pElem + 3));
+        }
+        else  /*  then access only available bytes  */
+        {
+            /*  Access to the bitstream beyond frame boundaries are not allowed,
+             *  Here, only what was available before the end of the frame will
+             *  be processed. Non-accessible bytes will be filled in with zeros.
+             *  Zero values guarantees that the data structures are filled in with values
+             *  that eventually will signal an error (like invalid parameters) or that allow
+             *  completion of the parsing routine.
+             *  Overrun is detected on file pvmp4audiodecodeframe.cpp.
+             */
+            switch (offset)
+            {
+                case 3:
+                    returnValue  = (((UInt32) * (pElem + 2)) << 8);
+                case 2:
+                    returnValue |= (((UInt32) * (pElem + 1)) << 16);
+                case 1:
+                    returnValue |= (((UInt32) * (pElem)) << 24);
+                default:
+                    break;
+            }
+        }
+
+
+#else
+
+        returnValue = (((UInt32) * (pElem)) << 24) |
+                      (((UInt32) * (pElem + 1)) << 16) |
+                      (((UInt32) * (pElem + 2)) << 8) |
+                      ((UInt32) * (pElem + 3));
+#endif
+
+        /* Remove extra high bits by shifting up */
+        bitIndex = (UInt)((pInputStream->usedBits) & INBUF_BIT_MODULO_MASK);
+
+        /* This line is faster way to mask off the high bits. */
+        returnValue = returnValue << (bitIndex);
+
+        /* Move the field down. */
+        returnValue = returnValue >> (32 - neededBits);
+
+        pInputStream->usedBits += neededBits;
+
+        return (returnValue);
+
+    }
+
+
+
+    __inline UInt get1bits(
+        BITS       *pInputStream)
+    {
+        UInt     returnValue;
+        UInt     offset;
+        UInt     bitIndex;
+        UChar    *pElem;        /* Needs to be same type as pInput->pBuffer */
+
+        offset = (pInputStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+        pElem = pInputStream->pBuffer + offset;
+
+#if CHECK_INPUT_BUFFER_LIMITS
+        returnValue = (offset < pInputStream->inputBufferCurrentLength) ? ((UInt) * (pElem)) : 0;
+#else
+        returnValue = ((UInt32) * (pElem));
+#endif
+
+
+        /* Remove extra high bits by shifting up */
+        bitIndex = (UInt)((pInputStream->usedBits++) & INBUF_BIT_MODULO_MASK);
+
+        /* This line is faster way to mask off the high bits. */
+        returnValue = 0xFF & (returnValue << (bitIndex));
+
+        /* Move the field down. */
+
+        return ((UInt)(returnValue >> 7));
+
+    }
+
+
+
+    __inline UInt get9_n_lessbits(
+        const UInt  neededBits,
+        BITS       *pInputStream)
+
+    {
+        UInt     returnValue;
+        UInt     offset;
+        UInt     bitIndex;
+        UChar    *pElem;        /* Needs to be same type as pInput->pBuffer */
+
+        offset = (pInputStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+        pElem = pInputStream->pBuffer + offset;
+
+#if CHECK_INPUT_BUFFER_LIMITS
+
+
+        offset =  pInputStream->inputBufferCurrentLength - offset;
+        /*  check if access to input buffer does not go beyond boundaries */
+        if (offset > 1)
+        {
+            returnValue = (((UInt32) * (pElem)) << 8) |
+                          ((UInt32) * (pElem + 1));
+        }
+        else  /*  then access only available bytes  */
+        {
+            /*  Access to the bitstream beyond frame boundaries are not allowed,
+             *  Here, only what was available before the end of the frame will
+             *  be processed. Non-accessible bytes will be filled in with zeros.
+             *  Zero values guarantees that the data structures are filled in with values
+             *  that eventually will signal an error (like invalid parameters) or that allow
+             *  completion of the parsing routine.
+             *  Overrun is detected on file pvmp4audiodecodeframe.cpp
+             */
+            switch (offset)
+            {
+                case 1:
+                    returnValue  = (((UInt32) * (pElem)) << 8);
+                    break;
+                default:
+                    returnValue = 0;
+                    break;
+            }
+        }
+
+
+#else
+        returnValue = (((UInt32) * (pElem)) << 8) |
+                      ((UInt32) * (pElem + 1)) ;
+#endif
+
+        /* Remove extra high bits by shifting up */
+        bitIndex = (UInt)((pInputStream->usedBits) & INBUF_BIT_MODULO_MASK);
+
+        pInputStream->usedBits += neededBits;
+
+        /* This line is faster way to mask off the high bits. */
+        returnValue = 0xFFFF & (returnValue << (bitIndex));
+
+        /* Move the field down. */
+
+        return (UInt)(returnValue >> (16 - neededBits));
+
+    }
+
+    __inline UInt32 get17_n_lessbits(
+        const UInt  neededBits,
+        BITS       *pInputStream)
+    {
+        UInt32   returnValue;
+        UInt     offset;
+        UInt     bitIndex;
+        UChar    *pElem;        /* Needs to be same type as pInput->pBuffer */
+
+        offset = (pInputStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+        pElem = pInputStream->pBuffer + offset;
+
+#if CHECK_INPUT_BUFFER_LIMITS
+
+        offset =  pInputStream->inputBufferCurrentLength - offset;
+        /*  check if access to input buffer does not go beyond boundaries */
+
+        if (offset > 2)
+        {
+            returnValue = (((UInt32) * (pElem)) << 16) |
+                          (((UInt32) * (pElem + 1)) << 8) |
+                          ((UInt32)  * (pElem + 2));
+        }
+        else   /*  then access only available bytes  */
+        {
+            /*  Access to the bitstream beyond frame boundaries are not allowed,
+             *  Here, only what was available before the end of the frame will
+             *  be processed. Non-accessible bytes will be filled in with zeros.
+             *  Zero values guarantees that the data structures are filled in with values
+             *  that eventually will signal an error (like invalid parameters) or that allow
+             *  completion of the parsing routine.
+             *  Overrun is detected on file pvmp4audiodecodeframe.cpp
+             */
+            returnValue = 0;
+            switch (offset)
+            {
+                case 2:
+                    returnValue  = (((UInt32) * (pElem + 1)) << 8);
+                case 1:
+                    returnValue |= (((UInt32) * (pElem)) << 16);
+                default:
+                    break;
+            }
+        }
+
+#else
+
+        returnValue = (((UInt32) * (pElem)) << 16) |
+                      (((UInt32) * (pElem + 1)) << 8) |
+                      ((UInt32)  * (pElem + 2));
+#endif
+
+        /* Remove extra high bits by shifting up */
+        bitIndex = (UInt)((pInputStream->usedBits) & INBUF_BIT_MODULO_MASK);
+
+        /* This line is faster way to mask off the high bits. */
+        returnValue = 0xFFFFFF & (returnValue << (bitIndex));
+
+        /* Move the field down. */
+        returnValue = returnValue >> (24 - neededBits);
+
+        pInputStream->usedBits += neededBits;
+
+        return (returnValue);
+
+    }
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif /* GETBITS_H*/
+
+
diff --git a/media/libstagefright/codecs/aacdec/getfill.cpp b/media/libstagefright/codecs/aacdec/getfill.cpp
new file mode 100644
index 0000000..3c4fc4c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getfill.cpp
@@ -0,0 +1,247 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getfill.c
+ Funtions: getfill
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  1. Used template to re-organize function and filled out
+                  Input/Output and Function definition section.
+               2. Optimized code.
+
+ Description:  Made the following changes based on review comments.
+               1. Exchanging MODIFYING and RETURNING on line 87, 88.
+               2. Added MPEG reference.
+               3. Changed "fill" to "pass over", "bitstreams are" to
+                  "bitstream is" in FUNCTION DESCRIPTION section.
+               4. Fixed tabs.
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pInputStream = pointer to structure BITS containing input stream
+                   information.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pInputStream->usedBits is updated to the newly calculated value.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function passes over fill bits in the raw data block to adjust the
+ instantaneous bit rate when the bitstream is to be transmitted over a
+ constant rate channel.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+     Subpart 4      p15     (Table 4.4.11)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    CALL getbits(
+            LEN_F_CNT,
+            pInputStream);
+    MODIFYING (pInputStream)
+    RETURNING (cnt)
+
+    IF ( cnt == (1<<LEN_F_CNT)-1 )
+
+        CALL getbits(
+                LEN_F_ESC,
+                pInputStream);
+        MODIFYING (pInputStream)
+        RETURNING (esc_cnt)
+
+        cnt +=  esc_cnt - 1;
+
+    ENDIF
+
+    pInputStream->usedBits += cnt * LEN_BYTE;
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_bits.h"
+#include "ibstream.h"
+#include "e_rawbitstreamconst.h"
+#include "getfill.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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 getfill(BITS *pInputStream)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Int cnt;
+    Int esc_cnt;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    cnt = get9_n_lessbits(
+              LEN_F_CNT,
+              pInputStream);
+
+    if (cnt == (1 << LEN_F_CNT) - 1)  /* if (cnt == 15) */
+    {
+        esc_cnt = get9_n_lessbits(
+                      LEN_F_ESC,
+                      pInputStream);
+
+        cnt +=  esc_cnt - 1;
+    }
+
+    /*
+     * The following codes are replaced by directly updating usedBits
+     * in BITS structure. This will save one call for getbits().
+     *
+     * for (i=0; i<cnt; i++)
+     * { getbits(LEN_BYTE, pInputStream); }
+     */
+
+    pInputStream->usedBits += cnt * LEN_BYTE;
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+
+} /* getfill */
+
diff --git a/media/libstagefright/codecs/aacdec/getfill.h b/media/libstagefright/codecs/aacdec/getfill.h
new file mode 100644
index 0000000..3ba976a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getfill.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getfill.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed "definition" to "declaration" on line 28 per
+              review comments.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains prototype declaration for getfill function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef GETFILL_H
+#define GETFILL_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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 getfill(BITS    *pInputStream);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/getgroup.cpp b/media/libstagefright/codecs/aacdec/getgroup.cpp
new file mode 100644
index 0000000..0f909cd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getgroup.cpp
@@ -0,0 +1,255 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getgroup.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description: (1) Modified to bring code in-line with PV standards
+              (2) Eliminated if(first_short) statement, move for-loop
+                  inside if statement
+              (3) Modified UChar -> Int on data types of group
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less.
+
+ Who:                       Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pInputStream = pointer to structure that holds input bitstream
+                   information. Type BITS
+
+    group[]     = array that holds the index of the first window in each
+                  group. Type Int
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    group   contains the index of first windows in each group
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads the window grouping information associated with an
+ Individual Channel Stream (ICS). If the window sequence is
+ EIGHT_SHORT_SEQUENCE, scalefactor grouping information is transmitted. If a
+ set of short windows form a group then they share scalefactors, intensity
+ positions and PNS information. The first short window is always a new group
+ so no grouping bit is transmitted. Subsequent short windows are in the same
+ group if the associated grouping bit is 1. A new group is started if the
+ associated grouping bit is 0.
+ The pointer pGroup points to an array that stores the first window index
+ of next group. For example, if the window grouping is:
+
+ window index:    |  0  |  1  |  2  |  3  |  4  |  5  |  6  |  7  |
+ grouping    :    |<-   0   ->|  1  |<-    2        ->|<-   3   ->|
+
+ Then:
+
+    group[]  :    |     2     |  3  |        6        |     8     |
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should replace the contents of the array pointed to by pGroup
+ with the first window indexes of groups starting from the second group.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4
+                    p16 (Table 4.4.6)
+                    p55 (Recovering ics_info)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF (pFrameInfo->coef_per_win[0] > SN2)
+
+        *pGroup++ = 1;
+        *pGroup   = 1;
+
+    ELSE
+
+        FOR (win = 1; win < pFrameInfo->num_win; win++)
+
+            IF (getbits(1,pInputStream) == 0)
+
+                *pGroup++ = win;
+
+            ENDIF
+
+        ENDFOR (win)
+
+        *pGroup = win;
+
+    ENDIF(pFrameInfo)
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "huffman.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define     SEVEN   7
+
+/*----------------------------------------------------------------------------
+; 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 getgroup(
+    Int         group[],
+    BITS        *pInputStream)
+{
+    Int      win;
+    Int     *pGroup;
+    UInt     mask;
+    UInt     groupBits;
+
+    pGroup      = group;
+
+    mask        = 0x40;
+
+    /* only short-window sequences are grouped!
+     * first short window is always a new group,
+     * start reading bitstream from the second
+     * window, a new group is indicated by an
+     * "0" bit in the input stream
+     */
+    groupBits =
+        get9_n_lessbits(
+            SEVEN,
+            pInputStream);
+
+    for (win = 1; win < NUM_SHORT_WINDOWS; win++)
+    {
+        if ((groupBits & mask) == 0)
+        {
+            *pGroup++ = win;
+
+        } /* if (groupBits) */
+
+        mask >>= 1;
+
+    } /* for (win) */
+
+    *pGroup = win;
+
+} /* getgroup */
diff --git a/media/libstagefright/codecs/aacdec/getics.cpp b/media/libstagefright/codecs/aacdec/getics.cpp
new file mode 100644
index 0000000..8d76744
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getics.cpp
@@ -0,0 +1,674 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getics.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables
+
+ Description: Remove pass-in parameter global_gain, define it on stack.
+
+ Description: (1) Modified to bring in-line with PV standards
+              (2) Modified pass in parameters
+              (3) Removed multiple returns, removed some if branch
+              (4) Replace for loop with pv_memset
+
+ Description: Remove prstflag, fix copyright.
+
+ Description: Fix pseudo-code
+
+ Description: Remove lpflag from get_ics_info
+
+ Description: (1) Removed widx, therefore, pChVarsWin is eliminated from
+                  pass in parameter
+
+ Description: merged the above changes from Michael and Wen
+
+ Description: Removed initialization of "pTnsFrameInfo->num_subblocks" since
+ this element was removed from that structure, as a part of
+ rearchitecting the TNS routines to use memory more efficiently.
+
+ Description:
+ (1) Added #include of "e_HuffmanConst.h"
+     Previously, this function was relying on another include file
+     to include "e_HuffmanConst.h"
+
+ (2) Updated the copyright header.
+
+ (3) Added #include of <stdlib.h> for NULL macro definition.
+
+ Description:
+ (1) Removed the first parameter to getics.c  This extra
+     FrameInfo was not needed, the contents of winmap can be used.
+ (2) Removed the memcpy of the data from winmap to the temporary
+     FrameInfo.
+
+ Description: Replace some instances of getbits to get1bits
+              when only 1 bit is read.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pInputStream    =   pointer to structure that holds input stream,
+                        Type BITS
+
+    common_window   =   flag that indicates whether left and right channel
+                        share the same window sequence & shape, Type Int
+
+    pVars           =   pointer to structure that holds decoder information
+                        Type tDec_Int_File
+
+    pChVarsCh       =   pointer to structure that holds channel related
+                        decoding information, Type tDec_Int_Chan
+
+    group[]         =   pointer to array that contains window grouping
+                        information of current frame, Type UChar
+
+    pMax_sfb        =   pointer to variable that stores maximum active
+                        scalefactor bands of current frame, Type UChar
+
+    pCodebookMap    =   pointer to array that holds the indexes of all
+                        Huffman codebooks used for current frame, ordered
+                        from section 0 to last section. Type UChar
+
+    pTnsFrameInfo   =   pointer to structure that holds TNS information.
+                        Type TNS_frame_info
+
+    pWinMap         =   array of pointers which points to structures that
+                        hold information of long and short window sequences
+                        Type FrameInfo
+
+    pPulseInfo       =   pointer to structure that holds pulse data decoding
+                        information, Type Nec_info
+
+    sect[]          =   array of structures that hold section codebook and
+                        section length in current frame, Type SectInfo
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    status = 0  if success
+             1  otherwise
+
+ Pointers and Buffers Modified:
+    pCodebookMap    contents are replaced by the indexes of all the huffman
+                    codebooks used for current frame
+
+    pWinMap         For short windows, the contents of frame_sfb_top are
+                    modified by calc_gsfb_table, with the top coefficient
+                    index of each scalefactor band.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function decodes individual channel stream by calling other Huffman
+ decoding functions.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function replaces the contents of pCodebookMap with the decoded
+ codebook indexes. By calling hufffac, it decodes scale factor data. Call
+ huffspec_fxp to decode spectral coefficients of current frame.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4           p24 (Table 4.4.24)
+                        p54 (4.5.2.3.2)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pGroup = group;
+
+    global_gain = CALL getbits(
+                            neededBits   = LEN_SCL_PCM,
+                            pInputStream = pInputStream)
+                        MODIFYING(pInputStream)
+                        ReTURNING(global_gain)
+
+    IF (common_window == FALSE)
+    THEN
+        status = CALL get_ics_info(
+                        pVars->mc_info.audioObjectType,
+                        pInputStream,
+                        common_window,
+                       &pChVars->wnd,
+                       &pChVars->wnd_shape_this_bk,
+                        group,
+                        pMax_sfb,
+                        pWinMap,
+                        &pChVars->lt_status,
+                        NULL)
+                    MODIFYING(pInputStream,pChVars,group,max_sfb,lt_status)
+                    RETURNING(status)
+    ENDIF
+
+    memcpy(pFrameInfo, pWinMap[pChVars->wnd], sizeof(FrameInfo))
+
+    IF (*pMax_sfb > 0)
+    THEN
+
+        i      = 0;
+        totSfb = 0;
+
+        DO
+
+            totSfb++;
+
+        WHILE( *pGroup++ < pFrameInfo->num_win);
+
+        totSfb  *=  pFrameInfo->sfb_per_win[0];
+
+        nsect = CALL huffcb(
+                        sect,
+                        pInputStream,
+                        pFrameInfo->sectbits,
+                        totSfb,
+                        pFrameInfo->sfb_per_win[0],
+                       *pMax_sfb)
+                    MODIFYING(sect,pInputStream,sectbits)
+                    RETURNING(nsect)
+
+        IF (nsect == 0)
+        THEN
+            status = 1
+
+        ENDIF
+
+        sectStart = 0;
+        FOR (i = 0; i < nsect; i++)
+
+            cb  = sect[i].sect_cb;
+            sectWidth =  sect[i].sect_end - sectStart;
+            sectStart += sectWidth;
+
+            WHILE (sectWidth > 0)
+
+                *pCodebookMap++ = cb
+                 sectWidth--
+            ENDWHILE
+
+        ENDFOR (i)
+
+    ELSE
+
+        memset(pCodebookMap,ZERO_HCB,MAXBANDS*sizeof(*pCodebookMap));
+
+    ENDIF (*pMax_sfb)
+
+    IF (pFrameInfo->islong == FALSE)
+    THEN
+        CALL calc_gsfb_table(
+                pFramInfo = pFrameInfo,
+                group[]   = group)
+              MODIFYING(pFrameInfo->frame_sfb_top)
+              RETURNING(void)
+    ENDIF
+
+    IF (status == SUCCESS)
+    THEN
+        status = CALL hufffac(
+                        pFrameInfo,
+                        pInputStream,
+                        group,
+                        nsect,
+                        sect,
+                        global_gain,
+                        pChVars->factors,
+                        pVars->huffBookUsed)
+                    MODIFYING(pInputStream,factors)
+                    RETURNING(status)
+
+    ENDIF (status)
+
+    IF (status == SUCCESS)
+    THEN
+        present = CALL getbits(
+                        neededBits   = LEN_PULSE_PRES,
+                        pInputStream = pInputStream)
+                    MODIFYING(pInputStream)
+                    RETURNING(present)
+
+        pPulseInfo->pulse_data_present = present;
+
+        IF (present != FALSE)
+        THEN
+            IF (pFrameInfo->islong == 1)
+            THEN
+                CALL get_pulse_data(
+                          pPulseInfo = pPulseInfo,
+                          pInputStream = pInputStream)
+                    MODIFYING(pInputStream,pPulseInfo)
+                    RETURNING(void)
+
+            ELSE
+
+                status = 1;
+
+            ENDIF (pFrameInfo)
+        ENDIF (present)
+
+    ENDIF (status)
+
+    IF (status == SUCCESS)
+    THEN
+        present = CALL getbits(
+                        neededBits = LEN_TNS_PRES,
+                        pInputStream = pInputStream)
+                    MODIFYING(pInputStream)
+                    RETURNING(present)
+
+        pTnsFrameInfo->tns_data_present = present;
+
+        IF (present != FALSE)
+        THEN
+            CALL get_tns(
+                    pFrameInfo = pFrameInfo,
+                    pTnsFrameInfo = pTnsFrameInfo,
+                    pInputStream = pInputStream)
+                MODIFYING(pInputStream, pTnsFrameInfo)
+                RETURNING(void)
+        ELSE
+
+            FOR (i = pTnsFrameInfo->n_subblocks - 1; i >= 0 ; i--)
+
+                pTnsFrameInfo->info[i].n_filt = 0;
+            ENDFOR
+
+        ENDIF(present)
+
+    ENDIF (status)
+
+    IF (status == SUCCESS)
+    THEN
+        present = CALL getbits(
+                        neededBits = LEN_GAIN_PRES,
+                        pInputStream = pInputStream)
+                MODIFYING(pInputStream)
+                RETURNING(present)
+
+        IF (present != FALSE)
+        THEN
+            status = 1;
+        ENDIF
+    ENDIF (status)
+
+    IF (status == SUCCESS)
+    THEN
+        status = CALL huffspec_fxp(
+                        pFrameInfo,
+                        pInputStream,
+                        nsect,
+                        sect,
+                        pChVars->factors,
+                        pChVars->fxpCoef,
+                        pVars->quantSpec,
+                        pVars->tmp_spec,
+                        pWinMap[ONLY_LONG_WINDOW],
+                        pPulseInfo,
+                        pChVars->qFormat)
+                MODIFYING(pInputStream,fxpCoef,quantSpec,tmp_spec,qFormat)
+                RETURNING(status)
+    ENDIF
+
+    RETURN status
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "e_huffmanconst.h"
+#include    "huffman.h"
+#include    "aac_mem_funcs.h"
+#include    "get_tns.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
+----------------------------------------------------------------------------*/
+Int getics(
+    BITS            *pInputStream,
+    Int             common_window,
+    tDec_Int_File   *pVars,
+    tDec_Int_Chan   *pChVars,
+    Int             group[],
+    Int             *pMax_sfb,
+    Int             *pCodebookMap,
+    TNS_frame_info  *pTnsFrameInfo,
+    FrameInfo       **pWinMap,
+    PulseInfo       *pPulseInfo,
+    SectInfo        sect[])
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Int     status = SUCCESS;
+
+    Int     nsect = 0;
+    Int     i;
+    Int     cb;
+    Int     sectWidth;
+    Int     sectStart;
+    Int     totSfb;
+    Int     *pGroup;
+
+    FrameInfo *pFrameInfo;
+
+    Int     global_gain; /* originally passed in from huffdecode */
+    Bool    present;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    pGroup = group;
+
+    /* read global gain from Input bitstream */
+    global_gain =
+        get9_n_lessbits(
+            LEN_SCL_PCM,
+            pInputStream);
+
+    if (common_window == FALSE)
+    {
+        status = get_ics_info(
+                     pVars->mc_info.audioObjectType,
+                     pInputStream,
+                     common_window,
+                     &pChVars->wnd,
+                     &pChVars->wnd_shape_this_bk,
+                     group,
+                     pMax_sfb,
+                     pWinMap,
+                     &pChVars->pShareWfxpCoef->lt_status,
+                     NULL);
+    }
+
+    pFrameInfo = pWinMap[pChVars->wnd];
+
+    /* First, calculate total number of scalefactor bands
+     * for this grouping. Then, decode section data
+     */
+    if (*pMax_sfb > 0)
+    {
+
+        /* calculate total number of sfb */
+        i      = 0;
+        totSfb = 0;
+
+        do
+        {
+            totSfb++;
+
+        }
+        while (*pGroup++ < pFrameInfo->num_win);
+
+        totSfb  *=  pFrameInfo->sfb_per_win[0];
+
+        /* decode section data */
+        nsect =
+            huffcb(
+                sect,
+                pInputStream,
+                pFrameInfo->sectbits,
+                totSfb,
+                pFrameInfo->sfb_per_win[0],
+                *pMax_sfb);
+
+        if (nsect == 0)
+        {
+            status = 1;     /* decode section data error */
+
+        }/* if (nsect) */
+
+        /* generate "linear" description from section info
+         * stored as codebook for each scalefactor band and group
+         * when nsect == 0, for-loop does not execute
+         */
+        sectStart = 0;
+        for (i = 0; i < nsect; i++)
+        {
+            cb  = sect[i].sect_cb;
+            sectWidth =  sect[i].sect_end - sectStart;
+            sectStart += sectWidth;
+
+            while (sectWidth > 0)
+            {
+                *pCodebookMap++ = cb;   /* cannot use memset for Int */
+                sectWidth--;
+            }
+
+        } /* for (i) */
+
+    }
+    else
+    {
+        /* set all sections with ZERO_HCB */
+        pv_memset(
+            pCodebookMap,
+            ZERO_HCB,
+            MAXBANDS*sizeof(*pCodebookMap));
+        /*
+                for (i=MAXBANDS; i>0; i--)
+                {
+                    *(pCodebookMap++) = ZERO_HCB;
+                }
+        */
+
+    } /* if (*pMax_sfb) */
+
+    /* calculate band offsets
+     * (because of grouping and interleaving this cannot be
+     * a constant: store it in pFrameInfo->frame_sfb_top)
+     */
+    if (pFrameInfo->islong == FALSE)
+    {
+        calc_gsfb_table(
+            pFrameInfo,
+            group);
+    }
+
+    /* decode scale factor data */
+    if (status == SUCCESS)
+    {
+        status =
+            hufffac(
+                pFrameInfo,
+                pInputStream,
+                group,
+                nsect,
+                sect,
+                global_gain,
+                pChVars->pShareWfxpCoef->factors,
+                pVars->scratch.huffbook_used);
+
+    } /* if (status) */
+
+    /* noiseless coding */
+    if (status == SUCCESS)
+    {
+        present =
+            get1bits(pInputStream);
+
+        pPulseInfo->pulse_data_present = present;
+
+        if (present != FALSE)
+        {
+            if (pFrameInfo->islong == 1)
+            {
+                status = get_pulse_data(
+                             pPulseInfo,
+                             pInputStream);
+            }
+            else
+            {
+                /* CommonExit(1,"Pulse data not allowed for short blocks"); */
+                status = 1;
+
+            } /* if (pFrameInfo) */
+        } /* if (present) */
+
+    } /* if (status) */
+
+
+    /* decode tns data */
+    if (status == SUCCESS)
+    {
+        present =
+            get1bits(pInputStream);
+
+        pTnsFrameInfo->tns_data_present = present;
+
+        if (present != FALSE)
+        {
+            get_tns(
+                pChVars->pShareWfxpCoef->max_sfb,
+                pInputStream,
+                pChVars->wnd,
+                pFrameInfo,
+                &pVars->mc_info,
+                pTnsFrameInfo,
+                pVars->scratch.tns_decode_coef);
+        }
+        else
+        {
+            for (i = pFrameInfo->num_win - 1; i >= 0 ; i--)
+            {
+                pTnsFrameInfo->n_filt[i] = 0;
+            }
+
+        } /* if(present) */
+
+    } /* if (status) */
+
+    /* gain control */
+    if (status == SUCCESS)
+    {
+        present =
+            get1bits(pInputStream);
+
+        if (present != FALSE)
+        {
+            /* CommonExit(1, "Gain control not implemented"); */
+            status = 1;
+        }
+    } /* if (status) */
+
+    if (status == SUCCESS)
+    {
+        status =
+            huffspec_fxp(
+                pFrameInfo,
+                pInputStream,
+                nsect,
+                sect,
+                pChVars->pShareWfxpCoef->factors,
+                pChVars->fxpCoef,
+                pVars->share.a.quantSpec,
+                pVars->scratch.tmp_spec,
+                pWinMap[ONLY_LONG_WINDOW],
+                pPulseInfo,
+                pChVars->pShareWfxpCoef->qFormat);
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return status
+    ----------------------------------------------------------------------------*/
+
+    return status;
+
+} /* getics */
diff --git a/media/libstagefright/codecs/aacdec/getmask.cpp b/media/libstagefright/codecs/aacdec/getmask.cpp
new file mode 100644
index 0000000..2fd34f1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/getmask.cpp
@@ -0,0 +1,384 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: getmask.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+               Replaced for-loop style memory initialization with memset()
+
+ Description: (1) Modified to bring code in-line with PV standard
+              (2) Removed multiple returns, Replaced multiple 'if's with
+                  switch
+
+ Description: (1) Modified per review comments
+              (2) increment pointer pMask after memset
+
+ Description: Make the maximum number of bits requested from getbits
+              become a constant.
+
+ Description: Typecast 1 to UInt32 for bitmask to avoid masking on a 16-bit
+              platform
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less.
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+        pFrameInfo  = pointer to structure that holds information for current
+                      frame, Type FrameInfo
+
+        pInputStream= pointer to structure that holds input stream information
+                      Type BITS
+
+        pGroup      = pointer to array that holds the stop window index for
+                      each group in current frame, Type Int
+
+        max_sfb     = number of active sfbs for each window, Type Int
+
+        mask[]      = array that holds the MS_mask information
+                      Type Int
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    mask_present = 0    (no Mid/Side mixed)
+                   2    (Mid/Side mixed present for entire frame)
+                   1    (Mid/Side mixed information read from bitstream)
+                   -1   (invalid mask_present read from bitstream)
+
+ Pointers and Buffers Modified:
+    pMask   contents replaced by MS information of each scalefactor band
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function reads the Mid/Side(MS) mask information from the input
+ bitstream. If the mask_present field is equal to 2, the mask bits is set to
+ 1 for the entire frame. If mask_present has a value of 0, the function
+ returns 0, If mask_present is set to 1, the Mid/Side(MS) information is
+ read from the input stream. When mask_present is 3, an error code (-1) is
+ generated.
+ The Mid/Side(MS) information is later used for mixing the left and right
+ channel sounds. Each scalefactor band has its own MS information.
+
+ (ISO comments: read a synthesis mask,  read a synthesis mask uses
+                EXTENDED_MS_MASK and grouped mask )
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall replace the contents of pMask with the MS information
+ of each scalefactor band
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4
+                    p15     (Table 4.4.5    getmask)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    CALL getbits(LEN_MASK_PRES, pInputStream)
+    MODIFYING (pInputStream)
+    RETURNING (mask present information)
+    mask_present = mask present information
+
+    SWITCH (mask_present)
+
+        CASE (0):
+            BREAK;
+
+        CASE (2):
+            nwin = pFrameInfo->num_win;
+            FOR(win = 0; win < nwin; win = *(pGroup++))
+
+                FOR(sfb = pFrameInfo->sfb_per_win[win]; sfb > 0; sfb--)
+                    *(pMask++) = 1;
+                ENDFOR
+
+            ENDFOR
+
+            BREAK;
+
+        CASE(1):
+
+            nwin = pFrameInfo->num_win;
+
+                nToDo = max_sfb;
+
+                WHILE (nToDo > 0)
+                    nCall = nToDo;
+
+                    IF (nCall > MAX_GETBITS)
+                    THEN
+                        nCall = MAX_GETBITS;
+                    ENDIF
+
+                    tempMask =
+                        getbits(
+                            nCall,
+                            pInputStream);
+
+                    bitmask = 1 << (nCall - 1);
+                    FOR (sfb = nCall; sfb > 0; sfb--)
+                       *(pMask++) = (tempMask & bitmask) >> (sfb - 1);
+                        bitmask >>= 1;
+                    ENDFOR
+
+                    nToDo -= nCall;
+                END WHILE
+
+                pv_memset(
+                    pMask,
+                    0,
+                    (pFrameInfo->sfb_per_win[win]-max_sfb)*sizeof(*pMask));
+
+            ENDFOR (win)
+
+            BREAK
+
+        DEFAULT:
+            mask_present = -1
+
+    ENDSWITCH
+
+    RETURN  mask_present
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "huffman.h"
+#include    "aac_mem_funcs.h"
+#include    "e_maskstatus.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
+----------------------------------------------------------------------------*/
+Int getmask(
+    FrameInfo   *pFrameInfo,
+    BITS        *pInputStream,
+    Int         group[],
+    Int         max_sfb,
+    Int         mask[])
+{
+
+    Int     win; /* window index */
+    Int     sfb;
+    Int     mask_present;
+    Int    *pMask;
+    Int    *pGroup;
+    Int     nwin;
+    Int     nCall;
+    Int     nToDo;
+    UInt32  tempMask;
+    UInt32  bitmask;
+
+    pMask  = mask;
+    pGroup = group;
+
+    mask_present =
+        get9_n_lessbits(
+            LEN_MASK_PRES,
+            pInputStream);
+
+    switch (mask_present)
+    {
+        case(MASK_NOT_PRESENT):
+            /* special EXTENDED_MS_MASK cases */
+            /* no ms at all */
+            break;
+
+        case(MASK_ALL_FRAME):
+            /* MS for whole spectrum on, mask bits set to 1 */
+            nwin = pFrameInfo->num_win;
+            for (win = 0; win < nwin; win = *(pGroup++))
+            {
+                for (sfb = pFrameInfo->sfb_per_win[win]; sfb > 0; sfb--)
+                {
+                    *(pMask++) = 1; /* cannot use memset for Int type */
+                }
+
+            }
+
+            break;
+
+        case(MASK_FROM_BITSTREAM):
+            /* MS_mask_present==1, get mask information*/
+            nwin = pFrameInfo->num_win;
+            for (win = 0; win < nwin; win = *(pGroup++))
+            {
+                /*
+                 * the following code is equivalent to
+                 *
+                 * for(sfb = max_sfb; sfb > 0; sfb--)
+                 * {
+                 *   *(pMask++) =
+                 *       getbits(
+                 *           LEN_MASK,
+                 *           pInputStream);
+                 * }
+                 *
+                 * in order to save the calls to getbits, the above
+                 * for-loop is broken into two parts
+                 */
+
+                nToDo = max_sfb;
+
+                while (nToDo > 0)
+                {
+                    nCall = nToDo;
+
+                    if (nCall > MAX_GETBITS)
+                    {
+                        nCall = MAX_GETBITS;
+                    }
+
+                    tempMask =
+                        getbits(
+                            nCall,
+                            pInputStream);
+
+                    bitmask = (UInt32) 1 << (nCall - 1);
+                    for (sfb = nCall; sfb > 0; sfb--)
+                    {
+                        *(pMask++) = (Int)((tempMask & bitmask) >> (sfb - 1));
+                        bitmask >>= 1;
+                    }
+
+                    nToDo -= nCall;
+                }
+
+                /*
+                 * set remaining sfbs to zero
+                 * re-use nCall to save one variable on stack
+                 */
+
+                nCall = pFrameInfo->sfb_per_win[win] - max_sfb;
+
+
+                if (nCall >= 0)
+                {
+                    pv_memset(pMask,
+                              0,
+                              nCall*sizeof(*pMask));
+
+                    pMask += nCall;
+                }
+                else
+                {
+                    mask_present = MASK_ERROR;
+                    break;
+                }
+
+
+            } /* for (win) */
+
+            break;
+
+        default:
+            /* error */
+            break;
+
+    } /* switch (mask_present) */
+
+    return mask_present;
+
+} /* getmask */
diff --git a/media/libstagefright/codecs/aacdec/hcbtables.h b/media/libstagefright/codecs/aacdec/hcbtables.h
new file mode 100644
index 0000000..a35fed0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/hcbtables.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: hcbtables.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) Add declaration of binary tree tables
+              (2) #if optimized Linear Search Huffman decoding
+
+ Description: Modified per review comments
+              (1) delete #if optimized Linear Search Huffman decoding
+              (2) modified copyright header
+
+ Description: (1) Add declaration different huffman tables
+
+ Who:                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Declare the structure array for Huffman Codebooks information.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef _HCBTABLES_H
+#define _HCBTABLES_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include    "s_hcb.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+    /* ISO: Hcb book[NSPECBOOKS + 2]; */
+
+    extern const Hcb hcbbook_binary[13];
+    extern const Int32 huff_tab1[88];
+    extern const Int32 huff_tab2[90];
+    extern const Int32 huff_tab3[151];
+    extern const Int32 huff_tab4[119];
+    extern const Int32 huff_tab5[110];
+    extern const Int32 huff_tab6[113];
+    extern const Int32 huff_tab7[107];
+    extern const Int32 huff_tab8[90];
+    extern const Int32 huff_tab9[204];
+    extern const Int32 huff_tab10[186];
+    extern const Int32 huff_tab11[301];
+    extern const UInt32 huff_tab_scl[188];
+
+    /*----------------------------------------------------------------------------
+    ; 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/aacdec/hcbtables_binary.cpp b/media/libstagefright/codecs/aacdec/hcbtables_binary.cpp
new file mode 100644
index 0000000..d097af1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/hcbtables_binary.cpp
@@ -0,0 +1,1938 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: hcbtables.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modifiy per review comments
+    (1) delete the following comments:
+        The LAV field has been deleted, since it is never used.
+
+ Description: Remove old structure of huffman table and add new table structure.
+
+ Description: Modified structure to avoid assigning addresses to constant
+              tables. This solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers
+              - Eliminated references to contant vector addresses in
+                hcbbook_binary
+
+
+ Who:                       Date:
+ 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
+
+ This file defines the 12 packed Huffman Tables and a structure that reference
+ to these tables.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ISO/IEC 14496-3: 1999(E)
+ Subpart 4          p78 (Table 4.6.1 and Table 4.6.2)
+                    p77 (pseudo code)
+
+------------------------------------------------------------------------------
+ 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)
+
+------------------------------------------------------------------------------
+*/
+#include    "s_hcb.h"
+#include    "hcbtables.h"
+
+/* This file store packed Huffman tables for binary tree search */
+
+/*
+ * all tables are packed in the following way:
+ * right pointer (7 bits) idx (9 bits)
+ */
+
+
+const Hcb hcbbook_binary[13] =
+{
+
+    { 0, -1,  -1, -1, -1 },   /* ZERO_HCB */
+    { 1,  4,   3,  1,  1 },   /* codebook 1 */
+    { 2,  4,   3,  1,  1 },   /* codebook 2 */
+    { 3,  4,   3,  0,  0 },   /* codebook 3 */
+    { 4,  4,   3,  0,  0 },   /* codebook 4 */
+    { 5,  2,   9,  4,  1 },
+    { 6,  2,   9,  4,  1 },
+    { 7,  2,   8,  0,  0 },
+    { 8,  2,   8,  0,  0 },
+    { 9,  2,  13,  0,  0 },
+    {10,  2,  13,  0,  0 },
+    {11,  2,  17,  0,  0 },  /* codebook 11 ESC book */
+    {12, -1,  -1, -1, -1 }   /* scalefactor codebook */
+
+
+};
+
+
+/* New look-up table for huffman decoding
+   Created by ordering the codeword in the table according to their
+   normalized shifted binary value, i.e., all the codewords are left
+   shifted to meet the maximum codelength. Example, max codelength is
+   10, the codeword with lenth 3 will left shift by 7.
+   The binary values of after the shift are sorted.
+   Then the sorted table is divided into several partition.
+   At the VLC decoding period, input is read in at max codelenght.
+   The partition is decided using if-else logic.
+   Inside each partition, a look-up table is used to map the input value
+   to a correct symbol. Table entries can appear to be repeated according
+   to the humming distance between adjacent codewords.
+*/
+
+const Int32 huff_tab1[88] =
+{
+    0x430005,
+    0xd0005,
+    0x270005,
+    0x310005,
+    0x290005,
+    0x250005,
+    0x2b0005,
+    0x1f0005,
+    0x3a0007,
+    0x160007,
+    0x260007,
+    0x2e0007,
+    0x220007,
+    0x2a0007,
+    0x4c0007,
+    0x240007,
+    0x40007,
+    0x1c0007,
+    0x400007,
+    0x300007,
+    0x100007,
+    0x2c0007,
+    0x460007,
+    0x200007,
+    0x340007,
+    0x320007,
+    0xa0007,
+    0x440007,
+    0xc0007,
+    0x420007,
+    0xe0007,
+    0x1e0007,
+    0x490009,
+    0x130009,
+    0x3d0009,
+    0x330009,
+    0x2f0009,
+    0x230009,
+    0x210009,
+    0x370009,
+    0x410009,
+    0x2d0009,
+    0x190009,
+    0xf0009,
+    0x70009,
+    0x1d0009,
+    0x3b0009,
+    0x390009,
+    0x150009,
+    0x10009,
+    0x1b0009,
+    0x350009,
+    0x450009,
+    0x4d0009,
+    0x170009,
+    0x4f0009,
+    0x5000a,
+    0x5000a,
+    0x9000a,
+    0x9000a,
+    0x4b000a,
+    0x4b000a,
+    0x3f000a,
+    0x3f000a,
+    0xb000a,
+    0xb000a,
+    0x3000a,
+    0x3000a,
+    0x11000a,
+    0x11000a,
+    0x47000a,
+    0x47000a,
+    0x3c000b,
+    0x14000b,
+    0x18000b,
+    0x38000b,
+    0x50000b,
+    0x8000b,
+    0x48000b,
+    0x6000b,
+    0xb,
+    0x4a000b,
+    0x3e000b,
+    0x1a000b,
+    0x12000b,
+    0x2000b,
+    0x36000b,
+    0x4e000b
+};
+
+const Int32 huff_tab2[90] =
+{
+    0x430004,
+    0x430004,
+    0x430004,
+    0x430004,
+    0xd0005,
+    0xd0005,
+    0x290005,
+    0x290005,
+    0x250005,
+    0x250005,
+    0x270005,
+    0x270005,
+    0x1f0005,
+    0x1f0005,
+    0x2b0005,
+    0x2b0005,
+    0x310005,
+    0x310005,
+    0x220006,
+    0x160006,
+    0x2e0006,
+    0x2a0006,
+    0x300006,
+    0x260006,
+    0xc0006,
+    0x3a0006,
+    0x400006,
+    0x40006,
+    0x240006,
+    0x460006,
+    0x440006,
+    0x200006,
+    0x100006,
+    0x320006,
+    0x1c0006,
+    0xe0006,
+    0x1e0006,
+    0xa0006,
+    0x4c0006,
+    0x340006,
+    0x2c0006,
+    0x420006,
+    0x2f0007,
+    0x410007,
+    0x130007,
+    0x210007,
+    0x3d0007,
+    0x4b0007,
+    0x470007,
+    0x190007,
+    0x1d0007,
+    0x4f0007,
+    0xf0007,
+    0x10007,
+    0xb0007,
+    0x370007,
+    0x490007,
+    0x3b0008,
+    0x150008,
+    0x70008,
+    0x110008,
+    0x50008,
+    0x30008,
+    0x1b0008,
+    0x450008,
+    0x3f0008,
+    0x2d0008,
+    0x350008,
+    0x170008,
+    0x90008,
+    0x330008,
+    0x390008,
+    0x230008,
+    0x4d0008,
+    0x3c0008,
+    0x140008,
+    0x380009,
+    0x9,
+    0x180009,
+    0x1a0009,
+    0x500009,
+    0x60009,
+    0x3e0009,
+    0x120009,
+    0x80009,
+    0x480009,
+    0x360009,
+    0x20009,
+    0x4a0009,
+    0x4e0009
+};
+
+const Int32 huff_tab3[151] =
+{
+    0x1b0004,
+    0x1b0004,
+    0x1b0004,
+    0x1b0004,
+    0x10004,
+    0x10004,
+    0x10004,
+    0x10004,
+    0x90004,
+    0x90004,
+    0x90004,
+    0x90004,
+    0x30004,
+    0x30004,
+    0x30004,
+    0x30004,
+    0x240005,
+    0x240005,
+    0x40005,
+    0x40005,
+    0xc0006,
+    0xa0006,
+    0x1e0006,
+    0xd0006,
+    0x1c0006,
+    0x270006,
+    0x280007,
+    0x280007,
+    0x280007,
+    0x280007,
+    0x1f0007,
+    0x1f0007,
+    0x1f0007,
+    0x1f0007,
+    0x250007,
+    0x250007,
+    0x250007,
+    0x250007,
+    0x360008,
+    0x360008,
+    0x20008,
+    0x20008,
+    0x50008,
+    0x50008,
+    0x3f0008,
+    0x3f0008,
+    0x300008,
+    0x300008,
+    0x70009,
+    0x100009,
+    0x2d0009,
+    0xe0009,
+    0x420009,
+    0x60009,
+    0x150009,
+    0xf0009,
+    0x120009,
+    0xb0009,
+    0x390009,
+    0x310009,
+    0x160009,
+    0x2a0009,
+    0x2b0009,
+    0x2e000a,
+    0x21000a,
+    0x22000a,
+    0x13000a,
+    0x43000a,
+    0x29000a,
+    0x40000a,
+    0x20000a,
+    0x8000a,
+    0x11000a,
+    0x4b000a,
+    0x33000a,
+    0x1d000a,
+    0x37000a,
+    0x19000a,
+    0x48000b,
+    0x48000b,
+    0x34000b,
+    0x34000b,
+    0x26000b,
+    0x26000b,
+    0x3a000b,
+    0x3a000b,
+    0x2c000b,
+    0x2c000b,
+    0x4c000b,
+    0x4c000b,
+    0x18000b,
+    0x18000b,
+    0x17000b,
+    0x17000b,
+    0x23000c,
+    0x49000c,
+    0x45000c,
+    0x4e000c,
+    0x1a000c,
+    0x4f000c,
+    0x46000c,
+    0x32000c,
+    0x35000c,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x14000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x3c000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x2f000d,
+    0x3d000e,
+    0x3d000e,
+    0x3d000e,
+    0x3d000e,
+    0x44000e,
+    0x44000e,
+    0x44000e,
+    0x44000e,
+    0x41000e,
+    0x41000e,
+    0x41000e,
+    0x41000e,
+    0x50000f,
+    0x50000f,
+    0x4d000f,
+    0x4d000f,
+    0x47000f,
+    0x47000f,
+    0x3b000f,
+    0x3b000f,
+    0x38000f,
+    0x38000f,
+    0x4a0010,
+    0x3e0010
+};
+
+const Int32 huff_tab4[119] =
+{
+    0x280004,
+    0x280004,
+    0xd0004,
+    0xd0004,
+    0x250004,
+    0x250004,
+    0x270004,
+    0x270004,
+    0x1f0004,
+    0x1f0004,
+    0x1b0004,
+    0x1b0004,
+    0x240004,
+    0x240004,
+    0x4,
+    0x4,
+    0x40004,
+    0x40004,
+    0x1e0004,
+    0x1e0004,
+    0x1c0005,
+    0xc0005,
+    0x10005,
+    0xa0005,
+    0x30005,
+    0x90005,
+    0x430007,
+    0x430007,
+    0x2b0007,
+    0x2b0007,
+    0x310007,
+    0x310007,
+    0x290007,
+    0x290007,
+    0x420007,
+    0x420007,
+    0x400007,
+    0x400007,
+    0x300007,
+    0x300007,
+    0x3a0007,
+    0x3a0007,
+    0x100007,
+    0x100007,
+    0xe0008,
+    0x2a0008,
+    0x160008,
+    0x200008,
+    0x2e0008,
+    0x260008,
+    0x220008,
+    0x3f0008,
+    0x390008,
+    0x2d0008,
+    0x370008,
+    0xb0008,
+    0x150008,
+    0x50008,
+    0xf0008,
+    0x130008,
+    0x1d0008,
+    0x70008,
+    0x210008,
+    0x360008,
+    0x20008,
+    0x120009,
+    0x120009,
+    0x60009,
+    0x60009,
+    0x340009,
+    0x340009,
+    0x4c0009,
+    0x4c0009,
+    0x460009,
+    0x460009,
+    0x2c0009,
+    0x2c0009,
+    0x320009,
+    0x320009,
+    0x440009,
+    0x440009,
+    0x33000a,
+    0x4b000a,
+    0x45000a,
+    0x19000a,
+    0x11000a,
+    0x49000a,
+    0x17000a,
+    0x3d000a,
+    0x23000a,
+    0x4f000a,
+    0x2f000a,
+    0x3b000a,
+    0x41000a,
+    0x35000a,
+    0x47000b,
+    0x47000b,
+    0x4d000b,
+    0x4d000b,
+    0x18000b,
+    0x18000b,
+    0x48000b,
+    0x48000b,
+    0x8000b,
+    0x8000b,
+    0x3c000b,
+    0x3c000b,
+    0x14000b,
+    0x14000b,
+    0x38000b,
+    0x38000b,
+    0x50000b,
+    0x50000b,
+    0x1a000b,
+    0x1a000b,
+    0x4e000b,
+    0x4e000b,
+    0x4a000c,
+    0x3e000c
+};
+
+const Int32 huff_tab5[110] =
+{
+    0x1f0004,
+    0x1f0004,
+    0x310004,
+    0x310004,
+    0x290004,
+    0x290004,
+    0x270004,
+    0x270004,
+    0x300005,
+    0x200005,
+    0x1e0005,
+    0x320005,
+    0x160007,
+    0x160007,
+    0x2a0007,
+    0x2a0007,
+    0x3a0007,
+    0x3a0007,
+    0x260007,
+    0x260007,
+    0x150008,
+    0x3b0008,
+    0x1d0008,
+    0x330008,
+    0x170008,
+    0x390008,
+    0x210008,
+    0x2f0008,
+    0xd0008,
+    0x430008,
+    0x250008,
+    0x2b0008,
+    0xc0009,
+    0xc0009,
+    0x340009,
+    0x340009,
+    0x440009,
+    0x440009,
+    0x1c0009,
+    0x1c0009,
+    0xe0009,
+    0xe0009,
+    0x420009,
+    0x420009,
+    0x2e0009,
+    0x2e0009,
+    0x220009,
+    0x220009,
+    0x180009,
+    0x180009,
+    0x3c0009,
+    0x3c0009,
+    0x140009,
+    0x140009,
+    0x380009,
+    0x380009,
+    0xb000a,
+    0x41000a,
+    0x19000a,
+    0x37000a,
+    0x45000a,
+    0x3d000a,
+    0xf000a,
+    0x13000a,
+    0x24000a,
+    0x4000a,
+    0x4d000a,
+    0x4c000a,
+    0x3000b,
+    0x2c000b,
+    0x4b000b,
+    0x1b000b,
+    0x35000b,
+    0x23000b,
+    0x5000b,
+    0x2d000b,
+    0x40000b,
+    0xa000b,
+    0x10000b,
+    0x1a000b,
+    0x2000b,
+    0x4e000b,
+    0x36000b,
+    0x3e000b,
+    0x46000b,
+    0x6000b,
+    0x12000c,
+    0x12000c,
+    0x4a000c,
+    0x4a000c,
+    0x3f000c,
+    0x3f000c,
+    0x1000c,
+    0x1000c,
+    0x7000c,
+    0x7000c,
+    0x47000c,
+    0x47000c,
+    0x11000c,
+    0x11000c,
+    0x4f000c,
+    0x4f000c,
+    0x49000c,
+    0x49000c,
+    0x9000c,
+    0x9000c,
+    0x48000d,
+    0x8000d,
+    0x50000d,
+    0xd
+};
+const Int32 huff_tab6[113] =
+{
+    0x280004,
+    0x310004,
+    0x270004,
+    0x290004,
+    0x1f0004,
+    0x320004,
+    0x200004,
+    0x300004,
+    0x1e0004,
+    0x390006,
+    0x390006,
+    0x3b0006,
+    0x3b0006,
+    0x170006,
+    0x170006,
+    0x150006,
+    0x150006,
+    0x160006,
+    0x160006,
+    0x210006,
+    0x210006,
+    0x3a0006,
+    0x3a0006,
+    0x2f0006,
+    0x2f0006,
+    0x330006,
+    0x330006,
+    0x260006,
+    0x260006,
+    0x1d0006,
+    0x1d0006,
+    0x2a0006,
+    0x2a0006,
+    0x380006,
+    0x380006,
+    0x180006,
+    0x180006,
+    0x140006,
+    0x140006,
+    0x3c0006,
+    0x3c0006,
+    0xe0007,
+    0x440007,
+    0x420007,
+    0x220007,
+    0xc0007,
+    0x340007,
+    0x2e0007,
+    0x1c0007,
+    0x430007,
+    0xd0007,
+    0x250007,
+    0x2b0007,
+    0x450007,
+    0xb0008,
+    0xb0008,
+    0x190008,
+    0x190008,
+    0x3d0008,
+    0x3d0008,
+    0x410008,
+    0x410008,
+    0x370008,
+    0x370008,
+    0x130008,
+    0x130008,
+    0xf0008,
+    0xf0008,
+    0x460008,
+    0x460008,
+    0x400009,
+    0xa0009,
+    0x100009,
+    0x2d0009,
+    0x1b0009,
+    0x4d0009,
+    0x50009,
+    0x30009,
+    0x350009,
+    0x4b0009,
+    0x230009,
+    0x240009,
+    0x60009,
+    0x20009,
+    0x3e0009,
+    0x120009,
+    0x40009,
+    0x4e0009,
+    0x4a0009,
+    0x1a0009,
+    0x4c0009,
+    0x360009,
+    0x2c0009,
+    0x9000a,
+    0x9000a,
+    0x11000a,
+    0x11000a,
+    0x3f000a,
+    0x3f000a,
+    0x49000a,
+    0x49000a,
+    0x47000a,
+    0x47000a,
+    0x4f000a,
+    0x4f000a,
+    0x7000a,
+    0x7000a,
+    0x1000a,
+    0x1000a,
+    0x50000b,
+    0x8000b,
+    0xb,
+    0x48000b
+};
+
+const Int32 huff_tab7[107] =
+{
+    0x80003,
+    0x80003,
+    0x80003,
+    0x80003,
+    0x80003,
+    0x80003,
+    0x80003,
+    0x80003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x10003,
+    0x90004,
+    0x90004,
+    0x90004,
+    0x90004,
+    0x110006,
+    0xa0006,
+    0x100006,
+    0x20006,
+    0x190007,
+    0x190007,
+    0xb0007,
+    0xb0007,
+    0x120007,
+    0x120007,
+    0x180007,
+    0x180007,
+    0x30007,
+    0x30007,
+    0x130008,
+    0x1a0008,
+    0xc0008,
+    0x210008,
+    0xd0008,
+    0x290008,
+    0x1b0008,
+    0x140008,
+    0x40008,
+    0x200008,
+    0x220009,
+    0x220009,
+    0x150009,
+    0x150009,
+    0x2a0009,
+    0x2a0009,
+    0x50009,
+    0x50009,
+    0x310009,
+    0x310009,
+    0x280009,
+    0x280009,
+    0xe0009,
+    0xe0009,
+    0x230009,
+    0x230009,
+    0x1d0009,
+    0x1d0009,
+    0x1c0009,
+    0x1c0009,
+    0x2b0009,
+    0x2b0009,
+    0x160009,
+    0x160009,
+    0x320009,
+    0x320009,
+    0xf0009,
+    0xf0009,
+    0x1e000a,
+    0x6000a,
+    0x30000a,
+    0x24000a,
+    0x39000a,
+    0x25000a,
+    0x3a000a,
+    0x2c000a,
+    0x33000a,
+    0x17000a,
+    0x3b000a,
+    0x34000a,
+    0x2d000a,
+    0x26000a,
+    0x1f000a,
+    0x38000b,
+    0x38000b,
+    0x7000b,
+    0x7000b,
+    0x35000b,
+    0x35000b,
+    0x2e000b,
+    0x2e000b,
+    0x3c000b,
+    0x3c000b,
+    0x27000b,
+    0x27000b,
+    0x2f000b,
+    0x2f000b,
+    0x3d000b,
+    0x3d000b,
+    0x3e000c,
+    0x36000c,
+    0x37000c,
+    0x3f000c
+};
+const Int32 huff_tab8[90] =
+{
+    0x90003,
+    0x90003,
+    0x90003,
+    0x90003,
+    0x110004,
+    0x110004,
+    0x80004,
+    0x80004,
+    0xa0004,
+    0xa0004,
+    0x10004,
+    0x10004,
+    0x120004,
+    0x120004,
+    0x5,
+    0x100005,
+    0x20005,
+    0x190005,
+    0xb0005,
+    0x1a0005,
+    0x130005,
+    0x1b0006,
+    0x1b0006,
+    0x210006,
+    0x210006,
+    0xc0006,
+    0xc0006,
+    0x220006,
+    0x220006,
+    0x140006,
+    0x140006,
+    0x180006,
+    0x180006,
+    0x30006,
+    0x30006,
+    0x230006,
+    0x230006,
+    0x1c0006,
+    0x1c0006,
+    0x2a0006,
+    0x2a0006,
+    0x290007,
+    0x150007,
+    0xd0007,
+    0x2b0007,
+    0x1d0007,
+    0x240007,
+    0x2c0007,
+    0x40007,
+    0x250007,
+    0x200007,
+    0x160007,
+    0x320007,
+    0x310007,
+    0xe0007,
+    0x1e0008,
+    0x330008,
+    0x2d0008,
+    0x280008,
+    0x340008,
+    0x50008,
+    0x260008,
+    0x390008,
+    0x3a0008,
+    0x170008,
+    0x350008,
+    0x3b0008,
+    0xf0008,
+    0x2e0008,
+    0x1f0008,
+    0x360009,
+    0x360009,
+    0x3c0009,
+    0x3c0009,
+    0x300009,
+    0x300009,
+    0x270009,
+    0x270009,
+    0x60009,
+    0x60009,
+    0x3d0009,
+    0x3d0009,
+    0x3e0009,
+    0x3e0009,
+    0x370009,
+    0x370009,
+    0x2f000a,
+    0x38000a,
+    0x7000a,
+    0x3f000a
+};
+const Int32 huff_tab9[204] =
+{
+    0x1,
+    0x1,
+    0x1,
+    0x1,
+    0x1,
+    0x1,
+    0x1,
+    0x1,
+    0xd0003,
+    0xd0003,
+    0x10003,
+    0x10003,
+    0xe0004,
+    0x1b0006,
+    0x1b0006,
+    0xf0006,
+    0xf0006,
+    0x1a0006,
+    0x1a0006,
+    0x20006,
+    0x20006,
+    0x280007,
+    0x1c0007,
+    0x100007,
+    0x270008,
+    0x270008,
+    0x30008,
+    0x30008,
+    0x1d0008,
+    0x1d0008,
+    0x290008,
+    0x290008,
+    0x110008,
+    0x110008,
+    0x350008,
+    0x350008,
+    0x1e0008,
+    0x1e0008,
+    0x120008,
+    0x120008,
+    0x360009,
+    0x2a0009,
+    0x40009,
+    0x340009,
+    0x420009,
+    0x1f0009,
+    0x130009,
+    0x2b0009,
+    0x430009,
+    0x4f0009,
+    0x370009,
+    0x5000a,
+    0x20000a,
+    0x41000a,
+    0x14000a,
+    0x2c000a,
+    0x15000a,
+    0x69000a,
+    0x38000a,
+    0x44000a,
+    0x50000a,
+    0x5c000a,
+    0x6000a,
+    0x6a000a,
+    0x22000a,
+    0x2d000a,
+    0x21000a,
+    0x39000a,
+    0x76000a,
+    0x16000a,
+    0x5d000a,
+    0x4e000b,
+    0x45000b,
+    0x51000b,
+    0x6b000b,
+    0x7000b,
+    0x77000b,
+    0x2f000b,
+    0x3a000b,
+    0x2e000b,
+    0x8000b,
+    0x83000b,
+    0x52000b,
+    0x23000b,
+    0x46000b,
+    0x68000b,
+    0x5b000b,
+    0x5e000b,
+    0x84000b,
+    0x78000b,
+    0x6c000b,
+    0x17000b,
+    0x5f000b,
+    0x53000b,
+    0x47000b,
+    0x3c000b,
+    0x3b000b,
+    0x30000b,
+    0x90000b,
+    0x49000b,
+    0x75000b,
+    0x6d000b,
+    0x85000c,
+    0x24000c,
+    0x9000c,
+    0x91000c,
+    0x79000c,
+    0x54000c,
+    0x9d000c,
+    0x3d000c,
+    0x6e000c,
+    0x18000c,
+    0x7a000c,
+    0x86000c,
+    0x48000c,
+    0x60000c,
+    0x25000c,
+    0x19000c,
+    0x9e000c,
+    0x92000c,
+    0x31000c,
+    0x4a000c,
+    0x55000c,
+    0x6f000c,
+    0x93000c,
+    0xa000c,
+    0x61000c,
+    0x9f000c,
+    0x82000c,
+    0x87000c,
+    0x3e000c,
+    0x56000c,
+    0x26000c,
+    0x7b000c,
+    0x7c000c,
+    0x3f000c,
+    0x8f000c,
+    0x57000c,
+    0x32000c,
+    0x4b000c,
+    0x70000d,
+    0x63000d,
+    0xa1000d,
+    0x33000d,
+    0x94000d,
+    0x62000d,
+    0xa0000d,
+    0x95000d,
+    0x88000d,
+    0x40000d,
+    0x64000d,
+    0x4c000d,
+    0xb000d,
+    0xa2000d,
+    0x58000d,
+    0x9c000d,
+    0x89000d,
+    0x4d000d,
+    0x65000d,
+    0x7d000d,
+    0xc000d,
+    0x96000d,
+    0x71000d,
+    0x7e000d,
+    0x8a000d,
+    0x66000d,
+    0xa3000d,
+    0x59000d,
+    0x73000d,
+    0x97000d,
+    0x67000d,
+    0x5a000d,
+    0x72000e,
+    0x72000e,
+    0x8b000e,
+    0x8b000e,
+    0x74000e,
+    0x74000e,
+    0x7f000e,
+    0x7f000e,
+    0x80000e,
+    0x80000e,
+    0x81000e,
+    0x81000e,
+    0x8d000e,
+    0x8d000e,
+    0xa5000e,
+    0xa5000e,
+    0x8c000e,
+    0x8c000e,
+    0x98000e,
+    0x98000e,
+    0xa4000e,
+    0xa4000e,
+    0x99000e,
+    0x99000e,
+    0xa6000e,
+    0xa6000e,
+    0xa7000e,
+    0xa7000e,
+    0x8e000f,
+    0x9a000f,
+    0x9b000f,
+    0xa8000f
+};
+const Int32 huff_tab10[186] =
+{
+    0xe0004,
+    0xe0004,
+    0xe0004,
+    0xe0004,
+    0xf0004,
+    0xf0004,
+    0xf0004,
+    0xf0004,
+    0x1b0004,
+    0x1b0004,
+    0x1b0004,
+    0x1b0004,
+    0x1c0005,
+    0x1c0005,
+    0xd0005,
+    0xd0005,
+    0x10005,
+    0x10005,
+    0x100005,
+    0x100005,
+    0x290005,
+    0x290005,
+    0x280005,
+    0x280005,
+    0x1d0005,
+    0x1d0005,
+    0x2a0005,
+    0x2a0005,
+    0x1a0006,
+    0x20006,
+    0x1e0006,
+    0x360006,
+    0x110006,
+    0x350006,
+    0x6,
+    0x370006,
+    0x2b0006,
+    0x270006,
+    0x30006,
+    0x380006,
+    0x1f0006,
+    0x430006,
+    0x120007,
+    0x420007,
+    0x440007,
+    0x2c0007,
+    0x450007,
+    0x390007,
+    0x500007,
+    0x200007,
+    0x510007,
+    0x340007,
+    0x4f0007,
+    0x40007,
+    0x130007,
+    0x2d0007,
+    0x460007,
+    0x520007,
+    0x3a0007,
+    0x530008,
+    0x5d0008,
+    0x2e0008,
+    0x210008,
+    0x470008,
+    0x6a0008,
+    0x5e0008,
+    0x410008,
+    0x5c0008,
+    0x50008,
+    0x690008,
+    0x140008,
+    0x6b0008,
+    0x5f0008,
+    0x3b0008,
+    0x220008,
+    0x540008,
+    0x600008,
+    0x150008,
+    0x2f0008,
+    0x6c0008,
+    0x3c0008,
+    0x480008,
+    0x6d0008,
+    0x490008,
+    0x610009,
+    0x550009,
+    0x770009,
+    0x4e0009,
+    0x560009,
+    0x780009,
+    0x300009,
+    0x760009,
+    0x230009,
+    0x60009,
+    0x6e0009,
+    0x790009,
+    0x3d0009,
+    0x840009,
+    0x160009,
+    0x620009,
+    0x6f0009,
+    0x7a0009,
+    0x630009,
+    0x850009,
+    0x4a0009,
+    0x860009,
+    0x240009,
+    0x830009,
+    0x310009,
+    0x7b0009,
+    0x570009,
+    0x680009,
+    0x3e0009,
+    0x5b0009,
+    0x910009,
+    0x64000a,
+    0x92000a,
+    0x88000a,
+    0x17000a,
+    0x90000a,
+    0x7c000a,
+    0x7000a,
+    0x70000a,
+    0x87000a,
+    0x32000a,
+    0x4b000a,
+    0x71000a,
+    0x94000a,
+    0x8000a,
+    0x93000a,
+    0x25000a,
+    0x65000a,
+    0x58000a,
+    0x89000a,
+    0x3f000a,
+    0x18000a,
+    0x9e000a,
+    0x7d000a,
+    0x9f000a,
+    0x95000a,
+    0x4c000a,
+    0xa0000a,
+    0x96000a,
+    0xa1000a,
+    0x33000a,
+    0x59000a,
+    0x75000a,
+    0x8a000a,
+    0x82000a,
+    0x9d000a,
+    0x9000a,
+    0x40000a,
+    0x7e000a,
+    0xa2000a,
+    0x26000a,
+    0x72000a,
+    0x7f000b,
+    0x19000b,
+    0x97000b,
+    0xa3000b,
+    0x66000b,
+    0x4d000b,
+    0x5a000b,
+    0x8b000b,
+    0x73000b,
+    0xa4000b,
+    0xa000b,
+    0x67000b,
+    0x8f000b,
+    0x8c000b,
+    0x98000b,
+    0x99000b,
+    0xb000b,
+    0x9a000b,
+    0x80000b,
+    0x8d000b,
+    0x9c000b,
+    0x74000b,
+    0xa5000c,
+    0x8e000c,
+    0x81000c,
+    0x9b000c,
+    0xa7000c,
+    0xc000c,
+    0xa6000c,
+    0xa8000c
+};
+const Int32 huff_tab11[301] =
+{
+    0x4,
+    0x4,
+    0x4,
+    0x4,
+    0x120004,
+    0x120004,
+    0x120004,
+    0x120004,
+    0x1200005,
+    0x1200005,
+    0x110005,
+    0x110005,
+    0x10005,
+    0x10005,
+    0x230005,
+    0x230005,
+    0x130005,
+    0x130005,
+    0x240005,
+    0x240005,
+    0x140006,
+    0x340006,
+    0x350006,
+    0x220006,
+    0x250006,
+    0x20006,
+    0x360006,
+    0x450007,
+    0x150007,
+    0x460007,
+    0x260007,
+    0x470007,
+    0x370007,
+    0x330007,
+    0x30007,
+    0x560007,
+    0x570007,
+    0x270007,
+    0x480007,
+    0x160007,
+    0x580007,
+    0x380007,
+    0x590007,
+    0x490008,
+    0x680008,
+    0x280008,
+    0x670008,
+    0x690008,
+    0x390008,
+    0x170008,
+    0x540008,
+    0x430008,
+    0x1150008,
+    0x1130008,
+    0x1140008,
+    0x6a0008,
+    0x1160008,
+    0x440008,
+    0x4a0008,
+    0x40008,
+    0x320008,
+    0x5a0008,
+    0x650008,
+    0x1170008,
+    0x1120008,
+    0x1180008,
+    0x290008,
+    0x790008,
+    0x3a0008,
+    0x6b0008,
+    0x5b0008,
+    0x760008,
+    0x11a0008,
+    0x7a0008,
+    0x780008,
+    0x1190008,
+    0x870008,
+    0x210008,
+    0x180008,
+    0x4b0008,
+    0x11b0008,
+    0x7b0008,
+    0x11c0008,
+    0x980008,
+    0x1110008,
+    0x6c0008,
+    0xa90008,
+    0x2a0008,
+    0x5c0008,
+    0xba0008,
+    0x11d0008,
+    0x8b0008,
+    0x8a0008,
+    0x3b0008,
+    0x550008,
+    0x11e0008,
+    0xcb0008,
+    0x7c0008,
+    0x4c0008,
+    0x6d0008,
+    0x7d0008,
+    0x50008,
+    0x8c0009,
+    0x11f0009,
+    0xdc0009,
+    0x190009,
+    0x890009,
+    0xfe0009,
+    0x5d0009,
+    0xed0009,
+    0x3c0009,
+    0x8d0009,
+    0x7e0009,
+    0x2b0009,
+    0x8e0009,
+    0x9b0009,
+    0x9c0009,
+    0x10f0009,
+    0x4d0009,
+    0x6e0009,
+    0x660009,
+    0x9d0009,
+    0x5e0009,
+    0x8f0009,
+    0x7f0009,
+    0x1a0009,
+    0xad0009,
+    0x60009,
+    0xac0009,
+    0x9a0009,
+    0x9e0009,
+    0x4e0009,
+    0x2c0009,
+    0x9f0009,
+    0x3d0009,
+    0x6f0009,
+    0xae0009,
+    0x900009,
+    0xaf0009,
+    0xa00009,
+    0xbe0009,
+    0x1b0009,
+    0x770009,
+    0xb00009,
+    0x800009,
+    0x3e0009,
+    0x5f0009,
+    0xab0009,
+    0x4f0009,
+    0xbd0009,
+    0xdf0009,
+    0x700009,
+    0xe00009,
+    0x2d0009,
+    0x1100009,
+    0x600009,
+    0xc00009,
+    0xbf000a,
+    0xa1000a,
+    0x81000a,
+    0x91000a,
+    0x10000a,
+    0x51000a,
+    0x7000a,
+    0x40000a,
+    0xc1000a,
+    0xde000a,
+    0xe1000a,
+    0xcf000a,
+    0x2f000a,
+    0xe2000a,
+    0x92000a,
+    0x71000a,
+    0xb2000a,
+    0xb1000a,
+    0xf0000a,
+    0xd0000a,
+    0x1c000a,
+    0x50000a,
+    0xbc000a,
+    0x3f000a,
+    0x1e000a,
+    0xce000a,
+    0x82000a,
+    0x41000a,
+    0x61000a,
+    0x62000a,
+    0xf2000a,
+    0x52000a,
+    0xc2000a,
+    0xf1000a,
+    0xd1000a,
+    0xe3000a,
+    0xd2000a,
+    0x88000a,
+    0xc3000a,
+    0x2e000a,
+    0xa2000a,
+    0xf3000a,
+    0x73000a,
+    0xb4000a,
+    0x101000a,
+    0x93000a,
+    0xa3000a,
+    0xf4000a,
+    0xb3000a,
+    0x63000a,
+    0xc4000a,
+    0xef000a,
+    0x30000a,
+    0x72000a,
+    0x1d000a,
+    0xe5000a,
+    0x8000a,
+    0xe4000a,
+    0x83000a,
+    0xd3000a,
+    0x84000a,
+    0x102000a,
+    0xcd000a,
+    0x74000a,
+    0x31000a,
+    0x104000a,
+    0x103000a,
+    0x1f000a,
+    0xa4000a,
+    0x53000a,
+    0xf5000a,
+    0x95000a,
+    0xe6000a,
+    0x94000a,
+    0x64000a,
+    0x42000a,
+    0xb5000a,
+    0xc5000a,
+    0xd4000a,
+    0x105000a,
+    0x106000a,
+    0x96000a,
+    0x100000a,
+    0x85000a,
+    0x99000a,
+    0x9000a,
+    0xa6000a,
+    0xa5000a,
+    0xd5000a,
+    0xf6000a,
+    0xb7000a,
+    0xf7000a,
+    0xd6000a,
+    0x75000a,
+    0x86000a,
+    0xa7000b,
+    0x107000b,
+    0xc6000b,
+    0xc9000b,
+    0x20000b,
+    0xb6000b,
+    0xb8000b,
+    0xe8000b,
+    0xe7000b,
+    0xc8000b,
+    0xc7000b,
+    0x97000b,
+    0xf9000b,
+    0xe9000b,
+    0xd9000b,
+    0x108000b,
+    0xf8000b,
+    0xaa000b,
+    0xd7000b,
+    0xa8000b,
+    0xa000b,
+    0xd8000b,
+    0xbb000b,
+    0xda000b,
+    0xb9000b,
+    0xea000b,
+    0xd000b,
+    0xfa000b,
+    0x109000b,
+    0x10a000b,
+    0xca000b,
+    0xfb000b,
+    0xdd000b,
+    0xb000b,
+    0xeb000b,
+    0x10b000b,
+    0x10c000b,
+    0xdb000b,
+    0xee000b,
+    0xfc000b,
+    0xec000b,
+    0xcc000b,
+    0xfd000b,
+    0xe000c,
+    0xc000c,
+    0x10d000c,
+    0xff000c,
+    0xf000c,
+    0x10e000c
+};
+
+const UInt32 huff_tab_scl[188] =
+{
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3b0003,
+    0x3d0004,
+    0x3d0004,
+    0x3d0004,
+    0x3d0004,
+    0x3a0004,
+    0x3a0004,
+    0x3a0004,
+    0x3a0004,
+    0x3e0004,
+    0x3e0004,
+    0x3e0004,
+    0x3e0004,
+    0x390005,
+    0x390005,
+    0x3f0005,
+    0x3f0005,
+    0x380006,
+    0x400006,
+    0x370006,
+    0x410006,
+    0x420007,
+    0x420007,
+    0x420007,
+    0x420007,
+    0x360007,
+    0x360007,
+    0x360007,
+    0x360007,
+    0x430007,
+    0x430007,
+    0x430007,
+    0x430007,
+    0x350008,
+    0x350008,
+    0x440008,
+    0x440008,
+    0x340008,
+    0x340008,
+    0x450008,
+    0x450008,
+    0x330008,
+    0x330008,
+    0x460009,
+    0x320009,
+    0x310009,
+    0x470009,
+    0x48000a,
+    0x48000a,
+    0x48000a,
+    0x48000a,
+    0x30000a,
+    0x30000a,
+    0x30000a,
+    0x30000a,
+    0x49000a,
+    0x49000a,
+    0x49000a,
+    0x49000a,
+    0x2f000a,
+    0x2f000a,
+    0x2f000a,
+    0x2f000a,
+    0x4a000a,
+    0x4a000a,
+    0x4a000a,
+    0x4a000a,
+    0x2e000a,
+    0x2e000a,
+    0x2e000a,
+    0x2e000a,
+    0x4c000b,
+    0x4c000b,
+    0x4b000b,
+    0x4b000b,
+    0x4d000b,
+    0x4d000b,
+    0x4e000b,
+    0x4e000b,
+    0x2d000b,
+    0x2d000b,
+    0x2b000b,
+    0x2b000b,
+    0x2c000c,
+    0x4f000c,
+    0x2a000c,
+    0x29000c,
+    0x50000c,
+    0x28000c,
+    0x51000d,
+    0x51000d,
+    0x27000d,
+    0x27000d,
+    0x52000d,
+    0x52000d,
+    0x26000d,
+    0x26000d,
+    0x53000d,
+    0x53000d,
+    0x25000e,
+    0x23000e,
+    0x55000e,
+    0x21000e,
+    0x24000e,
+    0x22000e,
+    0x54000e,
+    0x20000e,
+    0x57000f,
+    0x57000f,
+    0x59000f,
+    0x59000f,
+    0x1e000f,
+    0x1e000f,
+    0x1f000f,
+    0x1f000f,
+    0x560010,
+    0x1d0010,
+    0x1a0010,
+    0x1b0010,
+    0x1c0010,
+    0x180010,
+    0x580010,
+    0x190011,
+    0x190011,
+    0x160011,
+    0x160011,
+    0x170011,
+    0x170011,
+    0x5a0012,
+    0x150012,
+    0x130012,
+    0x30012,
+    0x10012,
+    0x20012,
+    0x12,
+    0x620013,
+    0x630013,
+    0x640013,
+    0x650013,
+    0x660013,
+    0x750013,
+    0x610013,
+    0x5b0013,
+    0x5c0013,
+    0x5d0013,
+    0x5e0013,
+    0x5f0013,
+    0x600013,
+    0x680013,
+    0x6f0013,
+    0x700013,
+    0x710013,
+    0x720013,
+    0x730013,
+    0x740013,
+    0x6e0013,
+    0x690013,
+    0x6a0013,
+    0x6b0013,
+    0x6c0013,
+    0x6d0013,
+    0x760013,
+    0x60013,
+    0x80013,
+    0x90013,
+    0xa0013,
+    0x50013,
+    0x670013,
+    0x780013,
+    0x770013,
+    0x40013,
+    0x70013,
+    0xf0013,
+    0x100013,
+    0x120013,
+    0x140013,
+    0x110013,
+    0xb0013,
+    0xc0013,
+    0xe0013,
+    0xd0013
+};
diff --git a/media/libstagefright/codecs/aacdec/huffcb.cpp b/media/libstagefright/codecs/aacdec/huffcb.cpp
new file mode 100644
index 0000000..30f38fa
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/huffcb.cpp
@@ -0,0 +1,381 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/huffcb.c
+ Funtions:
+    huffcb
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Change variable names for clarity,
+               change variables 'base', 'sect_len_inc', and 'esc_val' to
+               UChar type.
+
+ Description:  Add "if ((pSect[-1] % sfb_per_win) > max_sfb)" statement to
+               detect the error condition.
+               add more white space.
+
+ Description: eliminated "pSect[-1]%sfb_per_win" operation
+
+ Description: eliminated "pSect[-1]%sfb_per_win" operation
+
+ Description: (1) Pass in SectInfo pSect
+              (2) put BITS *pInputStream as second parameter
+
+ Description:  Fix a failure for thrid party AAC encoding.
+               The problem came when the total and the
+               maximun number of active scale factor bands do not coincide.
+               This is a rare situation but produces a problem when decoding
+               encoders that tolerate this.
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    UChar   *pSect  = pointer to array that contains the interleaved
+                      information of huffman codebook index and section
+                      length. Array contains:
+                      [codebook index]
+                      [section boundary]
+                      [codebook index]
+                      [section boundary]
+                      ...
+
+    Int     sectbits  =   array that defines the number of bits
+                          used for expressing the escape value of
+                          section length
+
+    Int     tot_sfb     = total number of sfb in one Frame
+
+    Int     sfb_per_win = number of sfb in each sub-block (window)
+
+    UChar   max_sfb     = 1 + number of active sfbs - see reference (2) p56
+
+    BITS    *pInputStream = pointer to input stream
+
+
+ Local Stores/Buffers/Pointers Needed:
+
+    UChar    base     = number of sfb in already detected sections
+
+    UChar    sect_len_inc = section length increment in number of sfbs'
+
+    UChar    esc_val  = escape value for section length
+
+    Int     bits     = number of bits needed for expressing section length
+
+
+ Global Stores/Buffers/Pointers Needed:
+
+
+ Outputs:
+
+    num_sect = total number of sections in one frame
+
+
+ Pointers and Buffers Modified:
+
+    UChar    *pSect = pointer to array where huffman codebook index and
+                     section length are stored
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Background knowledge: 1024(960) coef's are separated into several sections,
+ each section is encoded with one single Huffman codebook, and each section
+ has a length of multiples of sfb.
+
+ max_sfb <= sfb_per_win <= tot_sfb
+ tot_sfb = total number of scalefactor bands in one frame (1024 coefs)
+
+ This function reads the codebook index and section boundaries (expressed
+ in number of sfb) from the input bitstream, store these information in
+ *pSect, and return the number of sections been detected. Returns 0 if there
+ is an error.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should fill the array *pSect with section Huffman codebook
+ indexes and section boundaries
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3 1999(E)
+   Subpart 4    p55     (Recovering section_data())
+                p24-25  (Syntax of section_data())
+
+ (3) M. Bosi, K. Brandenburg, etc., "ISO/IEC MPEG-2 Advanced Audio Coding,"
+     J. Audio Eng. Soc., Vol.45, No.10, 1997 October
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ bits_needed_for_ESC  = sectbits[0];
+ ESC_value            = (1<<bits_needed_for_ESC) - 1;
+ num_of_section       = 0;
+
+
+ FOR (base = 0; base<total_sfb AND num_of_section<total_sfb)
+ {
+    *pSect++     = getbits(LEN_CB, pInputStream);   (read huffman_codebook_num)
+    sect_length_incr  = getbits(bits_needed_for_ESC, pInputStream);
+
+    WHILE (sect_length_incr == ESC_value AND base < total_sfb)
+    {
+        base              += ESC_value;
+        sect_length_incr  =  getbits(bits_needed_for_ESC, ebits);
+    }
+    ENDWHILE
+
+    base      += sect_length_incr;
+    *pSect++   =  base;
+    num_of_section++;
+
+   IF (num_of_sfb_for_this_group==max_sfb)
+   {
+        *pSect++    = 0; (use huffman codebook 0)
+        base       += sfb_per_win - max_sfb;
+        *pSect++    = base;
+        num_of_section++;
+   }
+   ENDIF
+
+   IF (num_of_sfb_for_this_group > max_sfb)
+        break;
+   ENDIF
+
+ }
+ ENDFOR
+
+ IF (base != total_sfb OR num_of_section>total_sfb)
+      return 0;
+ ENDIF
+
+ return num_sect;
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "huffman.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
+----------------------------------------------------------------------------*/
+Int huffcb(
+    SectInfo    *pSect,
+    BITS        *pInputStream,
+    Int         sectbits[],
+    Int         tot_sfb,
+    Int         sfb_per_win,
+    Int         max_sfb)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    Int   base;        /* section boundary */
+    Int   sect_len_incr;
+    Int   esc_val;     /* ESC of section length = 31(long), =7 (short) */
+    Int     bits;        /* # of bits used to express esc_val */
+    Int     num_sect;
+    Int     active_sfb;
+    Int   group_base;
+
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    bits       =  sectbits[0];     /* 3 for SHORT_WIN, 5 for LONG_WIN */
+    esc_val    = (1 << bits) - 1;   /* ESC_value for section length */
+    num_sect   =  0;
+    base       =  0;
+    group_base =  0;
+
+    /* read until the end of one frame */
+    while ((base < tot_sfb) && (num_sect < tot_sfb))
+    {
+
+        pSect->sect_cb  = get9_n_lessbits(
+                              LEN_CB,
+                              pInputStream); /* section codebook */
+
+        sect_len_incr   = get9_n_lessbits(
+                              bits,
+                              pInputStream); /* length_incr */
+
+
+        /* read until non-ESC value, see p55 reference 2 */
+        while ((sect_len_incr == esc_val) && (base < tot_sfb))
+        {
+            base            +=  esc_val;
+
+            sect_len_incr   = get9_n_lessbits(
+                                  bits,
+                                  pInputStream);
+        }
+
+        base      += sect_len_incr;
+        pSect->sect_end  =  base; /* total # of sfb until current section */
+        pSect++;
+        num_sect++;
+
+        /* active_sfb = base % sfb_per_win; */
+        active_sfb = base - group_base;
+
+        /*
+         *  insert a zero section for regions above max_sfb for each group
+         *  Make sure that active_sfb is also lesser than tot_sfb
+         */
+
+        if ((active_sfb == max_sfb) && (active_sfb < tot_sfb))
+        {
+            base      += (sfb_per_win - max_sfb);
+            pSect->sect_cb   =   0; /* huffman codebook 0 */
+            pSect->sect_end  =   base;
+            num_sect++;
+            pSect++;
+            group_base = base;
+        }
+        else if (active_sfb > max_sfb)
+        {
+            /* within each group, the sections must delineate the sfb
+             * from zero to max_sfb so that the 1st section within each
+             * group starts at sfb0 and the last section ends at max_sfb
+             * see p55 reference 2
+             */
+            break;
+        }
+
+    } /* while (base=0) */
+
+
+    if (base != tot_sfb || num_sect > tot_sfb)
+    {
+        num_sect = 0;   /* error */
+    }
+
+    return num_sect;
+
+} /* huffcb */
+
+
diff --git a/media/libstagefright/codecs/aacdec/huffdecode.cpp b/media/libstagefright/codecs/aacdec/huffdecode.cpp
new file mode 100644
index 0000000..890a6fb
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/huffdecode.cpp
@@ -0,0 +1,528 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: huffdecode.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Change variable types.
+
+ Description:  (1) Modified to bring in-line with PV standards.
+               (2) Eliminated global_gain on stack,
+                   getics() has to define this parameter on its stack.
+               (3) Eliminated multiple returns
+               (4) Altered return logic of getics()
+               (5) Convert Real coef -> Int32 coef
+               (6) Move BITS *pInputStream to 2nd parameter of huffdecode.c
+                   and getics.c
+               (7) Pass pFrameInfo per channel, because two channels can have
+                   different windows
+
+ Description: (1) Eliminated function call to chn_config
+              (2) Eliminate widx calculation
+              (3) copy channel info from left to right when common_window
+                  is enabled
+              (4) add error checking of getmask return value
+
+ Description:  Change default_position to current_program
+
+ Description:  Remove prstflag
+
+ Description:  Modify call to get_ics_info
+
+ Description:  Modified so getmask is NOT called if the status returned
+ from get_ics_info indicates an error.
+
+ Description:
+ (1) Added include of "e_ElementId.h"
+     Previously, this function was relying on another include file
+     to include e_ElementId.h
+
+ (2) Updated the copyright header.
+
+ Description:  Modified to include usage of the new "shared memory" structures
+ defined in s_tDec_Int_File.h and s_tDec_Int_Chan.h
+
+ Description:
+ (1) Updated to reflect the fact that the temporary FrameInfo used by getics.c
+ was moved into the region of memory shared with fxpCoef.
+
+ Description:
+ (1) Removed first parameter to getics.  The temporary FrameInfo was
+     unnecessary.
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Description: Relaxed tag verification. Some encoder do not match the tag
+              to the channel ID (as the standard request to differentiate
+              different channel), in our wireless work, with only mono
+              or stereo channel, this become restrictive to some encoders
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    id_syn_ele  = identification flag for channel syntactic element, Int
+
+    pInputStream= pointer to input bitstream, BITS.
+
+    pVars       = pointer to structure that holds information for decoding,
+                  tDec_Int_File
+
+    pChVars[]   = pointer to structure that holds channel information,
+                  tDec_Int_Chan
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    status = 0  if success
+             non-zero  otherwise
+
+ Pointers and Buffers Modified:
+    pChVars->sect   contents updated by newly decoded section information
+                    of current frame
+
+    pChVars->factors contents updated by newly decoded scalefactors
+
+    pChVars->ch_coef contents updated by newly decoded spectral coefficients
+
+    PChVars->tns    contents updated by newly decoded TNS information
+
+    pVars->hasmask  contents updated by newly decoded Mid/Side mask
+                    information
+
+    pVars->pulseInfo contents updated by newly decoded pulse data information
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  This function offers a framework for decoding the data of the next 1024
+  samples. It maps the channel configuration according to the id_syn_ele flag,
+  configures the channel information, and calls getics to do huffman decoding
+  The function returns 1 if there was an error
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should set up the channel configuration for huffman decoding
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4       p15     (single_channel_element, channel_pair_element)
+                    p15     (Table 4.4.5    getmask)
+                    p16     (Table 4.4.6    get_ics_info)
+                    p24     (Table 4.4.24   getics)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    tag = CALL getbits(LEN_TAG,pInputStream)
+                MODIFYING(pInputStream)
+                RETURNING(tag)
+
+    common_window = 0;
+
+    IF (id_syn_ele == ID_CPE)
+    THEN
+        common_window = CALL getbits(LEN_COM_WIN,pInputStream);
+                                MODIFYING(pInputStream)
+                                RETURNING(common_window)
+    ENDIF
+
+    pMcInfo = &pVars->mc_info;
+
+    IF ( (pMcInfo->ch_info[0].cpe != id_syn_ele) OR
+         (pMcInfo->ch_info[0].tag != tag) )
+    THEN
+        status = 1;
+    ENDIF
+
+
+    IF (status == SUCCESS)
+    THEN
+        IF (id_syn_ele == ID_SCE)
+        THEN
+
+            leftCh  = 0;
+            RIGHT = 0;
+            pChVars[leftCh]->hasmask = 0;
+        ELSEIF (id_syn_ele == ID_CPE)
+
+            leftCh = 0;
+            rightCh  = 1;
+
+            IF (common_window != FALSE)
+            THEN
+
+                CALL get_ics_info(
+                        audioObjectType = pVars->mc_info.audioObjectType,
+                        pInputStream = pInputStream,
+                        common_window = common_window,
+                        pWindowSequence = &pChVars[leftCh]->wnd,
+                        &pChVars[leftCh]->wnd_shape_this_bk,
+                        pChVars[leftCh]->group,
+                        &pChVars[leftCh]->max_sfb,
+                        pVars->winmap,
+                        &pChVars[leftCh]->lt_status,
+                        &pChVars[rightCh]->lt_status);
+                     MODIFYING(pInputStream, wnd, wnd_shape_this_bk,group,
+                               max_sfb, lt_status)
+                     RETURNING(status)
+
+                IF (status == SUCCESS)
+                THEN
+
+                    pChVars[rightCh]->wnd = pChVars[leftCh]->wnd;
+                    pChVars[rightCh]->wnd_shape_this_bk =
+                        pChVars[leftCh]->wnd_shape_this_bk;
+                    pChVars[rightCh]->max_sfb = pChVars[leftCh]->max_sfb;
+                    pv_memcpy(
+                        pChVars[rightCh]->group,
+                        pChVars[leftCh]->group,
+                        NSHORT*sizeof(pChVars[leftCh]->group[0]));
+
+                    hasmask = CALL getmask(
+                                    pVars->winmap[pChVars[leftCh]->wnd],
+                                    pInputStream,
+                                    pChVars[leftCh]->group,
+                                    pChVars[leftCh]->max_sfb,
+                                    pChVars[leftCh]->mask);
+                                MODIFYING(pInputStream, mask)
+                                RETURNING(hasmask)
+
+                    IF (hasmask == MASK_ERROR)
+                    THEN
+                        status = 1;
+                    ENDIF
+                    pChVars[leftCh]->hasmask  = hasmask;
+                    pChVars[rightCh]->hasmask = hasmask;
+
+                ENDIF
+
+            ELSE
+
+                 pChVars[leftCh]->hasmask  = 0;
+                 pChVars[rightCh]->hasmask = 0;
+            ENDIF(common_window)
+
+        ENDIF(id_syn_ele)
+
+    ENDIF (status)
+
+    ch = leftCh;
+
+    WHILE((ch <= rightCh) AND (status == SUCCESS))
+
+        status = CALL getics(
+                        pInputStream,
+                        common_window,
+                        pVars,
+                        pChVars[ch],
+                        pChVars[ch]->group,
+                        &pChVars[ch]->max_sfb,
+                        pChVars[ch]->cb_map,
+                        &pChVars[ch]->tns,
+                        pVars->winmap,
+                        &pVars->pulseInfo,
+                        pChVars[ch]->sect);
+                    MODIFYING(pInputStream,pVarsp,ChVars[ch],group,
+                              max_sfb,tns,pulseInfo,sect)
+                    RETURNING(status)
+
+        ch++;
+
+    ENDWHILE
+
+    RETURN status;
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "aac_mem_funcs.h"
+#include    "huffman.h"
+#include    "e_maskstatus.h"
+#include    "e_elementid.h"
+#include    "get_ics_info.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LEFT  (0)
+#define RIGHT (1)
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int huffdecode(
+    Int           id_syn_ele,
+    BITS          *pInputStream,
+    tDec_Int_File *pVars,
+    tDec_Int_Chan *pChVars[])
+
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Int      ch;
+    Int      common_window;
+    Int      hasmask;
+    Int      status   = SUCCESS;
+    Int      num_channels = 0;
+    MC_Info  *pMcInfo;
+
+    per_chan_share_w_fxpCoef *pChLeftShare;  /* Helper pointer */
+    per_chan_share_w_fxpCoef *pChRightShare; /* Helper pointer */
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    get9_n_lessbits(
+        LEN_TAG,
+        pInputStream);
+
+    /* suppose an un-supported id_syn_ele will never be passed */
+
+    common_window = 0;
+
+    if (id_syn_ele == ID_CPE)
+    {
+        common_window =
+            get1bits(pInputStream);
+    }
+
+    pMcInfo = &pVars->mc_info;
+
+    /*
+     *  check if provided info (num of channels) on audio config,
+     *  matches read bitstream data, if not, allow update only once.
+     *  In almost all cases it should match.
+     */
+    if ((pMcInfo->ch_info[0].cpe != id_syn_ele))
+    {
+        if (pVars->mc_info.implicit_channeling)     /* check done only once */
+        {
+            pMcInfo->ch_info[0].cpe = id_syn_ele & 1; /*  collect info from bitstream
+                                                     *  implicit_channeling flag is locked
+                                                     *  after 1st frame, to avoid toggling
+                                                     *  parameter in the middle of the clip
+                                                     */
+            pMcInfo->nch = (id_syn_ele & 1) + 1;     /* update number of channels */
+        }
+        else
+        {
+            status = 1; /* ERROR break if syntax error persist  */
+        }
+    }
+
+    if (status == SUCCESS)
+    {
+        if (id_syn_ele == ID_SCE)
+        {
+
+            num_channels = 1;
+            pVars->hasmask = 0;
+        }
+        else if (id_syn_ele == ID_CPE)
+        {
+            pChLeftShare = pChVars[LEFT]->pShareWfxpCoef;
+            pChRightShare = pChVars[RIGHT]->pShareWfxpCoef;
+            num_channels = 2;
+
+            if (common_window != FALSE)
+            {
+
+                status = get_ics_info(
+                             (tMP4AudioObjectType) pVars->mc_info.audioObjectType,
+                             pInputStream,
+                             (Bool)common_window,
+                             (WINDOW_SEQUENCE *) & pChVars[LEFT]->wnd,
+                             (WINDOW_SHAPE *) & pChVars[LEFT]->wnd_shape_this_bk,
+                             pChLeftShare->group,
+                             (Int *) & pChLeftShare->max_sfb,
+                             pVars->winmap,
+                             (LT_PRED_STATUS *) & pChLeftShare->lt_status,
+                             (LT_PRED_STATUS *) & pChRightShare->lt_status);
+
+                if (status == SUCCESS)
+                {
+                    /* copy left channel info to right channel */
+                    pChVars[RIGHT]->wnd = pChVars[LEFT]->wnd;
+                    pChVars[RIGHT]->wnd_shape_this_bk =
+                        pChVars[LEFT]->wnd_shape_this_bk;
+                    pChRightShare->max_sfb = pChLeftShare->max_sfb;
+                    pv_memcpy(
+                        pChRightShare->group,
+                        pChLeftShare->group,
+                        NSHORT*sizeof(pChLeftShare->group[0]));
+
+                    hasmask = getmask(
+                                  pVars->winmap[pChVars[LEFT]->wnd],
+                                  pInputStream,
+                                  pChLeftShare->group,
+                                  pChLeftShare->max_sfb,
+                                  pVars->mask);
+
+                    if (hasmask == MASK_ERROR)
+                    {
+                        status = 1; /* ERROR code */
+                    }
+                    pVars->hasmask  = hasmask;
+
+                } /* if (status == 0) */
+            }
+            else
+            {
+                pVars->hasmask  = 0;
+            } /* if (common_window) */
+
+        } /* if (id_syn_ele) */
+
+    } /* if (status) */
+
+    ch = 0;
+    while ((ch < num_channels) && (status == SUCCESS))
+    {
+        pChLeftShare = pChVars[ch]->pShareWfxpCoef;
+
+        status = getics(
+                     pInputStream,
+                     common_window,
+                     pVars,
+                     pChVars[ch],
+                     pChLeftShare->group,
+                     &pChLeftShare->max_sfb,
+                     pChLeftShare->cb_map,
+                     &pChLeftShare->tns,
+                     pVars->winmap,
+                     &pVars->share.a.pulseInfo,
+                     pVars->share.a.sect);
+
+        ch++;
+
+    } /* while (ch) */
+
+    /*----------------------------------------------------------------------------
+    ; Return status
+    ----------------------------------------------------------------------------*/
+
+    return status;
+
+} /* huffdecode */
+
diff --git a/media/libstagefright/codecs/aacdec/hufffac.cpp b/media/libstagefright/codecs/aacdec/hufffac.cpp
new file mode 100644
index 0000000..e5a9c59
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/hufffac.cpp
@@ -0,0 +1,550 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/hufffac.c
+ Funtions:
+    hufffac
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description: (1) Modified with new templates,
+              (2) Modified variable names for clarity
+              (3) adjusted variables of "for loop"
+              (4) eliminated multiple returns, use return valid
+
+ Description: (1) Change return logic: 0 if success, 1 if error
+              (2) Define SectInfo structure to store section codebook index
+                  and section boundary
+              (3) Substitute "switch" with "if- else if"
+              (4) move BITS *pInputStream to second pass-in parameter
+              (5) pass in huffBookUsed[] to save stack size
+
+ Description: (1) Remove pass in parameter Hcb pBook
+
+ Description: Use binary tree search in decode_huff_cw_binary
+
+ Description: Use decode_huff_scl function.
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    *pFrameInfo     = pointer to structure that holds information
+                      of each Frame. type FrameInfo
+
+    *pInputStream   = pointer to input bitstream. type BITS
+
+    *pGroup         = pointer to array that contains the index of the first
+                      window in each group, type UChar
+
+    nsect           = number of sections to be decoded. type Int
+
+    *pSect          = pointer to structure array that contains the huffman
+                      codebook index and section boundary for each section,
+                      type SectInfo
+
+    global_gain     = initial value for "DPCM encoded" scalefactors and noise
+                      energy, type Int
+
+    *pFactors       = pointer to array that stores the decoded scalefactors,
+                      intensity position or noise energy, type Int
+
+    huffBookUsed    = array that will hold the huffman codebook index for
+                      each sfb, type Int
+
+    *pBook          = pointer to structure that contains the huffman codebook
+                      information, such as dimension, Largest Absolute Value
+                      (LAV) of each huffman codebook, etc. type Hcb
+
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+         0 if success
+         1 if error
+
+ Pointers and Buffers Modified:
+
+        Int   *pFactors    contains the newly decoded scalefactors and/or
+                             intensity position and/or noise energy level
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function first reads the Huffman codebook index of all sections within
+ one Frame. Then, depending on the huffman codebook index of each section,
+ the function decodes the scalefactors, and/or intensity positions
+ (INTENSITY_HCB, INTENSITY_HCB2), and/or noise energy (NOISE_HCB)
+ for every scalefactor band in each section.
+ The function returns 0 upon successful decoding, returns 1 if error.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should replace the content of the array pFactors with the
+ decoded scalefactors and/or intensity positions and/or noise energy
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+     Subpart 4      p72-73  (scalefactors)
+                    p76     (decoding)
+                    p78     (Table 4.6.1, Table 4.6.2)
+                    p93-94  (INTENSITY_HCB)
+                    p123    (NOISE_HCB)
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ status = SUCCESS;
+
+ CALL pv_memset(pHuffBookUsed, ZERO_HCB, MAXBANDS*sizeof(*pHuffBookUsed));
+
+ CALL pv_memset(pFactors, ZERO_HCB, MAXBANDS*sizeof(*pFactors));
+
+ sect_start       = 0;
+
+ FOR(sect_idx = nsect; sect_idx > 0; sect_idx--)
+ {
+     sect_cb  = pSect->sect_cb;
+     sect_end = pSect->sect_end;
+     pSect++;
+
+     CALL pv_memset(
+        &pHuffBookUsed[sect_start],
+        sect_cb,
+        (sect_end - sect_start));
+
+ }
+ ENDFOR
+
+    fac       = global_gain;
+    is_pos    = 0;
+    noise_nrg = global_gain - NOISE_OFFSET;
+
+    pTable    = pBook[BOOKSCL].pTable;
+    group_win  = 0;
+    group_end  = 0;
+
+    WHILE((group_end < pFrameInfo->num_win)&&(status == SUCCESS))
+    {
+        nsfb_win  = pFrameInfo->sfb_per_win[group_end];
+        group_end = *pGroup++;
+
+        FOR(sfb = 0; sfb < nsfb_win; sfb++)
+        {
+            IF ((pHuffBookUsed[sfb] > 0)&&(pHuffBookUsed[sfb] < BOOKSCL))
+            {
+                cw_index = CALL decode_huff_cw_binary(pTable, pInputStream);
+
+                fac      += cw_index - MIDFAC;
+
+                IF((fac >= 2*TEXP) || (fac < 0))
+                {
+                    status = 1;
+                }
+                ELSE
+                {
+                    pFactors[sfb] = fac;
+                }
+                ENDIF (fac)
+
+            }
+            ELSE IF (pHuffBookUsed[sfb] == ZERO_HCB)
+            {
+                do nothing;
+            }
+
+            ELSE IF ((pHuffBookUsed[sfb] == INTENSITY_HCB)||
+                     (pHuffBookUsed[sfb] == INTENSITY_HCB2))
+            {
+                cw_index = CALL decode_huff_cw_binary(pTable, pInputStream);
+
+                is_pos        += cw_index - MIDFAC;
+                pFactors[sfb] =  is_pos;
+            }
+
+            ELSE IF (pHuffBookUsed[sfb] == NOISE_HCB)
+            {
+                IF (noise_pcm_flag == TRUE)
+                {
+                    noise_pcm_flag = FALSE;
+                    dpcm_noise_nrg = CALL getbits(
+                                              NOISE_PCM_BITS,
+                                              pInputStream);
+
+                    dpcm_noise_nrg -= NOISE_PCM_OFFSET;
+                }
+                ELSE
+                {
+                    dpcm_noise_nrg = CALL decode_huff_cw_binary(
+                                              pTable,
+                                              pInputStream);
+
+                    dpcm_noise_nrg -= MIDFAC;
+                }
+                ENDIF (noise_pcm_flag)
+
+                noise_nrg       += dpcm_noise_nrg;
+                pFactors[sfb]   =  noise_nrg;
+            }
+
+            ELSE IF (pHuffBookUsed[sfb] == BOOKSCL)
+            {
+                status = 1;
+            }
+            ENDIF (pHuffBookUsed[sfb])
+
+        }
+        ENDFOR (sfb)
+
+        IF (pFrameInfo->islong == FALSE)
+        {
+
+            FOR(group_win++; group_win < group_end; group_win++)
+            {
+                FOR (sfb=0; sfb < nsfb_win; sfb++)
+                {
+                    pFactors[sfb + nsfb_win]  =  pFactors[sfb];
+                }
+                ENDFOR
+
+                pFactors  +=  nsfb_win;
+            }
+            ENDFOR
+
+        }
+        ENDIF (pFrameInfo)
+
+        pHuffBookUsed   += nsfb_win;
+        pFactors        += nsfb_win;
+
+    }
+    ENDWHILE (group_end)
+
+    return status;
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "aac_mem_funcs.h"       /* pv_memset */
+#include    "s_frameinfo.h"
+#include    "s_bits.h"
+#include    "s_sectinfo.h"
+#include    "s_huffman.h"
+#include    "ibstream.h"
+
+#include    "hcbtables.h"
+#include    "e_huffmanconst.h"
+#include    "e_infoinitconst.h"
+#include    "huffman.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
+----------------------------------------------------------------------------*/
+Int hufffac(
+    FrameInfo   *pFrameInfo,
+    BITS        *pInputStream,
+    Int         *pGroup,    /* may be changed to Int */
+    Int         nsect,
+    SectInfo    *pSect,     /* may be changed to Int */
+    Int         global_gain,
+    Int         *pFactors,
+    Int         huffBookUsed[])
+{
+    Int     sect_idx;
+    Int     group_end;  /* index of 1st window in next group */
+    Int     group_win;  /* window index within group */
+    Int     cw_index;   /* huff codeword index */
+    Int     nsfb_win;   /* # of scfbands per window */
+    Int     sfb;        /* scalefactor band index */
+    Int     sect_cb;    /* huff codebook # for each section */
+    Int     fac;        /* decoded scf */
+    Int     is_pos;     /* intensity stereo position */
+    Int     noise_pcm_flag = TRUE;  /* first PNS sfb */
+    Int     dpcm_noise_nrg;     /* dpcm noise energy */
+    Int     noise_nrg;      /* noise energy */
+    Int     status = SUCCESS;  /* status of decoding */
+    Int     *pHuffBookUsed = &huffBookUsed[0];
+
+
+    pv_memset(pFactors,
+              ZERO_HCB,
+              MAXBANDS*sizeof(*pFactors));
+
+
+    if (nsect)
+    {
+        /* read section length and codebook */
+
+        if (nsect == 1) /* long window */
+        {
+            sect_cb  = pSect->sect_cb;  /* codebook for this section */
+
+            /* all sfbs in one section share the same codebook */
+
+            for (sfb = pSect->sect_end >> 2; sfb != 0; sfb--)
+            {
+                *(pHuffBookUsed++) = sect_cb;
+                *(pHuffBookUsed++) = sect_cb;
+                *(pHuffBookUsed++) = sect_cb;
+                *(pHuffBookUsed++) = sect_cb;
+            }
+            for (sfb = pSect->sect_end & 3; sfb != 0; sfb--)
+            {
+                *(pHuffBookUsed++) = sect_cb;
+            }
+
+        }
+        else            /* short */
+        {
+            Int sect_start = 0; /* start index of sfb for each section */
+            for (sect_idx = nsect; sect_idx > 0; sect_idx--)
+            {
+                sect_cb  = pSect->sect_cb;  /* codebook for this section */
+
+                /* all sfbs in one section share the same codebook */
+                for (sfb = sect_start; sfb < pSect->sect_end; sfb++)
+                {
+                    pHuffBookUsed[sfb] = sect_cb;
+                }
+
+                pSect++;
+                sect_start = sfb;
+
+            } /* for (sect_idx) */
+        }
+    }
+    else
+    {
+        /* clear array for the case of max_sfb == 0 */
+        pv_memset(pHuffBookUsed,
+                  ZERO_HCB,
+                  MAXBANDS*sizeof(*pHuffBookUsed));
+    }
+
+    pHuffBookUsed = &huffBookUsed[0];
+
+    /* scale factors and noise energy are dpcm relative to global gain
+     * intensity positions are dpcm relative to zero
+     */
+    fac       = global_gain;
+    is_pos    = 0;
+    noise_nrg = global_gain - NOISE_OFFSET;
+
+    /* get scale factors,
+     * use reserved Table entry = 12, see reference (2) p78 Table 4.6.2
+     */
+    group_win  = 0;
+    group_end  = 0;
+
+
+    /* group by group decoding scalefactors and/or noise energy
+     * and/or intensity position
+     */
+    while ((group_end < pFrameInfo->num_win) && (status == SUCCESS))
+    {
+        nsfb_win  = pFrameInfo->sfb_per_win[group_end];
+        group_end = *pGroup++;  /* index of 1st window in next group */
+
+        /* decode scf in first window of each group */
+
+        for (sfb = 0; sfb < nsfb_win; sfb++)
+        {
+
+            switch (pHuffBookUsed[sfb])
+            {
+                case ZERO_HCB:
+                    break;
+                case INTENSITY_HCB:
+                case INTENSITY_HCB2:
+                    /* intensity books */
+                    /* decode intensity position */
+                    cw_index = decode_huff_scl(pInputStream);
+
+                    is_pos        += cw_index - MIDFAC;
+                    pFactors[sfb] =  is_pos;
+                    break;
+                case NOISE_HCB:
+                    /* noise books */
+                    /* decode noise energy */
+                    if (noise_pcm_flag == TRUE)
+                    {
+                        noise_pcm_flag = FALSE;
+                        dpcm_noise_nrg = get9_n_lessbits(NOISE_PCM_BITS,
+                                                         pInputStream);
+
+                        dpcm_noise_nrg -= NOISE_PCM_OFFSET;
+                    }
+                    else
+                    {
+                        dpcm_noise_nrg = decode_huff_scl(pInputStream);
+
+                        dpcm_noise_nrg -= MIDFAC;
+                    } /* if (noise_pcm_flag) */
+
+                    noise_nrg       += dpcm_noise_nrg;
+                    pFactors[sfb]   =  noise_nrg;
+                    break;
+                case BOOKSCL:
+                    status = 1; /* invalid books */
+                    sfb = nsfb_win;  /* force out */
+                    break;
+                default:
+                    /* spectral books */
+                    /* decode scale factors */
+                    cw_index = decode_huff_scl(pInputStream);
+
+                    fac      += cw_index - MIDFAC;   /* 1.5 dB */
+                    if ((fac >= 2*TEXP) || (fac < 0))
+                    {
+                        status = 1;   /* error, MUST 0<=scf<256, Ref. p73 */
+                    }
+                    else
+                    {
+                        pFactors[sfb] = fac;  /* store scf */
+                    } /* if (fac) */
+            }
+
+        } /* for (sfb=0), first window decode ends */
+
+        /* expand scf to other windows in the same group */
+        if (pFrameInfo->islong == FALSE)
+        {
+
+            for (group_win++; group_win < group_end; group_win++)
+            {
+                for (sfb = 0; sfb < nsfb_win; sfb++)
+                {
+                    pFactors[sfb + nsfb_win]  =  pFactors[sfb];
+                }
+                pFactors  +=  nsfb_win;
+            }
+
+        } /* if (pFrameInfo->islong), one group decode ends */
+
+
+        /* points to next group */
+        pHuffBookUsed   += nsfb_win;
+        pFactors        += nsfb_win;
+
+    } /* while (group_end), all groups decode end */
+
+    return status;
+
+} /* hufffac */
+
diff --git a/media/libstagefright/codecs/aacdec/huffman.h b/media/libstagefright/codecs/aacdec/huffman.h
new file mode 100644
index 0000000..030ae23
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/huffman.h
@@ -0,0 +1,241 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: .huffman.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put declaration of getfill in this file.
+
+ Description: Remove prstflag from get_ics_info declaration.
+
+ Description: Trivial change of the data type of one of the parameters to
+              get_ics_info.
+
+ Description: Change where get_ics_info is declared.
+
+ Description: Clean up comments
+
+ Description: (1) Add declaration of binary tree search function for Huffman
+                  decoding
+              (2) #if the traditional and optimized linear seach methods.
+
+ Description: Modified per review comments
+              (1) delete #if traditional and optimized linear seach methods
+
+ Description: Merged Ken's change on getics: delete pFrameInfo from argument
+              list
+
+ Description: Added function definition for table specific huffman decoding
+              functions.
+
+ Who:                                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ include function prototype definitions for Huffman decoding module
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef HUFFMAN_H
+#define HUFFMAN_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_frameinfo.h"
+#include    "s_sectinfo.h"
+#include    "s_pulseinfo.h"
+#include    "s_tdec_int_file.h"
+#include    "s_tdec_int_chan.h"
+#include    "ibstream.h"
+
+#include    "s_hcb.h"
+#include    "hcbtables.h"
+
+#include    "get_pulse_data.h"
+#include    "get_ics_info.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define DIMENSION_4     4
+#define DIMENSION_2     2
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    Int decode_huff_cw_tab1(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab2(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab3(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab4(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab5(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab6(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab7(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab8(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab9(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab10(
+        BITS *pInputStream);
+
+    Int decode_huff_cw_tab11(
+        BITS *pInputStream);
+
+    Int decode_huff_scl(
+        BITS          *pInputStream);
+
+    Int infoinit(
+        const  Int sampling_rate_idx,
+        FrameInfo   **ppWin_seq_info,
+        Int    *pSfbwidth128);
+
+    Int huffcb(
+        SectInfo *pSect,
+        BITS     *pInputStream,
+        Int      *pSectbits,
+        Int       tot_sfb,
+        Int       sfb_per_sbk,
+        Int       max_sfb);
+
+    Int hufffac(
+        FrameInfo   *pFrameInfo,
+        BITS        *pInputStream,
+        Int         *pGroup,
+        Int          nsect,
+        SectInfo    *pSect,
+        Int          global_gain,
+        Int         *pFactors,
+        Int          huffBookUsed[]);
+
+    Int huffspec_fxp(
+        FrameInfo *pFrameInfo,
+        BITS      *pInputStream,
+        Int       nsect,
+        SectInfo  *pSectInfo,
+        Int       factors[],
+        Int32     coef[],
+        Int16     quantSpec[],
+        Int16     tmp_spec[],
+        const FrameInfo  *pLongFrameInfo,
+        PulseInfo  *pPulseInfo,
+        Int         qFormat[]);
+
+    Int huffdecode(
+        Int           id_syn_ele,
+        BITS          *pInputStream,
+        tDec_Int_File *pVars,
+        tDec_Int_Chan *pChVars[]);
+
+    void deinterleave(
+        Int16          interleaved[],
+        Int16        deinterleaved[],
+        FrameInfo   *pFrameInfo);
+
+    Int getics(
+
+        BITS            *pInputStream,
+        Int             common_window,
+        tDec_Int_File   *pVars,
+        tDec_Int_Chan   *pChVars,
+        Int             group[],
+        Int             *pMax_sfb,
+        Int             *pCodebookMap,
+        TNS_frame_info  *pTnsInfo,
+        FrameInfo       **pWinMap,
+        PulseInfo       *pPulseInfo,
+        SectInfo        sect[]);
+
+    void  calc_gsfb_table(
+        FrameInfo   *pFrameInfo,
+        Int         group[]);
+
+    Int getmask(
+        FrameInfo   *pFrameInfo,
+        BITS        *pInputStream,
+        Int         *pGroup,
+        Int         max_sfb,
+        Int         *pMask);
+
+    void getgroup(
+        Int         group[],
+        BITS        *pInputStream);
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/huffspec_fxp.cpp b/media/libstagefright/codecs/aacdec/huffspec_fxp.cpp
new file mode 100644
index 0000000..b18c12d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/huffspec_fxp.cpp
@@ -0,0 +1,671 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname:  huffspec_fxp.c
+ Funtions:
+    huffspec_fxp
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description: (1) Modified to keep in-line with PV standards
+              (2) Eliminated "continue" in if(sect_cb==ZERO_HCB||...)
+
+ Description: (1) Use SectInfo *pSect
+              (2) Convert 'Real' to 'Int32', float -> fixed-point
+              (3) move BITS *pInputStream to second parameter
+              (4) pass in quantSpec and tmp_spec, scratch shared with hufffac
+              (5) pass in FrameInfo *pLongFrameInfo, eliminate only_long_info
+
+ Description: (1) Eliminate parameter Hcb *book, because of eliminating
+                  function 'hufftab.c', Hcb hcbbook defined as a
+                  const structure in 'hcbtables.h'.
+              (2) Replace three nested 'for' loops with a for-while loop in
+                  the rescaling part.
+              (3) Change esc_iquant-> esc_iquant_fxp, call esc_iquant_fxp()
+                  by sfb
+
+ Description: Cleaned up include files.
+
+ Description:  Correct definition of stack variable "scale".
+        It was defined as Int, but it receives an UInt value,
+        this present a problem when Int is 16 bits and
+        the sign bit is not interpreted correctly. This does not
+        shows for 32-bit implementations. This problem manifest itself
+        as a flipping sign on some spectral coefficients (the ones
+        multiplied by 0x8000).
+
+ Description: Typecast b_low and b_high to 32-bits before multiplication, this
+              assures propoer compilation on a 16-bit platform (TI-C55x)
+
+ Description: Modified to speed up decode_huff_cw
+
+ Description: pass codebook index to decode_huff_cw, delete pointer to Huffman
+              structure
+
+ Description: keep memset to quantSpec, remove memset to temp_spec
+
+ Description: Modified per review comments
+
+ Description: Use Binary tree search in decode_huff_cw_binary
+
+ Description: Modified per review comments
+              (1) delete unused codes
+
+ Description: (1) Change the interface to decode huffman codeword.
+              (2) Move the scaling inside the inverse quantization.
+              (3) Change scaling factor accuracy to 10 bits.
+
+ Description:
+              (1) delete unused variable max_fac
+
+ Description: Addresses of huffman tables are now found by means of a
+              switch statement, this solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pFrameInfo  = ptr to structure that holds Information of current Frame,
+                  type FrameInfo
+
+    pInputStream = ptr to structure of bitstream, type BITS
+
+    nsect       = number of sections in current Frame, at fs = 44.1 kHz,
+                  range [0, 49] long block, [0,112] short blocks. type Int
+
+    pSect       = ptr to structure that holds section codebook and boundary
+                  type SectInfo
+
+    factors[]   = array that contains scalefactors for each sfb, type Int16
+
+    coef[]      = array that holds inverse quantized coefs, Int32 QFormat.
+
+    quantSpec[] = array that holds quantized spectral coefs, type Int
+
+    tmp_spec[]  = temporary buffer to hold the de-interleaved coefs.
+
+    pLongFrameInfo = ptr to structure that holds long frame info
+
+ Local Stores/Buffers/Pointers Needed:
+    exptable = array contains the Q15 format data for 2^0, 2^0.25, 2^0.5,
+               and 2^0.75, type const Int.
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+
+    return 0 if decoding properly.
+
+ Pointers and Buffers Modified:
+
+    pInputStream    read codeword index and/or sign bits and/or ESC value
+
+    coef            contains the newly inverse quantized 1024 spec coefs,
+                    type Int32 Q-format from esc_iquant()
+
+    quantSpec       contains decoded quantized 1024 spec coefs, type Int
+
+    tmp_spec        contains the de-interleaved version of quantSpec
+
+    qFormat         contains Q-Format for each scalefactor band
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function first reads the section info (codebook and boundary), then
+ decode the spectral coefficients if a spectral codebook is used.
+ If necessary, get the sign bits, ESC value or the NEC_pulse data. In case of
+ short window sequences, the decoded data is de-interleaved before
+ multiplied by scalefactors.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function should set the content of the array 'coef' with the inverse
+ quantized and rescaled value of spectral coefficients.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart (4)         p56 (spectral_data() parsing and decoding)
+                        p26 (Syntax of spectral_data())
+                        p74-78 (decoding: unpack_idx, get_sign_bits,
+                                getescape, pulse_nc, deinterleave)
+                        p72 (inverse quantization: esc_iquant)
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "aac_mem_funcs.h"
+#include    "esc_iquant_scaling.h"
+#include    "huffman.h"
+#include    "unpack_idx.h"
+#include    "pulse_nc.h"
+#include    "iquant_table.h"
+#include    "e_huffmanconst.h"
+
+
+#include "pv_normalize.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define ORDER        (3)
+
+/*
+ * Format the table is stored in.
+ */
+#define QTABLE       (27)
+
+/*
+ * Number of bits for data in a signed 32 bit integer.
+ */
+#define SIGNED32BITS  (31)
+
+/*
+ * Round up value for intermediate values obtained from the table
+ */
+#define ROUND_UP (( ((UInt32) 1) << (QTABLE) )-1)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const UInt16 exptable[4] =
+{
+    0,  /* (2^0.00)<<15 (Q10), use zero to signal no scaling required! */
+    19485,  /* (2^0.25)<<15 */
+    23171,  /* (2^0.50)<<15 */
+    27555   /* (2^0.75)<<15 */
+
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int huffspec_fxp(
+    FrameInfo *pFrameInfo,
+    BITS      *pInputStream,
+    Int       nsect,
+    SectInfo  *pSectInfo,
+    Int       factors[],
+    Int32     coef[],
+    Int16     quantSpec[],
+    Int16     tmp_spec[],
+    const FrameInfo  *pLongFrameInfo,
+    PulseInfo  *pPulseInfo,
+    Int         qFormat[])
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    const Hcb       *pHcb;
+    Int     i;
+    Int     sfb;
+    Int     idx_count;
+    Int     sect_cb;    /* section codebook */
+    Int     dim;
+    Int     idx;
+    Int     stop_idx;     /* index of 1st coef in next sfb */
+    Int     sect_start;   /* start index of sfb in one section*/
+    Int     sect_end;     /* index of 1st sfb in next section */
+    Int     *pSfbStart;
+    Int     *pSfb;
+    Int16     *pQuantSpec;        /* probably could be short */
+    Int     max = 0;
+    /* rescaling parameters */
+    Int     nsfb;
+    Int     tot_sfb;
+    Int     fac;
+
+    Int32   *pCoef; /* ptr to coef[], inverse quantized coefs */
+    UInt16     scale;
+
+    Int     power_scale_div_4;
+    Int     sfbWidth;
+
+    void (*pUnpack_idx)(
+        Int16  quant_spec[],
+        Int  codeword_indx,
+        const Hcb *pHuffCodebook,
+        BITS  *pInputStream,
+        Int *max);
+
+    Int(*pDec_huff_tab)(BITS *) = NULL;
+
+    UInt32 temp;
+    Int    binaryDigits, QFormat;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    sect_start = 0;
+    stop_idx   = 0;
+
+    /* pSfb: ptr to array that holds stop index of each sfb */
+    pSfbStart = pFrameInfo->frame_sfb_top;
+
+    if (pSfbStart == NULL)
+    {
+        return (-1);   /*  error condition */
+    }
+
+    pSfb      = pSfbStart;
+
+    /* decoding spectral values section by section */
+    for (i = nsect; i > 0; i--)
+    {
+        /* read the codebook and section length */
+        sect_cb  =  pSectInfo->sect_cb;     /* codebook */
+        if ((sect_cb > 15) || (sect_cb < 0))
+        {
+            return (-1);   /*  error condition */
+        }
+        sect_end =  pSectInfo->sect_end;    /* # of sfbs */
+
+        if (sect_end < 0)
+        {
+            return (-1);   /*  error condition */
+        }
+
+        pSectInfo++;
+
+        /*  sect_cb       sect_cb - 1
+         *  ZERO_HCB        1111b
+         *    1             0000b
+         *    2             0001b
+         *    3             0010b
+         *    4             0011b
+         *    5             0100b
+         *    6             0101b
+         *    7             0110b
+         *    8             0111b
+         *    9             1000b
+         *    10            1001b
+         *    11            1010b
+         *    12            1011b
+         * NOISE_HCB        1100b
+         * INTENSITY_HCB2   1101b
+         * INTENSITY_HCB    1110b
+         * if ( ((sect_cb - 1) & 0xC) == 0xC ) is identical to
+         * if !((sect_cb == ZERO_HCB) || (sect_cb == NOISE_HCB) ||
+         *      (sec_cb == INTENSITY_HCB) || (sect_cb==INTENSITY_HCB2) )
+         * use this compare scheme to speed up the execution
+         */
+
+        if (((sect_cb - 1) & 0xC) != 0xC)
+        {
+            /* decode spec in one section */
+            if (sect_cb > BY4BOOKS)
+            {
+                dim = DIMENSION_2; /* set codebook dimension */
+            }
+            else
+            {
+                dim = DIMENSION_4;
+            }
+
+            pHcb        = &hcbbook_binary[sect_cb];
+
+            if (sect_cb == ESCBOOK)
+            {
+                pUnpack_idx = &unpack_idx_esc;
+            }
+            else if (pHcb->signed_cb == FALSE)
+            {
+                pUnpack_idx = &unpack_idx_sgn;
+            }
+            else
+            {
+                pUnpack_idx = &unpack_idx;
+            }
+
+
+            switch (sect_cb)
+            {
+                case 1:
+                    pDec_huff_tab = decode_huff_cw_tab1;
+                    break;
+                case 2:
+                    pDec_huff_tab = decode_huff_cw_tab2;
+                    break;
+                case 3:
+                    pDec_huff_tab = decode_huff_cw_tab3;
+                    break;
+                case 4:
+                    pDec_huff_tab = decode_huff_cw_tab4;
+                    break;
+                case 5:
+                    pDec_huff_tab = decode_huff_cw_tab5;
+                    break;
+                case 6:
+                    pDec_huff_tab = decode_huff_cw_tab6;
+                    break;
+                case 7:
+                    pDec_huff_tab = decode_huff_cw_tab7;
+                    break;
+                case 8:
+                    pDec_huff_tab = decode_huff_cw_tab8;
+                    break;
+                case 9:
+                    pDec_huff_tab = decode_huff_cw_tab9;
+                    break;
+                case 10:
+                    pDec_huff_tab = decode_huff_cw_tab10;
+                    break;
+                case 11:
+                    pDec_huff_tab = decode_huff_cw_tab11;
+                    break;
+                default:
+                    return (-1); /* error condition */
+            }
+
+            /* move ptr to first sfb of current section */
+            pQuantSpec  = quantSpec + stop_idx;
+
+            /* step through all sfbs in current section */
+            for (sfb = sect_start; sfb < sect_end; sfb++)
+            {
+                idx_count = *pSfb - stop_idx;
+                stop_idx  = *pSfb++;
+
+                /* decode all coefs for one sfb */
+                while ((idx_count > 0) && (idx_count < 1024))
+                {
+
+                    idx = (*pDec_huff_tab)(pInputStream);
+
+                    (*pUnpack_idx)(pQuantSpec,
+                                   idx,
+                                   pHcb,
+                                   pInputStream,
+                                   &max);      /* unpack idx -> coefs */
+
+                    pQuantSpec += dim;
+                    idx_count  -= dim;
+
+                } /* while(idx_count) */
+
+            } /* for (sfb=sect_start) */
+        }
+        else
+        {
+
+            /* current section uses ZERO_HCB, NOISE_HCB, etc */
+
+            /* move sfb pointer to the start sfb of next section */
+            pSfb        = pSfbStart + sect_end;
+            /* number of coefs in current section */
+            idx_count   = *(pSfb - 1) - stop_idx;
+
+            if ((idx_count > 1024) || (idx_count < 0))
+            {
+                return (-1);   /*  error condition */
+            }
+
+            /*
+             * This memset is necessary in terms of (1) net savings in total
+             * MIPS and (2) accurate Q-Formats for fft_rx2
+             * In case a scalefactor band uses ZERO_HCB, all coefficients of
+             * that sfb should be zeros. Without this call to memset, the
+             * coefficients for a ZERO_HCB sfb are the "leftovers" of the
+             * previous frame, which may not have all zero values. This leads
+             * to a drastical increase in the cycles consumed by esc_iquant_fxp
+             * and fft_rx2, which is the most "expensive" function of the
+             * library.
+             * This memset also guarantees the Q_Format for sfbs with all zero
+             * coefficients will be set properly.
+             * Profiling data on ARM and TMS320C55x proves that there is a net
+             * gain in total MIPS if a memset is called here.
+             */
+            pv_memset(&quantSpec[stop_idx],
+                      0,
+                      idx_count * sizeof(quantSpec[0]));
+
+            /*
+             * This memset is called because pQuantSpec points to tmp_spec
+             * after deinterleaving
+             */
+
+            pv_memset(&tmp_spec[stop_idx],
+                      0,
+                      idx_count * sizeof(tmp_spec[0]));
+
+
+            /* stop_idx is the index of the 1st coef of next section */
+            stop_idx    = *(pSfb - 1);
+
+        }/* if (sect_cb) */
+
+        sect_start = sect_end;
+
+    } /* for (i=nsect) */
+
+    /* noisless coding reconstruction */
+    if (pFrameInfo->islong != FALSE)
+    {
+        if (pPulseInfo->pulse_data_present == 1)
+        {
+            pulse_nc(quantSpec,
+                     pPulseInfo,
+                     pLongFrameInfo,
+                     &max);    /* add pulse data */
+        }
+
+        pQuantSpec = quantSpec;
+
+    }
+    else
+    {
+        deinterleave(quantSpec,
+                     tmp_spec,
+                     pFrameInfo);
+
+        pQuantSpec = tmp_spec;
+    }
+
+
+    /* inverse quantization, Q_format: Int32 */
+    /* rescaling */
+
+    /* what we can do here is assuming that we already know maxInput for each band, we have to go
+    though each one of them for re-quant and scaling, and pick the right qFormat to apply to
+    all spectral coeffs.*/
+
+    if ((max < 0) || (max > 8192))    /* (8192>>ORDER) == 1024 is the inverseQuantTable size */
+    {
+        return (-1);   /*  error condition */
+    }
+    else
+    {
+        /* Get  (max/SPACING) ^ (1/3), in Q Format  */
+        temp = inverseQuantTable[(max >> ORDER) + 1];
+    }
+
+
+    /* Round up before shifting down to Q0 */
+    temp += ROUND_UP;
+
+    /* shift down to Q0 and multiply by 2 (FACTOR) in one step */
+    temp >>= (QTABLE - 1);
+
+    /* Now get max ^ (4/3) in Q0 */
+    temp *= max;
+
+
+    binaryDigits = 31 - pv_normalize(temp);
+
+
+    /* Prevent negative shifts caused by low maximums. */
+    if (binaryDigits < (SIGNED32BITS - QTABLE))
+    {
+        binaryDigits = SIGNED32BITS - QTABLE;
+    }
+
+    QFormat = SIGNED32BITS - binaryDigits;
+
+    /********************/
+    tot_sfb = 0;
+    nsfb = pFrameInfo->sfb_per_win[0];
+    pCoef = coef;
+
+    for (i = pFrameInfo->num_win; i > 0; i--)
+    {
+        stop_idx  = 0;
+
+        for (sfb = 0; sfb < nsfb; sfb++)
+        {
+            sfbWidth   =  pFrameInfo->win_sfb_top[0][sfb] - stop_idx;
+
+            if ((sfbWidth < 0) || (sfbWidth > 1024))
+            {
+                return (-1);   /*  error condition */
+            }
+
+            stop_idx  += sfbWidth;
+
+            fac   = factors[tot_sfb] - SF_OFFSET;
+            scale = exptable[fac & 0x3];
+
+            power_scale_div_4 = fac >> 2;
+
+            power_scale_div_4++;
+
+            qFormat[tot_sfb] = QFormat;
+
+            esc_iquant_scaling(pQuantSpec,
+                               pCoef,
+                               sfbWidth,
+                               QFormat,
+                               scale,
+                               max);
+
+            pQuantSpec += sfbWidth;
+            qFormat[tot_sfb] -= power_scale_div_4;
+            pCoef += sfbWidth;
+
+            tot_sfb++;
+
+        } /* for (sfb) */
+    } /* for (i) */
+
+
+    /*----------------------------------------------------------------------------
+    ; Return status
+    ----------------------------------------------------------------------------*/
+    return SUCCESS;
+
+} /* huffspec_fxp */
diff --git a/media/libstagefright/codecs/aacdec/ibstream.h b/media/libstagefright/codecs/aacdec/ibstream.h
new file mode 100644
index 0000000..8b644dc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ibstream.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ibstream.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change names of constants.
+
+ Description: Change the buffer from UInt to UInt32
+
+ Description: Remove declaration of getbits and include header file
+
+ Description: Change input buffer to UChar
+              Add constant
+
+ Who:                                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Contains defines, structures, and function definitions for the
+ input bit stream used in the AAC Decoder.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef IBSTREAM_H
+#define IBSTREAM_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bits.h"
+#include    "getbits.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+#define INBUF_ARRAY_INDEX_SHIFT  (3)
+#define INBUF_BIT_WIDTH         (1<<(INBUF_ARRAY_INDEX_SHIFT))
+#define INBUF_BIT_MODULO_MASK   ((INBUF_BIT_WIDTH)-1)
+
+#define MAX_GETBITS             (25)
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void byte_align(
+        BITS  *pInputStream);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif /* IBSTREAM_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/idct16.cpp b/media/libstagefright/codecs/aacdec/idct16.cpp
new file mode 100644
index 0000000..324fe9e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct16.cpp
@@ -0,0 +1,204 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: idct16.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 16
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement inverse discrete cosine transform of lenght 16
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "idct16.h"
+#include "idct8.h"
+
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+#define R_SHIFT     28
+#define Qfmt(x)     (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+#define Qfmt31(x)   (Int32)(x*(0x7FFFFFFF) + (x>=0?0.5F:-0.5F))
+
+const Int32 CosTable_8i[8] =
+{
+    Qfmt31(0.50241928618816F),   Qfmt31(0.52249861493969F),
+    Qfmt31(0.56694403481636F),   Qfmt31(0.64682178335999F),
+    Qfmt(0.78815462345125F),   Qfmt(1.06067768599035F),
+    Qfmt(1.72244709823833F),   Qfmt(5.10114861868916F)
+};
+
+
+
+/*----------------------------------------------------------------------------
+; 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 idct_16(Int32 vec[], Int32 scratch_mem[])    /* scratch_mem size 8 */
+{
+    Int32 *temp_even = scratch_mem;
+
+    Int32 i;
+    const Int32 *pt_cos = CosTable_8i;
+    Int32 tmp1, tmp2;
+    Int32 *pt_even = temp_even;
+    Int32 *pt_odd  = vec;
+    Int32 *pt_vec  = vec;
+
+    Int32 tmp3;
+    Int32 *pt_vecN_1;
+
+
+    *(pt_even++) = *(pt_vec++);
+    tmp1         = *(pt_vec++);
+    *(pt_odd++) = tmp1;
+
+    for (i = 2; i != 0; i--)
+    {
+        *(pt_even++) = *(pt_vec++);
+        tmp2         = *(pt_vec++);
+        *(pt_even++) = *(pt_vec++);
+        tmp3         = *(pt_vec++);
+        *(pt_odd++) = tmp2 + tmp1;
+        *(pt_odd++) = tmp3 + tmp2;
+        tmp1         = tmp3;
+    }
+
+    *(pt_even++) = *(pt_vec++);
+    tmp2         = *(pt_vec++);
+    *(pt_even++) = *(pt_vec++);
+    tmp3         = *(pt_vec++);
+    *(pt_odd++) = tmp2 + tmp1;
+    *(pt_odd++) = tmp3 + tmp2;
+
+
+    *(pt_even)   = *(pt_vec++);
+    *(pt_odd++) = *(pt_vec) + tmp3;
+
+
+    idct_8(temp_even);
+    idct_8(vec);
+
+
+    pt_cos = &CosTable_8i[7];
+
+    pt_vec  = &vec[7];
+
+    pt_even = &temp_even[7];
+    pt_vecN_1  = &vec[8];
+
+    tmp1 = *(pt_even--);
+
+    for (i = 2; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q28(*(pt_vec), *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp1 - tmp3;
+        *(pt_vec--)     = tmp1 + tmp3;
+        tmp3  = fxp_mul32_Q28(*(pt_vec), *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp2 - tmp3;
+        *(pt_vec--)     = tmp2 + tmp3;
+    }
+
+    tmp3  = fxp_mul32_Q31(*(pt_vec), *(pt_cos--)) << 1;
+    tmp2 = *(pt_even--);
+    *(pt_vecN_1++)  = tmp1 - tmp3;
+    *(pt_vec--)     = tmp1 + tmp3;
+    tmp3  = fxp_mul32_Q31(*(pt_vec), *(pt_cos--)) << 1;
+    tmp1 = *(pt_even--);
+    *(pt_vecN_1++)  = tmp2 - tmp3;
+    *(pt_vec--)     = tmp2 + tmp3;
+    tmp3  = fxp_mul32_Q31(*(pt_vec), *(pt_cos--)) << 1;
+    tmp2 = *(pt_even--);
+    *(pt_vecN_1++)  = tmp1 - tmp3;
+    *(pt_vec--)     = tmp1 + tmp3;
+    tmp3  = fxp_mul32_Q31(*(pt_vec), *(pt_cos)) << 1;
+    *(pt_vecN_1)  = tmp2 - tmp3;
+    *(pt_vec)     = tmp2 + tmp3;
+
+}
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/idct16.h b/media/libstagefright/codecs/aacdec/idct16.h
new file mode 100644
index 0000000..afade07
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct16.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Pathname: idct16.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef IDCT16_H
+#define IDCT16_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    void idct_16(Int32 vec[], Int32 scratch_mem[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* IDCT16_H */
diff --git a/media/libstagefright/codecs/aacdec/idct32.cpp b/media/libstagefright/codecs/aacdec/idct32.cpp
new file mode 100644
index 0000000..ac9773b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct32.cpp
@@ -0,0 +1,196 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Filename: idct32.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 32
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement inverse discrete cosine transform of lenght 32
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include "idct32.h"
+#include "dst32.h"
+#include "idct16.h"
+
+#include "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+
+#define R_SHIFT1     29
+#define Qfmt1(x)   (Int32)(x*((Int32)1<<R_SHIFT1) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt3(a)   (Int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+
+/*----------------------------------------------------------------------------
+; 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 idct_32(Int32 vec[], Int32 scratch_mem[])   /* scratch_mem size 32 */
+{
+    Int32 *temp_even = scratch_mem;
+
+    Int32 i;
+    const Int32 *pt_cos = CosTable_16;
+    Int32 tmp1, tmp2;
+    Int32 *pt_even = temp_even;
+    Int32 *pt_odd  = vec;
+    Int32 *pt_vec  = vec;
+    Int32 *pt_vecN_1;
+    Int32 tmp3;
+
+
+    *(pt_even++) = *(pt_vec++);
+    tmp1         = *(pt_vec++);
+    tmp2 = 0;
+
+    for (i = 7; i != 0; i--)
+    {
+        *(pt_odd++) = tmp2 + tmp1;
+        *(pt_even++) = *(pt_vec++);
+        tmp2         = *(pt_vec++);
+        *(pt_even++) = *(pt_vec++);
+        *(pt_odd++) = tmp2 + tmp1;
+        tmp1         = *(pt_vec++);
+    }
+
+    *(pt_odd++) = tmp2 + tmp1;
+    *(pt_even++) = *(pt_vec++);
+    tmp2         = *(pt_vec++);
+    *(pt_odd++) = tmp2 + tmp1;
+
+
+    idct_16(temp_even, &scratch_mem[16]);
+    idct_16(vec, &scratch_mem[24]);
+
+
+    pt_cos = &CosTable_16[13];
+
+    pt_vec  = &vec[15];
+
+    pt_even = &temp_even[15];
+    pt_vecN_1  = &vec[16];
+
+    tmp1 = *(pt_even--);
+
+
+    tmp3  = fxp_mul32_Q31(*(pt_vec) << 3, Qfmt3(0.63687550772175F)) << 2;
+    tmp2 = *(pt_even--);
+    *(pt_vecN_1++)  = tmp1 - tmp3;
+    *(pt_vec--)     = tmp1 + tmp3;
+    tmp3  = fxp_mul32_Q31(*(pt_vec) << 3, Qfmt3(0.85190210461718F));
+
+    tmp1 = *(pt_even--);
+    *(pt_vecN_1++)  = tmp2 - tmp3;
+    *(pt_vec--)     = tmp2 + tmp3;
+
+    for (i = 2; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q29(*(pt_vec), *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp1 - tmp3;
+        *(pt_vec--)     = tmp1 + tmp3;
+        tmp3  = fxp_mul32_Q29(*(pt_vec), *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp2 - tmp3;
+        *(pt_vec--)     = tmp2 + tmp3;
+    }
+
+    for (i = 5; i != 0; i--)
+    {
+        tmp3  = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_cos--));
+        tmp2 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp1 - tmp3;
+        *(pt_vec--)     = tmp1 + tmp3;
+        tmp3  = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_cos--));
+        tmp1 = *(pt_even--);
+        *(pt_vecN_1++)  = tmp2 - tmp3;
+        *(pt_vec--)     = tmp2 + tmp3;
+    }
+}
+
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/idct32.h b/media/libstagefright/codecs/aacdec/idct32.h
new file mode 100644
index 0000000..12c685a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct32.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: idct32.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef IDCT32_H
+#define IDCT32_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void idct_32(Int32 vec[], Int32 scratch_mem[]);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* IDCT32_H */
diff --git a/media/libstagefright/codecs/aacdec/idct8.cpp b/media/libstagefright/codecs/aacdec/idct8.cpp
new file mode 100644
index 0000000..8f040ce
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct8.cpp
@@ -0,0 +1,168 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: idct8.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 8
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement inverse discrete cosine transform of lenght 8
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#ifdef AAC_PLUS
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "idct8.h"
+
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+
+#define R_SHIFT     29
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+
+/*----------------------------------------------------------------------------
+; 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 idct_8(Int32 vec[])
+{
+
+    Int32 tmp0;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 tmp3;
+    Int32 tmp4;
+    Int32 tmp5;
+    Int32 tmp6;
+    Int32 tmp7;
+    Int32 tmp8;
+
+
+    tmp5 = fxp_mul32_by_16(vec[4] << 1, Qfmt15(0.70710678118655F));
+
+    tmp1 =  vec[0] + tmp5;
+    tmp5 =  vec[0] - tmp5;
+
+    tmp3 = fxp_mul32_by_16(vec[2] << 1, Qfmt15(0.54119610014620F));     /* (1/(2*cos(2*phi)));*/
+    tmp7 = fxp_mul32_Q29(vec[6], Qfmt(1.30656296487638F));      /* (1/(2*cos(6*phi)));*/
+
+    tmp0  = fxp_mul32_by_16((tmp3 - tmp7) << 1, Qfmt15(0.70710678118655F)); /* (1/(2*cos(2*phi)));  */
+    tmp7 = (tmp3 + tmp7) + tmp0;
+
+    vec[0] = tmp1 + tmp7;
+    tmp2 = fxp_mul32_by_16(vec[1] << 1, Qfmt15(0.50979557910416F));     /* (1/(2*cos(  phi)));*/
+    vec[1] = tmp5 + tmp0;
+    vec[2] = tmp5 - tmp0;
+    tmp4 = fxp_mul32_by_16(vec[3] << 1, Qfmt15(0.60134488693505F));     /* (1/(2*cos(3*phi)));*/
+    vec[3] = tmp1 - tmp7;
+
+    tmp6 = fxp_mul32_by_16(vec[5] << 1, Qfmt15(0.89997622313642F));     /* (1/(2*cos(5*phi)));*/
+    tmp8 = fxp_mul32_Q29(vec[7], Qfmt(2.56291544774151F));      /* (1/(2*cos(7*phi)));*/
+
+    tmp7  =  tmp2 + tmp8;
+    tmp5  = fxp_mul32_by_16((tmp2 - tmp8) << 1, Qfmt15(0.54119610014620F));
+    tmp8  =  tmp4 + tmp6;
+    tmp6  = fxp_mul32_Q29((tmp4 - tmp6), Qfmt(1.30656296487638F));
+
+    tmp0 =  tmp7 + tmp8;
+    tmp2 = fxp_mul32_by_16((tmp7 - tmp8) << 1, Qfmt15(0.70710678118655F));
+
+    tmp3 = fxp_mul32_by_16((tmp5 - tmp6) << 1, Qfmt15(0.70710678118655F));
+    tmp1 = (tmp5 + tmp6) + tmp3;
+
+    tmp5 = tmp0 + tmp1;
+    tmp6 = tmp1 + tmp2;
+    tmp7 = tmp2 + tmp3;
+
+    vec[7]  = vec[0] - tmp5;
+    vec[0] +=          tmp5;
+    vec[6]  = vec[1] - tmp6;
+    vec[1] +=          tmp6;
+    vec[5]  = vec[2] - tmp7;
+    vec[2] +=          tmp7;
+    vec[4]  = vec[3] - tmp3;
+    vec[3] +=          tmp3;
+
+}
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/idct8.h b/media/libstagefright/codecs/aacdec/idct8.h
new file mode 100644
index 0000000..ad7eaae
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/idct8.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: idct8.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef IDCT8_H
+#define IDCT8_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    void idct_8(Int32 vec[]);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* IDCT8_H */
diff --git a/media/libstagefright/codecs/aacdec/imdct_fxp.cpp b/media/libstagefright/codecs/aacdec/imdct_fxp.cpp
new file mode 100644
index 0000000..ad67f20
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/imdct_fxp.cpp
@@ -0,0 +1,476 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: imdct_fxp.c
+ Funtions: imdct_fxp
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    data_quant    = Input vector, with quantized spectral lines:
+                    type Int32
+
+    freq_2_time_buffer =  Scratch memory used for in-place FFT calculation,
+                    min size required 1024,
+                    type Int32
+
+    n            =  Length of input vector "data_quant". Currently 256 or 2048
+                    type const Int
+
+    Q_format     =  Q_format of the input vector "data_quant"
+                    type Int
+
+    max          =  Maximum value inside input vector "data_quant"
+                    type Int32
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    shift = shift factor to reflect scaling introduced by IFFT and imdct_fxp,
+
+ Pointers and Buffers Modified:
+    Results are return in "Data_Int_precision"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    The IMDCT is a linear orthogonal lapped transform, based on the idea of
+    time domain aliasing cancellation (TDAC).
+    IMDCT is critically sampled, which means that though it is 50% overlapped,
+    a sequence data after IMDCT has the same number of coefficients as samples
+    before the transform (after overlap-and-add). This means, that a single
+    block of IMDCT data does not correspond to the original block on which the
+    IMDCT was performed. When subsequent blocks of inverse transformed data
+    are added (still using 50% overlap), the errors introduced by the
+    transform cancels out.Thanks to the overlapping feature, the IMDCT is very
+    useful for quantization. It effectively removes the otherwise easily
+    detectable blocking artifact between transform blocks.
+
+    N = twice the length of input vector X
+    y = vector of length N, will hold fixed point IDCT
+    p = 0:1:N-1
+
+                    2   N/2-1
+            y(p) = ---   SUM   X(m)*cos(pi/(2*N)*(2*p+1+N/2)*(2*m+1))
+                    N    m=0
+
+    The window that completes the TDAC is applied before calling this function.
+    The IMDCT can be calculated using an IFFT, for this, the IMDCT need be
+    rewritten as an odd-time odd-frequency discrete Fourier transform. Thus,
+    the IMDCT can be calculated using only one n/4 point FFT and some pre and
+    post-rotation of the sample points.
+
+
+    where X(k) is the input with N frequency lines
+
+    X(k) ----------------------------
+                                     |
+                                     |
+                    Pre-rotation by exp(j(2pi/N)(k+1/8))
+                                     |
+                                     |
+                              N/4- point IFFT
+                                     |
+                                     |
+                    Post-rotation by exp(j(2pi/N)(n+1/8))
+                                     |
+                                     |
+                                      ------------- x(n)  In the time domain
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should provide a fixed point IMDCT with an average
+    quantization error less than 1 % (variance and mean).
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] Analysis/Synthesis Filter Bank design based on time domain
+        aliasing cancellation
+        Jhon Princen, et. al.
+        IEEE Transactions on ASSP, vol ASSP-34, No. 5 October 1986
+        Pg 1153 - 1161
+
+    [2] Regular FFT-related transform kernels for DCT/DST based
+        polyphase filterbanks
+        Rolf Gluth
+        Proc. ICASSP 1991, pg. 2205 - 2208
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+  Cx, Cy are complex number
+
+
+    exp = log2(n)-1
+
+    FOR ( k=0; k< n/2; k +=2)
+
+        Cx = - data_quant[k] + j data_quant[n/2-1 - k]
+
+        freq_2_time_buffer = Cx * exp(j(2pi/n)(k+1/8))
+
+    ENDFOR
+
+    CALL IFFT( freq_2_time_buffer, n/4)
+
+    MODIFYING( freq_2_time_buffer )
+
+    RETURNING( shift )
+
+    FOR ( k=0; k< n/4; k +=2)
+
+        Cx = freq_2_time_buffer[ k] + j freq_2_time_buffer[ k+1]
+
+        Cy = Cx * exp(j(2pi/n)(k+1/8))
+
+        data_quant[3n/4-1 - k ] =   Real(Cy)
+        data_quant[ n/4-1 - k ] = - Imag(Cy)
+        data_quant[3n/4   + k ] =   Real(Cy)
+        data_quant[ n/4   + k ] =   Imag(Cy)
+
+    ENDFOR
+
+    FOR ( k=n/4; k< n/2; k +=2)
+
+        Cx = freq_2_time_buffer[ k] + j freq_2_time_buffer[ k+1]
+
+        Cy = Cx * exp(j(2pi/n)(k+1/8))
+
+        data_quant[3n/4-1 - k ] =   Real(Cy)
+        data_quant[ n/4   + k ] = - Real(Cy)
+        data_quant[5n/4   - k ] =   Imag(Cy)
+        data_quant[ n/4   + k ] =   Imag(Cy)
+
+    ENDFOR
+
+    MODIFIED    data_quant[]
+
+    RETURN      (exp - shift)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "imdct_fxp.h"
+
+
+#include "mix_radix_fft.h"
+#include "digit_reversal_tables.h"
+#include "fft_rx4.h"
+#include "inv_short_complex_rot.h"
+#include "inv_long_complex_rot.h"
+#include "pv_normalize.h"
+#include "fxp_mul32.h"
+#include "aac_mem_funcs.h"
+
+#include "window_block_fxp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define ERROR_IN_FRAME_SIZE 10
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+Int imdct_fxp(Int32   data_quant[],
+              Int32   freq_2_time_buffer[],
+              const   Int     n,
+              Int     Q_format,
+              Int32   max)
+{
+
+    Int32     exp_jw;
+    Int     shift = 0;
+
+    const   Int32 *p_rotate;
+    const   Int32 *p_rotate_2;
+
+    Int32   *p_data_1;
+    Int32   *p_data_2;
+
+    Int32   temp_re32;
+    Int32   temp_im32;
+
+    Int     shift1 = 0;
+    Int32   temp1;
+    Int32   temp2;
+
+    Int     k;
+    Int     n_2   = n >> 1;
+    Int     n_4   = n >> 2;
+
+
+
+    if (max != 0)
+    {
+
+        switch (n)
+        {
+            case SHORT_WINDOW_TYPE:
+                p_rotate = exp_rotation_N_256;
+                shift = 21;           /* log2(n)-1 + 14 acomodates 2/N factor */
+                break;
+
+            case LONG_WINDOW_TYPE:
+                p_rotate = exp_rotation_N_2048;
+                shift = 24;           /* log2(n)-1 +14 acomodates 2/N factor */
+                break;
+
+            default:
+                /*
+                 * There is no defined behavior for a non supported frame
+                 * size. By returning a fixed scaling factor, the input will
+                 * scaled down and the will be heard as a low level noise
+                 */
+                return(ERROR_IN_FRAME_SIZE);
+
+        }
+
+        /*
+         *   p_data_1                                        p_data_2
+         *       |                                            |
+         *       RIRIRIRIRIRIRIRIRIRIRIRIRIRIRI....RIRIRIRIRIRI
+         *        |                                          |
+         *
+         */
+
+        p_data_1 =  data_quant;             /* uses first  half of buffer */
+        p_data_2 = &data_quant[n_2 - 1];    /* uses second half of buffer */
+
+        p_rotate_2 = &p_rotate[n_4-1];
+
+        shift1 = pv_normalize(max) - 1;     /* -1 to leave room for addition */
+        Q_format -= (16 - shift1);
+        max = 0;
+
+
+        if (shift1 >= 0)
+        {
+            temp_re32 =   *(p_data_1++) << shift1;
+            temp_im32 =   *(p_data_2--) << shift1;
+
+            for (k = n_4 >> 1; k != 0; k--)
+            {
+                /*
+                 *  Real and Imag parts have been swaped to use FFT as IFFT
+                 */
+                /*
+                 * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+                 */
+                exp_jw = *p_rotate++;
+
+                temp1      =  cmplx_mul32_by_16(temp_im32, -temp_re32, exp_jw);
+                temp2      = -cmplx_mul32_by_16(temp_re32,  temp_im32, exp_jw);
+
+                temp_im32 =   *(p_data_1--) << shift1;
+                temp_re32 =   *(p_data_2--) << shift1;
+                *(p_data_1++) = temp1;
+                *(p_data_1++) = temp2;
+                max         |= (temp1 >> 31) ^ temp1;
+                max         |= (temp2 >> 31) ^ temp2;
+
+
+                /*
+                 *  Real and Imag parts have been swaped to use FFT as IFFT
+                 */
+
+                /*
+                 * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+                 */
+
+                exp_jw = *p_rotate_2--;
+
+                temp1      =  cmplx_mul32_by_16(temp_im32, -temp_re32, exp_jw);
+                temp2      = -cmplx_mul32_by_16(temp_re32,  temp_im32, exp_jw);
+
+
+                temp_re32 =   *(p_data_1++) << shift1;
+                temp_im32 =   *(p_data_2--) << shift1;
+
+                *(p_data_2 + 2) = temp1;
+                *(p_data_2 + 3) = temp2;
+                max         |= (temp1 >> 31) ^ temp1;
+                max         |= (temp2 >> 31) ^ temp2;
+
+            }
+        }
+        else
+        {
+            temp_re32 =   *(p_data_1++) >> 1;
+            temp_im32 =   *(p_data_2--) >> 1;
+
+            for (k = n_4 >> 1; k != 0; k--)
+            {
+                /*
+                 *  Real and Imag parts have been swaped to use FFT as IFFT
+                 */
+                /*
+                 * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+                 */
+                exp_jw = *p_rotate++;
+
+                temp1      =  cmplx_mul32_by_16(temp_im32, -temp_re32, exp_jw);
+                temp2      = -cmplx_mul32_by_16(temp_re32,  temp_im32, exp_jw);
+
+                temp_im32 =   *(p_data_1--) >> 1;
+                temp_re32 =   *(p_data_2--) >> 1;
+                *(p_data_1++) = temp1;
+                *(p_data_1++) = temp2;
+
+                max         |= (temp1 >> 31) ^ temp1;
+                max         |= (temp2 >> 31) ^ temp2;
+
+
+                /*
+                 *  Real and Imag parts have been swaped to use FFT as IFFT
+                 */
+
+                /*
+                 * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+                 */
+                exp_jw = *p_rotate_2--;
+
+                temp1      =  cmplx_mul32_by_16(temp_im32, -temp_re32, exp_jw);
+                temp2      = -cmplx_mul32_by_16(temp_re32,  temp_im32, exp_jw);
+
+                temp_re32 =   *(p_data_1++) >> 1;
+                temp_im32 =   *(p_data_2--) >> 1;
+
+                *(p_data_2 + 3) = temp2;
+                *(p_data_2 + 2) = temp1;
+
+                max         |= (temp1 >> 31) ^ temp1;
+                max         |= (temp2 >> 31) ^ temp2;
+
+            }
+        }
+
+
+        if (n != SHORT_WINDOW_TYPE)
+        {
+
+            shift -= mix_radix_fft(data_quant,
+                                   &max);
+
+            shift -= inv_long_complex_rot(data_quant,
+                                          max);
+
+        }
+        else        /*  n_4 is 64 */
+        {
+
+            shift -= fft_rx4_short(data_quant,   &max);
+
+
+            shift -= inv_short_complex_rot(data_quant,
+                                           freq_2_time_buffer,
+                                           max);
+
+            pv_memcpy(data_quant,
+                      freq_2_time_buffer,
+                      SHORT_WINDOW*sizeof(*data_quant));
+        }
+
+    }
+    else
+    {
+        Q_format = ALL_ZEROS_BUFFER;
+    }
+
+    return(shift + Q_format);
+
+} /* imdct_fxp */
diff --git a/media/libstagefright/codecs/aacdec/imdct_fxp.h b/media/libstagefright/codecs/aacdec/imdct_fxp.h
new file mode 100644
index 0000000..5837750
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/imdct_fxp.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: imdct_fxp.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: This extern had the incorrect length of the arrays.  The true
+ lengths are 128 and 1024, not 64 and 512.
+
+ Description:  Modified interface so a vector with extended precision is
+               returned, this is a 32 bit vector whose MSB 16 bits will be
+               extracted later.  Added copyright notice.
+
+ Description:   Modified function interface to accomodate the normalization
+                that now is done in this function.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function imdct_fxp()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef IMDCT_FXP_H
+#define IMDCT_FXP_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+#define     LONG_WINDOW_TYPE  2048
+#define     SHORT_WINDOW_TYPE  256
+
+#define     ALL_ZEROS_BUFFER       31
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    extern const Int32 exp_rotation_N_256[64];
+    extern const Int32 exp_rotation_N_2048[512];
+    /*
+    extern const Int exp_rotation_N_256[128];
+    extern const Int exp_rotation_N_2048[1024];
+    */
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Int imdct_fxp(
+        Int32   data_quant[],
+        Int32   freq_2_time_buffer[],
+        const   Int     n,
+        Int     Q_format,
+        Int32   max
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* IMDCT_FXP_H */
diff --git a/media/libstagefright/codecs/aacdec/infoinit.cpp b/media/libstagefright/codecs/aacdec/infoinit.cpp
new file mode 100644
index 0000000..7bdcdcd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/infoinit.cpp
@@ -0,0 +1,355 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: infoinit.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Pass eight_short_info and the array 'sfbwidth128'.
+               Change function arguments' names for clarity
+
+ Description:  move sfb definitions to "sfb.h", and "sfb.c", eliminated
+               the function "huffbookinit.c"
+
+ Description:  Remove initialization of the never used array,
+               pFrameInfo->group_offs
+
+ Description:
+ (1) Changed "stdinc.h" to <stdlib.h> - this avoids linking in the math
+ library and stdio.h.  (All for just defining the NULL pointer macro)
+
+ (2) Updated copyright header.
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Description: Addresses of constant vectors are now found by means of a
+              switch statement, this solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers
+
+ Who:                               Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pSi              = pointer to sampling rate info
+    ppWin_seq_info   = pointer array to window sequence Info struct
+    pSfbwidth128     = pointer to sfb bandwidth array of short window
+
+ Local Stores/Buffers/Pointers Needed:
+
+ Global Stores/Buffers/Pointers Needed:
+
+ Outputs:
+
+ Pointers and Buffers Modified:
+
+    ppWin_seq_info[ONLY_LONG_WINDOW]{all structure members} = setup values
+    ppWin_seq_info[EIGHT_SHORT_WINDOW]{all structure members} = setup values
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function sets the values of 'Info' structure for blocks containing long
+ and short window sequences, the following structures are being set:
+
+ win_seq_info[ONLY_LONG_WINDOW], win_seq_info[EIGHT_SHORT_WINDOW],
+ only_long_info and eight_short_info
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+ (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 4       p66     (sfb tables)
+                    p111    (4.6.10)
+                    p200    (Annex 4.B.5)
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pFrameInfo  =   pointer to only_long_info;
+    win_seq_info[ONLY_LONG_WINDOW]  =   pFrameInfo;
+    pFrameInfo{all structure members} = setup values;
+
+
+    pFrameInfo  =   pointer to eight_short_info;
+    win_seq_info[EIGHT_SHORT_WINDOW]  =   pFrameInfo;
+    pFrameInfo{all structure.members} =   setup values;
+
+
+    FOR (window_seq = 0; window_seq < NUM_WIN_SEQ; win_seq++)
+
+        win_seq_info[window_seq].members = setup values;
+
+    ENDFOR
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor the
+     the resources used should be documented below.
+
+ STACK USAGE:
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES:
+
+------------------------------------------------------------------------------
+*/
+
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sr_info.h"
+#include    "s_frameinfo.h"
+#include    "e_blockswitching.h"
+#include    "e_huffmanconst.h"
+#include    "sfb.h"
+#include    "huffman.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
+----------------------------------------------------------------------------*/
+
+Int infoinit(
+    const Int samp_rate_idx,
+    FrameInfo   **ppWin_seq_info,
+    Int    *pSfbwidth128)
+
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    Int     i;
+    Int     sfb_idx, sfb_sbk;
+    Int     bins_sbk;
+    Int     win_seq;
+    Int     start_idx, end_idx;
+    Int     nsfb_short;
+    Int16   *sfbands;
+    FrameInfo    *pFrameInfo;
+
+    const SR_Info *pSi = &(samp_rate_info[samp_rate_idx]);
+
+    const Int16 * pt_SFbands1024 = NULL;
+    const Int16 * pt_SFbands128  = NULL;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    switch (pSi->samp_rate)
+    {
+        case 96000:
+        case 88200:
+            pt_SFbands1024  = sfb_96_1024;
+            pt_SFbands128   = sfb_64_128;  /* equal to table sfb_96_128, (eliminated) */
+            break;
+        case 64000:
+            pt_SFbands1024  = sfb_64_1024;
+            pt_SFbands128   = sfb_64_128;
+            break;
+        case 48000:
+        case 44100:
+            pt_SFbands1024  = sfb_48_1024;
+            pt_SFbands128   = sfb_48_128;
+            break;
+        case 32000:
+            pt_SFbands1024  = sfb_32_1024;
+            pt_SFbands128   = sfb_48_128;
+            break;
+        case 24000:
+        case 22050:
+            pt_SFbands1024  = sfb_24_1024;
+            pt_SFbands128   = sfb_24_128;
+            break;
+        case 16000:
+        case 12000:
+        case 11025:
+            pt_SFbands1024  = sfb_16_1024;
+            pt_SFbands128   = sfb_16_128;
+            break;
+        case 8000:
+            pt_SFbands1024  = sfb_8_1024;
+            pt_SFbands128   = sfb_8_128;
+            break;
+        default:
+            // sampling rate not supported
+            return -1;
+    }
+
+    /* long block info */
+
+    pFrameInfo = ppWin_seq_info[ONLY_LONG_WINDOW];
+    pFrameInfo->islong               = 1;
+    pFrameInfo->num_win              = 1;
+    pFrameInfo->coef_per_frame       = LN2; /* = 1024 */
+
+    pFrameInfo->sfb_per_win[0]  = pSi->nsfb1024;
+    pFrameInfo->sectbits[0]     = LONG_SECT_BITS;
+    pFrameInfo->win_sfb_top[0]  = (Int16 *)pt_SFbands1024;
+
+    pFrameInfo->sfb_width_128 = NULL; /* no short block sfb */
+    pFrameInfo->num_groups    = 1; /* long block, one group */
+    pFrameInfo->group_len[0]  = 1; /* only one window */
+
+    /* short block info */
+    pFrameInfo = ppWin_seq_info[EIGHT_SHORT_WINDOW];
+    pFrameInfo->islong                  = 0;
+    pFrameInfo->num_win                 = NSHORT;
+    pFrameInfo->coef_per_frame          = LN2;
+
+    for (i = 0; i < pFrameInfo->num_win; i++)
+    {
+        pFrameInfo->sfb_per_win[i] = pSi->nsfb128;
+        pFrameInfo->sectbits[i]    = SHORT_SECT_BITS;
+        pFrameInfo->win_sfb_top[i] = (Int16 *)pt_SFbands128;
+    }
+
+    /* construct sfb width table */
+    pFrameInfo->sfb_width_128 = pSfbwidth128;
+    for (i = 0, start_idx = 0, nsfb_short = pSi->nsfb128; i < nsfb_short; i++)
+    {
+        end_idx = pt_SFbands128[i];
+        pSfbwidth128[i] = end_idx - start_idx;
+        start_idx = end_idx;
+    }
+
+
+    /* common to long and short */
+    for (win_seq = 0; win_seq < NUM_WIN_SEQ; win_seq++)
+    {
+
+        if (ppWin_seq_info[win_seq] != NULL)
+        {
+            pFrameInfo                 = ppWin_seq_info[win_seq];
+            pFrameInfo->sfb_per_frame  = 0;
+            sfb_sbk                    = 0;
+            bins_sbk                   = 0;
+
+            for (i = 0; i < pFrameInfo->num_win; i++)
+            {
+
+                /* compute coef_per_win */
+                pFrameInfo->coef_per_win[i] =
+                    pFrameInfo->coef_per_frame / pFrameInfo->num_win;
+
+                /* compute sfb_per_frame */
+                pFrameInfo->sfb_per_frame += pFrameInfo->sfb_per_win[i];
+
+                /* construct default (non-interleaved) bk_sfb_top[] */
+                sfbands = pFrameInfo->win_sfb_top[i];
+                for (sfb_idx = 0; sfb_idx < pFrameInfo->sfb_per_win[i];
+                        sfb_idx++)
+                {
+                    pFrameInfo->frame_sfb_top[sfb_idx+sfb_sbk] =
+                        sfbands[sfb_idx] + bins_sbk;
+                }
+
+                bins_sbk += pFrameInfo->coef_per_win[i];
+                sfb_sbk  += pFrameInfo->sfb_per_win[i];
+            } /* for i = sbk ends */
+        }
+
+    } /* for win_seq ends */
+
+    return SUCCESS;
+
+} /* infoinit */
diff --git a/media/libstagefright/codecs/aacdec/init_sbr_dec.cpp b/media/libstagefright/codecs/aacdec/init_sbr_dec.cpp
new file mode 100644
index 0000000..fc47dd3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/init_sbr_dec.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: init_sbr_dec.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        initializes sbr decoder structure
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "init_sbr_dec.h"
+#include    "aac_mem_funcs.h"
+#include    "extractframeinfo.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
+----------------------------------------------------------------------------*/
+
+Int32 init_sbr_dec(Int32 codecSampleRate,
+                   Int   upsampleFac,
+                   SBR_DEC *sbrDec,
+                   SBR_FRAME_DATA *hFrameData)
+{
+    Int32 outFrameSize;
+    Int32 coreCodecFrameSize = 1024;
+#ifdef HQ_SBR
+    Int32 i;
+#endif
+
+
+    sbrDec->sbStopCodec    =  upsampleFac << 5;
+    sbrDec->prevLowSubband =  upsampleFac << 5;
+
+
+    /* set sbr sampling frequency */
+    sbrDec->outSampleRate = 2 * codecSampleRate;
+    outFrameSize = upsampleFac * coreCodecFrameSize;
+
+    hFrameData->nSfb[LO] = 0;    /* number of scale factor bands for high resp.low frequency resolution */
+    hFrameData->nSfb[HI] = 0;
+    hFrameData->offset   = 0;
+
+    hFrameData->nNfb = hFrameData->sbr_header.noNoiseBands;
+    hFrameData->prevEnvIsShort = -1;
+
+    /* Initializes pointers */
+#ifdef HQ_SBR
+    for (i = 0; i < 5; i++)
+    {
+        hFrameData->fBuf_man[i]  = hFrameData->fBuffer_man[i];
+        hFrameData->fBufN_man[i] = hFrameData->fBufferN_man[i];
+        hFrameData->fBuf_exp[i]  = hFrameData->fBuffer_exp[i];
+        hFrameData->fBufN_exp[i] = hFrameData->fBufferN_exp[i];
+    }
+#endif
+
+
+    pv_memset((void *)hFrameData->sbr_invf_mode_prev,
+              0,
+              MAX_NUM_NOISE_VALUES*sizeof(INVF_MODE));
+
+    /* Direct assignments */
+
+    sbrDec->noCols = 32;
+
+    sbrDec->bufWriteOffs = 6 + 2;
+    sbrDec->bufReadOffs  = 2;
+    sbrDec->qmfBufLen = sbrDec->noCols + sbrDec->bufWriteOffs;
+
+    sbrDec->lowBandAddSamples = 288;
+
+    sbrDec->startIndexCodecQmf = 0;
+
+    sbrDec->lowSubband =  32;
+
+
+    return outFrameSize;
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/init_sbr_dec.h b/media/libstagefright/codecs/aacdec/init_sbr_dec.h
new file mode 100644
index 0000000..844fa0e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/init_sbr_dec.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: init_sbr_dec.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef INIT_SBR_DEC_H
+#define INIT_SBR_DEC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "sbr_dec.h"
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int32 init_sbr_dec(Int32 codecSampleRate,
+                   Int  upsampleFac,
+                   SBR_DEC *sbrDec,
+                   SBR_FRAME_DATA *hFrameData);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/intensity_right.cpp b/media/libstagefright/codecs/aacdec/intensity_right.cpp
new file mode 100644
index 0000000..106298a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/intensity_right.cpp
@@ -0,0 +1,457 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: intensity_right.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified per review comments.
+
+ Description: Noticed that the code could be more efficient by
+ using some other method for storing the sign.  The code was changed to
+ use a signed Int to store the table, and an adjustment of the q-format to
+ reflect the difference between the data being shifted by 16 and the table
+ being stored in q-15 format.
+
+ Description: Updated pseudocode
+
+ Description: When the multiplication of two 16-bits variables is stored in
+              an 32-bits variable, the result should be typecasted explicitly
+              to Int32 before it is stored.
+              *(pCoefRight++) = (Int32) tempInt2 * multiplier;
+
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    scalefactor  =  Multiplier used to scale the data extracted from the left
+                    channel for use on the right.
+                    [const Int]
+
+    coef_per_win =  Number of coefficients per window.
+                    (128 for short, 1024 for long)
+                    [const Int]
+
+    sfb_per_win  =  Number of scalefactor bands per window.  This should be
+                    a number divisible by four.
+                    [const Int]
+
+    wins_in_group = The number of windows in the group being decoded.
+                    This number falls within the range 1-8.
+                    [const Int]
+
+    band_length  =  The length of the scalefactor band being decoded.
+                    This value is divisible by 4.
+                    [const Int]
+
+    codebook     =  Value that denotes which Huffman codebook was used for
+                    the encoding of this grouped scalefactor band.
+                    [const Int]
+
+    ms_used      =  Flag that denotes whether M/S is active for this band.
+                    [const Bool]
+
+    q_formatLeft = The Q-format for the left channel's fixed-point spectral
+                   coefficients, on a per-scalefactor band, non-grouped basis.
+                   [const Int *, length MAXBANDS]
+
+    q_formatRight = The Q-format for the right channel's fixed-point spectral
+                    coefficients, on a per-scalefactor band, non-grouped basis.
+                    [Int *, length MAXBANDS]
+
+    coefLeft =  Array containing the fixed-point spectral coefficients
+                for the left channel.
+                [const Int32 *, length 1024]
+
+    coefRight = Array containing the fixed-point spectral coefficients
+                for the right channel.
+                [Int32 *, length 1024]
+
+ Local Stores/Buffers/Pointers Needed:
+    intensity_factor =  Table which stores the values of
+                        0.5^(0), 0.5^(1/4), 0.5^(2/4) and 0.5^(3/4)
+                        [UInt, length 4]
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coefRight[]         Contains the new spectral information
+
+    q_formatRight[]     Q-format may be updated with changed fixed-point
+                        data in coefRight.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function applies Intensity Stereo, generating data on the right channel
+ that is derived from data on the Left.  A scalefactor is applied using the
+ following formula...
+
+ RightCh = LeftCh*0.5^(scalefactor/4)
+
+ This function works for one scalefactor band, which may belong to a group.
+ (i.e. the same scalefactor band repeated across multiple windows belonging
+  to one group.)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ codebook must be either INTENSITY_HCB or INTENSITY_HCB2 when this function
+ is called.
+
+ ms_used must be 1 when TRUE, 0 when FALSE.
+
+ wins_in_group falls within the range [1-8]
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.7.2.3 Decoding Process (Intensity Stereo)
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+    multiplier = codebook AND 0x1;
+
+    multiplier = multiplier XOR ms_used;
+
+    multiplier = multiplier << 1;
+
+    multiplier = multiplier - 1;
+
+    multiplier = multiplier * intensity_factor[scalefactor & 0x3];
+
+    scf_div_4 = (scalefactor >> 2);
+
+    nextWinPtrUpdate = (coef_per_win - band_length);
+
+    FOR (win_indx = wins_in_group; win_indx > 0; win_indx--)
+
+        *(pQformatRight) = scf_div_4 + *(pQformatLeft) - 1;
+
+        FOR (tempInt = band_length; tempInt > 0; tempInt--)
+           tempInt2 = (Int)(*(pCoefLeft) >> 16);
+
+           *(pCoefRight) = tempInt2 * multiplier;
+
+           pCoefRight = pCoefRight + 1;
+           pCoefLeft  = pCoefLeft  + 1;
+
+        ENDFOR
+
+        pCoefRight = pCoefRight + nextWinPtrUpdate;
+        pCoefLeft  = pCoefLeft + nextWinPtrUpdate;
+
+        pQformatRight = pQformatRight + sfb_per_win;
+        pQformatLeft  = pQformatLeft  + sfb_per_win;
+    ENDFOR
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor 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 "pv_audio_type_defs.h"
+#include "intensity_right.h"
+#include "e_huffmanconst.h"
+
+#include "fxp_mul32.h"
+#include "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+const Int16 intensity_factor[4] =
+{
+    32767,  /* (0.5^0.00)*2^15 - 1 (minus 1 for storage as type Int) */
+    27554,  /* (0.5^0.25)*2^15 */
+    23170,  /* (0.5^0.50)*2^15 */
+    19484
+}; /* (0.5^0.75)*2^15 */
+
+
+/*----------------------------------------------------------------------------
+; 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 intensity_right(
+    const Int   scalefactor,
+    const Int   coef_per_win,
+    const Int   sfb_per_win,
+    const Int   wins_in_group,
+    const Int   band_length,
+    const Int   codebook,
+    const Bool  ms_used,
+    const Int   q_formatLeft[],
+    Int   q_formatRight[],
+    const Int32 coefLeft[],
+    Int32 coefRight[])
+
+{
+    const Int32 *pCoefLeft  = coefLeft;
+    Int32 *pCoefRight = coefRight;
+
+    const Int *pQformatLeft  = q_formatLeft;
+    Int *pQformatRight = q_formatRight;
+
+    Int   multiplier;
+    Int   scf_div_4;
+    Int   nextWinPtrUpdate;
+
+    /*
+     * The sign of the intensity multiplier obeys the following table...
+     *
+     * codebook       | ms_used | multiplier
+     * --------------------------------------
+     * INTENSITY_HCB  | TRUE    |    -1
+     * INTENSITY_HCB  | FALSE   |    +1
+     * INTENSITY_HCB2 | TRUE    |    +1
+     * INTENSITY_HCB2 | FALSE   |    -1
+     *
+     * In binary, the above table is represented as...
+     *
+     * codebook       | ms_used | multiplier
+     * --------------------------------------
+     * 1111b          | 1       |    -1
+     * 1111b          | 0       |    +1
+     * 1110b          | 1       |    +1
+     * 1110b          | 0       |    -1
+     *
+     */
+
+    /*
+     * Deriving the correct value for "multiplier" is illustrated
+     * below for all 4 possible combinations of codebook and ms_used
+     */
+
+    /*
+     * 1111b AND 0x1 = 1b
+     * 1111b AND 0x1 = 1b
+     * 1110b AND 0x1 = 0b
+     * 1110b AND 0x1 = 0b
+     */
+    multiplier  = (codebook & 0x1);
+
+    /*
+     * 1b XOR 1 = 0b
+     * 1b XOR 0 = 1b
+     * 0b XOR 1 = 1b
+     * 0b XOR 0 = 0b
+     */
+    multiplier ^= ms_used;
+
+    /*
+     * 0b << 1 = 0
+     * 1b << 1 = 2
+     * 1b << 1 = 2
+     * 0b << 1 = 0
+     */
+    multiplier <<= 1;
+
+    /*
+     * 0 - 1 = -1
+     * 2 - 1 = +1
+     * 2 - 1 = +1
+     * 0 - 1 = -1
+     */
+    multiplier--;
+
+    multiplier *= intensity_factor[scalefactor & 0x3];
+
+    scf_div_4 = (scalefactor >> 2);
+
+    /*
+     * Step through all the windows in this group, replacing this
+     * band in each window's spectrum with
+     * left-channel correlated data
+     */
+
+    nextWinPtrUpdate = (coef_per_win - band_length);
+
+    for (Int win_indx = wins_in_group; win_indx > 0; win_indx--)
+    {
+
+        /*
+         * Calculate q_formatRight
+         *
+         * q_formatLeft must be included, since the values
+         * on the right-channel are derived from the values
+         * on the left-channel.
+         *
+         * scalefactor/4 is included, since the intensity
+         * formula is RightCh = LeftCh*0.5^(scalefactor/4)
+         *
+         * powers of 0.5 increase the q_format by 1.
+         * (Another way to multiply something by 0.5^(x)
+         *  is to increase its q-format by x.)
+         *
+         * Finally the q-format must be decreased by 1.
+         * The reason for this is because the table is stored
+         * in q-15 format, but we are shifting by 16 to do
+         * a 16 x 16 multiply.
+         */
+
+        *(pQformatRight) = scf_div_4 + *(pQformatLeft);
+
+        /*
+         * reconstruct right intensity values
+         *
+         * to make things faster, this for loop
+         * can be partially unrolled, since band_length is a multiple
+         * of four.
+         */
+
+
+        if (multiplier == 32767)
+        {
+            Int32 tempInt2 = *(pCoefLeft++);
+            Int32 tempInt22 = *(pCoefLeft++);
+
+            for (Int tempInt = band_length >> 1; tempInt > 0; tempInt--)
+            {
+                *(pCoefRight++) = tempInt2;
+                *(pCoefRight++) = tempInt22;
+                tempInt2 = *(pCoefLeft++);
+                tempInt22 = *(pCoefLeft++);
+            }
+
+        }
+        else
+        {
+
+            Int32 tempInt2 = *(pCoefLeft++);
+            Int32 tempInt22 = *(pCoefLeft++);
+            for (Int tempInt = band_length >> 1; tempInt > 0; tempInt--)
+            {
+                *(pCoefRight++) = fxp_mul32_by_16(tempInt2, multiplier) << 1;
+                *(pCoefRight++) = fxp_mul32_by_16(tempInt22, multiplier) << 1;
+                tempInt2 = *(pCoefLeft++);
+                tempInt22 = *(pCoefLeft++);
+            }
+        }
+
+        /*
+         * Set pCoefRight and pCoefLeft to the beginning of
+         * this sfb in the next window in the group.
+         */
+
+        pCoefRight += nextWinPtrUpdate;
+        pCoefLeft  += (nextWinPtrUpdate - 2);
+
+        /*
+         * Update pQformatRight and pQformatLeft to this sfb in
+         * in the next window in the group.
+         */
+
+        pQformatRight += sfb_per_win;
+        pQformatLeft  += sfb_per_win;
+
+    } /* for (win_indx) */
+
+
+} /* void intensity_right */
diff --git a/media/libstagefright/codecs/aacdec/intensity_right.h b/media/libstagefright/codecs/aacdec/intensity_right.h
new file mode 100644
index 0000000..823da07
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/intensity_right.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: intensity_right.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change ms_used from Int to Bool
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Contains the function definitions for intensity_right
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef INTENSITY_RIGHT_H
+#define INTENSITY_RIGHT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 intensity_right(
+    const Int   scalefactor,
+    const Int   coef_per_win,
+    const Int   sfb_per_win,
+    const Int   wins_in_group,
+    const Int   band_length,
+    const Int   codebook,
+    const Bool  ms_used,
+    const Int   q_formatLeft[],
+    Int   q_formatRight[],
+    const Int32 coefLeft[],
+    Int32 coefRight[]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/inv_long_complex_rot.cpp b/media/libstagefright/codecs/aacdec/inv_long_complex_rot.cpp
new file mode 100644
index 0000000..84a7ec8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/inv_long_complex_rot.cpp
@@ -0,0 +1,408 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: .inv_long_complex_rot.c
+ Funtions:  inv_long_complex_rot
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Change the input argument, no shifts information from long fft_rx4
+               , do not have to check for shifts.
+
+ Date: 10/18/2002
+ Description:
+            (1) Change the input argument, only a single max is passed.
+            (2) Eliminate search for max, a fixed shift has replaced the
+                search for max with minimal loss of precision.
+            (3) Eliminated unused variables
+
+ Date: 10/28/2002
+ Description:
+            (1) Added comments per code review
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    Data_in   = Input vector (sized for long windows
+                TWICE_INV_LONG_CX_ROT_LENGTH), with time domain samples
+                type Int32 *
+
+    Data_out  = Output vector with a post-rotation by exp(j(2pi/N)(k+1/8)),
+                (sized for long windows TWICE_INV_LONG_CX_ROT_LENGTH)
+                type Int32 *
+
+    max       = Input, carries the maximum value of the input vector
+                "Data_in"
+                type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exp = shift factor to reflect signal scaling
+
+ Pointers and Buffers Modified:
+    Results are return in "Data_out"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    inv_long_complex_rot() performs the complex rotation for the inverse MDCT
+    for the case of long windows. It also performs digit reverse ordering of
+    the first and second halves of the input vector "Data_in", as well as
+    reordering of the two half vectors (following radix-2 decomposition)
+    Word normalization is also done to ensure 16 by 16 bit multiplications.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    inv_long_complex_rot() should execute a post-rotation by
+    exp(-j(2pi/N)(k+1/8)), digit reverse ordering and word normalization
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ 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 "digit_reversal_tables.h"
+#include "inv_long_complex_rot.h"
+#include "imdct_fxp.h"
+#include "inv_long_complex_rot.h"
+#include "pv_normalize.h"
+
+#include "fxp_mul32.h"
+#include "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+
+
+Int inv_long_complex_rot(
+    Int32 *Data,
+    Int32  max)
+{
+    Int     i;
+    Int16     I;
+    const   Int32 *p_rotate;
+    Int32   temp_re;
+    Int32   temp_im;
+
+    Int32    exp_jw;
+    Int32   *pData_in_1;
+    Int32   *pData_in_2;
+    Int     exp;
+    Int32   *pData_in_ref1;
+    Int32   *pData_in_ref2;
+
+
+    Int16   temp_re_0;
+    Int16   temp_im_0;
+    Int16   temp_re_1;
+    Int16   temp_im_1;
+    Int16   *p_Data_Int_precision;
+    Int     n     = 2048;
+    Int     n_2   = n >> 1;
+    Int     n_4   = n >> 2;
+    Int     n_3_4 = n_2 + n_4;
+
+    Int16   *px_1;
+    Int16   *px_2;
+    Int16   *px_3;
+    Int16   *px_4;
+
+    Int16     J;
+    const   Int32 *p_rotate2;
+
+
+
+
+    p_rotate    =  &exp_rotation_N_2048[255];
+    p_rotate2   =  &exp_rotation_N_2048[256];
+
+    pData_in_ref1  =  Data;
+    pData_in_ref2  = &Data[TWICE_INV_LONG_CX_ROT_LENGTH];
+
+
+    /*
+     *  Apply  A/2^(diff) + B
+     */
+
+    p_Data_Int_precision = (Int16 *)Data;
+
+    exp = 16 - pv_normalize(max);
+
+
+    /*
+     *        px2-->               <--px1 px4-->               <--px3
+     *
+     *                     |                           |             |
+     *       |+++++++++++++|+++++++++++++|+++++++++++++|+++++++++++++|
+     *                     |             |             |             |
+     *                    n/4           n/2          3n/4
+     */
+
+    I = 255;
+    J = 256;
+
+    pData_in_1 = pData_in_ref2 + I;
+
+    px_1 = (Int16 *)pData_in_1;
+    px_1++;
+
+    pData_in_2 = pData_in_ref2 + J;
+
+    px_4 = (Int16 *)pData_in_2;
+
+
+
+    exp -= 1;
+
+
+    for (i = INV_LONG_CX_ROT_LENGTH >> 1; i != 0; i--)
+    {
+
+        pData_in_2 = pData_in_ref1 + J;
+
+        temp_im =  *(pData_in_2++);
+        temp_re =  *(pData_in_2);
+
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+        exp_jw = *p_rotate2++;
+
+        /*
+         *   Post-rotation
+         */
+
+
+
+        temp_re_0  = (Int16)(cmplx_mul32_by_16(temp_re,  -temp_im,  exp_jw) >> exp);
+        temp_im_0  = (Int16)(cmplx_mul32_by_16(temp_im,   temp_re,  exp_jw) >> exp);
+
+
+        pData_in_1 = pData_in_ref2 + I;
+
+        /*
+         *  Use auxiliary variables to avoid double accesses to memory.
+         *  Data in is scaled to use only lower 16 bits.
+         */
+
+        temp_re =  *(pData_in_1--);
+        temp_im =  *(pData_in_1);
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+        exp_jw = *p_rotate--;
+
+
+        /*
+         *   Post-rotation
+         */
+
+        temp_re_1  = (Int16)(cmplx_mul32_by_16(temp_re,  -temp_im,  exp_jw) >> exp);
+        temp_im_1  = (Int16)(cmplx_mul32_by_16(temp_im,   temp_re,  exp_jw) >> exp);
+
+
+        /*
+         *   Repeat procedure for odd index at the output
+         */
+
+        pData_in_2 = pData_in_ref2 + J;
+        J += 2;
+
+        temp_im =  *(pData_in_2++);
+        temp_re =  *(pData_in_2);
+
+
+        *(px_1--) =  temp_re_0;
+        *(px_1--) =  temp_im_1;
+        *(px_4++) =  temp_im_0;
+        *(px_4++) =  temp_re_1;
+
+
+        exp_jw = *p_rotate2++;
+
+
+        *(px_1--)  = (Int16)(cmplx_mul32_by_16(temp_re,  -temp_im,  exp_jw) >> exp);
+        *(px_4++)  = (Int16)(cmplx_mul32_by_16(temp_im,   temp_re,  exp_jw) >> exp);
+
+
+
+        /*
+         *   Repeat procedure for odd index at the output
+         */
+
+        pData_in_1 = pData_in_ref1 + I;
+        I -= 2;
+
+        temp_re =  *(pData_in_1--);
+        temp_im =  *(pData_in_1);
+
+
+        exp_jw = *p_rotate--;
+
+
+        *(px_4++)  = (Int16)(cmplx_mul32_by_16(temp_re,  -temp_im,  exp_jw) >> exp);
+        *(px_1--)  = (Int16)(cmplx_mul32_by_16(temp_im,   temp_re,  exp_jw) >> exp);
+
+    }
+
+    /*
+     *                                           <--px1 px4-->
+     *
+     *                     |                           |             |
+     *       |-------------|-------------|/////////////|\\\\\\\\\\\\\|
+     *                     |             |             |             |
+     *                    n/4           n/2          3n/4
+     */
+
+
+    px_1 = p_Data_Int_precision + n_2 - 1;
+    px_2 = p_Data_Int_precision;
+
+    px_4 = p_Data_Int_precision + n_3_4 - 1;
+
+    for (i = 0; i<INV_LONG_CX_ROT_LENGTH >> 1; i++)
+    {
+
+        Int16 temp_re_0 = *(px_4--);
+        Int16 temp_im_1 = *(px_4--);
+        Int16 temp_re_2 = *(px_4--);
+        Int16 temp_im_3 = *(px_4--);
+        *(px_1--) = temp_re_0;
+        *(px_1--) = temp_im_1;
+        *(px_1--) = temp_re_2;
+        *(px_1--) = temp_im_3;
+
+        *(px_2++) = (-temp_re_0);
+        *(px_2++) = (-temp_im_1);
+        *(px_2++) = (-temp_re_2);
+        *(px_2++) = (-temp_im_3);
+
+    }
+
+
+    px_4 = p_Data_Int_precision + n_2;
+
+
+    pv_memcpy(px_4, pData_in_ref2 + 256, TWICE_INV_LONG_CX_ROT_LENGTH*sizeof(*px_4));
+
+
+
+    /*
+     *        px2-->               <--px1 px4-->               <--px3
+     *
+     *                     |                           |             |
+     *       |+++++++++++++|+++++++++++++|+++++++++++++|+++++++++++++|
+     *                     |             |             |             |
+     *                    n/4           n/2          3n/4
+     */
+    px_3 = p_Data_Int_precision + n - 1;
+
+
+    for (i = 0; i<INV_LONG_CX_ROT_LENGTH >> 1; i++)
+    {
+
+        Int16 temp_im_0 = *(px_4++);
+        Int16 temp_re_1 = *(px_4++);
+        Int16 temp_im_2 = *(px_4++);
+        Int16 temp_re_3 = *(px_4++);
+        *(px_3--) =  temp_im_0;
+        *(px_3--) =  temp_re_1;
+        *(px_3--) =  temp_im_2;
+        *(px_3--) =  temp_re_3;
+
+    }
+
+
+    return (exp + 1);
+}
+
diff --git a/media/libstagefright/codecs/aacdec/inv_long_complex_rot.h b/media/libstagefright/codecs/aacdec/inv_long_complex_rot.h
new file mode 100644
index 0000000..8b95867
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/inv_long_complex_rot.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: inv_long_complex_rot.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function inv_long_complex_rot()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef INV_LONG_COMPLEX_ROT_H
+#define INV_LONG_COMPLEX_ROT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define INV_LONG_CX_ROT_LENGTH          256
+#define TWICE_INV_LONG_CX_ROT_LENGTH (INV_LONG_CX_ROT_LENGTH<<1)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int inv_long_complex_rot(
+        Int32 *Data,
+        Int32  max);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* INV_LONG_COMPLEX_ROT_H */
diff --git a/media/libstagefright/codecs/aacdec/inv_short_complex_rot.cpp b/media/libstagefright/codecs/aacdec/inv_short_complex_rot.cpp
new file mode 100644
index 0000000..5b4f1c5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/inv_short_complex_rot.cpp
@@ -0,0 +1,305 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: inv_short_complex_rot.c
+ Funtions:  inv_short_complex_rot
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Date: 10/18/2002
+ Description:
+            (1) Change the input argument, only a single max is passed.
+            (2) Eliminate search for max, a fixed shift has replaced the
+                search for max with minimal loss of precision.
+            (3) Eliminated unused variables
+
+ Date: 10/28/2002
+ Description:
+            (1) Added comments per code review
+            (2) Eliminated hardly used condition on if-else (exp==0)
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    Data_in   = Input vector (sized for short windows
+                2*INV_SHORT_CX_ROT_LENGTH elements), with time domain samples
+                type Int32 *
+
+    Data_out  = Output vector with a post-rotation by exp(j(2pi/N)(k+1/8)),
+                (sized for short windows 2*INV_SHORT_CX_ROT_LENGTH)
+                type Int32 *
+
+    max       = Input, carries the maximum value of the input vector
+                "Data_in"
+                type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exp = shift factor to reflect signal scaling
+
+ Pointers and Buffers Modified:
+    Results are return in "Data_out"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    inv_short_complex_rot() performs the complex rotation for the inverse MDCT
+    for the case of short windows. It performs digit reverse ordering as well
+    word normalization to ensure 16 by 16 bit multiplications.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    inv_short_complex_rot() should execute a post-rotation by
+    exp( j(2pi/N)(k+1/8)), digit reverse ordering and word normalization
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ 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 "digit_reversal_tables.h"
+#include "imdct_fxp.h"
+#include "inv_short_complex_rot.h"
+#include "pv_normalize.h"
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+
+Int inv_short_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max)
+
+{
+    Int     i;
+    Int16     I;
+    const   Int16 *pTable;
+    const   Int32 *p_rotate;
+
+    Int32   *pData_in_1;
+    Int     exp;
+    Int32   temp_re;
+    Int32   temp_im;
+
+    Int32   exp_jw;
+    Int16   *pData_re;
+    Int16   *pData_im;
+    Int32   *pData_in_ref;
+
+    Int16   temp_re_0;
+    Int16   temp_im_0;
+    Int16   temp_re_1;
+    Int16   temp_im_1;
+    Int16   *p_data_1;
+    Int16   *p_data_2;
+    Int16   *p_Data_Int_precision;
+    Int16   *p_Data_Int_precision_1;
+    Int16   *p_Data_Int_precision_2;
+
+    Int     n     = 256;
+    Int     n_2   = n >> 1;
+    Int     n_4   = n >> 2;
+    Int     n_8   = n >> 3;
+    Int     n_3_4 = n_2 + n_4;
+
+
+    p_data_1 = (Int16 *)Data_out;
+    p_data_1 += n;
+    pData_re  = p_data_1;
+    pData_im  = p_data_1 + n_4;
+
+
+    p_rotate  =  exp_rotation_N_256;
+    pTable    =  digit_reverse_64;
+
+    pData_in_ref  =  Data_in;
+
+    exp = 16 - pv_normalize(max);
+
+
+    if (exp < 0)
+    {
+        exp = 0;
+    }
+
+    exp -= 1;
+
+    for (i = INV_SHORT_CX_ROT_LENGTH; i != 0; i--)
+    {
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+
+        /*
+         *   Perform digit reversal by accessing index I from table
+         */
+
+        I = *pTable++;
+        pData_in_1 = pData_in_ref + I;
+        /*
+         *  Use auxiliary variables to avoid double accesses to memory.
+         *  Data in is scaled to use only lower 16 bits.
+         */
+
+        temp_im =  *(pData_in_1++);
+        temp_re =  *(pData_in_1);
+
+        exp_jw = *p_rotate++;
+
+        /*
+         *   Post-rotation
+         */
+
+        *(pData_re++)  = (Int16)(cmplx_mul32_by_16(temp_re, -temp_im, exp_jw) >> exp);
+        *(pData_im++)  = (Int16)(cmplx_mul32_by_16(temp_im,  temp_re, exp_jw) >> exp);
+    }
+
+
+    p_data_2 = pData_im -  1;
+
+
+    p_Data_Int_precision = (Int16 *)Data_out;
+    p_Data_Int_precision_1 = p_Data_Int_precision + n_3_4 - 1;
+    p_Data_Int_precision_2 = p_Data_Int_precision + n_3_4;
+
+    for (i = n_8 >> 1; i != 0; i--)
+    {
+        temp_re_0 = (*(p_data_1++));
+        temp_re_1 = (*(p_data_1++));
+        temp_im_0 = (*(p_data_2--));
+        temp_im_1 = (*(p_data_2--));
+
+        *(p_Data_Int_precision_1--) =  temp_re_0;
+        *(p_Data_Int_precision_1--) =  temp_im_0;
+        *(p_Data_Int_precision_1--) =  temp_re_1;
+        *(p_Data_Int_precision_1--) =  temp_im_1;
+
+        *(p_Data_Int_precision_2++) =  temp_re_0;
+        *(p_Data_Int_precision_2++) =  temp_im_0;
+        *(p_Data_Int_precision_2++) =  temp_re_1;
+        *(p_Data_Int_precision_2++) =  temp_im_1;
+
+    }
+
+
+    /*
+     *  loop is split to avoid conditional testing inside loop
+     */
+
+    p_Data_Int_precision_2 = p_Data_Int_precision;
+
+    for (i = n_8 >> 1; i != 0; i--)
+    {
+
+        temp_re_0 = (*(p_data_1++));
+        temp_re_1 = (*(p_data_1++));
+        temp_im_0 = (*(p_data_2--));
+        temp_im_1 = (*(p_data_2--));
+
+        *(p_Data_Int_precision_1--) =   temp_re_0;
+        *(p_Data_Int_precision_1--) =   temp_im_0;
+        *(p_Data_Int_precision_1--) =   temp_re_1;
+        *(p_Data_Int_precision_1--) =   temp_im_1;
+
+        *(p_Data_Int_precision_2++) = (Int16)(-temp_re_0);
+        *(p_Data_Int_precision_2++) = (Int16)(-temp_im_0);
+        *(p_Data_Int_precision_2++) = (Int16)(-temp_re_1);
+        *(p_Data_Int_precision_2++) = (Int16)(-temp_im_1);
+
+    }
+
+    return (exp + 1);
+}
diff --git a/media/libstagefright/codecs/aacdec/inv_short_complex_rot.h b/media/libstagefright/codecs/aacdec/inv_short_complex_rot.h
new file mode 100644
index 0000000..97ed730
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/inv_short_complex_rot.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: inv_short_complex_rot.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions inv_short_complex_rot()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef INV_SHORT_COMPLEX_ROT_H
+#define INV_SHORT_COMPLEX_ROT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define INV_SHORT_CX_ROT_LENGTH 64
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int inv_short_complex_rot(
+    Int32 *Data_in,
+    Int32 *Data_out,
+    Int32  max);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* INV_SHORT_COMPLEX_ROT_H */
diff --git a/media/libstagefright/codecs/aacdec/iquant_table.cpp b/media/libstagefright/codecs/aacdec/iquant_table.cpp
new file mode 100644
index 0000000..aee47d6
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/iquant_table.cpp
@@ -0,0 +1,1131 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: iquant_table.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ None, just contains tables.
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Holds a table used for esc_iquant, containing the values of x^1/3 in
+ Q format.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7:1997 Titled "Information technology - Generic coding
+   of moving pictures and associated audio information - Part 7: Advanced
+   Audio Coding (AAC)", Section 10.3, "Decoding process", page 43.
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+ None.
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+ None.
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "iquant_table.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
+----------------------------------------------------------------------------*/
+
+/*
+   This table contains the value of x ^ (1/3) where x is in the range of
+   [0..1024], in Q27 format.
+   Note that the length of the table is 1025, and not 1024 - this is because
+   the function esc_iquant may need to do an interpolation for numbers near
+   8191, which in that case it needs to get 8192 ^(1/3).
+ */
+const UInt32 inverseQuantTable[] =
+{
+    0x00000000, /*    0 */
+    0x08000000, /*    1 */
+    0x0a14517d, /*    2 */
+    0x0b89ba25, /*    3 */
+    0x0cb2ff53, /*    4 */
+    0x0dae07de, /*    5 */
+    0x0e897685, /*    6 */
+    0x0f4daedd, /*    7 */
+    0x10000000, /*    8 */
+    0x10a402fd, /*    9 */
+    0x113c4841, /*   10 */
+    0x11cab613, /*   11 */
+    0x1250bfe2, /*   12 */
+    0x12cf8890, /*   13 */
+    0x1347f8ab, /*   14 */
+    0x13bacd65, /*   15 */
+    0x1428a2fa, /*   16 */
+    0x1491fc15, /*   17 */
+    0x14f74744, /*   18 */
+    0x1558e2f7, /*   19 */
+    0x15b72095, /*   20 */
+    0x161246d7, /*   21 */
+    0x166a9399, /*   22 */
+    0x16c03d55, /*   23 */
+    0x17137449, /*   24 */
+    0x17646369, /*   25 */
+    0x17b33124, /*   26 */
+    0x18000000, /*   27 */
+    0x184aef29, /*   28 */
+    0x18941ad8, /*   29 */
+    0x18db9cb7, /*   30 */
+    0x19218c2e, /*   31 */
+    0x1965fea5, /*   32 */
+    0x19a907c2, /*   33 */
+    0x19eab998, /*   34 */
+    0x1a2b24d0, /*   35 */
+    0x1a6a58d5, /*   36 */
+    0x1aa863ee, /*   37 */
+    0x1ae5535d, /*   38 */
+    0x1b213377, /*   39 */
+    0x1b5c0fbd, /*   40 */
+    0x1b95f2ec, /*   41 */
+    0x1bcee70f, /*   42 */
+    0x1c06f590, /*   43 */
+    0x1c3e2745, /*   44 */
+    0x1c74847a, /*   45 */
+    0x1caa1501, /*   46 */
+    0x1cdee035, /*   47 */
+    0x1d12ed0b, /*   48 */
+    0x1d464212, /*   49 */
+    0x1d78e582, /*   50 */
+    0x1daadd3a, /*   51 */
+    0x1ddc2ecf, /*   52 */
+    0x1e0cdf8c, /*   53 */
+    0x1e3cf476, /*   54 */
+    0x1e6c7257, /*   55 */
+    0x1e9b5dba, /*   56 */
+    0x1ec9baf6, /*   57 */
+    0x1ef78e2c, /*   58 */
+    0x1f24db4e, /*   59 */
+    0x1f51a620, /*   60 */
+    0x1f7df23c, /*   61 */
+    0x1fa9c314, /*   62 */
+    0x1fd51bf2, /*   63 */
+    0x20000000, /*   64 */
+    0x202a7244, /*   65 */
+    0x205475a6, /*   66 */
+    0x207e0cee, /*   67 */
+    0x20a73aca, /*   68 */
+    0x20d001cc, /*   69 */
+    0x20f8646d, /*   70 */
+    0x2120650e, /*   71 */
+    0x214805fa, /*   72 */
+    0x216f4963, /*   73 */
+    0x2196316c, /*   74 */
+    0x21bcc020, /*   75 */
+    0x21e2f77a, /*   76 */
+    0x2208d961, /*   77 */
+    0x222e67ad, /*   78 */
+    0x2253a425, /*   79 */
+    0x22789082, /*   80 */
+    0x229d2e6e, /*   81 */
+    0x22c17f82, /*   82 */
+    0x22e5854f, /*   83 */
+    0x23094155, /*   84 */
+    0x232cb509, /*   85 */
+    0x234fe1d5, /*   86 */
+    0x2372c918, /*   87 */
+    0x23956c26, /*   88 */
+    0x23b7cc47, /*   89 */
+    0x23d9eabb, /*   90 */
+    0x23fbc8b9, /*   91 */
+    0x241d676e, /*   92 */
+    0x243ec7ff, /*   93 */
+    0x245feb86, /*   94 */
+    0x2480d319, /*   95 */
+    0x24a17fc3, /*   96 */
+    0x24c1f28b, /*   97 */
+    0x24e22c6c, /*   98 */
+    0x25022e5f, /*   99 */
+    0x2521f954, /*  100 */
+    0x25418e33, /*  101 */
+    0x2560ede2, /*  102 */
+    0x2580193e, /*  103 */
+    0x259f111f, /*  104 */
+    0x25bdd657, /*  105 */
+    0x25dc69b4, /*  106 */
+    0x25facbfe, /*  107 */
+    0x2618fdf8, /*  108 */
+    0x26370060, /*  109 */
+    0x2654d3ef, /*  110 */
+    0x2672795c, /*  111 */
+    0x268ff156, /*  112 */
+    0x26ad3c8a, /*  113 */
+    0x26ca5ba2, /*  114 */
+    0x26e74f41, /*  115 */
+    0x27041808, /*  116 */
+    0x2720b695, /*  117 */
+    0x273d2b81, /*  118 */
+    0x27597762, /*  119 */
+    0x27759acb, /*  120 */
+    0x2791964b, /*  121 */
+    0x27ad6a6f, /*  122 */
+    0x27c917c0, /*  123 */
+    0x27e49ec5, /*  124 */
+    0x28000000, /*  125 */
+    0x281b3bf3, /*  126 */
+    0x2836531b, /*  127 */
+    0x285145f3, /*  128 */
+    0x286c14f5, /*  129 */
+    0x2886c096, /*  130 */
+    0x28a1494b, /*  131 */
+    0x28bbaf85, /*  132 */
+    0x28d5f3b3, /*  133 */
+    0x28f01641, /*  134 */
+    0x290a179b, /*  135 */
+    0x2923f82a, /*  136 */
+    0x293db854, /*  137 */
+    0x2957587e, /*  138 */
+    0x2970d90a, /*  139 */
+    0x298a3a59, /*  140 */
+    0x29a37cca, /*  141 */
+    0x29bca0bb, /*  142 */
+    0x29d5a687, /*  143 */
+    0x29ee8e87, /*  144 */
+    0x2a075914, /*  145 */
+    0x2a200684, /*  146 */
+    0x2a38972c, /*  147 */
+    0x2a510b5f, /*  148 */
+    0x2a696370, /*  149 */
+    0x2a819fae, /*  150 */
+    0x2a99c069, /*  151 */
+    0x2ab1c5ed, /*  152 */
+    0x2ac9b088, /*  153 */
+    0x2ae18085, /*  154 */
+    0x2af9362c, /*  155 */
+    0x2b10d1c6, /*  156 */
+    0x2b28539b, /*  157 */
+    0x2b3fbbef, /*  158 */
+    0x2b570b09, /*  159 */
+    0x2b6e412b, /*  160 */
+    0x2b855e97, /*  161 */
+    0x2b9c6390, /*  162 */
+    0x2bb35056, /*  163 */
+    0x2bca2527, /*  164 */
+    0x2be0e242, /*  165 */
+    0x2bf787e4, /*  166 */
+    0x2c0e1649, /*  167 */
+    0x2c248dad, /*  168 */
+    0x2c3aee4a, /*  169 */
+    0x2c513859, /*  170 */
+    0x2c676c13, /*  171 */
+    0x2c7d89af, /*  172 */
+    0x2c939164, /*  173 */
+    0x2ca98368, /*  174 */
+    0x2cbf5ff1, /*  175 */
+    0x2cd52731, /*  176 */
+    0x2cead95e, /*  177 */
+    0x2d0076a9, /*  178 */
+    0x2d15ff45, /*  179 */
+    0x2d2b7363, /*  180 */
+    0x2d40d332, /*  181 */
+    0x2d561ee4, /*  182 */
+    0x2d6b56a7, /*  183 */
+    0x2d807aaa, /*  184 */
+    0x2d958b19, /*  185 */
+    0x2daa8823, /*  186 */
+    0x2dbf71f4, /*  187 */
+    0x2dd448b7, /*  188 */
+    0x2de90c98, /*  189 */
+    0x2dfdbdc0, /*  190 */
+    0x2e125c5c, /*  191 */
+    0x2e26e892, /*  192 */
+    0x2e3b628d, /*  193 */
+    0x2e4fca75, /*  194 */
+    0x2e642070, /*  195 */
+    0x2e7864a8, /*  196 */
+    0x2e8c9741, /*  197 */
+    0x2ea0b862, /*  198 */
+    0x2eb4c831, /*  199 */
+    0x2ec8c6d3, /*  200 */
+    0x2edcb46c, /*  201 */
+    0x2ef09121, /*  202 */
+    0x2f045d14, /*  203 */
+    0x2f18186a, /*  204 */
+    0x2f2bc345, /*  205 */
+    0x2f3f5dc7, /*  206 */
+    0x2f52e812, /*  207 */
+    0x2f666247, /*  208 */
+    0x2f79cc88, /*  209 */
+    0x2f8d26f4, /*  210 */
+    0x2fa071ac, /*  211 */
+    0x2fb3acd0, /*  212 */
+    0x2fc6d87f, /*  213 */
+    0x2fd9f4d7, /*  214 */
+    0x2fed01f8, /*  215 */
+    0x30000000, /*  216 */
+    0x3012ef0c, /*  217 */
+    0x3025cf39, /*  218 */
+    0x3038a0a6, /*  219 */
+    0x304b636d, /*  220 */
+    0x305e17ad, /*  221 */
+    0x3070bd81, /*  222 */
+    0x30835504, /*  223 */
+    0x3095de51, /*  224 */
+    0x30a85985, /*  225 */
+    0x30bac6b9, /*  226 */
+    0x30cd2609, /*  227 */
+    0x30df778d, /*  228 */
+    0x30f1bb60, /*  229 */
+    0x3103f19c, /*  230 */
+    0x31161a59, /*  231 */
+    0x312835b0, /*  232 */
+    0x313a43ba, /*  233 */
+    0x314c4490, /*  234 */
+    0x315e3849, /*  235 */
+    0x31701efd, /*  236 */
+    0x3181f8c4, /*  237 */
+    0x3193c5b4, /*  238 */
+    0x31a585e6, /*  239 */
+    0x31b7396f, /*  240 */
+    0x31c8e066, /*  241 */
+    0x31da7ae1, /*  242 */
+    0x31ec08f6, /*  243 */
+    0x31fd8abc, /*  244 */
+    0x320f0047, /*  245 */
+    0x322069ac, /*  246 */
+    0x3231c702, /*  247 */
+    0x3243185c, /*  248 */
+    0x32545dcf, /*  249 */
+    0x32659770, /*  250 */
+    0x3276c552, /*  251 */
+    0x3287e78a, /*  252 */
+    0x3298fe2c, /*  253 */
+    0x32aa094a, /*  254 */
+    0x32bb08f9, /*  255 */
+    0x32cbfd4a, /*  256 */
+    0x32dce652, /*  257 */
+    0x32edc423, /*  258 */
+    0x32fe96d0, /*  259 */
+    0x330f5e6a, /*  260 */
+    0x33201b04, /*  261 */
+    0x3330ccb0, /*  262 */
+    0x33417380, /*  263 */
+    0x33520f85, /*  264 */
+    0x3362a0d0, /*  265 */
+    0x33732774, /*  266 */
+    0x3383a380, /*  267 */
+    0x33941506, /*  268 */
+    0x33a47c17, /*  269 */
+    0x33b4d8c4, /*  270 */
+    0x33c52b1b, /*  271 */
+    0x33d5732f, /*  272 */
+    0x33e5b10f, /*  273 */
+    0x33f5e4ca, /*  274 */
+    0x34060e71, /*  275 */
+    0x34162e14, /*  276 */
+    0x342643c1, /*  277 */
+    0x34364f88, /*  278 */
+    0x34465178, /*  279 */
+    0x345649a1, /*  280 */
+    0x34663810, /*  281 */
+    0x34761cd6, /*  282 */
+    0x3485f800, /*  283 */
+    0x3495c99d, /*  284 */
+    0x34a591bb, /*  285 */
+    0x34b55069, /*  286 */
+    0x34c505b4, /*  287 */
+    0x34d4b1ab, /*  288 */
+    0x34e4545b, /*  289 */
+    0x34f3edd2, /*  290 */
+    0x35037e1d, /*  291 */
+    0x3513054b, /*  292 */
+    0x35228367, /*  293 */
+    0x3531f881, /*  294 */
+    0x354164a3, /*  295 */
+    0x3550c7dc, /*  296 */
+    0x35602239, /*  297 */
+    0x356f73c5, /*  298 */
+    0x357ebc8e, /*  299 */
+    0x358dfca0, /*  300 */
+    0x359d3408, /*  301 */
+    0x35ac62d1, /*  302 */
+    0x35bb8908, /*  303 */
+    0x35caa6b9, /*  304 */
+    0x35d9bbf0, /*  305 */
+    0x35e8c8b9, /*  306 */
+    0x35f7cd20, /*  307 */
+    0x3606c92f, /*  308 */
+    0x3615bcf3, /*  309 */
+    0x3624a878, /*  310 */
+    0x36338bc8, /*  311 */
+    0x364266ee, /*  312 */
+    0x365139f6, /*  313 */
+    0x366004ec, /*  314 */
+    0x366ec7d9, /*  315 */
+    0x367d82c9, /*  316 */
+    0x368c35c6, /*  317 */
+    0x369ae0dc, /*  318 */
+    0x36a98414, /*  319 */
+    0x36b81f7a, /*  320 */
+    0x36c6b317, /*  321 */
+    0x36d53ef7, /*  322 */
+    0x36e3c323, /*  323 */
+    0x36f23fa5, /*  324 */
+    0x3700b488, /*  325 */
+    0x370f21d5, /*  326 */
+    0x371d8797, /*  327 */
+    0x372be5d7, /*  328 */
+    0x373a3ca0, /*  329 */
+    0x37488bf9, /*  330 */
+    0x3756d3ef, /*  331 */
+    0x37651489, /*  332 */
+    0x37734dd1, /*  333 */
+    0x37817fd1, /*  334 */
+    0x378faa92, /*  335 */
+    0x379dce1d, /*  336 */
+    0x37abea7c, /*  337 */
+    0x37b9ffb7, /*  338 */
+    0x37c80dd7, /*  339 */
+    0x37d614e6, /*  340 */
+    0x37e414ec, /*  341 */
+    0x37f20df1, /*  342 */
+    0x38000000, /*  343 */
+    0x380deb20, /*  344 */
+    0x381bcf5a, /*  345 */
+    0x3829acb6, /*  346 */
+    0x3837833d, /*  347 */
+    0x384552f8, /*  348 */
+    0x38531bee, /*  349 */
+    0x3860de28, /*  350 */
+    0x386e99af, /*  351 */
+    0x387c4e89, /*  352 */
+    0x3889fcc0, /*  353 */
+    0x3897a45b, /*  354 */
+    0x38a54563, /*  355 */
+    0x38b2dfdf, /*  356 */
+    0x38c073d7, /*  357 */
+    0x38ce0152, /*  358 */
+    0x38db885a, /*  359 */
+    0x38e908f4, /*  360 */
+    0x38f68329, /*  361 */
+    0x3903f701, /*  362 */
+    0x39116483, /*  363 */
+    0x391ecbb6, /*  364 */
+    0x392c2ca1, /*  365 */
+    0x3939874d, /*  366 */
+    0x3946dbc0, /*  367 */
+    0x39542a01, /*  368 */
+    0x39617218, /*  369 */
+    0x396eb40c, /*  370 */
+    0x397befe4, /*  371 */
+    0x398925a7, /*  372 */
+    0x3996555c, /*  373 */
+    0x39a37f09, /*  374 */
+    0x39b0a2b7, /*  375 */
+    0x39bdc06a, /*  376 */
+    0x39cad82b, /*  377 */
+    0x39d7ea01, /*  378 */
+    0x39e4f5f0, /*  379 */
+    0x39f1fc01, /*  380 */
+    0x39fefc3a, /*  381 */
+    0x3a0bf6a2, /*  382 */
+    0x3a18eb3e, /*  383 */
+    0x3a25da16, /*  384 */
+    0x3a32c32f, /*  385 */
+    0x3a3fa691, /*  386 */
+    0x3a4c8441, /*  387 */
+    0x3a595c46, /*  388 */
+    0x3a662ea6, /*  389 */
+    0x3a72fb67, /*  390 */
+    0x3a7fc28f, /*  391 */
+    0x3a8c8425, /*  392 */
+    0x3a99402e, /*  393 */
+    0x3aa5f6b1, /*  394 */
+    0x3ab2a7b3, /*  395 */
+    0x3abf533a, /*  396 */
+    0x3acbf94d, /*  397 */
+    0x3ad899f1, /*  398 */
+    0x3ae5352c, /*  399 */
+    0x3af1cb03, /*  400 */
+    0x3afe5b7d, /*  401 */
+    0x3b0ae6a0, /*  402 */
+    0x3b176c70, /*  403 */
+    0x3b23ecf3, /*  404 */
+    0x3b306830, /*  405 */
+    0x3b3cde2c, /*  406 */
+    0x3b494eeb, /*  407 */
+    0x3b55ba74, /*  408 */
+    0x3b6220cc, /*  409 */
+    0x3b6e81f9, /*  410 */
+    0x3b7ade00, /*  411 */
+    0x3b8734e5, /*  412 */
+    0x3b9386b0, /*  413 */
+    0x3b9fd364, /*  414 */
+    0x3bac1b07, /*  415 */
+    0x3bb85d9e, /*  416 */
+    0x3bc49b2f, /*  417 */
+    0x3bd0d3be, /*  418 */
+    0x3bdd0751, /*  419 */
+    0x3be935ed, /*  420 */
+    0x3bf55f97, /*  421 */
+    0x3c018453, /*  422 */
+    0x3c0da427, /*  423 */
+    0x3c19bf17, /*  424 */
+    0x3c25d52a, /*  425 */
+    0x3c31e662, /*  426 */
+    0x3c3df2c6, /*  427 */
+    0x3c49fa5b, /*  428 */
+    0x3c55fd24, /*  429 */
+    0x3c61fb27, /*  430 */
+    0x3c6df468, /*  431 */
+    0x3c79e8ed, /*  432 */
+    0x3c85d8b9, /*  433 */
+    0x3c91c3d2, /*  434 */
+    0x3c9daa3c, /*  435 */
+    0x3ca98bfc, /*  436 */
+    0x3cb56915, /*  437 */
+    0x3cc1418e, /*  438 */
+    0x3ccd156a, /*  439 */
+    0x3cd8e4ae, /*  440 */
+    0x3ce4af5e, /*  441 */
+    0x3cf0757f, /*  442 */
+    0x3cfc3714, /*  443 */
+    0x3d07f423, /*  444 */
+    0x3d13acb0, /*  445 */
+    0x3d1f60bf, /*  446 */
+    0x3d2b1055, /*  447 */
+    0x3d36bb75, /*  448 */
+    0x3d426224, /*  449 */
+    0x3d4e0466, /*  450 */
+    0x3d59a23f, /*  451 */
+    0x3d653bb4, /*  452 */
+    0x3d70d0c8, /*  453 */
+    0x3d7c6180, /*  454 */
+    0x3d87ede0, /*  455 */
+    0x3d9375ec, /*  456 */
+    0x3d9ef9a8, /*  457 */
+    0x3daa7918, /*  458 */
+    0x3db5f43f, /*  459 */
+    0x3dc16b23, /*  460 */
+    0x3dccddc7, /*  461 */
+    0x3dd84c2e, /*  462 */
+    0x3de3b65d, /*  463 */
+    0x3def1c58, /*  464 */
+    0x3dfa7e22, /*  465 */
+    0x3e05dbc0, /*  466 */
+    0x3e113535, /*  467 */
+    0x3e1c8a85, /*  468 */
+    0x3e27dbb3, /*  469 */
+    0x3e3328c4, /*  470 */
+    0x3e3e71bb, /*  471 */
+    0x3e49b69c, /*  472 */
+    0x3e54f76b, /*  473 */
+    0x3e60342b, /*  474 */
+    0x3e6b6ce0, /*  475 */
+    0x3e76a18d, /*  476 */
+    0x3e81d237, /*  477 */
+    0x3e8cfee0, /*  478 */
+    0x3e98278d, /*  479 */
+    0x3ea34c40, /*  480 */
+    0x3eae6cfe, /*  481 */
+    0x3eb989ca, /*  482 */
+    0x3ec4a2a8, /*  483 */
+    0x3ecfb79a, /*  484 */
+    0x3edac8a5, /*  485 */
+    0x3ee5d5cb, /*  486 */
+    0x3ef0df10, /*  487 */
+    0x3efbe478, /*  488 */
+    0x3f06e606, /*  489 */
+    0x3f11e3be, /*  490 */
+    0x3f1cdda2, /*  491 */
+    0x3f27d3b6, /*  492 */
+    0x3f32c5fd, /*  493 */
+    0x3f3db47b, /*  494 */
+    0x3f489f32, /*  495 */
+    0x3f538627, /*  496 */
+    0x3f5e695c, /*  497 */
+    0x3f6948d5, /*  498 */
+    0x3f742494, /*  499 */
+    0x3f7efc9d, /*  500 */
+    0x3f89d0f3, /*  501 */
+    0x3f94a19a, /*  502 */
+    0x3f9f6e94, /*  503 */
+    0x3faa37e4, /*  504 */
+    0x3fb4fd8e, /*  505 */
+    0x3fbfbf94, /*  506 */
+    0x3fca7dfb, /*  507 */
+    0x3fd538c4, /*  508 */
+    0x3fdfeff3, /*  509 */
+    0x3feaa38a, /*  510 */
+    0x3ff5538e, /*  511 */
+    0x40000000, /*  512 */
+    0x400aa8e4, /*  513 */
+    0x40154e3d, /*  514 */
+    0x401ff00d, /*  515 */
+    0x402a8e58, /*  516 */
+    0x40352921, /*  517 */
+    0x403fc06a, /*  518 */
+    0x404a5436, /*  519 */
+    0x4054e488, /*  520 */
+    0x405f7164, /*  521 */
+    0x4069facb, /*  522 */
+    0x407480c1, /*  523 */
+    0x407f0348, /*  524 */
+    0x40898264, /*  525 */
+    0x4093fe16, /*  526 */
+    0x409e7663, /*  527 */
+    0x40a8eb4c, /*  528 */
+    0x40b35cd4, /*  529 */
+    0x40bdcafe, /*  530 */
+    0x40c835cd, /*  531 */
+    0x40d29d43, /*  532 */
+    0x40dd0164, /*  533 */
+    0x40e76231, /*  534 */
+    0x40f1bfae, /*  535 */
+    0x40fc19dc, /*  536 */
+    0x410670c0, /*  537 */
+    0x4110c45a, /*  538 */
+    0x411b14af, /*  539 */
+    0x412561c0, /*  540 */
+    0x412fab90, /*  541 */
+    0x4139f222, /*  542 */
+    0x41443578, /*  543 */
+    0x414e7595, /*  544 */
+    0x4158b27a, /*  545 */
+    0x4162ec2c, /*  546 */
+    0x416d22ac, /*  547 */
+    0x417755fd, /*  548 */
+    0x41818621, /*  549 */
+    0x418bb31a, /*  550 */
+    0x4195dcec, /*  551 */
+    0x41a00399, /*  552 */
+    0x41aa2722, /*  553 */
+    0x41b4478b, /*  554 */
+    0x41be64d6, /*  555 */
+    0x41c87f05, /*  556 */
+    0x41d2961a, /*  557 */
+    0x41dcaa19, /*  558 */
+    0x41e6bb03, /*  559 */
+    0x41f0c8db, /*  560 */
+    0x41fad3a3, /*  561 */
+    0x4204db5d, /*  562 */
+    0x420ee00c, /*  563 */
+    0x4218e1b1, /*  564 */
+    0x4222e051, /*  565 */
+    0x422cdbeb, /*  566 */
+    0x4236d484, /*  567 */
+    0x4240ca1d, /*  568 */
+    0x424abcb8, /*  569 */
+    0x4254ac58, /*  570 */
+    0x425e98fe, /*  571 */
+    0x426882ae, /*  572 */
+    0x42726969, /*  573 */
+    0x427c4d31, /*  574 */
+    0x42862e09, /*  575 */
+    0x42900bf3, /*  576 */
+    0x4299e6f1, /*  577 */
+    0x42a3bf05, /*  578 */
+    0x42ad9432, /*  579 */
+    0x42b76678, /*  580 */
+    0x42c135dc, /*  581 */
+    0x42cb025e, /*  582 */
+    0x42d4cc01, /*  583 */
+    0x42de92c7, /*  584 */
+    0x42e856b2, /*  585 */
+    0x42f217c4, /*  586 */
+    0x42fbd5ff, /*  587 */
+    0x43059166, /*  588 */
+    0x430f49f9, /*  589 */
+    0x4318ffbc, /*  590 */
+    0x4322b2b1, /*  591 */
+    0x432c62d8, /*  592 */
+    0x43361036, /*  593 */
+    0x433fbaca, /*  594 */
+    0x43496298, /*  595 */
+    0x435307a2, /*  596 */
+    0x435ca9e8, /*  597 */
+    0x4366496e, /*  598 */
+    0x436fe636, /*  599 */
+    0x43798041, /*  600 */
+    0x43831790, /*  601 */
+    0x438cac28, /*  602 */
+    0x43963e08, /*  603 */
+    0x439fcd33, /*  604 */
+    0x43a959ab, /*  605 */
+    0x43b2e372, /*  606 */
+    0x43bc6a89, /*  607 */
+    0x43c5eef3, /*  608 */
+    0x43cf70b2, /*  609 */
+    0x43d8efc7, /*  610 */
+    0x43e26c34, /*  611 */
+    0x43ebe5fb, /*  612 */
+    0x43f55d1e, /*  613 */
+    0x43fed19f, /*  614 */
+    0x44084380, /*  615 */
+    0x4411b2c1, /*  616 */
+    0x441b1f66, /*  617 */
+    0x44248970, /*  618 */
+    0x442df0e1, /*  619 */
+    0x443755bb, /*  620 */
+    0x4440b7fe, /*  621 */
+    0x444a17ae, /*  622 */
+    0x445374cc, /*  623 */
+    0x445ccf5a, /*  624 */
+    0x44662758, /*  625 */
+    0x446f7ccb, /*  626 */
+    0x4478cfb2, /*  627 */
+    0x4482200f, /*  628 */
+    0x448b6de5, /*  629 */
+    0x4494b935, /*  630 */
+    0x449e0201, /*  631 */
+    0x44a7484b, /*  632 */
+    0x44b08c13, /*  633 */
+    0x44b9cd5d, /*  634 */
+    0x44c30c29, /*  635 */
+    0x44cc4879, /*  636 */
+    0x44d5824f, /*  637 */
+    0x44deb9ac, /*  638 */
+    0x44e7ee93, /*  639 */
+    0x44f12105, /*  640 */
+    0x44fa5103, /*  641 */
+    0x45037e8f, /*  642 */
+    0x450ca9ab, /*  643 */
+    0x4515d258, /*  644 */
+    0x451ef899, /*  645 */
+    0x45281c6e, /*  646 */
+    0x45313dd8, /*  647 */
+    0x453a5cdb, /*  648 */
+    0x45437977, /*  649 */
+    0x454c93ae, /*  650 */
+    0x4555ab82, /*  651 */
+    0x455ec0f3, /*  652 */
+    0x4567d404, /*  653 */
+    0x4570e4b7, /*  654 */
+    0x4579f30c, /*  655 */
+    0x4582ff05, /*  656 */
+    0x458c08a4, /*  657 */
+    0x45950fea, /*  658 */
+    0x459e14d9, /*  659 */
+    0x45a71773, /*  660 */
+    0x45b017b8, /*  661 */
+    0x45b915aa, /*  662 */
+    0x45c2114c, /*  663 */
+    0x45cb0a9e, /*  664 */
+    0x45d401a1, /*  665 */
+    0x45dcf658, /*  666 */
+    0x45e5e8c4, /*  667 */
+    0x45eed8e6, /*  668 */
+    0x45f7c6c0, /*  669 */
+    0x4600b253, /*  670 */
+    0x46099ba0, /*  671 */
+    0x461282a9, /*  672 */
+    0x461b6770, /*  673 */
+    0x462449f6, /*  674 */
+    0x462d2a3c, /*  675 */
+    0x46360844, /*  676 */
+    0x463ee40f, /*  677 */
+    0x4647bd9f, /*  678 */
+    0x465094f5, /*  679 */
+    0x46596a12, /*  680 */
+    0x46623cf8, /*  681 */
+    0x466b0da8, /*  682 */
+    0x4673dc24, /*  683 */
+    0x467ca86c, /*  684 */
+    0x46857283, /*  685 */
+    0x468e3a69, /*  686 */
+    0x46970021, /*  687 */
+    0x469fc3ab, /*  688 */
+    0x46a88509, /*  689 */
+    0x46b1443b, /*  690 */
+    0x46ba0144, /*  691 */
+    0x46c2bc25, /*  692 */
+    0x46cb74df, /*  693 */
+    0x46d42b74, /*  694 */
+    0x46dcdfe4, /*  695 */
+    0x46e59231, /*  696 */
+    0x46ee425c, /*  697 */
+    0x46f6f068, /*  698 */
+    0x46ff9c54, /*  699 */
+    0x47084622, /*  700 */
+    0x4710edd4, /*  701 */
+    0x4719936b, /*  702 */
+    0x472236e7, /*  703 */
+    0x472ad84b, /*  704 */
+    0x47337798, /*  705 */
+    0x473c14cf, /*  706 */
+    0x4744aff1, /*  707 */
+    0x474d48ff, /*  708 */
+    0x4755dffb, /*  709 */
+    0x475e74e6, /*  710 */
+    0x476707c1, /*  711 */
+    0x476f988e, /*  712 */
+    0x4778274d, /*  713 */
+    0x4780b400, /*  714 */
+    0x47893ea8, /*  715 */
+    0x4791c746, /*  716 */
+    0x479a4ddc, /*  717 */
+    0x47a2d26b, /*  718 */
+    0x47ab54f3, /*  719 */
+    0x47b3d577, /*  720 */
+    0x47bc53f7, /*  721 */
+    0x47c4d074, /*  722 */
+    0x47cd4af0, /*  723 */
+    0x47d5c36c, /*  724 */
+    0x47de39e9, /*  725 */
+    0x47e6ae69, /*  726 */
+    0x47ef20ec, /*  727 */
+    0x47f79173, /*  728 */
+    0x48000000, /*  729 */
+    0x48086c94, /*  730 */
+    0x4810d730, /*  731 */
+    0x48193fd5, /*  732 */
+    0x4821a685, /*  733 */
+    0x482a0b40, /*  734 */
+    0x48326e07, /*  735 */
+    0x483acedd, /*  736 */
+    0x48432dc1, /*  737 */
+    0x484b8ab5, /*  738 */
+    0x4853e5bb, /*  739 */
+    0x485c3ed2, /*  740 */
+    0x486495fd, /*  741 */
+    0x486ceb3c, /*  742 */
+    0x48753e91, /*  743 */
+    0x487d8ffd, /*  744 */
+    0x4885df80, /*  745 */
+    0x488e2d1d, /*  746 */
+    0x489678d3, /*  747 */
+    0x489ec2a4, /*  748 */
+    0x48a70a91, /*  749 */
+    0x48af509b, /*  750 */
+    0x48b794c4, /*  751 */
+    0x48bfd70c, /*  752 */
+    0x48c81774, /*  753 */
+    0x48d055fe, /*  754 */
+    0x48d892aa, /*  755 */
+    0x48e0cd7a, /*  756 */
+    0x48e9066e, /*  757 */
+    0x48f13d88, /*  758 */
+    0x48f972c9, /*  759 */
+    0x4901a632, /*  760 */
+    0x4909d7c3, /*  761 */
+    0x4912077e, /*  762 */
+    0x491a3564, /*  763 */
+    0x49226175, /*  764 */
+    0x492a8bb4, /*  765 */
+    0x4932b420, /*  766 */
+    0x493adabc, /*  767 */
+    0x4942ff87, /*  768 */
+    0x494b2283, /*  769 */
+    0x495343b1, /*  770 */
+    0x495b6312, /*  771 */
+    0x496380a7, /*  772 */
+    0x496b9c71, /*  773 */
+    0x4973b670, /*  774 */
+    0x497bcea7, /*  775 */
+    0x4983e515, /*  776 */
+    0x498bf9bc, /*  777 */
+    0x49940c9e, /*  778 */
+    0x499c1db9, /*  779 */
+    0x49a42d11, /*  780 */
+    0x49ac3aa5, /*  781 */
+    0x49b44677, /*  782 */
+    0x49bc5088, /*  783 */
+    0x49c458d8, /*  784 */
+    0x49cc5f69, /*  785 */
+    0x49d4643c, /*  786 */
+    0x49dc6750, /*  787 */
+    0x49e468a9, /*  788 */
+    0x49ec6845, /*  789 */
+    0x49f46627, /*  790 */
+    0x49fc624f, /*  791 */
+    0x4a045cbe, /*  792 */
+    0x4a0c5575, /*  793 */
+    0x4a144c76, /*  794 */
+    0x4a1c41c0, /*  795 */
+    0x4a243555, /*  796 */
+    0x4a2c2735, /*  797 */
+    0x4a341763, /*  798 */
+    0x4a3c05de, /*  799 */
+    0x4a43f2a7, /*  800 */
+    0x4a4bddc0, /*  801 */
+    0x4a53c729, /*  802 */
+    0x4a5baee3, /*  803 */
+    0x4a6394ef, /*  804 */
+    0x4a6b794f, /*  805 */
+    0x4a735c02, /*  806 */
+    0x4a7b3d09, /*  807 */
+    0x4a831c67, /*  808 */
+    0x4a8afa1b, /*  809 */
+    0x4a92d626, /*  810 */
+    0x4a9ab089, /*  811 */
+    0x4aa28946, /*  812 */
+    0x4aaa605d, /*  813 */
+    0x4ab235ce, /*  814 */
+    0x4aba099b, /*  815 */
+    0x4ac1dbc5, /*  816 */
+    0x4ac9ac4c, /*  817 */
+    0x4ad17b31, /*  818 */
+    0x4ad94876, /*  819 */
+    0x4ae1141a, /*  820 */
+    0x4ae8de1f, /*  821 */
+    0x4af0a686, /*  822 */
+    0x4af86d50, /*  823 */
+    0x4b00327d, /*  824 */
+    0x4b07f60d, /*  825 */
+    0x4b0fb803, /*  826 */
+    0x4b17785f, /*  827 */
+    0x4b1f3722, /*  828 */
+    0x4b26f44b, /*  829 */
+    0x4b2eafde, /*  830 */
+    0x4b3669d9, /*  831 */
+    0x4b3e223e, /*  832 */
+    0x4b45d90e, /*  833 */
+    0x4b4d8e4a, /*  834 */
+    0x4b5541f2, /*  835 */
+    0x4b5cf407, /*  836 */
+    0x4b64a48a, /*  837 */
+    0x4b6c537c, /*  838 */
+    0x4b7400dd, /*  839 */
+    0x4b7bacaf, /*  840 */
+    0x4b8356f2, /*  841 */
+    0x4b8affa7, /*  842 */
+    0x4b92a6ce, /*  843 */
+    0x4b9a4c69, /*  844 */
+    0x4ba1f079, /*  845 */
+    0x4ba992fd, /*  846 */
+    0x4bb133f8, /*  847 */
+    0x4bb8d369, /*  848 */
+    0x4bc07151, /*  849 */
+    0x4bc80db2, /*  850 */
+    0x4bcfa88c, /*  851 */
+    0x4bd741df, /*  852 */
+    0x4bded9ad, /*  853 */
+    0x4be66ff6, /*  854 */
+    0x4bee04bb, /*  855 */
+    0x4bf597fc, /*  856 */
+    0x4bfd29bc, /*  857 */
+    0x4c04b9f9, /*  858 */
+    0x4c0c48b6, /*  859 */
+    0x4c13d5f2, /*  860 */
+    0x4c1b61af, /*  861 */
+    0x4c22ebed, /*  862 */
+    0x4c2a74ad, /*  863 */
+    0x4c31fbf0, /*  864 */
+    0x4c3981b6, /*  865 */
+    0x4c410600, /*  866 */
+    0x4c4888d0, /*  867 */
+    0x4c500a25, /*  868 */
+    0x4c578a00, /*  869 */
+    0x4c5f0862, /*  870 */
+    0x4c66854c, /*  871 */
+    0x4c6e00bf, /*  872 */
+    0x4c757abb, /*  873 */
+    0x4c7cf341, /*  874 */
+    0x4c846a52, /*  875 */
+    0x4c8bdfee, /*  876 */
+    0x4c935416, /*  877 */
+    0x4c9ac6cb, /*  878 */
+    0x4ca2380e, /*  879 */
+    0x4ca9a7de, /*  880 */
+    0x4cb1163e, /*  881 */
+    0x4cb8832d, /*  882 */
+    0x4cbfeead, /*  883 */
+    0x4cc758bd, /*  884 */
+    0x4ccec15f, /*  885 */
+    0x4cd62894, /*  886 */
+    0x4cdd8e5c, /*  887 */
+    0x4ce4f2b7, /*  888 */
+    0x4cec55a7, /*  889 */
+    0x4cf3b72c, /*  890 */
+    0x4cfb1747, /*  891 */
+    0x4d0275f8, /*  892 */
+    0x4d09d340, /*  893 */
+    0x4d112f21, /*  894 */
+    0x4d188999, /*  895 */
+    0x4d1fe2ab, /*  896 */
+    0x4d273a57, /*  897 */
+    0x4d2e909d, /*  898 */
+    0x4d35e57f, /*  899 */
+    0x4d3d38fc, /*  900 */
+    0x4d448b16, /*  901 */
+    0x4d4bdbcd, /*  902 */
+    0x4d532b21, /*  903 */
+    0x4d5a7914, /*  904 */
+    0x4d61c5a7, /*  905 */
+    0x4d6910d9, /*  906 */
+    0x4d705aab, /*  907 */
+    0x4d77a31e, /*  908 */
+    0x4d7eea34, /*  909 */
+    0x4d862feb, /*  910 */
+    0x4d8d7445, /*  911 */
+    0x4d94b743, /*  912 */
+    0x4d9bf8e6, /*  913 */
+    0x4da3392d, /*  914 */
+    0x4daa7819, /*  915 */
+    0x4db1b5ac, /*  916 */
+    0x4db8f1e6, /*  917 */
+    0x4dc02cc7, /*  918 */
+    0x4dc76650, /*  919 */
+    0x4dce9e81, /*  920 */
+    0x4dd5d55c, /*  921 */
+    0x4ddd0ae1, /*  922 */
+    0x4de43f10, /*  923 */
+    0x4deb71eb, /*  924 */
+    0x4df2a371, /*  925 */
+    0x4df9d3a3, /*  926 */
+    0x4e010283, /*  927 */
+    0x4e083010, /*  928 */
+    0x4e0f5c4b, /*  929 */
+    0x4e168735, /*  930 */
+    0x4e1db0cf, /*  931 */
+    0x4e24d918, /*  932 */
+    0x4e2c0012, /*  933 */
+    0x4e3325bd, /*  934 */
+    0x4e3a4a1a, /*  935 */
+    0x4e416d2a, /*  936 */
+    0x4e488eec, /*  937 */
+    0x4e4faf62, /*  938 */
+    0x4e56ce8c, /*  939 */
+    0x4e5dec6b, /*  940 */
+    0x4e6508ff, /*  941 */
+    0x4e6c2449, /*  942 */
+    0x4e733e4a, /*  943 */
+    0x4e7a5702, /*  944 */
+    0x4e816e71, /*  945 */
+    0x4e888498, /*  946 */
+    0x4e8f9979, /*  947 */
+    0x4e96ad13, /*  948 */
+    0x4e9dbf67, /*  949 */
+    0x4ea4d075, /*  950 */
+    0x4eabe03e, /*  951 */
+    0x4eb2eec4, /*  952 */
+    0x4eb9fc05, /*  953 */
+    0x4ec10803, /*  954 */
+    0x4ec812bf, /*  955 */
+    0x4ecf1c39, /*  956 */
+    0x4ed62471, /*  957 */
+    0x4edd2b68, /*  958 */
+    0x4ee4311f, /*  959 */
+    0x4eeb3596, /*  960 */
+    0x4ef238cd, /*  961 */
+    0x4ef93ac6, /*  962 */
+    0x4f003b81, /*  963 */
+    0x4f073afe, /*  964 */
+    0x4f0e393f, /*  965 */
+    0x4f153642, /*  966 */
+    0x4f1c320a, /*  967 */
+    0x4f232c96, /*  968 */
+    0x4f2a25e8, /*  969 */
+    0x4f311dff, /*  970 */
+    0x4f3814dc, /*  971 */
+    0x4f3f0a80, /*  972 */
+    0x4f45feeb, /*  973 */
+    0x4f4cf21f, /*  974 */
+    0x4f53e41a, /*  975 */
+    0x4f5ad4de, /*  976 */
+    0x4f61c46c, /*  977 */
+    0x4f68b2c4, /*  978 */
+    0x4f6f9fe6, /*  979 */
+    0x4f768bd3, /*  980 */
+    0x4f7d768c, /*  981 */
+    0x4f846011, /*  982 */
+    0x4f8b4862, /*  983 */
+    0x4f922f81, /*  984 */
+    0x4f99156d, /*  985 */
+    0x4f9ffa27, /*  986 */
+    0x4fa6ddb0, /*  987 */
+    0x4fadc008, /*  988 */
+    0x4fb4a12f, /*  989 */
+    0x4fbb8127, /*  990 */
+    0x4fc25ff0, /*  991 */
+    0x4fc93d8a, /*  992 */
+    0x4fd019f5, /*  993 */
+    0x4fd6f533, /*  994 */
+    0x4fddcf43, /*  995 */
+    0x4fe4a827, /*  996 */
+    0x4feb7fde, /*  997 */
+    0x4ff2566a, /*  998 */
+    0x4ff92bca, /*  999 */
+    0x50000000, /* 1000 */
+    0x5006d30b, /* 1001 */
+    0x500da4ed, /* 1002 */
+    0x501475a5, /* 1003 */
+    0x501b4535, /* 1004 */
+    0x5022139c, /* 1005 */
+    0x5028e0dc, /* 1006 */
+    0x502facf4, /* 1007 */
+    0x503677e5, /* 1008 */
+    0x503d41b0, /* 1009 */
+    0x50440a55, /* 1010 */
+    0x504ad1d5, /* 1011 */
+    0x50519830, /* 1012 */
+    0x50585d67, /* 1013 */
+    0x505f217a, /* 1014 */
+    0x5065e469, /* 1015 */
+    0x506ca635, /* 1016 */
+    0x507366df, /* 1017 */
+    0x507a2667, /* 1018 */
+    0x5080e4cd, /* 1019 */
+    0x5087a212, /* 1020 */
+    0x508e5e37, /* 1021 */
+    0x5095193c, /* 1022 */
+    0x509bd320, /* 1023 */
+    0x50a28be6, /* 1024 */
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/aacdec/iquant_table.h b/media/libstagefright/codecs/aacdec/iquant_table.h
new file mode 100644
index 0000000..dadc3d0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/iquant_table.h
@@ -0,0 +1,85 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: iquant_table.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for iquant_table.c, which contains a table used with
+ esc_iquant.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef IQUANT_TABLE_H
+#define IQUANT_TABLE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 UInt32 inverseQuantTable[];
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/long_term_prediction.cpp b/media/libstagefright/codecs/aacdec/long_term_prediction.cpp
new file mode 100644
index 0000000..69e4c46
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/long_term_prediction.cpp
@@ -0,0 +1,648 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: long_term_prediction.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made changes based on comments and experiment results.
+
+ Description: Passed in buffer sizes based on review comments and prototype
+              agreements.
+
+ Description: 1. Passed in "weight_index" instead of "weight".
+              2. Added weight table.
+
+ Description: 1. Removed some passed in buffer size variables since they are
+                 not used for long window.
+              2. Modified comments format.
+
+ Description:
+    Modified casting to ensure proper operations for different platforms
+
+ Description:
+    Implemented circular buffer techniques, which save 4096 memmoves per
+    frame.
+
+ Description:
+    Implemented some optimizations found during the code review of this
+    module.  The optimizations related to the rules on the range of
+    ltp_buffer_index and num_samples, which allows for a simpler
+    code construct to be used in the processing of the predicted samples.
+
+ Description:
+    Add max calculation on the filter implementation, this to eliminate
+    function buffer_adaptation() on the time to frequency transformation.
+    Function interface changed. It now return the amount of shifting needed
+    to garb only the top 16 MSB.
+
+ Description:
+     Replace clearing memory with for-loop with pvmemset function
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    win_seq = type of window sequence (WINDOW_SEQUENCE).
+
+    weight_index = index (Int) of LTP coefficient table for all windows in
+                   current frame.
+
+    delay = buffer (Int) containing delays for each window.
+
+    buffer = history buffer (Int16) containing the reconstructed time domain
+             signals of previous frames.
+
+    buffer_offset = value (Int) that indicates the location of the first
+                    element in the LTP circular buffer.  (Either 0 or 1024)
+
+    time_quant    = filterbank buffer (Int32) This buffer is used by the
+                    filterbank, but it's first 1024 elements are equivalent
+                    to the last 1024 elements in the conventionally
+                    implemented LTP buffer.  Using this buffer directly avoids
+                    costly duplication of memory.
+
+    predicted_samples = buffer (Int32) with length of 2048 to hold
+                        predicted time domain signals.
+
+    buffer_index = index into buffer where the first sample of data from
+                   the frame (t-2) (two frames ago) resides.  (Int)
+
+    frame_length = length of one frame, type of Int.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    Amount of shifting needed to grab the top 16 MSB from teh predicted buffer
+
+ Pointers and Buffers Modified:
+    predicted_samples contents are the newly calculated predicted time
+    domain signals
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Long term prediction (LTP) is used to reduce the redundancy of a signal
+ between successive coding frames. This function performs prediction by
+ applying 1-tap IIR filtering to calculate the predicted time domain
+ signals of current frame from previous reconstructed frames stored in
+ time domain history buffer.
+
+ The equation used for IIR filter is as following.
+
+            y(n) = weight * x(n - delay)
+
+    where   y(n) ----- predicted time domain signals
+            x(n) ----- reconstructed time domain signals
+            weight ----- LTP coefficient
+            delay ----- optimal delay from 0 to 2047
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3: Audio
+        Subpart 4.6.6   Long Term Prediction (LTP)
+
+ (2) MPEG-2 NBC Audio Decoder
+     "This software module was originally developed by Nokia in the course
+     of development of the MPEG-2 AAC/MPEG-4 Audio standard ISO/IEC13818-7,
+     14496-1, 2 and 3. This software module is an implementation of a part
+     of one or more MPEG-2 AAC/MPEG-4 Audio tools as specified by the MPEG-2
+     aac/MPEG-4 Audio standard. ISO/IEC  gives users of the MPEG-2aac/MPEG-4
+     Audio standards free license to this software module or modifications
+     thereof for use in hardware or software products claiming conformance
+     to the MPEG-2 aac/MPEG-4 Audio  standards. Those intending to use this
+     software module in hardware or software products are advised that this
+     use may infringe existing patents. The original developer of this
+     software module, the subsequent editors and their companies, and ISO/IEC
+     have no liability for use of this software module or modifications
+     thereof in an implementation. Copyright is not released for non MPEG-2
+     aac/MPEG-4 Audio conforming products. The original developer retains
+     full right to use the code for the developer's own purpose, assign or
+     donate the code to a third party and to inhibit third party from using
+     the code for non MPEG-2 aac/MPEG-4 Audio conforming products. This
+     copyright notice must be included in all copies or derivative works.
+     Copyright (c)1997.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pPredicted_samples = &predicted_samples[0];
+
+    weight = codebook[weight_index];
+
+    IF (win_seq != EIGHT_SHORT_SEQUENCE)
+    THEN
+
+        block_length = frame_length << 1;
+
+        lag = delay[0];
+
+        j = block_length - lag;
+
+        IF (lag < frame_length)
+        THEN
+
+            num_samples = frame_length + lag;
+
+        ELSE
+
+            num_samples = block_length;
+
+        ENDIF
+
+        pBuffer = &buffer[j];
+
+        FOR (i = num_samples; i>0; i--)
+
+            *pPredicted_samples = weight * (*pBuffer);
+            pPredicted_samples = pPredicted_samples + 1;
+            pBuffer = pBuffer + 1;
+
+        ENDFOR
+
+        FOR (i = block_length - num_samples; i>0; i--)
+
+            *pPredicted_samples = 0;
+            pPredicted_samples = pPredicted_samples + 1;
+
+        ENDFOR
+
+    ELSE
+
+        FOR (wnd = 0; wnd < short_window_num; wnd++)
+
+            IF (win_prediction_used[wnd] != FALSE)
+            THEN
+
+                delay[wnd] = delay[0] + ltp_short_lag[wnd];
+
+                lag = delay[wnd];
+
+                j = wnd*short_block_length - lag;
+
+                IF (lag < short_frame_length)
+                THEN
+
+                    num_samples = short_frame_length + lag;
+
+                ELSE
+
+                    num_samples = short_block_length;
+
+                ENDIF
+
+                pBuffer = &buffer[j];
+
+                FOR (i = num_samples; i>0; i--)
+
+                    *pPredicted_samples = weight * (*pBuffer);
+                    pPredicted_samples = pPredicted_samples + 1;
+                    pBuffer = pBuffer + 1;
+
+                ENDFOR
+
+                FOR (i = short_block_length - num_samples; i>0; i--)
+
+                    *pPredicted_samples = 0;
+                    pPredicted_samples = pPredicted_samples + 1;
+
+                ENDFOR
+
+            ELSE
+
+                CALL pv_memset(
+                        pPredicted_samples,
+                        0,
+                        sizeof(*pPredicted_samples)*short_block_length);
+                MODIFYING (predicted_samples[]);
+
+                pPredicted_samples = pPredicted_samples + short_block_length;
+
+            ENDIF [ IF (win_prediction_used[wnd] != FALSE) ]
+
+        ENDFOR [ FOR (wnd=0; wnd<short_window_num; wnd++) ]
+
+    ENDIF [ IF (win_seq != EIGHT_SHORT_SEQUENCE) ]
+
+    RETURN
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "e_window_sequence.h"
+#include "ltp_common_internal.h"
+#include "long_term_prediction.h"
+#include "aac_mem_funcs.h"
+#include "pv_normalize.h"
+#include "window_block_fxp.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
+----------------------------------------------------------------------------*/
+/* Purpose: Codebook for LTP weight coefficients. Stored in Q15 format */
+const UInt codebook[CODESIZE] =
+{
+    18705,  /* 0 */
+    22827,  /* 1 */
+    26641,  /* 2 */
+    29862,  /* 3 */
+    32273,  /* 4 */
+    34993,  /* 5 */
+    39145,  /* 6 */
+    44877   /* 7 */
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int long_term_prediction(
+    WINDOW_SEQUENCE     win_seq,
+    const Int           weight_index,
+    const Int           delay[],
+    const Int16         buffer[],
+    const Int           buffer_offset,
+    const Int32         time_quant[],
+    Int32         predicted_samples[],    /* Q15 */
+    const Int           frame_length)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    /*
+     * Window index
+     *
+     * Int wnd;
+     *
+     * will be enabled when short window information is available.
+     */
+
+    /* Pointer to time domain history buffer */
+
+    const Int16 *pBuffer;
+
+    const Int32 *pTimeQuant = time_quant;
+
+    /* Pointer to array containing predicted samples */
+    Int32 *pPredicted_samples;
+
+    Int32   test;
+    Int32   datum;
+
+    /* IIR coefficient with Q15 format */
+    UInt    weight;
+
+    /* Length of one block (two frames) */
+    Int     block_length;
+
+    Int     shift;
+    Int     k;
+    Int     ltp_buffer_index;
+    Int     jump_point;
+    Int     lag;
+    Int     num_samples;
+
+    Int32   max = 0;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Initialize pointers */
+    pPredicted_samples = &predicted_samples[0];
+
+    weight = codebook[weight_index];
+
+    /****************************************/
+    /* LTP decoding process for long window */
+    /****************************************/
+
+    if (win_seq != EIGHT_SHORT_SEQUENCE)
+    {
+        /****************************************************/
+        /* Prediction based on previous time domain signals */
+        /****************************************************/
+        block_length = frame_length << 1;
+
+        /* Calculate time lag for 1-tap IIR filter */
+        lag = delay[0];
+
+        ltp_buffer_index = block_length - lag;
+
+        /* Calculate number of samples used in IIR filter */
+        if (lag < frame_length)
+        {
+            num_samples = frame_length + lag;
+        }
+        else
+        {
+            num_samples = block_length;
+        }
+
+
+        /*
+         * Calculate the predicted time domain signals from the
+         * reconstructed time domain signals of previous frames.
+         */
+
+        /* The data is stored in TWO buffers, either as...
+         *
+         *                                       [   t ==  0  ]
+         *
+         * [   t == -1   ][   t == -2   ]
+         *
+         * OR...
+         *                                       [   t ==  0  ]
+         *
+         * [   t == -2   ][   t == -1   ]
+         *
+         *
+         *
+         * In the first case, all of the buffers are non-contiguous,
+         * and each must be handled separately.  Code for this first case
+         * will function correctly for both cases.
+         *
+         * In the second case, the buffers storing t == -2, and t == -1
+         * data are contiguous, and an optimization could take advantage
+         * of this, at the cost of an increase in code size for this function.
+         */
+
+        /* Decrement block_length by num_samples.  This is important
+         * for the loop at the end of the "ACCESS DATA IN THE LTP BUFFERS"
+         * section that sets all remaining samples in the block to zero.
+         */
+
+        block_length -= num_samples;
+
+
+
+
+
+
+        /*
+         ************************************ ACCESS DATA IN THE LTP BUFFERS
+         */
+
+        /*
+         * This section of the code handles the t == -2
+         * buffer, which corresponds to 0 <= ltp_buffer_index < 1024
+         *
+         * BUFFER t == -2
+         *
+         * [0][][][][][][][][][][][...][][][][][][][][][][][][1023]
+         *
+         */
+
+        jump_point = (frame_length - ltp_buffer_index);
+
+        if (jump_point > 0)
+        {
+            pBuffer = &(buffer[ltp_buffer_index + buffer_offset]);
+
+            for (k = jump_point; k > 0; k--)
+            {
+                /* Q15 = Q15 * Q0 */
+                test = (Int32) weight * (*(pBuffer++));
+                *(pPredicted_samples++) =  test;
+                max                   |= (test >> 31) ^ test;
+            }
+
+            num_samples -= jump_point;
+
+            ltp_buffer_index += jump_point;
+        }
+
+        /*
+         * This section of the code handles the t == -1
+         * buffer, which corresponds to 1024 <= ltp_buffer_index < 2048
+         *
+         * BUFFER t == -1
+         *
+         * [1024][][][][][][][][][][][...][][][][][][][][][][][][2047]
+         *
+         */
+
+        jump_point = 2 * frame_length - ltp_buffer_index;
+
+        pBuffer = &(buffer[ltp_buffer_index - buffer_offset]);
+
+        if (num_samples < jump_point)
+        {
+            jump_point = num_samples;
+        }
+
+        for (k = jump_point; k > 0; k--)
+        {
+            /* Q15 = Q15 * Q0 */
+            test = (Int32) weight * (*(pBuffer++));
+            *(pPredicted_samples++) =  test;
+            max                   |= (test >> 31) ^ test;
+        }
+
+        num_samples -= jump_point;
+
+        ltp_buffer_index += jump_point;
+
+        /*
+         * This section of the code handles the t == 0
+         * buffer, which corresponds to 2048 <= ltp_buffer_index < 3072
+         *
+         * BUFFER t == 0
+         *
+         * [2048][][][][][][][][][][][...][][][][][][][][][][][][3071]
+         *
+         */
+        for (k = num_samples; k > 0; k--)
+        {
+
+            datum = *(pTimeQuant++) >> SCALING;
+
+            /*
+             * Limit the values in the 32-bit filterbank's buffer to
+             * 16-bit resolution.
+             *
+             * Value's greater than 32767 or less than -32768 are saturated
+             * to 32767 and -32768, respectively.
+             */
+
+            test                    = (Int32)datum * weight;
+            *(pPredicted_samples++) =  test;
+            max                    |= (test >> 31) ^ test;
+
+        }
+
+        /* Set any remaining samples in the block to 0. */
+
+        pv_memset(
+            pPredicted_samples,
+            0,
+            block_length*sizeof(*pPredicted_samples));
+
+    } /* if (win_seq != EIGHT_SHORT_SEQUENCE) */
+
+
+    /*****************************************/
+    /* LTP decoding process for short window */
+    /*****************************************/
+
+    /*
+     * For short window LTP, since there is no "ltp_short_lag"
+     * information being passed, the following code for short
+     * window LTP will be applied in the future when those
+     * information are available.
+     */
+
+    /*
+     *----------------------------------------------------------------------------
+     *  else
+     *  {
+     *      for (wnd = 0; wnd < short_window_num; wnd++)
+     *      {
+     *          if (win_prediction_used[wnd] != FALSE)
+     *          {
+     *              delay[wnd] = delay[0] + ltp_short_lag[wnd];
+     *
+     *              lag = delay[wnd];
+     *
+     *              j = wnd*short_block_length - lag;
+     *
+     *              if (lag < short_frame_length)
+     *              {
+     *                  num_samples = short_frame_length + lag;
+     *              }
+     *              else
+     *              {
+     *                  num_samples = short_block_length;
+     *              }
+     *
+     *              pBuffer = &buffer[j];
+     *
+     *              for(i = num_samples; i>0; i--)
+     *              {
+     *                  *(pPredicted_samples++) = weight * (*(pBuffer++));
+     *              }
+     *
+     *              for(i = short_block_length - num_samples; i>0; i--)
+     *              {
+     *                  *(pPredicted_samples++) = 0;
+     *              }
+     *          }
+     *          else
+     *          {
+     *              pv_memset(
+     *                  pPredicted_samples,
+     *                  0,
+     *                  sizeof(*pPredicted_samples)*short_block_length);
+     *
+     *              pPredicted_samples += short_block_length;
+     *          }
+     *      }
+     *  }
+     *----------------------------------------------------------------------------
+     */
+
+    shift = 16 - pv_normalize(max);
+
+    if (shift < 0)
+    {
+        shift = 0;
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (shift);
+} /* long_term_prediction */
+
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/long_term_prediction.h b/media/libstagefright/codecs/aacdec/long_term_prediction.h
new file mode 100644
index 0000000..014934b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/long_term_prediction.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: long_term_prediction.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified prototype with array size passed in per review
+              comments.
+
+ Description: Changed prototype with "weight_index" instead of "weight".
+
+ Description: Removed some passed in buffer size variables since they are
+              not being used for long window.
+
+ Description: Temporarily define LTP_Q_FORMAT for current release.
+              Need to change function prototype and pass out Q_format
+              information later.
+
+ Description: Updated function prototype to reflect the usage of a
+ circular buffer by LTP.
+
+ Description:  Updated function interface with new return type
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes function prototype declaration for long_term_prediction().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LONG_TERM_PREDICTION_H
+#define LONG_TERM_PREDICTION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_window_sequence.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define LTP_Q_FORMAT    (15)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    Int long_term_prediction(
+        WINDOW_SEQUENCE     win_seq,
+        const Int           weight_index,
+        const Int           delay[],
+        const Int16         buffer[],
+        const Int           buffer_offset,
+        const Int32         time_quant[],
+        Int32               predicted_samples[],    /* Q15 */
+        const Int           frame_length);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/long_term_synthesis.cpp b/media/libstagefright/codecs/aacdec/long_term_synthesis.cpp
new file mode 100644
index 0000000..c361db1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/long_term_synthesis.cpp
@@ -0,0 +1,1158 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: long_term_synthesis.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made the following changes based on the review comments.
+              1. Separated "shift_factor>=0" on line 395 to "shift_factor>0"
+                 and "shift_factor=0" two cases.
+              2. Added comments on line 393 to explain why factor 2 is being
+                 used to calculate shift_factor.
+              3. Added comments for short window implementation.
+              4. Changed "*(pPredicted_spectral++) = *pPredicted_spectral>>2"
+                 to "*(pPredicted++)>>=2" although they are the same.
+              5. Changed pseudo code "X+=Y" to "X=X+Y".
+              6. Fixed ending comment of "for" loop.
+              7. Passed in the size of the array and deleted some of the
+                 include files.
+
+ Description: Unroll the loops.
+
+ Description: Changed index "wnd" in previous line 584 with "wnd_offset"
+              and made other correspondent changes to the code.
+
+
+ Description: Based on Ken's suggestion, modified the function with the
+              passing-in Q format as scalefactor band basis in order to
+              simplify TNS block functions.
+
+ Description: Optimization.
+
+ Description: Made changes based on review comments.
+              1. Changed misspellings.
+              2. Changed win_sfb_top[] from two dimensional array to one
+              dimensional array and correspondently changed the code.
+              3. Changed function prototype to remove some redundant
+              informations.
+              4. Fixed the adjusting Q format part code.
+              5. Fixed lines 825, 826 with correct updating pointers.
+
+ Description: Due to TNS and LTP Q format issue, added code to adjust
+              predicted_spectral() to maximum resolution before perform
+              long term synthesis.
+
+ Description: Modified based on review comments.
+
+ Description: Changed "max" data type from UInt to UInt32.
+
+ Description: Changed so that nothing is done for the case of "all zero"
+ data coming from the output of Trans4m_time_2_freq. Also, included more
+ efficient calculation of the abs(x).  And, I updated the pseudocode.
+
+ Description: Use an auxiliary variable temp, to avoid using the same
+    pointer and a post-increment pointer in the same line. This may not
+    work with all compilers.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    win_seq = type of window sequence (WINDOW_SEQUENCE).
+    sfb_per_win = number of scalefactor bands for each window, 1024 for
+                  long window, 128 for short window, type of Int.
+    win_sfb_top = buffer (Int16) containing the top coefficient per
+                  scalefactor band for each window.
+    win_prediction_used = buffer (Int) containing the prediction flag
+                          information for short windows. Each item in the
+                          buffer toggles prediction on(1)/off(0) for each
+                          window separately.
+    sfb_prediction_used = buffer (Int) containing the prediction flag
+                          information for scalefactor band(sfb). Each item
+                          toggle prediction on(1)/off(0) on each scalefactor
+                          band of every window.
+    current_frame = channel buffer (Int32) containing the dequantized
+                    spectral coefficients or errors of current frame.
+    q_format = buffer (Int) containing Q format for each scalefactor band of
+               input current_frame.
+    predicted_spectral = buffer (Int32) containing predicted spectral
+                         components of current frame.
+    pred_q_format = Q format (Int) for predicted spectral components of
+                    current frame.
+    coef_per_win = number of coefficients per window for short windows.
+                   type of Int.
+    short_window_num = number of short windows, type of Int.
+    reconstruct_sfb_num = number of scalefactor bands used for reconstruction
+                          for short windows, type of Int.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    current_frame contents are the dequantized spectrum with a prediction
+    vector added when prediction is turned on.
+
+    q_format contents are updated with the new Q format (Int) for each
+    scalefactor band of output current_frame buffer.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs long term synthesis using transmitted spectral
+ coeffients or errors and predicted spectral components.
+
+ Long term synthesis is part of long term prediction (LTP) which is used to
+ reduce the redundancy of a signal between successive coding frames. The
+ functionality of long term synthesis is to reconstruct the frequency domain
+ spectral by adding the predicted spectral components and the transmitted
+ spectral error when prediction is turned on.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3: Audio
+        Subpart 4.6.6   Long Term Prediction (LTP)
+
+ (2) MPEG-2 NBC Audio Decoder
+     "This software module was originally developed by Nokia in the course
+     of development of the MPEG-2 AAC/MPEG-4 Audio standard ISO/IEC13818-7,
+     14496-1, 2 and 3. This software module is an implementation of a part
+     of one or more MPEG-2 AAC/MPEG-4 Audio tools as specified by the MPEG-2
+     aac/MPEG-4 Audio standard. ISO/IEC  gives users of the MPEG-2aac/MPEG-4
+     Audio standards free license to this software module or modifications
+     thereof for use in hardware or software products claiming conformance
+     to the MPEG-2 aac/MPEG-4 Audio  standards. Those intending to use this
+     software module in hardware or software products are advised that this
+     use may infringe existing patents. The original developer of this
+     software module, the subsequent editors and their companies, and ISO/IEC
+     have no liability for use of this software module or modifications
+     thereof in an implementation. Copyright is not released for non MPEG-2
+     aac/MPEG-4 Audio conforming products. The original developer retains
+     full right to use the code for the developer's own purpose, assign or
+     donate the code to a third party and to inhibit third party from using
+     the code for non MPEG-2 aac/MPEG-4 Audio conforming products. This
+     copyright notice must be included in all copies or derivative works.
+     Copyright (c)1997.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pPredicted_spectral = &predicted_spectral[0];
+    pPredicted_spectral_start = pPredicted_spectral;
+    pSfb_prediction_used = &sfb_prediction_used[0];
+
+    IF (win_seq != EIGHT_SHORT_SEQUENCE)
+    THEN
+
+        sfb_offset = 0;
+
+        pWinSfbTop = &pWin_sfb_top[0];
+
+        pQ_format = &q_format[0];
+
+        FOR (i = sfb_per_frame; i>0; i--)
+
+            IF (*(pSfb_prediction_used++) != FALSE)
+            THEN
+
+                pPredicted_offset = pPredicted_spectral_start +
+                                                            sfb_offset;
+                pCurrent_frame = &current_frame[sfb_offset];
+
+                quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
+
+                max = 0;
+
+                pPredicted_spectral = pPredicted_offset;
+
+                FOR (j = (*pWinSfbTop - sfb_offset); j>0 ; j--)
+
+                    tmpInt32 = *(pPredicted_spectral++);
+
+                    IF (tmpInt32 < 0)
+                    THEN
+
+                        tmpInt32 = -tmpInt32;
+
+                    ENDIF
+
+                    max |= tmpInt32;
+
+                ENDFOR
+
+                tmpInt = 0;
+
+                IF (max != 0)
+                THEN
+
+                    WHILE (max < 0x40000000L)
+
+                        max <<= 1;
+                        tmpInt++;
+
+                    ENDWHILE
+
+                    pPredicted_spectral = pPredicted_offset;
+
+                    FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                        *(pPredicted_spectral++) <<= tmpInt;
+                        *(pPredicted_spectral++) <<= tmpInt;
+                        *(pPredicted_spectral++) <<= tmpInt;
+                        *(pPredicted_spectral++) <<= tmpInt;
+
+                    ENDFOR
+
+                    adjusted_pred_q = pred_q_format + tmpInt;
+
+                    pPredicted_spectral = pPredicted_offset;
+
+                    shift_factor = *(pQ_format) - adjusted_pred_q;
+
+                    IF ((shift_factor >= 0) && (shift_factor < 31))
+                    THEN
+
+                        shift_factor = shift_factor + 1;
+
+                        FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                            *(pCurrent_frame++) =
+                                (*pCurrent_frame>>shift_factor)
+                              + (*(pPredicted_spectral++)>>1);
+                            *(pCurrent_frame++) =
+                                (*pCurrent_frame>>shift_factor)
+                              + (*(pPredicted_spectral++)>>1);
+                            *(pCurrent_frame++) =
+                                (*pCurrent_frame>>shift_factor)
+                              + (*(pPredicted_spectral++)>>1);
+                            *(pCurrent_frame++) =
+                                (*pCurrent_frame>>shift_factor)
+                              + (*(pPredicted_spectral++)>>1);
+
+                        ENDFOR
+
+                        *(pQ_format) = adjusted_pred_q - 1;
+
+                    ELSEIF (shift_factor >= 31)
+                    THEN
+
+                        FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                            *(pCurrent_frame++) = *(pPredicted_spectral++);
+                            *(pCurrent_frame++) = *(pPredicted_spectral++);
+                            *(pCurrent_frame++) = *(pPredicted_spectral++);
+                            *(pCurrent_frame++) = *(pPredicted_spectral++);
+
+                        ENDFOR
+
+                        *(pQ_format) = adjusted_pred_q;
+
+                    ELSEIF ((shift_factor < 0) && (shift_factor > -31))
+                    THEN
+
+                        shift_factor = 1 - shift_factor;
+
+                        FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                            *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                (*(pPredicted_spectral++)>>shift_factor);
+                            *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                (*(pPredicted_spectral++)>>shift_factor);
+                            *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                (*(pPredicted_spectral++)>>shift_factor);
+                            *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                (*(pPredicted_spectral++)>>shift_factor);
+
+                        ENDFOR
+
+                        *(pQ_format) = *(pQ_format) - 1;
+
+                    ENDIF
+
+                ENDIF
+
+            ENDIF [ IF (*(pSfb_prediction_used++) != FALSE) ]
+
+            sfb_offset = *pWinSfbTop;
+            pWinSfbTop = pWinSfbTop + 1;
+            pQ_format = pQ_format + 1;
+
+        ENDFOR [ FOR (i = sfb_per_frame; i>0; i--) ]
+
+    ELSE
+
+        pCurrent_frame_start = &current_frame[0];
+
+        pQ_format_start = &q_format[0];
+
+        num_sfb = sfb_per_win[0];
+
+        FOR (wnd=0; wnd<short_window_num; wnd++)
+
+            pWinSfbTop = &pWin_sfb_top[0];
+
+            pQ_format = pQ_format_start;
+
+            IF (win_prediction_used[wnd] != FALSE)
+            THEN
+
+                sfb_offset = 0;
+
+                FOR (i = reconstruct_sfb_num; i > 0; i--)
+
+                    pPredicted_offset = pPredicted_spectral_start +
+                                                                sfb_offset;
+                    pCurrent_frame = pCurrent_frame_start + sfb_offset;
+
+                    quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
+
+                    max = 0;
+
+                    pPredicted_spectral = pPredicted_offset;
+
+                    FOR (j = (*pWinSfbTop - sfb_offset); j>0 ; j--)
+
+                        tmpInt32 = *(pPredicted_spectral++);
+
+                        IF (tmpInt32 < 0)
+                        THEN
+
+                            tmpInt32 = -tmpInt32;
+
+                        ENDIF
+
+                        max |= tmpInt32;
+
+                    ENDFOR
+
+                    tmpInt = 0;
+
+                    IF (max != 0)
+                    THEN
+
+                        WHILE (max < 0x40000000L)
+
+                            max <<= 1;
+                            tmpInt++;
+
+                        ENDWHILE
+
+
+                        pPredicted_spectral = pPredicted_offset;
+
+                        FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                            *(pPredicted_spectral++) <<= tmpInt;
+                            *(pPredicted_spectral++) <<= tmpInt;
+                            *(pPredicted_spectral++) <<= tmpInt;
+                            *(pPredicted_spectral++) <<= tmpInt;
+
+                        ENDFOR
+
+                        adjusted_pred_q = pred_q_format + tmpInt;
+
+                        pPredicted_spectral = pPredicted_offset;
+
+                        shift_factor = *(pQ_format) - adjusted_pred_q;
+
+                        IF ((shift_factor >= 0) && (shift_factor < 31))
+                        THEN
+
+                            shift_factor = shift_factor + 1;
+
+                            FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                                *(pCurrent_frame++) =
+                                    (*pCurrent_frame>>shift_factor) +
+                                                (*(pPredicted_spectral++)>>1);
+                                *(pCurrent_frame++) =
+                                    (*pCurrent_frame>>shift_factor) +
+                                                (*(pPredicted_spectral++)>>1);
+                                *(pCurrent_frame++) =
+                                    (*pCurrent_frame>>shift_factor) +
+                                                (*(pPredicted_spectral++)>>1);
+                                *(pCurrent_frame++) =
+                                    (*pCurrent_frame>>shift_factor) +
+                                                (*(pPredicted_spectral++)>>1);
+
+                            ENDFOR
+
+                            *(pQ_format) = adjusted_pred_q - 1;
+
+                        ELSEIF (shift_factor >= 31)
+                        THEN
+
+                            FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                                *(pCurrent_frame++) = *(pPredicted_spectral++);
+                                *(pCurrent_frame++) = *(pPredicted_spectral++);
+                                *(pCurrent_frame++) = *(pPredicted_spectral++);
+                                *(pCurrent_frame++) = *(pPredicted_spectral++);
+
+                            ENDFOR
+
+                            *(pQ_format) = adjusted_pred_q;
+
+                        ELSEIF ((shift_factor < 0) && (shift_factor > -31))
+                        THEN
+
+                            shift_factor = 1 - shift_factor;
+
+                            FOR (j = quarter_sfb_width; j>0 ; j--)
+
+                                *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                    (*(pPredicted_spectral++)>>shift_factor);
+                                *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                    (*(pPredicted_spectral++)>>shift_factor);
+                                *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                    (*(pPredicted_spectral++)>>shift_factor);
+                                *(pCurrent_frame++) = (*pCurrent_frame>>1) +
+                                    (*(pPredicted_spectral++)>>shift_factor);
+
+                            ENDFOR
+
+                            *(pQ_format) = *(pQ_format) - 1;
+
+                        ENDIF
+
+                    ENDIF
+
+                    sfb_offset = *pWinSfbTop;
+                    pWinSfbTop = pWinSfbTop + 1;
+                    pQ_format = pQ_format + 1;
+
+                ENDFOR [ FOR (i = reconstruct_sfb_num; i > 0; i--) ]
+
+            ENDIF [ IF (win_prediction_used[wnd] != FALSE) ]
+
+            pPredicted_spectral_start = pPredicted_spectral_start + num_sfb;
+            pCurrent_frame_start = pCurrent_frame_start + num_sfb;
+            wnd_offset = wnd_offset + num_sfb;
+            pQ_format_start = pQ_format_start + num_sfb;
+
+        ENDFOR [ FOR (wnd=0; wnd<short_window_num; wnd++) ]
+
+    ENDIF [ IF (win_seq != EIGHT_SHORT_SEQUENCE) ]
+
+    RETURN
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "e_window_sequence.h"
+#include "long_term_synthesis.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 long_term_synthesis(
+    WINDOW_SEQUENCE     win_seq,
+    Int                 sfb_per_win,
+    Int16               win_sfb_top[],
+    Int                 win_prediction_used[],
+    Int                 sfb_prediction_used[],
+    Int32               current_frame[],
+    Int                 q_format[],         /* for each sfb */
+    Int32               predicted_spectral[],
+    Int                 pred_q_format,      /* for predicted_spectral[] */
+    Int                 coef_per_win,
+    Int                 short_window_num,
+    Int                 reconstruct_sfb_num)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    /* Scalefactor band offset */
+    Int sfb_offset;
+
+    /* Window index */
+    Int wnd;
+
+    /* Pointer to array containing predicted samples */
+    Int32 *pPredicted_spectral;
+
+    /* Pointer to the beginning of array containing predicted samples */
+    Int32 *pPredicted_spectral_start;
+
+    Int32 *pPredicted_offset;
+
+    /* Pointer to array containing current spectral components for a channel*/
+    Int32 *pCurrent_frame;
+
+    /* Another pointer to array containing current spectral components */
+    Int32 *pCurrent_frame_start;
+
+    /* Pointer to prediction flag for each scalefactor band */
+    Int *pSfb_prediction_used;
+
+    /* Pointer to top coef per scalefactor band */
+    Int16 *pWinSfbTop;
+
+    /* Pointer to q_format array */
+    Int *pQ_format;
+    Int *pQ_format_start;
+    Int32   temp;
+
+    Int i;
+    Int j;
+
+    Int quarter_sfb_width;
+    Int num_sfb;
+    Int shift_factor;
+
+    UInt32  max;
+    Int32   tmpInt32;
+
+    Int tmpInt;
+    Int adjusted_pred_q;
+    Int pred_shift;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Initialize pointers */
+    pPredicted_spectral = &predicted_spectral[0];
+    pPredicted_spectral_start = pPredicted_spectral;
+
+    /*
+     * NOTE:
+     * sfb_prediction_used[] start from 0 or 1 depending on nok_lt_decode.c;
+     * currently we agree to make it start from 0;
+     */
+    pSfb_prediction_used = &sfb_prediction_used[0];
+
+    /*********************************/
+    /* LTP synthesis for long window */
+    /*********************************/
+    if (win_seq != EIGHT_SHORT_SEQUENCE)
+    {
+
+        /*******************************************************/
+        /* Reconstruction of current frequency domain spectrum */
+        /*******************************************************/
+
+        /* Initialize scalefactor band offset */
+        sfb_offset = 0;
+
+        /*
+         * Reconstruction is processed on scalefactor band basis.
+         * 1. When prediction is turned on, all the predicted spectral
+         * components will be used for reconstruction.
+         * 2. When prediction is turned off, reconstruction is not
+         * needed. Spectral components of current frame will directly
+         * come from the transmitted data.
+         */
+        pWinSfbTop = &win_sfb_top[0];
+
+        pQ_format = &q_format[0];
+
+        for (i = sfb_per_win; i > 0; i--)
+        {
+            /* Check prediction flag for each scalefactor band. */
+            if (*(pSfb_prediction_used++) != FALSE)
+            {
+                /*
+                 * Prediction is on. Do reconstruction routine.
+                 * Reconstruct spectral component of current
+                 * frame by adding the predicted spectral
+                 * components and the quantized prediction
+                 * errors that reconstructed from transmitted
+                 * data when prediction is turned on.
+                 */
+
+                /* Set pointers to the offset of scalefactor bands */
+                pPredicted_offset = pPredicted_spectral_start +
+                                    sfb_offset;
+                pCurrent_frame = &current_frame[sfb_offset];
+
+                /*
+                 * (*pWinSfbTop - sfb_offset) is number of coefficients
+                 * of the scalefactor band.
+                 * ">>2" is used to set up for later unrolling the loop.
+                 */
+                quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
+
+                /*
+                 * Adjust pred_q_format and predicted_spectral() to
+                 * maximum resolution.
+                 */
+                max = 0;
+
+                pPredicted_spectral = pPredicted_offset;
+
+                /* Find the maximum absolute value */
+                for (j = (*pWinSfbTop - sfb_offset); j > 0 ; j--)
+                {
+                    tmpInt32 = *(pPredicted_spectral++);
+
+                    /*
+                     * Note: overflow is protected here even though
+                     * tmpInt32 = 0x80000000 is very rare case.
+                     *
+                     *  if (tmpInt32 == LONG_MIN)
+                     *  {
+                     *      tmpInt32 = LONG_MAX;
+                     *  }
+                     *  if (tmpInt32 < 0)
+                     *  {
+                     *      tmpInt32 = -tmpInt32;
+                     *  }
+                     */
+
+                    max |= tmpInt32 ^(tmpInt32 >> 31);
+                }
+
+                /*
+                 * IF the LTP data is all zeros
+                 * (max == 0) - do nothing for this sfb.
+                 */
+
+                if (max != 0)
+                {
+                    /* Find the number of bits to reach the max resolution */
+                    tmpInt = 0;
+
+                    while (max < 0x40000000L)
+                    {
+                        max <<= 1;
+                        tmpInt++;
+                    }
+
+                    /*
+                     * The following codes are combinded into shift factor
+                     * adjusting and reconstruction section.
+                     *
+                     * pPredicted_spectral = pPredicted_offset;
+                     * for(j = quarter_sfb_width; j>0 ; j--)
+                     * {
+                     *      *(pPredicted_spectral++) <<= tmpInt;
+                     *      *(pPredicted_spectral++) <<= tmpInt;
+                     *      *(pPredicted_spectral++) <<= tmpInt;
+                     *      *(pPredicted_spectral++) <<= tmpInt;
+                     * }
+                     *
+                     */
+
+                    /* Adjust Q format for predicted_spectral() */
+                    adjusted_pred_q = pred_q_format + tmpInt;
+
+                    /*
+                     * Adjust Q format to prevent overflow that may occur during
+                     * frequency domain reconstruction.
+                     *
+                     */
+                    pPredicted_spectral = pPredicted_offset;
+
+                    shift_factor = *(pQ_format) - adjusted_pred_q;
+
+                    if ((shift_factor >= 0) && (shift_factor < 31))
+                    {
+                        shift_factor = shift_factor + 1;
+                        pred_shift = tmpInt - 1;
+
+                        if (pred_shift >= 0)
+                        {
+                            for (j = quarter_sfb_width; j > 0 ; j--)
+                            {
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) << pred_shift);
+                            }
+                        }
+                        else
+                        {
+                            for (j = quarter_sfb_width; j > 0 ; j--)
+                            {
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) >> 1);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) >> 1);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) >> 1);
+                                temp = *pCurrent_frame >> shift_factor;
+                                *(pCurrent_frame++) = temp
+                                                      + (*(pPredicted_spectral++) >> 1);
+                            }
+                        }
+
+                        /* Updated new Q format for current scalefactor band */
+                        *(pQ_format) = adjusted_pred_q  - 1;
+                    }
+                    else if (shift_factor >= 31)
+                    {
+                        for (j = quarter_sfb_width; j > 0 ; j--)
+                        {
+                            *(pCurrent_frame++) =
+                                *(pPredicted_spectral++) << tmpInt;
+                            *(pCurrent_frame++) =
+                                *(pPredicted_spectral++) << tmpInt;
+                            *(pCurrent_frame++) =
+                                *(pPredicted_spectral++) << tmpInt;
+                            *(pCurrent_frame++) =
+                                *(pPredicted_spectral++) << tmpInt;
+                        }
+
+                        /* Updated new Q format for current scalefactor band */
+                        *(pQ_format) = adjusted_pred_q ;
+                    }
+                    else if ((shift_factor < 0) && (shift_factor > -31))
+                    {
+                        shift_factor = 1 - shift_factor;
+                        pred_shift = tmpInt - shift_factor;
+
+                        if (pred_shift >= 0)
+                        {
+                            for (j = quarter_sfb_width; j > 0 ; j--)
+                            {
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) << pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) << pred_shift);
+                            }
+                        }
+                        else
+                        {
+                            pred_shift = -pred_shift;
+
+                            for (j = quarter_sfb_width; j > 0 ; j--)
+                            {
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) >> pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) >> pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) >> pred_shift);
+                                temp = *pCurrent_frame >> 1;
+                                *(pCurrent_frame++) =  temp +
+                                                       (*(pPredicted_spectral++) >> pred_shift);
+                            }
+                        }
+
+                        /*
+                         * Updated new Q format for current scalefactor band
+                         *
+                         * This is NOT a pointer decrement
+                         */
+                        (*pQ_format)--;
+                    }
+
+                } /* if (max != 0) */
+
+                /*
+                 * For case (shift_factor <= -31), *pCurrent_frame and
+                 * *pQ_format do not need to be updated.
+                 */
+
+            } /* if (*(pSfb_prediction_used++) != FALSE) */
+
+            /* Updated to next scalefactor band. */
+            sfb_offset = *(pWinSfbTop++);
+
+            /* Updated pointer to next scalefactor band's Q-format */
+            pQ_format++;
+
+        } /* for (i = sfb_per_frame; i>0; i--) */
+
+    } /* if (win_seq!=EIGHT_SHORT_SEQUENCE) */
+
+    /**********************************/
+    /* LTP synthesis for short window */
+    /**********************************/
+    else
+    {
+        /******************************************************/
+        /*Reconstruction of current frequency domain spectrum */
+        /******************************************************/
+        pCurrent_frame_start = &current_frame[0];
+
+        pQ_format_start = &q_format[0];
+
+        num_sfb = sfb_per_win;
+
+        /* Reconstruction is processed on window basis */
+        for (wnd = 0; wnd < short_window_num; wnd++)
+        {
+            pWinSfbTop = &win_sfb_top[0];
+
+            pQ_format = pQ_format_start;
+
+            /* Check if prediction flag is on for each window */
+            if (win_prediction_used[wnd] != FALSE)
+            {
+                /* Initialize scalefactor band offset */
+                sfb_offset = 0;
+
+                /*
+                 * Reconstruction is processed on scalefactor band basis.
+                 * 1. When prediction is turned on, all the predicted
+                 * spectral components will be used for reconstruction.
+                 * 2. When prediction is turned off, reconstruction is
+                 * not needed. Spectral components of current frame
+                 * will directly come from the transmitted data.
+                 */
+
+                /*
+                 * According to ISO/IEC 14496-3 pg.91
+                 * Only the spectral components in first eight scalefactor
+                 * bands are added to the quantized prediction error.
+                 */
+                for (i = reconstruct_sfb_num; i > 0; i--)
+                {
+                    /* Set pointer to the offset of scalefactor bands */
+                    pPredicted_offset = pPredicted_spectral_start +
+                                        sfb_offset;
+                    pCurrent_frame = pCurrent_frame_start + sfb_offset;
+
+                    /*
+                     * Prediction is on. Do reconstruction routine.
+                     * Reconstruct spectral component of
+                     * current frame by adding the predicted
+                     * spectral components and the quantized
+                     * prediction errors that reconstructed
+                     * from transmitted data when prediction
+                     * is turned on.
+                     */
+
+                    /*
+                     * (*pWinSfbTop - sfb_offset) is number of coefficients
+                     * of the scalefactor band.
+                     * ">>2" is used to set up for later unrolling the loop.
+                     */
+                    quarter_sfb_width = (*pWinSfbTop - sfb_offset) >> 2;
+
+                    /*
+                     * Adjust pred_q_format and predicted_spectral() to
+                     * maximum resolution.
+                     */
+                    max = 0;
+                    pPredicted_spectral = pPredicted_offset;
+
+                    /* Find the maximum absolute value */
+                    for (j = (*pWinSfbTop - sfb_offset); j > 0 ; j--)
+                    {
+                        tmpInt32 = *(pPredicted_spectral++);
+
+
+                        /*
+                         * Note: overflow is protected here even though
+                         * tmpInt32 = 0x80000000 is very rare case.
+                         *
+                         *  if (tmpInt32 == LONG_MIN)
+                         *  {
+                         *      tmpInt32 = LONG_MAX;
+                         *  }
+                         *  if (tmpInt32 < 0)
+                         *  {
+                         *      tmpInt32 = -tmpInt32;
+                         *  }
+                         */
+
+                        max |= tmpInt32 ^(tmpInt32 >> 31);
+                    }
+
+                    if (max != 0)
+                    {
+                        /* Find the number of bits to reach
+                         * the max resolution
+                         */
+                        tmpInt = 0;
+
+                        while (max < 0x40000000L)
+                        {
+                            max <<= 1;
+                            tmpInt++;
+                        }
+                        /*
+                         * The following codes are combined into shift factor
+                         * adjusting and reconstruction section.
+                         *
+                         * pPredicted_spectral = pPredicted_offset;
+                         * for(j = quarter_sfb_width; j>0 ; j--)
+                         * {
+                         *      *(pPredicted_spectral++) <<= tmpInt;
+                         *      *(pPredicted_spectral++) <<= tmpInt;
+                         *      *(pPredicted_spectral++) <<= tmpInt;
+                         *      *(pPredicted_spectral++) <<= tmpInt;
+                         * }
+                         *
+                         */
+
+                        /* Adjust Q format for predicted_spectral() */
+                        adjusted_pred_q = pred_q_format + tmpInt;
+
+                        /*
+                         * Adjust Q format to prevent overflow that may occur
+                         * during frequency domain reconstruction.
+                         */
+                        pPredicted_spectral = pPredicted_offset;
+
+                        shift_factor = *(pQ_format) - adjusted_pred_q;
+
+                        if ((shift_factor >= 0) && (shift_factor < 31))
+                        {
+                            shift_factor = shift_factor + 1;
+
+                            pred_shift = tmpInt - 1;
+
+                            if (pred_shift >= 0)
+                            {
+                                for (j = quarter_sfb_width; j > 0 ; j--)
+                                {
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) << pred_shift);
+
+                                }
+                            }
+                            else
+                            {
+                                for (j = quarter_sfb_width; j > 0 ; j--)
+                                {
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) >> 1);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) >> 1);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) >> 1);
+                                    temp = *pCurrent_frame >> shift_factor;
+                                    *(pCurrent_frame++) = temp
+                                                          + (*(pPredicted_spectral++) >> 1);
+                                }
+                            }
+
+                            /* Updated new Q format for current scalefactor band*/
+                            *(pQ_format) = adjusted_pred_q - 1;
+                        }
+                        else if (shift_factor >= 31)
+                        {
+                            for (j = quarter_sfb_width; j > 0 ; j--)
+                            {
+                                *(pCurrent_frame++) =
+                                    *(pPredicted_spectral++) << tmpInt;
+                                *(pCurrent_frame++) =
+                                    *(pPredicted_spectral++) << tmpInt;
+                                *(pCurrent_frame++) =
+                                    *(pPredicted_spectral++) << tmpInt;
+                                *(pCurrent_frame++) =
+                                    *(pPredicted_spectral++) << tmpInt;
+                            }
+
+                            /* Updated new Q format for current scalefactor band*/
+                            *(pQ_format) = adjusted_pred_q;
+                        }
+                        else if ((shift_factor < 0) && (shift_factor > -31))
+                        {
+                            shift_factor = 1 - shift_factor;
+
+                            pred_shift = tmpInt - shift_factor;
+
+                            if (pred_shift >= 0)
+                            {
+                                for (j = quarter_sfb_width; j > 0 ; j--)
+                                {
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) << pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) << pred_shift);
+
+                                }
+                            }
+                            else
+                            {
+                                pred_shift = -pred_shift;
+
+                                for (j = quarter_sfb_width; j > 0 ; j--)
+                                {
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) >> pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) >> pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) >> pred_shift);
+                                    temp = *pCurrent_frame >> 1;
+                                    *(pCurrent_frame++) =  temp +
+                                                           (*(pPredicted_spectral++) >> pred_shift);
+                                }
+                            }
+
+                            /* Updated new Q format for current scalefactor band*/
+                            *(pQ_format) = *(pQ_format) - 1;
+                        }
+
+                        /*
+                         * For case (shift_factor <= -31), *pCurrent_frame and
+                         * *pQ_format do not need to be updated.
+                         */
+
+                    } /* if (max != 0) */
+
+                    /* Updated to next scalefactor band. */
+                    sfb_offset = *(pWinSfbTop++);
+
+                    /* Updated pointer to next scalefactor band's Q-format */
+                    pQ_format++;
+
+                } /* for (i = reconstruct_sfb_num; i > 0; i--) */
+
+            } /* if (win_prediction_used[wnd] != FALSE) */
+
+            /* Updated to next window */
+            pPredicted_spectral_start += coef_per_win;
+            pCurrent_frame_start += coef_per_win;
+            pQ_format_start += num_sfb;
+
+        } /* for (wnd=0; wnd<short_window_num; wnd++) */
+
+    } /* else */
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+} /* long_term_synthesis */
+
+
diff --git a/media/libstagefright/codecs/aacdec/long_term_synthesis.h b/media/libstagefright/codecs/aacdec/long_term_synthesis.h
new file mode 100644
index 0000000..1195709
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/long_term_synthesis.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: long_term_synthesis.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: 1. Changed protoype with array size passed in per review
+                 comments.
+              2. Moved #define NUM_RECONSTRUCTED_SFB to ltp_common_internal.h
+
+ Description: Modified prototype based on review comments for new version
+          long_term_synthesis.c.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes function prototype declaration for long_term_synthesis().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LONG_TERM_SYNTHESIS_H
+#define LONG_TERM_SYNTHESIS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_window_sequence.h"
+
+/*----------------------------------------------------------------------------
+; 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 long_term_synthesis(
+    WINDOW_SEQUENCE     win_seq,
+    Int                 sfb_per_win,
+    Int16               win_sfb_top[],
+    Int                 win_prediction_used[],
+    Int                 sfb_prediction_used[],
+    Int32               current_frame[],
+    Int                 q_format[],
+    Int32               predicted_spectral[],
+    Int                 pred_q_format,
+    Int                 coef_per_win,
+    Int                 short_window_num,
+    Int                 reconstruct_sfb_num);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/lt_decode.cpp b/media/libstagefright/codecs/aacdec/lt_decode.cpp
new file mode 100644
index 0000000..e5f5f91
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/lt_decode.cpp
@@ -0,0 +1,507 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: lt_decode.c
+
+
+------------------------------------------------------------------------------
+
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  First round of optimizations.
+
+ Description:  pInputStream is now the 2nd parameter to this function.
+
+ Description:  Changed to work with MT's new get_ics_info.c function, which
+ only calls lt_decode if LTP is enabled.  This removes one grab from the
+ bitstream and one "if" from this code.  Also, changed setting of weight.
+ Now, rather than setting the actual weight, I only set the index into
+ a table in this function.
+
+ Description: Replace some instances of getbits to get9_n_lessbits
+              when the number of bits read is 9 or less and get1bits
+              when only 1 bit is read.
+
+ Who:                                   Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    win_type        Type of window (SHORT or LONG)
+                    [WINDOW_TYPE]
+
+    max_sfb         Maximum number of active scalefactor bands
+                    [Int]
+
+    pLt_pred        Pointer to structure containing information for
+                    long-term prediction.
+                    [LT_PRED_STATUS *]
+
+    pInputStream    Pointer to structure containing bitstream
+                    information.
+                    [BITS *]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pLt_pred->weight_index - updated with index into weight table for LTP.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function decodes the bitstream elements for long term prediction
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by Nokia
+   in the course of development of the MPEG-2 AAC/MPEG-4 Audio standard
+   ISO/IEC13818-7, 14496-1, 2 and 3.  This software module is an implementation
+   of a part of one or more MPEG-2 AAC/MPEG-4 Audio tools as specified by the
+   MPEG-2 aac/MPEG-4 Audio standard. ISO/IEC  gives users of the
+   MPEG-2aac/MPEG-4 Audio standards free license to this software module or
+   modifications thereof for use in hardware or software products claiming
+   conformance to the MPEG-2 aac/MPEG-4 Audio  standards. Those intending to
+   use this software module in hardware or software products are advised that
+   this use may infringe existing patents. The original developer of this
+   software module, the subsequent editors and their companies, and ISO/IEC
+   have no liability for use of this software module or modifications thereof
+   in an implementation. Copyright is not released for non MPEG-2 aac/MPEG-4
+   Audio conforming products. The original developer retains full right to use
+   the code for the developer's own purpose, assign or donate the code to a
+   third party and to inhibit third party from using the code for non
+   MPEG-2 aac/MPEG-4 Audio conforming products. This copyright notice
+   must be included in all copies or derivative works."
+   Copyright (c)1997.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pDelay[0] = (Int) getbits(
+                        LEN_LTP_LAG,
+                        pInputStream);
+
+    temp_reg  = (Int) getbits(
+                        LEN_LTP_COEF,
+                        pInputStream);
+
+    pLt_pred->weight = codebook[temp_reg];
+
+    last_band = max_sfb;
+
+    IF (win_type != EIGHT_SHORT_SEQUENCE)
+
+        IF (last_band > MAX_LT_PRED_LONG_SFB)
+
+            last_band = MAX_LT_PRED_LONG_SFB;
+
+        ENDIF
+
+        FOR (m = last_band; m > 0; m--)
+
+            *(pSfbPredictionUsed++) = (Int) getbits(
+                                               LEN_LTP_LONG_USED,
+                                               pInputStream);
+        ENDFOR
+
+        FOR (m = (max_sfb - last_band); m > 0; m--)
+
+            *(pSfbPredictionUsed++) = 0;
+
+        ENDFOR
+
+    ELSE
+
+        IF (last_band > MAX_LT_PRED_SHORT_SFB)
+
+            last_band = MAX_LT_PRED_SHORT_SFB;
+
+        ENDIF
+
+        prev_subblock = pDelay[0];
+
+        pWinPredictionUsed++;
+
+        pTempPtr = &pSfbPredictionUsed[0];
+
+        FOR (m = NUM_SHORT_WINDOWS; m > 0;)
+
+            m--;
+            temp_reg = (Int) getbits(
+                                LEN_LTP_SHORT_USED,
+                                pInputStream);
+
+            *(pWinPredictionUsed++) = temp_reg;
+
+            IF (temp_reg != FALSE)
+            {
+                *(pDelay++) = prev_subblock;
+
+                FOR (k = last_band; k > 0; k--)
+                {
+                    *(pTempPtr++) = 1;
+                }
+                break;
+            ELSE
+            {
+                pDelay++;
+                pTempPtr += last_band;
+            }
+
+        ENDFOR (m = NUM_SHORT_WINDOWS; m > 0;)
+
+        prev_subblock += LTP_LAG_OFFSET;
+
+        FOR (; m > 0; m--)
+
+            temp_reg = (Int) getbits (
+                                LEN_LTP_SHORT_USED,
+                                pInputStream);
+
+            *(pWinPredictionUsed++) = temp_reg;
+
+            IF (temp_reg != FALSE)
+
+                temp_reg = (Int) getbits(
+                                    LEN_LTP_SHORT_LAG_PRESENT,
+                                    pInputStream);
+                IF (temp_reg != 0)
+
+                    temp_reg  = (Int) getbits(
+                                         LEN_LTP_SHORT_LAG,
+                                         pInputStream);
+
+                    *(pDelay++) = prev_subblock - temp_reg;
+
+                ELSE
+
+                    *(pDelay++) = prev_subblock - LTP_LAG_OFFSET;
+
+                ENDIF
+
+                FOR (k = last_band; k > 0; k--)
+                    *(pTempPtr++) = 1;
+                ENDFOR
+
+            ELSE
+
+                pDelay++;
+                pTempPtr += last_band;
+
+            ENDIF
+
+        ENDFOR (; m > 0; m--)
+
+    ENDIF (win_type != EIGHT_SHORT_SEQUENCE)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "lt_decode.h"
+#include "ltp_common_internal.h"
+#include "window_block_fxp.h"
+#include "e_window_sequence.h"
+#include "s_lt_pred_status.h"
+#include "s_bits.h"
+#include "ibstream.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 lt_decode(
+    const WINDOW_SEQUENCE  win_type,
+    BITS            *pInputStream,
+    const Int              max_sfb,
+    LT_PRED_STATUS  *pLt_pred)
+{
+    Int wnd_num;
+    Int k;
+    Int last_band;
+    Int prev_subblock;
+    Int prev_subblock_nonzero;
+    Int temp_reg;
+
+    Bool *pWinPredictionUsed = pLt_pred->win_prediction_used;
+    Bool *pSfbPredictionUsed = pLt_pred->sfb_prediction_used;
+    Int  *pTempPtr;
+    Int  *pDelay = pLt_pred->delay;
+
+    pDelay[0] = (Int) get17_n_lessbits(
+                    LEN_LTP_LAG,  /* 11 bits */
+                    pInputStream);
+
+    pLt_pred->weight_index  = (Int) get9_n_lessbits(
+                                  LEN_LTP_COEF, /*  3 bits */
+                                  pInputStream);
+
+    last_band = max_sfb;
+
+    if (win_type != EIGHT_SHORT_SEQUENCE)
+    {
+
+        /* last_band = min(MAX_LT_PRED_LONG_SFB, max_sfb) MAX_SCFAC_BANDS */
+        if (last_band > MAX_LT_PRED_LONG_SFB)
+        {
+            last_band = MAX_LT_PRED_LONG_SFB;
+        }
+
+        for (k = last_band; k > 0; k--)
+        {
+            *(pSfbPredictionUsed++) = (Int) get1bits(pInputStream);
+        }
+
+        /*
+         * This is not a call to memset, because
+         * (max_sfb - last_band) should typically be a small value.
+         */
+        for (k = (max_sfb - last_band); k > 0; k--)
+        {
+            *(pSfbPredictionUsed++) = FALSE;
+        }
+    }
+    else /* (win_type == EIGHT_SHORT_SEQUENCE) */
+    {
+        /* last_band = min(MAX_LT_PRED_SHORT_SFB, max_sfb) */
+
+        if (last_band > MAX_LT_PRED_SHORT_SFB)
+        {
+            last_band = MAX_LT_PRED_SHORT_SFB;
+        }
+
+        /*
+         * The following two coding constructs are equivalent...
+         *
+         *  first_time == 1
+         *  for (wnd_num=NUM_SHORT_WINDOWS; wnd_num > 0; wnd_num--)
+         *  {
+         *     if (condition)
+         *     {
+         *       if (first_time == 1)
+         *       {
+         *           CODE SECTION A
+         *           first_time = 0;
+         *       }
+         *       else
+         *       {
+         *           CODE SECTION B
+         *       }
+         *     }
+         *  }
+         *
+         * -----------------------------------EQUIVALENT TO------------
+         *
+         *  wnd_num=NUM_SHORT_WINDOWS;
+         *
+         *  do
+         *  {
+         *     wnd_num--;
+         *     if (condition)
+         *     {
+         *         CODE SECTION A
+         *         break;
+         *     }
+         *  } while( wnd_num > 0)
+         *
+         *  while (wnd_num > 0)
+         *  {
+         *     if (condition)
+         *     {
+         *         CODE SECTION B
+         *     }
+         *     wnd_num--;
+         *  }
+         *
+         */
+
+        prev_subblock = pDelay[0];
+
+        pTempPtr = &pSfbPredictionUsed[0];
+
+        wnd_num = NUM_SHORT_WINDOWS;
+
+        prev_subblock_nonzero = prev_subblock;
+        prev_subblock += LTP_LAG_OFFSET;
+
+        do
+        {
+            /*
+             * Place decrement of wnd_num here, to insure
+             * that the decrement occurs before the
+             * break out of the do-while loop.
+             */
+            wnd_num--;
+
+            temp_reg = (Int) get1bits(pInputStream);
+
+            *(pWinPredictionUsed++) = temp_reg;
+
+            if (temp_reg != FALSE)
+            {
+                *(pDelay++) = prev_subblock_nonzero;
+
+                for (k = last_band; k > 0; k--)
+                {
+                    *(pTempPtr++) = TRUE;
+                }
+                for (k = (max_sfb - last_band); k > 0; k--)
+                {
+                    *(pTempPtr++) = FALSE;
+                }
+                break;
+
+            } /* if(pWinPredictionUsed) */
+            else
+            {
+                pDelay++;
+                pTempPtr += max_sfb;
+            }
+
+        }
+        while (wnd_num > 0);
+
+        /*
+         * This while loop picks up where the previous one left off.
+         * Notice that the code functions differently inside the loop
+         */
+
+        while (wnd_num > 0)
+        {
+            temp_reg = (Int) get1bits(pInputStream);
+
+            *(pWinPredictionUsed++) = temp_reg;
+
+            if (temp_reg != FALSE)
+            {
+                temp_reg = (Int) get1bits(pInputStream);
+                if (temp_reg != 0)
+                {
+                    temp_reg  = (Int) get9_n_lessbits(
+                                    LEN_LTP_SHORT_LAG,
+                                    pInputStream);
+
+                    *(pDelay++) = prev_subblock - temp_reg;
+                }
+                else
+                {
+                    *(pDelay++) = prev_subblock_nonzero;
+                }
+                for (k = last_band; k > 0; k--)
+                {
+                    *(pTempPtr++) = TRUE;
+                }
+                for (k = (max_sfb - last_band); k > 0; k--)
+                {
+                    *(pTempPtr++) = FALSE;
+                }
+
+            } /* if (temp_reg) */
+            else
+            {
+                pDelay++;
+                pTempPtr += max_sfb;
+            }
+
+            wnd_num--;
+
+        } /* while(wnd_num) */
+
+    } /* else (win_type == EIGHT_SHORT_SEQUENCE) */
+
+} /* lt_decode */
diff --git a/media/libstagefright/codecs/aacdec/lt_decode.h b/media/libstagefright/codecs/aacdec/lt_decode.h
new file mode 100644
index 0000000..c655270
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/lt_decode.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: lt_decode.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changing to move pInputStream to 2nd parameter.
+
+ Description: Replaced "e_WINDOW_TYPE.h" with "e_WINDOW_SEQUENCE.h"
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the global function declaration for lt_decode
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LT_DECODE_H
+#define LT_DECODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_window_sequence.h"
+#include "s_lt_pred_status.h"
+#include "s_bits.h"
+
+/*----------------------------------------------------------------------------
+; 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 lt_decode(
+    const WINDOW_SEQUENCE win_type,
+    BITS           *pInputStream,
+    const Int             max_sfb,
+    LT_PRED_STATUS *pLt_pred);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/lt_prediction.h b/media/libstagefright/codecs/aacdec/lt_prediction.h
new file mode 100644
index 0000000..e52a1e8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/lt_prediction.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**************************************************************************
+
+This software module was originally developed by
+Nokia in the course of development of the MPEG-2 AAC/MPEG-4
+Audio standard ISO/IEC13818-7, 14496-1, 2 and 3.
+This software module is an implementation of a part
+of one or more MPEG-2 AAC/MPEG-4 Audio tools as specified by the
+MPEG-2 aac/MPEG-4 Audio standard. ISO/IEC  gives users of the
+MPEG-2aac/MPEG-4 Audio standards free license to this software module
+or modifications thereof for use in hardware or software products
+claiming conformance to the MPEG-2 aac/MPEG-4 Audio  standards. Those
+intending to use this software module in hardware or software products
+are advised that this use may infringe existing patents. The original
+developer of this software module, the subsequent
+editors and their companies, and ISO/IEC have no liability for use of
+this software module or modifications thereof in an
+implementation. Copyright is not released for non MPEG-2 aac/MPEG-4
+Audio conforming products. The original developer retains full right to
+use the code for the developer's own purpose, assign or donate the code to a
+third party and to inhibit third party from using the code for non
+MPEG-2 aac/MPEG-4 Audio conforming products. This copyright notice
+must be included in all copies or derivative works.
+Copyright (c)1997.
+
+***************************************************************************/
+
+#ifndef _LT_PREDICTION_H
+#define _LT_PREDICTION_H
+
+#include "block.h"
+#include "ltp_common.h"
+#include "ibstream.h"
+#include "lt_decode.h"
+#include "s_frameinfo.h"
+#include "window_block.h"
+
+void init_lt_pred(LT_PRED_STATUS * lt_status);
+
+void lt_predict(
+    Int                  object,
+    FrameInfo           *pFrameInfo,
+    WINDOW_SEQUENCE      win_seq,
+    Wnd_Shape           *pWin_shape,
+    LT_PRED_STATUS  *pLt_status,
+    Real                *pPredicted_samples,
+    Real                *pOverlap_buffer,
+    Real                *pCurrent_frame_copy,
+    Real                 current_frame[]);
+
+short double_to_int(double sig_in);
+
+#endif /* not defined _LT_PREDICTION_H */
diff --git a/media/libstagefright/codecs/aacdec/ltp_common_internal.h b/media/libstagefright/codecs/aacdec/ltp_common_internal.h
new file mode 100644
index 0000000..d76ac75
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ltp_common_internal.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**************************************************************************
+
+This software module was originally developed by
+
+Mikko Suonio (Nokia)
+
+in the course of development of the MPEG-2 NBC/MPEG-4 Audio standard
+ISO/IEC 13818-7, 14496-1,2 and 3. This software module is an
+implementation of a part of one or more MPEG-2 NBC/MPEG-4 Audio tools
+as specified by the MPEG-2 NBC/MPEG-4 Audio standard. ISO/IEC gives
+users of the MPEG-2 NBC/MPEG-4 Audio standards free license to this
+software module or modifications thereof for use in hardware or
+software products claiming conformance to the MPEG-2 NBC/ MPEG-4 Audio
+standards. Those intending to use this software module in hardware or
+software products are advised that this use may infringe existing
+patents. The original developer of this software module and his/her
+company, the subsequent editors and their companies, and ISO/IEC have
+no liability for use of this software module or modifications thereof
+in an implementation. Copyright is not released for non MPEG-2
+NBC/MPEG-4 Audio conforming products. The original developer retains
+full right to use the code for his/her own purpose, assign or donate
+the code to a third party and to inhibit third party from using the
+code for non MPEG-2 NBC/MPEG-4 Audio conforming products. This
+copyright notice must be included in all copies or derivative works.
+
+Copyright (c) 1997.
+
+***************************************************************************/
+
+#ifndef _LTP_COMMON_INTERNAL_H
+#define _LTP_COMMON_INTERNAL_H
+
+
+/*
+  Purpose:      Number of LTP coefficients. */
+#define LPC 1
+
+/*
+  Purpose:      Maximum LTP lag.  */
+#define DELAY 2048
+
+/*
+  Purpose:  Length of the bitstream element ltp_data_present.  */
+#define LEN_LTP_DATA_PRESENT 1
+
+/*
+  Purpose:  Length of the bitstream element ltp_lag.  */
+#define LEN_LTP_LAG 11
+
+/*
+  Purpose:  Length of the bitstream element ltp_coef.  */
+#define LEN_LTP_COEF 3
+
+/*
+  Purpose:  Length of the bitstream element ltp_short_used.  */
+#define LEN_LTP_SHORT_USED 1
+
+/*
+  Purpose:  Length of the bitstream element ltp_short_lag_present.  */
+#define LEN_LTP_SHORT_LAG_PRESENT 1
+
+/*
+  Purpose:  Length of the bitstream element ltp_short_lag.  */
+#define LEN_LTP_SHORT_LAG 5
+
+/*
+  Purpose:  Offset of the lags written in the bitstream.  */
+#define LTP_LAG_OFFSET 16
+
+/*
+  Purpose:  Length of the bitstream element ltp_long_used.  */
+#define LEN_LTP_LONG_USED 1
+
+/*
+  Purpose:  Upper limit for the number of scalefactor bands
+        which can use lt prediction with long windows.
+  Explanation:  Bands 0..MAX_LT_PRED_SFB-1 can use lt prediction.  */
+#define MAX_LT_PRED_LONG_SFB 40
+
+/*
+  Purpose:  Upper limit for the number of scalefactor bands
+        which can use lt prediction with short windows.
+  Explanation:  Bands 0..MAX_LT_PRED_SFB-1 can use lt prediction.  */
+#define MAX_LT_PRED_SHORT_SFB 13
+
+/*
+   Purpose:      Buffer offset to maintain block alignment.
+   Explanation:  This is only used for a short window sequence.  */
+#define SHORT_SQ_OFFSET (BLOCK_LEN_LONG-(BLOCK_LEN_SHORT*4+BLOCK_LEN_SHORT/2))
+
+/*
+  Purpose:  Number of codes for LTP weight. */
+#define CODESIZE 8
+
+/* number of scalefactor bands used for reconstruction for short windows */
+#define NUM_RECONSTRUCTED_SFB (8)
+
+#endif /* _LTP_COMMON_INTERNAL_H */
diff --git a/media/libstagefright/codecs/aacdec/mdct_fxp.cpp b/media/libstagefright/codecs/aacdec/mdct_fxp.cpp
new file mode 100644
index 0000000..df371e8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mdct_fxp.cpp
@@ -0,0 +1,450 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mdct_fxp.c
+ Funtions: fft_rx2
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    data_quant  = Input vector, with quantized Q15 spectral lines:
+                  type Int32
+
+    Q_FFTarray  = Scratch memory used for in-place IFFT calculation,
+                  min size required 1024, type Int32
+
+    n           = Length of input vector "data_quant". Currently 256 or 2048.
+                  type const Int
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    shift = shift factor to reflect scaling introduced by FFT and mdct_fxp,
+
+ Pointers and Buffers Modified:
+    calculation are done in-place and returned in "data_quant"
+
+ Local Stores Modified:
+     None
+
+ Global Stores Modified:
+     None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    The MDCT is a linear orthogonal lapped transform, based on the idea of
+    time domain aliasing cancellation (TDAC).
+    MDCT is critically sampled, which means that though it is 50% overlapped,
+    a sequence data after MDCT has the same number of coefficients as samples
+    before the transform (after overlap-and-add). This means, that a single
+    block of MDCT data does not correspond to the original block on which the
+    MDCT was performed. When subsequent blocks of data are added (still using
+    50% overlap), the errors introduced by the transform cancels out.
+    Thanks to the overlapping feature, the MDCT is very useful for
+    quantization. It effectively removes the otherwise easily detectable
+    blocking artifact between transform blocks.
+    N = length of input vector X
+    X = vector of length N/2, will hold fixed point DCT
+    k = 0:1:N-1
+
+                        N-1
+            X(m) =  2   SUM   x(k)*cos(pi/(2*N)*(2*k+1+N/2)*(2*m+1))
+                        k=0
+
+
+    The window that completes the TDAC is applied before calling this function.
+    The MDCT can be calculated using an FFT, for this, the MDCT needs to be
+    rewritten as an odd-time odd-frequency discrete Fourier transform. Thus,
+    the MDCT can be calculated using only one n/4 point FFT and some pre and
+    post-rotation of the sample points.
+
+    Computation of the MDCT implies computing
+
+        x  = ( y   - y        ) + j( y       +  y       )
+         n      2n    N/2-1-2n        N-1-2n     N/2+2n
+
+    using the Fast discrete cosine transform as described in [2]
+
+    where x(n) is an input with N points
+
+    x(n) ----------------------------
+                                     |
+                                     |
+                    Pre-rotation by exp(j(2pi/N)(n+1/8))
+                                     |
+                                     |
+                              N/4- point FFT
+                                     |
+                                     |
+                    Post-rotation by exp(j(2pi/N)(k+1/8))
+                                     |
+                                     |
+                                      ------------- DCT
+
+    By considering the N/2 overlap, a relation between successive input blocks
+    is found:
+
+        x   (2n) = x (N/2 + 2n)
+         m+1        m
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should provide a fixed point MDCT with an average
+    quantization error less than 1 %.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] Analysis/Synthesis Filter Bank design based on time domain
+        aliasing cancellation
+        Jhon Princen, et. al.
+        IEEE Transactions on ASSP, vol ASSP-34, No. 5 October 1986
+        Pg 1153 - 1161
+
+    [2] Regular FFT-related transform kernels for DCT/DST based
+        polyphase filterbanks
+        Rolf Gluth
+        Proc. ICASSP 1991, pg. 2205 - 2208
+
+------------------------------------------------------------------------------
+  PSEUDO-CODE
+
+  Cx, Cy are complex number
+
+
+    exp = log2(n)-1
+
+    FOR ( k=0; k< n/4; k +=2)
+
+        Cx =   (data_quant[3n/4 + k] + data_quant[3n/4 - 1 - k]) +
+             j (data_quant[ n/4 + k] - data_quant[ n/4 - 1 - k])
+
+        Q_FFTarray = Cx * exp(-j(2pi/n)(k+1/8))
+
+    ENDFOR
+
+    FOR ( k=n/4; k< n/2; k +=2)
+
+        Cx =   (data_quant[3n/4 - 1 - k] + data_quant[ - n/4 + k]) +
+             j (data_quant[5n/4 - 1 - k] - data_quant[   n/4 + k])
+
+        Q_FFTarray = Cx * exp(-j(2pi/n)(k+1/8))
+
+    ENDFOR
+
+    CALL FFT( Q_FFTarray, n/4)
+
+    MODIFYING( Q_FFTarray )
+
+    RETURNING( shift )
+
+    FOR ( k=0; k< n/2; k +=2)
+
+        Cx = Q_FFTarray[ k] + j Q_FFTarray[ k+1]
+
+        Cy = 2 * Cx * exp(-j(2pi/n)(k+1/8))
+
+        data_quant[           k ] = - Real(Cy)
+        data_quant[ n/2 - 1 - k ] =   Imag(Cy)
+        data_quant[ n/2     + k ] = - Imag(Cy)
+        data_quant[ n       - k ] =   Real(Cy)
+
+    ENDFOR
+
+    MODIFIED    data_quant[]
+
+    RETURN      (-shift-1)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "mdct_fxp.h"
+#include "fft_rx4.h"
+#include "mix_radix_fft.h"
+#include "fwd_long_complex_rot.h"
+#include "fwd_short_complex_rot.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define ERROR_IN_FRAME_SIZE 10
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+Int mdct_fxp(
+    Int32   data_quant[],
+    Int32   Q_FFTarray[],
+    Int     n)
+{
+
+    Int32   temp_re;
+    Int32   temp_im;
+
+    Int32   temp_re_32;
+    Int32   temp_im_32;
+
+    Int16     cos_n;
+    Int16     sin_n;
+    Int32     exp_jw;
+    Int     shift;
+
+
+    const Int32 *p_rotate;
+
+
+    Int32   *p_data_1;
+    Int32   *p_data_2;
+    Int32   *p_data_3;
+    Int32   *p_data_4;
+
+    Int32 *p_Q_FFTarray;
+
+    Int32   max1;
+
+    Int k;
+    Int n_2   = n >> 1;
+    Int n_4   = n >> 2;
+    Int n_8   = n >> 3;
+    Int n_3_4 = 3 * n_4;
+
+    switch (n)
+    {
+        case SHORT_WINDOW_TYPE:
+            p_rotate = (Int32 *)exp_rotation_N_256;
+            break;
+
+        case LONG_WINDOW_TYPE:
+            p_rotate = (Int32 *)exp_rotation_N_2048;
+            break;
+
+        default:
+            /*
+             *  There is no defined behavior for a non supported frame
+             *  size. By returning a fixed scaling factor, the input will
+             *  scaled down and this will be heard as a low level noise
+             */
+            return(ERROR_IN_FRAME_SIZE);
+
+    }
+
+    /*--- Reordering and Pre-rotation by exp(-j(2pi/N)(r+1/8))   */
+    p_data_1 = &data_quant[n_3_4];
+    p_data_2 = &data_quant[n_3_4 - 1];
+    p_data_3 = &data_quant[n_4];
+    p_data_4 = &data_quant[n_4 - 1];
+
+    p_Q_FFTarray = Q_FFTarray;
+
+    max1 = 0;
+
+    for (k = n_8; k > 0; k--)
+    {
+        /*
+         *  scale down to ensure numbers are Q15
+         *  temp_re and temp_im are 32-bit but
+         *  only the lower 16 bits are used
+         */
+
+        temp_re = (*(p_data_1++) + *(p_data_2--)) >> 1;
+        temp_im = (*(p_data_3++) - *(p_data_4--)) >> 1;
+
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+
+        exp_jw = *p_rotate++;
+
+        cos_n = (Int16)(exp_jw >> 16);
+        sin_n = (Int16)(exp_jw & 0xFFFF);
+
+        temp_re_32 = temp_re * cos_n + temp_im * sin_n;
+        temp_im_32 = temp_im * cos_n - temp_re * sin_n;
+        *(p_Q_FFTarray++) = temp_re_32;
+        *(p_Q_FFTarray++) = temp_im_32;
+        max1         |= (temp_re_32 >> 31) ^ temp_re_32;
+        max1         |= (temp_im_32 >> 31) ^ temp_im_32;
+
+
+        p_data_1++;
+        p_data_2--;
+        p_data_4--;
+        p_data_3++;
+    }
+
+
+    p_data_1 = &data_quant[n - 1];
+    p_data_2 = &data_quant[n_2 - 1];
+    p_data_3 = &data_quant[n_2];
+    p_data_4 =  data_quant;
+
+    for (k = n_8; k > 0; k--)
+    {
+        /*
+         *  scale down to ensure numbers are Q15
+         */
+        temp_re = (*(p_data_2--) - *(p_data_4++)) >> 1;
+        temp_im = (*(p_data_1--) + *(p_data_3++)) >> 1;
+
+        p_data_2--;
+        p_data_1--;
+        p_data_4++;
+        p_data_3++;
+
+        /*
+         * cos_n + j*sin_n == exp(j(2pi/N)(k+1/8))
+         */
+
+        exp_jw = *p_rotate++;
+
+        cos_n = (Int16)(exp_jw >> 16);
+        sin_n = (Int16)(exp_jw & 0xFFFF);
+
+        temp_re_32 = temp_re * cos_n + temp_im * sin_n;
+        temp_im_32 = temp_im * cos_n - temp_re * sin_n;
+
+        *(p_Q_FFTarray++) = temp_re_32;
+        *(p_Q_FFTarray++) = temp_im_32;
+        max1         |= (temp_re_32 >> 31) ^ temp_re_32;
+        max1         |= (temp_im_32 >> 31) ^ temp_im_32;
+
+
+    } /* for(k) */
+
+
+
+    p_Q_FFTarray = Q_FFTarray;
+
+    if (max1)
+    {
+
+        if (n != SHORT_WINDOW_TYPE)
+        {
+
+            shift = mix_radix_fft(
+                        Q_FFTarray,
+                        &max1);
+
+            shift += fwd_long_complex_rot(
+                         Q_FFTarray,
+                         data_quant,
+                         max1);
+
+        }
+        else        /*  n_4 is 64 */
+        {
+
+            shift = fft_rx4_short(
+                        Q_FFTarray,
+                        &max1);
+
+            shift += fwd_short_complex_rot(
+                         Q_FFTarray,
+                         data_quant,
+                         max1);
+        }
+
+    }
+    else
+    {
+        shift = -31;
+    }
+
+    /*
+     *  returns shift introduced by FFT and mdct_fxp, 12 accounts for
+     *  regular downshift (14) and MDCT scale factor (-2)
+     *  number are returned as 16 bits
+     */
+    return (12 - shift);
+
+} /* mdct_fxp */
+
diff --git a/media/libstagefright/codecs/aacdec/mdct_fxp.h b/media/libstagefright/codecs/aacdec/mdct_fxp.h
new file mode 100644
index 0000000..b8d5a80
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mdct_fxp.h
@@ -0,0 +1,107 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mdct_fxp.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: This extern had the incorrect length of the arrays.  The true
+ lengths are 128 and 1024, not 64 and 512.
+
+ Description:  Modified interface so a vector with extended precision is
+               returned. Added copyright notice.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function mdct_fxp()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MDCT_FXP_H
+#define MDCT_FXP_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define     LONG_WINDOW_TYPE  2048
+#define     SHORT_WINDOW_TYPE  256
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    extern const Int exp_rotation_N_256[128];
+    extern const Int exp_rotation_N_2048[1024];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Int mdct_fxp(
+        Int32   data_quant[],
+        Int32   Q_FFTarray[],
+        Int     n);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* MDCT_FXP_H */
diff --git a/media/libstagefright/codecs/aacdec/mdct_tables_fxp.cpp b/media/libstagefright/codecs/aacdec/mdct_tables_fxp.cpp
new file mode 100644
index 0000000..709cbf2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mdct_tables_fxp.cpp
@@ -0,0 +1,253 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mdct_tables_fxp.c
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Created from fft_rx2.c
+
+ Description:  Modified to include forward and inverse tables
+
+ Who:                       Date:
+ Description:
+
+  ------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    MDCT rotation tables fixpoint tables
+
+    For a table with N complex points:
+
+    cos_n + j*sin_n == exp(j(2pi/N)(n+1/8))
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.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 FUNCTION REFERENCES
+    ; Declare functions defined elsewhere and referenced in this module
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+
+
+
+    extern const Int32 exp_rotation_N_256[64] =
+    {
+
+        0x5A820047,  0x5A7A0280, 0x5A6304B8, 0x5A3E06EF,
+        0x5A0C0926,  0x59CB0B5B, 0x597D0D8E, 0x59210FBF,
+        0x58B711EE,  0x5840141A, 0x57BB1643, 0x57281868,
+        0x56881A8A,  0x55DB1CA8, 0x55201EC1, 0x545820D5,
+        0x538322E5,  0x52A224EF, 0x51B326F3, 0x50B828F1,
+        0x4FB12AE9,  0x4E9D2CDA, 0x4D7D2EC5, 0x4C5230A8,
+        0x4B1A3284,  0x49D73458, 0x48883624, 0x472F37E7,
+        0x45CA39A2,  0x445A3B54, 0x42E03CFD, 0x415C3E9C,
+        0x3FCE4032,  0x3E3541BE, 0x3C944340, 0x3AE844B7,
+        0x39344624,  0x37774786, 0x35B148DD, 0x33E44A29,
+        0x320E4B69,  0x30304C9E, 0x2E4B4DC6, 0x2C5F4EE3,
+        0x2A6C4FF4,  0x287250F8, 0x267251F0, 0x246D52DB,
+        0x226153BA,  0x2051548B, 0x1E3B5550, 0x1C215607,
+        0x1A0256B1,  0x17DF574E, 0x15B957DD, 0x138F585F,
+        0x116358D3,  0x0F335939, 0x0D015992, 0x0ACE59DD,
+        0x08985A1A,  0x06625A49, 0x042A5A6A, 0x01F25A7D
+    };
+
+
+
+
+
+
+    extern const Int32 exp_rotation_N_2048[512] =
+    {
+
+        0x5A820009,  0x5A820050, 0x5A820097, 0x5A8100DE,
+        0x5A810125,  0x5A80016C, 0x5A7E01B3, 0x5A7D01FA,
+        0x5A7B0242,  0x5A790289, 0x5A7702D0, 0x5A750317,
+        0x5A72035E,  0x5A7003A5, 0x5A6D03EC, 0x5A6A0433,
+        0x5A66047A,  0x5A6304C1, 0x5A5F0508, 0x5A5B054F,
+        0x5A560596,  0x5A5205DD, 0x5A4D0624, 0x5A48066A,
+        0x5A4306B1,  0x5A3E06F8, 0x5A38073F, 0x5A320786,
+        0x5A2C07CD,  0x5A260814, 0x5A20085A, 0x5A1908A1,
+        0x5A1208E8,  0x5A0B092F, 0x5A040975, 0x59FC09BC,
+        0x59F40A03,  0x59EC0A49, 0x59E40A90, 0x59DC0AD7,
+        0x59D30B1D,  0x59CA0B64, 0x59C10BAA, 0x59B80BF1,
+        0x59AE0C37,  0x59A50C7E, 0x599B0CC4, 0x59910D0A,
+        0x59860D51,  0x597C0D97, 0x59710DDD, 0x59660E23,
+        0x595B0E6A,  0x594F0EB0, 0x59440EF6, 0x59380F3C,
+        0x592C0F82,  0x59200FC8, 0x5913100E, 0x59061054,
+        0x58F9109A,  0x58EC10E0, 0x58DF1126, 0x58D1116B,
+        0x58C411B1,  0x58B611F7, 0x58A7123C, 0x58991282,
+        0x588A12C8,  0x587B130D, 0x586C1353, 0x585D1398,
+        0x584E13DD,  0x583E1423, 0x582E1468, 0x581E14AD,
+        0x580D14F2,  0x57FD1538, 0x57EC157D, 0x57DB15C2,
+        0x57CA1607,  0x57B9164C, 0x57A71690, 0x579516D5,
+        0x5783171A,  0x5771175F, 0x575E17A3, 0x574C17E8,
+        0x5739182C,  0x57261871, 0x571218B5, 0x56FF18FA,
+        0x56EB193E,  0x56D71982, 0x56C319C6, 0x56AF1A0A,
+        0x569A1A4F,  0x56851A93, 0x56701AD6, 0x565B1B1A,
+        0x56461B5E,  0x56301BA2, 0x561A1BE5, 0x56041C29,
+        0x55EE1C6D,  0x55D81CB0, 0x55C11CF3, 0x55AA1D37,
+        0x55931D7A,  0x557C1DBD, 0x55651E00, 0x554D1E43,
+        0x55351E86,  0x551D1EC9, 0x55051F0C, 0x54EC1F4F,
+        0x54D31F91,  0x54BB1FD4, 0x54A12016, 0x54882059,
+        0x546F209B,  0x545520DE, 0x543B2120, 0x54212162,
+        0x540721A4,  0x53EC21E6, 0x53D12228, 0x53B62269,
+        0x539B22AB,  0x538022ED, 0x5364232E, 0x53492370,
+        0x532D23B1,  0x531123F2, 0x52F42434, 0x52D82475,
+        0x52BB24B6,  0x529E24F7, 0x52812538, 0x52642578,
+        0x524625B9,  0x522825FA, 0x520B263A, 0x51EC267A,
+        0x51CE26BB,  0x51B026FB, 0x5191273B, 0x5172277B,
+        0x515327BB,  0x513427FB, 0x5114283A, 0x50F4287A,
+        0x50D428BA,  0x50B428F9, 0x50942938, 0x50742978,
+        0x505329B7,  0x503229F6, 0x50112A35, 0x4FF02A74,
+        0x4FCE2AB2,  0x4FAD2AF1, 0x4F8B2B2F, 0x4F692B6E,
+        0x4F472BAC,  0x4F242BEA, 0x4F022C29, 0x4EDF2C67,
+        0x4EBC2CA4,  0x4E992CE2, 0x4E752D20, 0x4E522D5D,
+        0x4E2E2D9B,  0x4E0A2DD8, 0x4DE62E15, 0x4DC22E53,
+        0x4D9D2E90,  0x4D792ECD, 0x4D542F09, 0x4D2F2F46,
+        0x4D0A2F83,  0x4CE42FBF, 0x4CBF2FFB, 0x4C993038,
+        0x4C733074,  0x4C4D30B0, 0x4C2630EC, 0x4C003127,
+        0x4BD93163,  0x4BB2319E, 0x4B8B31DA, 0x4B643215,
+        0x4B3D3250,  0x4B15328B, 0x4AED32C6, 0x4AC53301,
+        0x4A9D333C,  0x4A753376, 0x4A4C33B1, 0x4A2433EB,
+        0x49FB3425,  0x49D2345F, 0x49A83499, 0x497F34D3,
+        0x4955350C,  0x492C3546, 0x4902357F, 0x48D835B9,
+        0x48AD35F2,  0x4883362B, 0x48583664, 0x482E369C,
+        0x480336D5,  0x47D7370E, 0x47AC3746, 0x4781377E,
+        0x475537B6,  0x472937EE, 0x46FD3826, 0x46D1385E,
+        0x46A43895,  0x467838CD, 0x464B3904, 0x461E393B,
+        0x45F13972,  0x45C439A9, 0x459739E0, 0x45693A16,
+        0x453C3A4D,  0x450E3A83, 0x44E03AB9, 0x44B13AEF,
+        0x44833B25,  0x44553B5B, 0x44263B90, 0x43F73BC6,
+        0x43C83BFB,  0x43993C30, 0x43693C65, 0x433A3C9A,
+        0x430A3CCF,  0x42DA3D04, 0x42AA3D38, 0x427A3D6C,
+        0x424A3DA0,  0x42193DD4, 0x41E93E08, 0x41B83E3C,
+        0x41873E6F,  0x41563EA3, 0x41253ED6, 0x40F33F09,
+        0x40C23F3C,  0x40903F6F, 0x405E3FA1, 0x402C3FD4,
+        0x3FFA4006,  0x3FC74038, 0x3F95406A, 0x3F62409C,
+        0x3F2F40CE,  0x3EFC4100, 0x3EC94131, 0x3E964162,
+        0x3E634193,  0x3E2F41C4, 0x3DFB41F5, 0x3DC74226,
+        0x3D934256,  0x3D5F4286, 0x3D2B42B6, 0x3CF642E6,
+        0x3CC24316,  0x3C8D4346, 0x3C584375, 0x3C2343A5,
+        0x3BEE43D4,  0x3BB84403, 0x3B834432, 0x3B4D4460,
+        0x3B18448F,  0x3AE244BD, 0x3AAC44EB, 0x3A754519,
+        0x3A3F4547,  0x3A094575, 0x39D245A2, 0x399B45CF,
+        0x396445FD,  0x392D462A, 0x38F64656, 0x38BF4683,
+        0x388746B0,  0x385046DC, 0x38184708, 0x37E04734,
+        0x37A84760,  0x3770478B, 0x373847B7, 0x36FF47E2,
+        0x36C7480D,  0x368E4838, 0x36554863, 0x361D488E,
+        0x35E348B8,  0x35AA48E2, 0x3571490C, 0x35384936,
+        0x34FE4960,  0x34C44989, 0x348B49B3, 0x345149DC,
+        0x34164A05,  0x33DC4A2E, 0x33A24A56, 0x33684A7F,
+        0x332D4AA7,  0x32F24ACF, 0x32B74AF7, 0x327C4B1F,
+        0x32414B46,  0x32064B6E, 0x31CB4B95, 0x31904BBC,
+        0x31544BE3,  0x31184C0A, 0x30DD4C30, 0x30A14C56,
+        0x30654C7C,  0x30294CA2, 0x2FEC4CC8, 0x2FB04CEE,
+        0x2F734D13,  0x2F374D38, 0x2EFA4D5D, 0x2EBD4D82,
+        0x2E804DA7,  0x2E434DCB, 0x2E064DEF, 0x2DC94E13,
+        0x2D8C4E37,  0x2D4E4E5B, 0x2D104E7E, 0x2CD34EA2,
+        0x2C954EC5,  0x2C574EE8, 0x2C194F0A, 0x2BDB4F2D,
+        0x2B9D4F4F,  0x2B5E4F71, 0x2B204F93, 0x2AE14FB5,
+        0x2AA34FD7,  0x2A644FF8, 0x2A255019, 0x29E6503A,
+        0x29A7505B,  0x2968507C, 0x2929509C, 0x28E950BC,
+        0x28AA50DC,  0x286A50FC, 0x282B511C, 0x27EB513B,
+        0x27AB515B,  0x276B517A, 0x272B5199, 0x26EB51B7,
+        0x26AB51D6,  0x266A51F4, 0x262A5212, 0x25E95230,
+        0x25A9524E,  0x2568526B, 0x25275288, 0x24E652A5,
+        0x24A652C2,  0x246452DF, 0x242352FB, 0x23E25318,
+        0x23A15334,  0x235F5350, 0x231E536B, 0x22DC5387,
+        0x229B53A2,  0x225953BD, 0x221753D8, 0x21D553F3,
+        0x2193540D,  0x21515427, 0x210F5442, 0x20CD545B,
+        0x208B5475,  0x2048548F, 0x200654A8, 0x1FC354C1,
+        0x1F8154DA,  0x1F3E54F2, 0x1EFB550B, 0x1EB85523,
+        0x1E76553B,  0x1E335553, 0x1DF0556A, 0x1DAC5582,
+        0x1D695599,  0x1D2655B0, 0x1CE355C7, 0x1C9F55DD,
+        0x1C5C55F4,  0x1C18560A, 0x1BD55620, 0x1B915636,
+        0x1B4D564B,  0x1B095661, 0x1AC55676, 0x1A82568B,
+        0x1A3E569F,  0x19F956B4, 0x19B556C8, 0x197156DC,
+        0x192D56F0,  0x18E95704, 0x18A45717, 0x1860572A,
+        0x181B573E,  0x17D75750, 0x17925763, 0x174D5775,
+        0x17095788,  0x16C4579A, 0x167F57AB, 0x163A57BD,
+        0x15F557CE,  0x15B057DF, 0x156B57F0, 0x15265801,
+        0x14E15812,  0x149C5822, 0x14575832, 0x14115842,
+        0x13CC5851,  0x13875861, 0x13415870, 0x12FC587F,
+        0x12B6588E,  0x1271589D, 0x122B58AB, 0x11E558B9,
+        0x11A058C7,  0x115A58D5, 0x111458E2, 0x10CE58F0,
+        0x108858FD,  0x1042590A, 0x0FFD5916, 0x0FB75923,
+        0x0F71592F,  0x0F2A593B, 0x0EE45947, 0x0E9E5952,
+        0x0E58595E,  0x0E125969, 0x0DCC5974, 0x0D85597E,
+        0x0D3F5989,  0x0CF95993, 0x0CB2599D, 0x0C6C59A7,
+        0x0C2559B1,  0x0BDF59BA, 0x0B9959C4, 0x0B5259CD,
+        0x0B0B59D5,  0x0AC559DE, 0x0A7E59E6, 0x0A3859EE,
+        0x09F159F6,  0x09AA59FE, 0x09645A05, 0x091D5A0D,
+        0x08D65A14,  0x08905A1B, 0x08495A21, 0x08025A28,
+        0x07BB5A2E,  0x07745A34, 0x072D5A3A, 0x06E75A3F,
+        0x06A05A44,  0x06595A49, 0x06125A4E, 0x05CB5A53,
+        0x05845A57,  0x053D5A5C, 0x04F65A60, 0x04AF5A63,
+        0x04685A67,  0x04215A6A, 0x03DA5A6D, 0x03935A70,
+        0x034C5A73,  0x03055A76, 0x02BE5A78, 0x02775A7A,
+        0x02305A7C,  0x01E95A7D, 0x01A25A7F, 0x015B5A80,
+        0x01135A81,  0x00CC5A82, 0x00855A82, 0x003E5A82
+    };
+
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/media/libstagefright/codecs/aacdec/mdst.cpp b/media/libstagefright/codecs/aacdec/mdst.cpp
new file mode 100644
index 0000000..19f82e3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mdst.cpp
@@ -0,0 +1,294 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: mdst.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input length 64
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    mdst
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#include "pv_audio_type_defs.h"
+#include "synthesis_sub_band.h"
+#include "dct16.h"
+#include "dct64.h"
+#include "mdst.h"
+
+#ifdef HQ_SBR
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#include "fxp_mul32.h"
+#include "dst32.h"
+
+
+#define Qfmt1(a)   (Int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+#define Qfmt(a)   (Int32)(a*((Int32)1<<27) + (a>=0?0.5F:-0.5F))
+
+const Int32 CosTable_32[32] =
+{
+    Qfmt1(0.50015063602065F),  Qfmt1(0.50135845244641F),
+    Qfmt1(0.50378872568104F),  Qfmt1(0.50747117207256F),
+    Qfmt1(0.51245147940822F),  Qfmt1(0.51879271310533F),
+    Qfmt1(0.52657731515427F),  Qfmt1(0.53590981690799F),
+    Qfmt1(0.54692043798551F),  Qfmt1(0.55976981294708F),
+    Qfmt1(0.57465518403266F),  Qfmt1(0.59181853585742F),
+    Qfmt1(0.61155734788251F),  Qfmt1(0.63423893668840F),
+    Qfmt1(0.66031980781371F),  Qfmt1(0.69037212820021F),
+    Qfmt1(0.72512052237720F),  Qfmt1(0.76549416497309F),
+    Qfmt1(0.81270209081449F),  Qfmt1(0.86834471522335F),
+    Qfmt(0.93458359703641F),  Qfmt(1.01440826499705F),
+    Qfmt(1.11207162057972F),  Qfmt(1.23383273797657F),
+    Qfmt(1.38929395863283F),  Qfmt(1.59397228338563F),
+    Qfmt(1.87467598000841F),  Qfmt(2.28205006800516F),
+    Qfmt(2.92462842815822F),  Qfmt(4.08461107812925F),
+    Qfmt(6.79675071167363F),  Qfmt(10.18693908361573F)
+};
+
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; mdst_32
+----------------------------------------------------------------------------*/
+
+void mdst_32(Int32 vec[], Int32 scratch_mem[])
+{
+
+    Int i;
+    const Int32 *pt_cos = CosTable_32;
+    Int32 *pt_vec = vec;
+    Int32 tmp1;
+    Int32 tmp2;
+
+
+
+    Int32 tmp3;
+
+    tmp3 = *(pt_vec++);
+    tmp2 = *(pt_vec);
+
+    for (i = 5; i != 0; i--)
+    {
+        *(pt_vec++)  += tmp3;
+        tmp1 = *(pt_vec);
+        *(pt_vec++)  += tmp2;
+        tmp3 = *(pt_vec);
+        *(pt_vec++)  += tmp1;
+        tmp2 = *(pt_vec);
+        *(pt_vec++)  += tmp3;
+        tmp1 = *(pt_vec);
+        *(pt_vec++)  += tmp2;
+        tmp3 = *(pt_vec);
+        *(pt_vec++)  += tmp1;
+        tmp2 = *(pt_vec);
+    }
+
+    *(pt_vec)  += tmp3;
+
+    dst_32(vec, scratch_mem);
+
+    pt_vec = vec;
+
+    for (i = 5; i != 0; i--)
+    {
+        *(pt_vec)   = fxp_mul32_Q31((*(pt_vec) << 1) + tmp2, *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q31((*(pt_vec) << 1) - tmp2, *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q31((*(pt_vec) << 1) + tmp2, *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q31((*(pt_vec) << 1) - tmp2, *(pt_cos++));
+        pt_vec++;
+    }
+
+    tmp2 >>= 1;
+    for (i = 3; i != 0; i--)
+    {
+        *(pt_vec)   = fxp_mul32_Q27((*(pt_vec) + tmp2), *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q27((*(pt_vec) - tmp2), *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q27((*(pt_vec) + tmp2), *(pt_cos++));
+        pt_vec++;
+        *(pt_vec)   = fxp_mul32_Q27((*(pt_vec) - tmp2), *(pt_cos++));
+        pt_vec++;
+    }
+
+    *(pt_vec - 1)   <<= 1;
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+; mdct_32
+----------------------------------------------------------------------------*/
+
+void mdct_32(Int32 vec[])
+{
+    Int i;
+    Int32 *pt_vec  = vec;
+    Int32 tmp1, tmp2;
+
+
+    const Int32 *pt_CosTable = CosTable_32;
+
+
+    for (i = 5; i != 0; i--)
+    {
+        *(pt_vec) = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q31(*(pt_vec) << 1, *(pt_CosTable++));
+        pt_vec++;
+    }
+    for (i = 3; i != 0; i--)
+    {
+        *(pt_vec) = fxp_mul32_Q27(*(pt_vec), *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q27(*(pt_vec), *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q27(*(pt_vec), *(pt_CosTable++));
+        pt_vec++;
+        *(pt_vec) = fxp_mul32_Q27(*(pt_vec), *(pt_CosTable++));
+        pt_vec++;
+    }
+    *(pt_vec - 1)   <<= 1;
+
+
+    dct_32(vec);
+
+
+    pt_vec  = &vec[31];
+
+    tmp1 = *(pt_vec--);
+
+    for (i = 5; i != 0; i--)
+    {
+        tmp2 = *(pt_vec);
+        *(pt_vec--)  += tmp1;
+        tmp1 = *(pt_vec);
+        *(pt_vec--)  += tmp2;
+        tmp2 = *(pt_vec);
+        *(pt_vec--)  += tmp1;
+        tmp1 = *(pt_vec);
+        *(pt_vec--)  += tmp2;
+        tmp2 = *(pt_vec);
+        *(pt_vec--)  += tmp1;
+        tmp1 = *(pt_vec);
+        *(pt_vec--)  += tmp2;
+    }
+
+    *(pt_vec)  += tmp1;
+
+}
+
+#endif /*  HQ_SBR  */
+
+
+/*----------------------------------------------------------------------------
+; dct_32
+----------------------------------------------------------------------------*/
+
+
+void dct_32(Int32 vec[])
+{
+
+    pv_split(&vec[16]);
+
+    dct_16(&vec[16], 0);
+    dct_16(vec, 1);     // Even terms
+
+    pv_merge_in_place_N32(vec);
+}
+
+#endif  /* AAC_PLUS */
+
+
diff --git a/media/libstagefright/codecs/aacdec/mdst.h b/media/libstagefright/codecs/aacdec/mdst.h
new file mode 100644
index 0000000..5b3e1c9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mdst.h
@@ -0,0 +1,73 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mdst.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef MDST_H
+#define MDST_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    void mdst_32(Int32 vec[], Int32 scratch_mem[]);
+
+    void  dct_32(Int32 vec[]);
+
+    void mdct_32(Int32 vec[]);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* MDST_H */
diff --git a/media/libstagefright/codecs/aacdec/mix_radix_fft.cpp b/media/libstagefright/codecs/aacdec/mix_radix_fft.cpp
new file mode 100644
index 0000000..6081c46
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mix_radix_fft.cpp
@@ -0,0 +1,319 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mix_radix_fft.c
+ Funtions: mix_radix_fft
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Eliminated pointer dependency ( pData_1) on Buffer address.
+               Modified for-loop to countdown loops.
+
+ Description:  No shift information going in/out from fft_rx4_long.
+
+ Description:
+            (1) Increased precision on the radix 2 fft coeff. (from Q10 to Q12)
+            (2) Increased precision on the input (from 0.5 to 1.0).
+            (3) Eliminated hardly used condition (exp = 0).
+            (4) Change interface to fft_rx4_long, so now the same function is
+                used for forward and inverse calculations.
+
+ Description:  per code review comments, eliminated unnecessary headers
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Data         = Input vector, with quantized spectral with a pre-rotation
+                   by exp(j(2pi/N)(k+1/8))
+                   type Int32 *
+
+    peak_value   = Input, carries the maximum value in input vector "Data"
+                   Output, maximum value computed in the first FFT, used
+                   to set precision on next stages
+                   type Int32 *
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    exponent = shift factor to reflect signal scaling
+
+ Pointers and Buffers Modified:
+    Results are return in "Data"
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    mix_radix_fft() mixes radix-2 and radix-4 FFT. This is needed to be able
+    to use power of 4 length when the input length sequence is a power of 2.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    mix_radix_fft() should support only the FFT for the long window case of
+    the inverse modified cosine transform (IMDCT)
+------------------------------------------------------------------------------
+ REFERENCES
+
+  ------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+   MODIFY( x[] )
+   RETURN( exponent )
+
+------------------------------------------------------------------------------
+ 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 "fft_rx4.h"
+#include "mix_radix_fft.h"
+#include "pv_normalize.h"
+
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void digit_reversal_swapping(Int32 *y, Int32 *x);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Int mix_radix_fft(
+    Int32   *Data,
+    Int32   *peak_value
+)
+
+{
+
+    const Int32     *p_w;
+    Int32   *pData_1;
+    Int32   *pData_2;
+
+    Int32   *pData_3;
+    Int32   *pData_4;
+
+    Int32   exp_jw;
+    Int32   max1;
+    Int32   max2;
+    Int32   temp1;
+    Int32   temp2;
+    Int32   temp3;
+    Int32   temp4;
+    Int32   diff1;
+    Int32   diff2;
+    Int     i;
+    Int   exp;
+
+    max1 = *peak_value;
+    p_w  = w_512rx2;
+
+    pData_1 = Data;
+    pData_3 = Data + HALF_FFT_RX4_LENGTH_FOR_LONG;
+
+
+    /*
+     * normalization to 0.9999 (0x7FFF) guarantees proper operation
+     */
+
+    exp = 8 - pv_normalize(max1);   /* use 24 bits for mix radix fft */
+
+    if (exp < 4)
+    {
+        exp = 4;
+    }
+
+
+    temp1      = (*pData_3);
+    pData_4    = pData_3 + FFT_RX4_LENGTH_FOR_LONG;
+    temp2      = (*pData_4++);
+
+
+
+    diff1      = (temp1  - temp2) >> exp;
+    *pData_3++ = (temp1  + temp2) >> exp;
+
+    temp3      = (*pData_3);
+    temp4      = (*pData_4);
+
+    *pData_4-- = -diff1;
+    *pData_3++ = (temp3  + temp4) >> exp;
+    *pData_4   = (temp3  - temp4) >> exp;
+
+    temp1      = (*pData_1);
+    pData_2    = pData_1 + FFT_RX4_LENGTH_FOR_LONG;
+    temp2      = (*pData_2++);
+    temp4      = (*pData_2);
+
+    *pData_1++ = (temp1  + temp2) >> exp;
+
+    temp3      = (*pData_1);
+    diff1      = (temp1  - temp2) >> exp ;
+
+    *pData_1++ = (temp3  + temp4) >> exp;
+    *pData_2-- = (temp3  - temp4) >> exp;
+    *pData_2   =  diff1;
+
+    temp1      = (*pData_3);
+    pData_4    = pData_3 + FFT_RX4_LENGTH_FOR_LONG;
+    temp2      = (*pData_4++);
+
+
+    for (i = ONE_FOURTH_FFT_RX4_LENGTH_FOR_LONG - 1; i != 0; i--)
+    {
+        /*
+         * radix 2 Butterfly
+         */
+
+        diff1      = (temp1  - temp2) >> (exp - 4);
+        *pData_3++ = (temp1  + temp2) >> exp;
+
+        temp3      = (*pData_3);
+        temp4      = (*pData_4);
+
+        exp_jw     = *p_w++;
+
+
+        diff2      = (temp3  - temp4) >> (exp - 4);
+        *pData_3++ = (temp3  + temp4) >> exp;
+
+        *pData_4-- = -cmplx_mul32_by_16(diff1,  diff2, exp_jw) >> 3;
+        *pData_4   =  cmplx_mul32_by_16(diff2, -diff1, exp_jw) >> 3;
+
+
+        temp1      = (*pData_1);
+        pData_2    = pData_1 + FFT_RX4_LENGTH_FOR_LONG;
+        temp2      = (*pData_2++);
+        temp4      = (*pData_2);
+
+        *pData_1++ = (temp1  + temp2) >> exp;
+
+        temp3      = (*pData_1);
+        diff1      = (temp1  - temp2) >> (exp - 4);
+
+        diff2      = (temp3  - temp4) >> (exp - 4);
+        *pData_1++ = (temp3  + temp4) >> exp;
+
+        *pData_2-- =  cmplx_mul32_by_16(diff2, -diff1, exp_jw) >> 3;
+        *pData_2   =  cmplx_mul32_by_16(diff1,  diff2, exp_jw) >> 3;
+
+        temp1      = (*pData_3);
+        pData_4    = pData_3 + FFT_RX4_LENGTH_FOR_LONG;
+        temp2      = (*pData_4++);
+
+    }/* for i  */
+
+
+    fft_rx4_long(
+        Data,
+        &max1);
+
+
+    fft_rx4_long(
+        &Data[FFT_RX4_LENGTH_FOR_LONG],
+        &max2);
+
+    digit_reversal_swapping(Data, &Data[FFT_RX4_LENGTH_FOR_LONG]);
+
+    *peak_value = max1 | max2;
+
+    return(exp);
+}
+
diff --git a/media/libstagefright/codecs/aacdec/mix_radix_fft.h b/media/libstagefright/codecs/aacdec/mix_radix_fft.h
new file mode 100644
index 0000000..563c280
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/mix_radix_fft.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: mix_radix_fft.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions mix_radix_fft
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MIX_RADIX_FFT_H
+#define MIX_RADIX_FFT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define     FFT_RX4_LENGTH_FOR_LONG         512
+#define     HALF_FFT_RX4_LENGTH_FOR_LONG    (FFT_RX4_LENGTH_FOR_LONG>>1)
+#define     ONE_FOURTH_FFT_RX4_LENGTH_FOR_LONG   (FFT_RX4_LENGTH_FOR_LONG>>2)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int mix_radix_fft(
+        Int32   *Data,
+        Int32   *peak_value);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* MIX_RADIX_FFT_H */
diff --git a/media/libstagefright/codecs/aacdec/ms_map_mask.h b/media/libstagefright/codecs/aacdec/ms_map_mask.h
new file mode 100644
index 0000000..fbbec78
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ms_map_mask.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ [Describe the contents of the include file.]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MS_MAP_MASK_H
+#define MS_MAP_MASK_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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 MS_map_mask(
+    FrameInfo  *info,
+    Int        *group,
+    Int        *mask,
+    Int        *cb_map);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/ms_synt.cpp b/media/libstagefright/codecs/aacdec/ms_synt.cpp
new file mode 100644
index 0000000..1f25516
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ms_synt.cpp
@@ -0,0 +1,403 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ms_synt.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Cleaned up a bit, not finished.
+
+ Description:
+ Copied in code from pns_intensity_right.c, which has the same structure as
+ this file.  Also, merged in code from ms_map_mask.c
+
+ Description:
+ (1) Various optimizations (eliminated extra variables by making use of a
+ single temporary register throughout the code, etc.)
+ (2) Wrote pseudocode, pasted in correct function template, etc.
+
+ Description:  Unrolled loops to get speed up code
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    wins_in_group        = Number of windows in the current group.
+                           [const Int]
+
+    coef_per_win         = Number of coefficients per window.
+                           [const Int]
+
+    num_bands            = Number of scalefactor bands.
+                           [const Int]
+
+    band_length          = Number of coefficients per scalefactor band.
+                           [const Int]
+
+    pFirst_Window_CoefsL = Array containing the spectral coefficients for
+                           the left channel.
+                           [Int32 *, length LN]
+    pFirst_Window_CoefsR = Array containing the spectral coefficients for
+                           the right channel.
+                           [Int32 *, length LN]
+    q_formatLeft         = Array containing the q-format used to encode each
+                           scalefactor band's data on the left channel.
+                           [Int *, length MAXBANDS]
+    q_formatRight        = Array containing the q-format used to encode each
+                           scalefactor band's data on the right channel.
+                           [Int *, length MAXBANDS]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+   pFirst_Window_CoefsL  The coefficients in the group will be modified per the
+                         formula for M/S stereo on each scalefactor band where
+                         M/S stereo is active.
+
+   pFirst_Window_CoefsR  The coefficients in the group will be modified per the
+                         formula for M/S stereo on each scalefactor band where
+                         M/S stereo is active.
+
+   q_formatLeft          The q_format may be modified on scalefactor bands
+                         where M/S stereo is active.
+
+   q_formatRight         The q_format may be modified on scalefactor bands
+                         where M/S stereo is active.
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module applies the formula for M/S coding to one grouped scalefactor
+ band.  The ISO code has a similar function which applies M/S coding to an
+ entire frame.
+
+ It is the calling function's responsibility to check the map_mask array, which
+ is filled by the function getmask.  If a scalefactor band is identified as
+ using M/S stereo, the coefficients in that array are calculated using
+ the following formula...
+
+ TempLeft = LeftCoefficient;
+
+ LeftCoefficient  = LeftCoefficient  + RightCoefficient;
+ RightCoefficient = TempLeft         - RightCoefficient;
+
+ This function should be inlined if the compiler supports C99 inlining,
+ as this short function is only called by sfb_tools_ms().
+ Therefore, inlining will not increase the code size.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.7.1   M/S stereo
+        Subpart 4.6.2     ScaleFactors
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    start_indx = 0;
+
+    pCoefR = coefLeft;
+    pCoefL = coefRight;
+
+    FOR (win_indx = wins_in_group; win_indx > 0; win_indx--)
+
+
+        tempInt = q_formatLeft[start_indx] - q_formatRight[start_indx];
+
+        IF (tempInt > 0)
+        THEN
+
+            shift_left_chan  = 1 + tempInt;
+            shift_right_chan = 1;
+
+            q_formatLeft[start_indx]  = (q_formatRight[start_indx] - 1);
+            q_formatRight[start_indx] = (q_formatRight[start_indx] - 1);
+
+        ELSE
+            shift_left_chan  = 1;
+            shift_right_chan = 1 - tempInt;
+
+            q_formatRight[start_indx] = (q_formatLeft[start_indx] - 1);
+            q_formatLeft[start_indx]  = (q_formatLeft[start_indx] - 1);
+
+        ENDIF
+
+        FOR (tempInt = band_length; tempInt > 0; tempInt--)
+
+            temp_left  = *(pCoefL) >> shift_left_chan;
+            temp_right = *(pCoefR) >> shift_right_chan;
+
+            *(pCoefL++) = temp_left + temp_right;
+            *(pCoefR++) = temp_left - temp_right;
+
+        ENDFOR
+
+        tempInt = (coef_per_win - band_length);
+
+        pCoefR = pCoefR + tempInt;
+        pCoefL = pCoefL + tempInt;
+
+        start_indx = start_indx + num_bands;
+
+    ENDFOR
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor 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 "pv_audio_type_defs.h"
+#include "ms_synt.h"
+#include "fxp_mul32.h"
+#include "aac_mem_funcs.h"
+#include "window_block_fxp.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 ms_synt(
+    const Int   wins_in_group,
+    const Int   coef_per_win,
+    const Int   num_bands,
+    const Int   band_length,
+    Int32 coefLeft[],
+    Int32 coefRight[],
+    Int q_formatLeft[],
+    Int q_formatRight[])
+{
+
+    Int32 *pCoefL = coefLeft;
+    Int32 *pCoefR = coefRight;
+    Int start_indx = 0;
+
+
+    if (band_length < 0 || band_length > LONG_WINDOW)
+    {
+        return;     /*  avoid any processing on error condition */
+    }
+
+
+    Int nextWinPtrUpdate = (coef_per_win - band_length);
+
+    for (Int win_indx = wins_in_group; win_indx > 0; win_indx--)
+    {
+
+        if (q_formatRight[start_indx] < 31)
+        {
+            Int tempInt = q_formatLeft[start_indx] - q_formatRight[start_indx];
+
+            /* Normalize the left and right channel to the same q-format */
+            if (tempInt > 0)
+            {
+                /*
+                 * shift_left_chan and shift_right_chan each have an offset
+                 * of 1.  Even if the left and right channel share the same
+                 * q-format, we must shift each by 1 to guard against
+                 * overflow.
+                 */
+                Int shift_left_chan  = 1 + tempInt;
+
+                /*
+                 * Following code line is equivalent to...
+                 * q_formatLeft  = q_formatRight - 1;
+                 * q_formatRight = q_formatRight - 1;
+                 */
+                q_formatLeft[start_indx] = --(q_formatRight[start_indx]);
+
+
+                /*
+                 *  band_length is always an even number (check tables in pg.66 IS0 14496-3)
+                 */
+
+                Int32 temp_left  = *(pCoefL) >> shift_left_chan;
+                Int32 temp_right = *(pCoefR) >> 1;
+
+
+
+                for (Int i = band_length; i != 0; i--)
+                {
+                    *(pCoefL++) = temp_left + temp_right;
+                    *(pCoefR++) = temp_left - temp_right;
+                    temp_left  = *(pCoefL) >> shift_left_chan;
+                    temp_right = *(pCoefR) >> 1;
+
+                }
+
+            }
+            else
+            {
+                /*
+                 * shift_left_chan and shift_right_chan each have an offset
+                 * of 1.  Even if the left and right channel share the same
+                 * q-format, we must shift each by 1 to guard against
+                 * overflow.
+                 */
+                Int shift_right_chan = 1 - tempInt;
+
+                /*
+                 * Following code line is equivalent to...
+                 * q_formatRight = q_formatLeft - 1;
+                 * q_formatLeft  = q_formatLeft - 1;
+                 */
+                q_formatRight[start_indx] = --(q_formatLeft[start_indx]);
+
+                /*
+                 *  band_length is always an even number (check tables in pg.66 IS0 14496-3)
+                 */
+
+                Int32 temp_left  = *(pCoefL) >> 1;
+                Int32 temp_right = *(pCoefR) >> shift_right_chan;
+
+                for (Int i = band_length; i != 0; i--)
+                {
+                    *(pCoefL++) = temp_left + temp_right;
+                    *(pCoefR++) = temp_left - temp_right;
+
+                    temp_left  = *(pCoefL) >> 1;
+                    temp_right = *(pCoefR) >> shift_right_chan;
+
+                }
+            }
+
+        }
+        else
+        {
+            /*
+             *  Nothing on right channel, just copy left into right
+             */
+            q_formatRight[start_indx] = (q_formatLeft[start_indx]);
+
+            pv_memcpy(pCoefR, pCoefL, band_length*sizeof(*pCoefR));
+            pCoefR += band_length;
+            pCoefL += band_length;
+        }
+
+        /*
+         * Increment the window pointers so they point
+         * to the next window in the group
+         */
+        pCoefL += nextWinPtrUpdate;
+        pCoefR += nextWinPtrUpdate;
+
+        start_indx += num_bands;
+
+    } /* for (win_indx) */
+
+    return;
+
+} /* MS_synt */
diff --git a/media/libstagefright/codecs/aacdec/ms_synt.h b/media/libstagefright/codecs/aacdec/ms_synt.h
new file mode 100644
index 0000000..a00e6e2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ms_synt.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ms_synt.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Updated to reflect new functionality of ms_synt() routine.
+ (ms_synt now only decodes one grouped scalefactor band at a time.)
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes the function declaration for ms_synt().
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MS_SYNT_H
+#define MS_SYNT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 ms_synt(
+    const Int   wins_in_group,
+    const Int   coef_per_win,
+    const Int   num_bands,
+    const Int   band_length,
+    Int32 spectralCoefLeft[],
+    Int32 spectralCoefRight[],
+    Int   q_formatLeft[],
+    Int   q_formatRight[]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pns_corr.cpp b/media/libstagefright/codecs/aacdec/pns_corr.cpp
new file mode 100644
index 0000000..4cfe720
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_corr.cpp
@@ -0,0 +1,342 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pns_corr.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made changes per review comments, the most major of which
+ being the change of the scaling into a 16 x 16 multiply.
+
+ Description: When the multiplication of two 16-bits variables is stored in
+              an 32-bits variable, the result should be typecasted explicitly
+              to Int32 before it is stored.
+              *(pCoefRight++) = (Int32) tempInt2 * multiplier;
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    scale        =  Multiplier used to scale the noise extracted from the left
+                    channel for use on the right.
+                    [const Int]
+
+    coef_per_win =  Number of coefficients per window.
+                    (128 for short, 1024 for long)
+                    [const Int]
+
+    sfb_per_win  =  Number of scalefactors per window.
+                    [const Int]
+
+    wins_in_group = The number of windows in the group being decoded.
+                    [const Int]
+
+    band_length  =  The length of the scalefactor band being decoded.
+                    [const Int]
+
+    sfb_prediction_used =  Flag that denotes the activation of long term
+                           prediction on a per-scalefactor band,
+                           non-grouped basis.
+                           [const Int *, length MAX_SFB]
+
+    q_formatLeft = The Q-format for the left channel's fixed-point spectral
+                   coefficients, on a per-scalefactor band, non-grouped basis.
+                   [const Int]
+
+    q_formatRight = The Q-format for the right channel's fixed-point spectral
+                    coefficients, on a per-scalefactor band, non-grouped basis.
+                    [Int *, length MAX_SFB]
+
+    coefLeft = Array containing the fixed-point spectral coefficients
+               for the left channel.
+               [const Int32 *, length 1024]
+
+    coefRight = Array containing the fixed-point spectral coefficients
+                for the right channel.
+                [Int32 *, length 1024]
+
+ Local Stores/Buffers/Pointers Needed:
+
+ Global Stores/Buffers/Pointers Needed:
+
+ Outputs:
+
+ Pointers and Buffers Modified:
+    pcoefRight  Contains the new spectral information
+
+    q_formatRight       Q-format may be updated with changed to fixed-point
+                        data in coefRight.
+
+    sfb_prediction_used              LTP may be disabled by presence of PNS tool on the
+                        same scalefactor band.
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function derives noise from the left channel.  The PNS tool is assumed
+ to have been used on the same scalefactor band on the left channel.  The
+ noise on the left/right channels are not necessarily of the same amplitude,
+ and therefore have separate scalefactors.  The noise is thus scaled by the
+ difference between the two transmitted scalefactors.  This scaling is done
+ in fixed-point using a constant 4-element table.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.7.1   M/S stereo
+        Subpart 4.6.12.3  Decoding Process (PNS)
+        Subpart 4.6.2     ScaleFactors
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    q_format = q_formatLeft - (scale >> 2);
+    q_format = q_format - 1;
+    q_formatRight = q_format;
+
+    multiplier = hcb2_scale_mod_4[scale & 0x3];
+
+    pCoefLeft = coefLeft;
+    pCoefRight = coefRight;
+
+    start_indx = 0;
+
+    FOR (win_indx = wins_in_group; win_indx > 0; win_indx--)
+
+        q_formatRight[start_indx] = q_format;
+
+        sfb_prediction_used[start_indx] = FALSE;
+
+        start_indx = start_indx + sfb_per_win;
+
+        FOR (tempInt = band_length; tempInt > 0; tempInt--)
+
+            *(pCoefRight) = (*(pCoefLeft) >> 9) * multiplier;
+            pCoefRight = pCoefRight + 1;
+            pCoefLeft = pCoefLeft + 1;
+
+        ENDFOR
+
+        tempInt = (coef_per_win - band_length);
+        pCoefRight = pCoefRight + tempInt;
+        pCoefLeft = pCoefLeft + tempInt;
+
+    ENDFOR
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor 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 "pv_audio_type_defs.h"
+#include "pns_corr.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
+----------------------------------------------------------------------------*/
+
+const UInt hcb2_scale_mod_4[4] =
+{
+    32768,  /* (2.0^0.00)*2^15 */
+    38968,  /* (2.0^0.25)*2^15 */
+    46341,  /* (2.0^0.50)*2^15 */
+    55109
+}; /* (2.0^0.75)*2^15 */
+
+/*----------------------------------------------------------------------------
+; 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 pns_corr(
+    const Int scale,
+    const Int coef_per_win,
+    const Int sfb_per_win,
+    const Int wins_in_group,
+    const Int band_length,
+    const Int q_formatLeft,
+    Int q_formatRight[],
+    const Int32 coefLeft[],
+    Int32 coefRight[])
+{
+    Int tempInt;
+    Int nextWinPtrUpdate;
+
+    Int q_format;
+
+    Int start_indx;
+    Int win_indx;
+
+    const Int32   *pCoefLeft;
+    Int32   *pCoefRight;
+
+    UInt multiplier;
+
+    /*
+     * Generate noise correlated with the noise on the left channel
+     *
+     */
+
+    /*
+     * scale is interpreted as 2^(scale/4)
+     * Therefore, we can adjust the q-format by floor(scale/4)
+     * and save some complexity in the multiplier.
+     */
+    q_format = q_formatLeft - (scale >> 2);
+
+    /*
+     * Reduce the q-format by 1 to guard against overflow.
+     * This must be done because the hcb2_scale_mod_4 table
+     * must be stored in a common q-format, and we must shift
+     * by 16 to get *pCoefLeft into a 16-bit value, but we
+     * cannot store 2^0*2^16 and 2^0.75*2^16 in a table.
+     */
+    q_format--;
+
+    multiplier = hcb2_scale_mod_4[scale & 0x3];
+
+    pCoefLeft  = coefLeft;
+    pCoefRight = coefRight;
+
+    nextWinPtrUpdate = (coef_per_win - band_length);
+
+    /*
+     * Step through all the windows in this group, replacing this
+     * band in each window's spectrum with correlated random noise
+     */
+
+    start_indx = 0;
+
+    for (win_indx = wins_in_group; win_indx > 0; win_indx--)
+    {
+        /*
+         * Set the q-format for all scalefactor bands in the group.
+         * Normally, we could not assume that grouped scalefactors
+         * share the same q-format.
+         * However, here we can make this assumption.  The reason
+         * being -- if this function is called, it is assumed
+         * PNS was used on the left channel.  When PNS is used,
+         * all scalefactors in a group share the same q-format.
+         *
+         */
+        q_formatRight[start_indx] = q_format;
+
+        start_indx += sfb_per_win;
+
+        /* reconstruct right noise values */
+        for (tempInt = band_length; tempInt > 0; tempInt--)
+        {
+            *(pCoefRight++) = (Int32)(*(pCoefLeft++) >> 16) * multiplier;
+        }
+
+        pCoefRight += nextWinPtrUpdate;
+        pCoefLeft  += nextWinPtrUpdate;
+
+    } /* for (win_indx) */
+
+    return;
+
+} /* void pns_corr */
diff --git a/media/libstagefright/codecs/aacdec/pns_corr.h b/media/libstagefright/codecs/aacdec/pns_corr.h
new file mode 100644
index 0000000..c892a8c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_corr.h
@@ -0,0 +1,95 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pns_corr.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made changes per review comments.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Contains the function declaration for pns_corr.c
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PNS_CORR_H
+#define PNS_CORR_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 pns_corr(
+    const Int scale,
+    const Int coef_per_win,
+    const Int sfb_per_win,
+    const Int wins_in_group,
+    const Int band_length,
+    const Int q_formatLeft,
+    Int q_formatRight[],
+    const Int32 coefLeft[],
+    Int32 coefRight[]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pns_intensity_right.cpp b/media/libstagefright/codecs/aacdec/pns_intensity_right.cpp
new file mode 100644
index 0000000..f2d50c1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_intensity_right.cpp
@@ -0,0 +1,653 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pns_intensity_right.c
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    hasmask    = mask status for the frame. Enumerated.
+
+    pFrameInfo = Pointer to structure that holds information about each group.
+                 (long block flag, number of windows, scalefactor bands
+                  per group, etc.)
+                 [const pFrameInfo * const]
+
+    group      = Array that contains indexes of the
+                 first window in the next group.
+                 [const Int *, length num_win]
+
+    mask_map   = Array that denotes whether M/S stereo is turned on for
+                 each grouped scalefactor band.
+                 [const Int *, length MAX_SFB]
+
+    codebook_map = Array that denotes which Huffman codebook was used for
+                   the encoding of each grouped scalefactor band.
+                   [const Int *, length MAX_SFB]
+
+    factorsL     =  Array of grouped scalefactors for left chan.
+                    [const Int *, length MAX_SFB]
+
+    factorsR     =  Array of scalefactors for right chan.
+                    [const Int *, length MAX_SFB]
+
+    sfb_prediction_used =  Flag that denotes the activation of long term prediction
+                           on a per-scalefactor band, non-grouped basis.
+                           [const Int *, length MAX_SFB]
+
+    ltp_data_present = Flag that indicates whether LTP is enbaled for this frame.
+                       [const Bool]
+
+    coefLeft = Array containing the fixed-point spectral coefficients
+                       for the left channel.
+                       [Int32 *, length 1024]
+
+    coefRight = Array containing the fixed-point spectral coefficients
+                        for the right channel.
+                        [Int32 *, length 1024]
+
+    q_formatLeft = The Q-format for the left channel's fixed-point spectral
+                   coefficients, on a per-scalefactor band, non-grouped basis.
+                   [Int *, length MAX_SFB]
+
+    q_formatRight = The Q-format for the right channel's fixed-point spectral
+                    coefficients, on a per-scalefactor band, non-grouped basis.
+                    [Int *, length MAX_SFB]
+
+    pCurrentSeed  = Pointer to the current seed for the random number
+                    generator in the function gen_rand_vector().
+                    [Int32 * const]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coefLeft  = Contains the new spectral information.
+
+    coefRight = Contains the new spectral information.
+
+    q_formatLeft      = Q-format may be updated with changed to fixed-point
+                        data in coefLeft.
+
+    q_formatRight     = Q-format may be updated with changed to fixed-point
+                        data in coefRight.
+
+    pCurrentSeed      = Value pointed to by pCurrentSeed updated by calls
+                        to gen_rand_vector().
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function steps through all of the scalefactor bands, looking for
+ either PNS or IS to be enabled on the right channel.
+
+ If the codebook used is >= NOISE_HCB, the code then checks for the use
+ of Huffman codebooks NOISE_HCB, INTENSITY_HCB, or INTENSITY_HCB2.
+
+ When a SFB utilizing the codebook NOISE_HCB is detected, a check is made to
+ see if M/S has also been enabled for that SFB.
+
+ If M/S is not enabled, the band's spectral information is filled with
+ scaled random data.   The scaled random data is generated by the function
+ gen_rand_vector.  This is done across all windows in the group.
+
+ If M/S is enabled, the band's spectral information is derived from the data
+ residing in the same band on the left channel.  The information on the right
+ channel has independent scaling, so this is a bit more involved than a
+ direct copy of the information on the left channel.  This is done by calling
+ the inline function pns_corr().
+
+ When a SFB utilizing an intensity codebook is detected, the band's spectral
+ information is generated from the information on the left channel.
+ This is done across all windows in the group.  M/S being enabled has the
+ effect of reversing the sign of the data on the right channel.  This code
+ resides in the inline function intensity_right().
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.7.1   M/S stereo
+        Subpart 4.6.7.2.3 Decoding Process (Intensity Stereo)
+        Subpart 4.6.12.3  Decoding Process (PNS)
+        Subpart 4.6.2     ScaleFactors
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+    pCoefRight = coefRight;
+    pCoefLeft = coefLeft;
+
+    window_start = 0;
+    tot_sfb = 0;
+    start_indx = 0;
+
+    coef_per_win = pFrameInfo->coef_per_win[0];
+
+    sfb_per_win = pFrameInfo->sfb_per_win[0];
+
+    DO
+        pBand     = pFrameInfo->win_sfb_top[window_start];
+
+        partition = *pGroup;
+        pGroup = pGroup + 1;
+
+        band_start = 0;
+
+        wins_in_group = (partition - window_start);
+
+        FOR (sfb = sfb_per_win; sfb > 0; sfb--)
+
+            band_stop = *(pBand);
+            pBand = pBand + 1;
+
+            codebook = *(pCodebookMap);
+            pCodebookMap = pCodebookMap + 1;
+
+            mask_enabled = *(pMaskMap);
+            pMaskMap = pMaskMap + 1;
+
+            band_length = band_stop - band_start;
+
+            IF (codebook == NOISE_HCB)
+
+                sfb_prediction_used[tot_sfb] &= ltp_data_present;
+
+                IF (sfb_prediction_used[tot_sfb] == FALSE)
+
+                    mask_enabled = mask_enabled AND hasmask;
+
+                    IF (mask_enabled == FALSE)
+
+                        pWindow_CoefR = &(pCoefRight[band_start]);
+
+                        start_indx = tot_sfb;
+
+                        FOR (win_indx = wins_in_group;
+                             win_indx > 0;
+                             win_indx--)
+
+                            CALL
+                            q_formatRight[start_indx] =
+                                 gen_rand_vector(
+                                     pWindow_CoefR,
+                                     band_length,
+                                     pCurrentSeed,
+                                     *(pFactorsRight));
+                            MODIFYING
+                                pCoefRight[band_start]
+                            RETURNING
+                                q_formatRight[start_indx]
+
+                            pWindow_CoefR += coef_per_win;
+
+                            start_indx = start_indx + sfb_per_win;
+
+                        ENDFOR
+
+                    ELSE
+                        CALL
+                        pns_corr(
+                             (*(pFactorsRight) -
+                              *(pFactorsLeft) ),
+                             coef_per_win,
+                             sfb_per_win,
+                             wins_in_group,
+                             band_length,
+                             q_formatLeft[tot_sfb],
+                            &(q_formatRight[tot_sfb]),
+                            &(pCoefLeft[band_start]),
+                            &(pCoefRight[band_start]));
+
+                        MODIFYING
+                            pCoefRightt[band_start]
+                            q_formatRight[tot_sfb]
+                        RETURNING
+                NONE
+                    ENDIF
+
+                ENDIF
+
+            ELSE IF (codebook >= INTENSITY_HCB2)
+
+                mask_enabled = mask_enabled AND hasmask;
+
+                CALL
+                    intensity_right(
+                        *(pFactorsRight),
+                        coef_per_win,
+                        sfb_per_win,
+                        wins_in_group,
+                        band_length,
+                        codebook,
+                        mask_enabled,
+                       &(q_formatLeft[tot_sfb]),
+                       &(q_formatRight[tot_sfb]),
+                       &(pCoefLeft[band_start]),
+                       &(pCoefRight[band_start]));
+
+                MODIFYING
+                    pCoefRightt[band_start]
+                    q_formatRight[tot_sfb]
+                RETURNING
+                    NONE
+
+            ENDIF
+
+            band_start = band_stop;
+
+            tot_sfb = tot_sfb + 1;
+
+        ENDFOR
+
+        coef_per_win = coef_per_win * (wins_in_group);
+
+        wins_in_group = wins_in_group - 1;
+
+        tot_sfb = tot_sfb + sfb_per_win * wins_in_group;
+        pFactorsRight = pFactorsRight + sfb_per_win * wins_in_group;
+        pFactorsLeft  = pFactorsLeft + sfb_per_win * wins_in_group;
+
+        pCoefRight = pCoefRight + coef_per_win;
+        pCoefLeft  = pCoefLeft + coef_per_win;
+
+        window_start = partition;
+
+    WHILE (partition < pFrameInfo->num_win);
+
+    return;
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+   When the code is written for a specific target processor 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 "pv_audio_type_defs.h"
+#include "pns_intensity_right.h"
+#include "e_huffmanconst.h"
+#include "gen_rand_vector.h"
+#include "intensity_right.h"
+#include "pns_corr.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 pns_intensity_right(
+    const Int        hasmask,
+    const FrameInfo * const pFrameInfo,
+    const Int        group[],
+    const Bool       mask_map[],
+    const Int        codebook_map[],
+    const Int        factorsL[],
+    const Int        factorsR[],
+    Int        sfb_prediction_used[],
+    const Bool       ltp_data_present,
+    Int32      coefLeft[],
+    Int32      coefRight[],
+    Int        q_formatLeft[MAXBANDS],
+    Int        q_formatRight[MAXBANDS],
+    Int32 * const pCurrentSeed)
+{
+
+    Int32   *pCoefRight;
+    Int32   *pWindow_CoefR;
+
+    Int32   *pCoefLeft;
+
+    Int     tot_sfb;
+    Int     start_indx;
+    Int     sfb;
+
+    Int     band_length;
+    Int     band_start;
+    Int     band_stop;
+    Int     coef_per_win;
+
+    Int     codebook;
+    Int     partition;
+    Int     window_start;
+
+    Int     sfb_per_win;
+    Int     wins_in_group;
+    Int     win_indx;
+
+    const Int16 *pBand;
+    const Int   *pFactorsLeft  = factorsL;
+    const Int   *pFactorsRight = factorsR;
+    const Int   *pCodebookMap  = codebook_map;
+    const Int   *pGroup        = group;
+    const Bool  *pMaskMap      = mask_map;
+
+    Bool mask_enabled;
+
+    pCoefRight = coefRight;
+    pCoefLeft = coefLeft;
+
+    window_start = 0;
+    tot_sfb = 0;
+    start_indx = 0;
+
+    /*
+     * Each window in the frame should have the same number of coef's,
+     * so coef_per_win is constant in all the loops
+     */
+    coef_per_win = pFrameInfo->coef_per_win[0];
+
+    /*
+     * Because the number of scalefactor bands per window should be
+     * constant for each frame, sfb_per_win can be determined outside
+     * of the loop.
+     *
+     * For 44.1 kHz sampling rate   sfb_per_win = 14 for short windows
+     *                              sfb_per_win = 49 for long  windows
+     */
+
+    sfb_per_win = pFrameInfo->sfb_per_win[0];
+
+    do
+    {
+        pBand     = pFrameInfo->win_sfb_top[window_start];
+
+        /*----------------------------------------------------------
+        Partition is equal to the first window in the next group
+
+        { Group 0    }{      Group 1      }{    Group 2 }{Group 3}
+        [win 0][win 1][win 2][win 3][win 4][win 5][win 6][win 7]
+
+        pGroup[0] = 2
+        pGroup[1] = 5
+        pGroup[2] = 7
+        pGroup[3] = 8
+        -----------------------------------------------------------*/
+        partition = *(pGroup++);
+
+        band_start = 0;
+
+        wins_in_group = (partition - window_start);
+
+        for (sfb = sfb_per_win; sfb > 0; sfb--)
+        {
+            /* band is offset table, band_stop is last coef in band */
+            band_stop = *(pBand++);
+
+            codebook = *(pCodebookMap++);
+
+            mask_enabled = *(pMaskMap++);
+
+            /*
+             * When a tool utilizing sfb is found, apply the correct tool
+             * to that sfb in each window in the group
+             *
+             * Example...  sfb[3] == NOISE_HCB
+             *
+             * [ Group 1                                      ]
+             * [win 0                 ][win 1                 ]
+             * [0][1][2][X][4][5][6][7][0][1][2][X][4][5][6][7]
+             *
+             * The for(sfb) steps through the sfb's 0-7 in win 0.
+             *
+             * Finding sfb[3]'s codebook == NOISE_HCB, the code
+             * steps through all the windows in the group (they share
+             * the same scalefactors) and replaces that sfb with noise.
+             */
+
+            /*
+             * Experimental results suggest that ms_synt is the most
+             * commonly used tool, so check for it first.
+             *
+             */
+
+            band_length = band_stop - band_start;
+
+            if (codebook == NOISE_HCB)
+            {
+                sfb_prediction_used[tot_sfb] &= ltp_data_present;
+
+                if (sfb_prediction_used[tot_sfb] == FALSE)
+                {
+                    /*
+                     * The branch and the logical AND interact in the
+                     * following manner...
+                     *
+                     * mask_enabled == 0 hasmask == X -- gen_rand_vector
+                     * mask_enabled == 1 hasmask == 1 -- pns_corr
+                     * mask_enabled == 0 hasmask == 1 -- gen_rand_vector
+                     * mask_enabled == 1 hasmask == 2 -- gen_rand_vector
+                     * mask_enabled == 0 hasmask == 2 -- gen_rand_vector
+                     */
+
+                    mask_enabled &= hasmask;
+
+                    if (mask_enabled == FALSE)
+                    {
+                        pWindow_CoefR = &(pCoefRight[band_start]);
+
+                        /*
+                         * Step through all the windows in this group,
+                         * replacing this band in each window's
+                         * spectrum with random noise
+                         */
+                        start_indx = tot_sfb;
+
+                        for (win_indx = wins_in_group;
+                                win_indx > 0;
+                                win_indx--)
+                        {
+
+                            /* generate random noise */
+                            q_formatRight[start_indx] =
+                                gen_rand_vector(
+                                    pWindow_CoefR,
+                                    band_length,
+                                    pCurrentSeed,
+                                    *(pFactorsRight));
+
+                            pWindow_CoefR += coef_per_win;
+
+                            start_indx += sfb_per_win;
+                        }
+
+                    }
+                    else
+                    {
+                        pns_corr(
+                            (*(pFactorsRight) -
+                             *(pFactorsLeft)),
+                            coef_per_win,
+                            sfb_per_win,
+                            wins_in_group,
+                            band_length,
+                            q_formatLeft[tot_sfb],
+                            &(q_formatRight[tot_sfb]),
+                            &(pCoefLeft[band_start]),
+                            &(pCoefRight[band_start]));
+
+                    } /* if (mask_map == FALSE) */
+
+                } /* if (sfb_prediction_used[tot_sfb] == FALSE) */
+
+            } /* if (codebook == 0) */
+            else if (codebook >= INTENSITY_HCB2)
+            {
+                /*
+                 * The logical AND flags the inversion of intensity
+                 * in the following manner.
+                 *
+                 * mask_enabled == X hasmask == 0 -- DO NOT INVERT
+                 * mask_enabled == 0 hasmask == X -- DO NOT INVERT
+                 * mask_enabled == 1 hasmask == 1 -- DO     INVERT
+                 * mask_enabled == 0 hasmask == 1 -- DO NOT INVERT
+                 * mask_enabled == 1 hasmask == 2 -- DO NOT INVERT
+                 * mask_enabled == 0 hasmask == 2 -- DO NOT INVERT
+                 */
+
+                mask_enabled &= hasmask;
+
+                intensity_right(
+                    *(pFactorsRight),
+                    coef_per_win,
+                    sfb_per_win,
+                    wins_in_group,
+                    band_length,
+                    codebook,
+                    mask_enabled,
+                    &(q_formatLeft[tot_sfb]),
+                    &(q_formatRight[tot_sfb]),
+                    &(pCoefLeft[band_start]),
+                    &(pCoefRight[band_start]));
+
+            } /* END else codebook must be INTENSITY_HCB or ... */
+
+            band_start = band_stop;
+
+            tot_sfb++;
+
+            pFactorsLeft++;
+            pFactorsRight++;
+
+        } /* for (sfb) */
+
+        /*
+         * Increment pCoefRight and pCoefLeft by
+         * coef_per_win * the number of windows
+         */
+
+        pCoefRight += coef_per_win * wins_in_group;
+        pCoefLeft  += coef_per_win * wins_in_group--;
+
+        /*
+         * Increase tot_sfb by sfb_per_win times the number of windows minus 1.
+         * The minus 1 comes from the fact that tot_sfb is already pointing
+         * to the first sfb in the 2nd window of the group.
+         */
+        tot_sfb += sfb_per_win * wins_in_group;
+
+        pFactorsRight += sfb_per_win * wins_in_group;
+        pFactorsLeft  += sfb_per_win * wins_in_group;
+
+        window_start = partition;
+
+    }
+    while (partition < pFrameInfo->num_win);
+
+    /* pFrameInfo->num_win = 1 for long windows, 8 for short_windows */
+
+    return;
+
+} /* pns_intensity_right() */
+
+
diff --git a/media/libstagefright/codecs/aacdec/pns_intensity_right.h b/media/libstagefright/codecs/aacdec/pns_intensity_right.h
new file mode 100644
index 0000000..7b6f79f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_intensity_right.h
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pns_intensity_right.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Add hasmask parameter
+
+ Description: Changed name to from right_ch_sfb_tools_ms to intensity_right
+ to more correct reflect the purpose of the function.
+
+ Who:                                  Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the function declaration for
+ pns_intensity_right.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PNS_INTENSITY_RIGHT_H
+#define PNS_INTENSITY_RIGHT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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 pns_intensity_right(
+    const Int        hasmask,
+    const FrameInfo * const pFrameInfo,
+    const Int        group[],
+    const Bool       mask_map[],
+    const Int        codebook_map[],
+    const Int        factorsL[],
+    const Int        factorsR[],
+    Int        sfb_prediction_used[],
+    const Bool       ltp_data_present,
+    Int32      spectralCoefLeft[],
+    Int32      spectralCoefRight[],
+    Int        q_formatLeft[MAXBANDS],
+    Int        q_formatRight[MAXBANDS],
+    Int32     * const pCurrentSeed);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pns_left.cpp b/media/libstagefright/codecs/aacdec/pns_left.cpp
new file mode 100644
index 0000000..2446de2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_left.cpp
@@ -0,0 +1,431 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Pathname: pns_left.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Brought code in-line with PV standards.
+               Merged PNS and Intensity blocks into one function.
+               Modified routine to interface with a fixed-point implementation.
+               Modified variable names for clarity.
+               Improved for-loop structure that was previously checking
+               the codebook used in each scale factor band multiple times.
+
+ Description:  Added some comments for clarity.
+
+ Description:  Changed strategy for q-format.  Q-format for SFBs should not
+ be grouped.
+
+ Description: Function had to be modified to obey new interpretation of the
+ sfb_prediction_used flag.  LTP takes precedence, and PNS should not be
+ executed when a collision occurs between these two tools.
+
+ Description:
+ (1) Added flag "ltp_data_present"
+ (2) Where feasible, I updated the code to resemble right_ch_sfb_tools_ms.c
+     Just for conformance, readability.
+
+ Description: Added include file - "e_huffmanconst.h"
+
+ Description: The same "Factors" pointer indexing problem that existed in
+ right_ch_sfb_tools_ms also existed here in pns_left.c
+
+ Description:  Modified how groups and windows are handled, as the multigroup
+ case was not correct
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    const FrameInfo *pFrameInfo         = Pointer to structure that holds
+                                          information about each group.
+                                          (long block flag,
+                                           number of windows,
+                                           scalefactor bands per group, etc.)
+
+    const Int        group[]            = Array that contains indexes of the
+                                          the first window in the next group.
+
+    const Int        codebook_map[]     = Array that denotes which Huffman
+                                          codebook was used for the encoding
+                                          of each scalefactor band.
+
+    const Int        factors[]          = Array of scalefactors
+
+    Int              sfb_prediction_used[] = Flag that denotes the activation
+                                             of long term prediction on a sfb
+                                             basis.
+
+    Bool             ltp_data_present   = Flag that denotes whether LTP
+                                          is active for the entire frame.  If
+                                          this flag is FALSE,
+                                          sfb_prediction_used is garbage.
+
+    Int32            spectral_coef[]    = Array of pointers pointing to the
+                                          spectral coef's for the LEFT channel.
+
+    Int              q_format[]           = Q-format for the information
+                                            pointed to by spectral_coef.
+                                            Indexed by scalefactor band.
+
+    Int32           *pCurrentSeed         = Pointer to the current seed for the
+                                            random number generator.
+                                            (gen_rand_vector)
+
+ Local Stores/Buffers/Pointers Needed:
+
+ Global Stores/Buffers/Pointers Needed:
+
+ Outputs:
+
+ Pointers and Buffers Modified:
+    Int32  spectral_coef[]    =   Contains the new spectral information
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ The function steps through each scalefactor band in the group, and
+ checks for the use of Huffman codebook NOISE_HCB.
+
+ When a SFB utilizing NOISE_HCB is detected, the band in every window in the
+ group has its spectral information filled with scaled random data.
+
+ The scaled random data is generated by the function gen_rand_vector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This module shall replace bands that were encoded with the Huffman codebook
+ NOISE_HCB with random noise as returned from gen_rand_vector().  The result
+ shall be perceptually indistinguishable from the result obtained by the
+ ISO decoder.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.5.5   Figures
+        Subpart 4.6.2   ScaleFactors
+        Subpart 4.6.12  Perceptual Noise Substituion (PNS)
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pFirst_Window_Coefs = spectral_coef;
+
+    window_start = 0;
+
+    tot_sfb = 0;
+
+    DO
+
+        num_bands = pFrameInfo->sfb_per_win[window_start];
+        pBand     = pFrameInfo->win_sfb_top[window_start];
+
+        partition = *(pGroup);
+        pGroup = pGroup + 1;
+
+        band_start = 0;
+
+        coef_per_win = pFrameInfo->coef_per_win[window_start];
+
+        wins_in_group = (partition - window_start);
+
+        FOR (sfb = num_bands; sfb > 0; sfb--)
+
+            band_stop = *pBand;
+            pBand = pBand + 1;
+
+            IF (*(pCodebookMap++) == NOISE_HCB )
+
+                tempInt = sfb_prediction_used[tot_sfb] AND ltp_data_present;
+
+                IF (tempInt == FALSE)
+
+                    pWindow_Coef = pFirst_Window_Coefs + band_start;
+
+                    band_length = (band_stop - band_start);
+
+                    start_indx = tot_sfb;
+
+                    tempInt = *(pFactors);
+
+                    FOR (win_indx = wins_in_group; win_indx > 0; win_indx--)
+
+                        CALL gen_rand_vector( pWindow_CoefR,
+                                              band_length,
+                                              pCurrentSeed,
+                                              tempInt);
+
+                        MODIFYING pWindow_CoefR = scaled random noise
+                                  pCurrentSeed  = current state of the random
+                                                  noise generator.
+
+                        RETURNING q_format[start_indx] = q-format for this sfb.
+
+                        pWindow_Coef = pWindow_Coef + coef_per_win;
+
+                        start_indx = start_indx +
+                                     pFrameInfo->sfb_per_win[win_indx];
+
+                    ENDFOR
+
+                ENDIF
+
+            ENDIF
+
+            band_start = band_stop;
+
+            tot_sfb = tot_sfb + 1;
+
+            pFactors = pFactors + 1;
+
+        ENDFOR
+
+        coef_per_win = coef_per_win * wins_in_group;
+        wins_in_group = wins_in_group - 1;
+
+        tot_sfb = tot_sfb + num_bands * wins_in_group;
+        pFactors = pFactors + num_bands * wins_in_group;
+
+        pFirst_Window_Coefs = pFirst_Window_Coefs + coef_per_win;
+
+        window_start = partition;
+
+    WHILE (partition < pFrameInfo->num_win);
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "pns_left.h"
+#include "e_huffmanconst.h"
+#include "gen_rand_vector.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 pns_left(
+    const FrameInfo *pFrameInfo,
+    const Int        group[],
+    const Int        codebook_map[],
+    const Int        factors[],
+    const Int        sfb_prediction_used[],
+    const Bool       ltp_data_present,
+    Int32      spectral_coef[],
+    Int        q_format[],
+    Int32     *pCurrentSeed)
+{
+
+    Int     tot_sfb;
+    Int     start_indx;
+
+    Int     sfb;
+    Int     band_stop;
+
+    const Int16  *pBand;
+
+    const Int *pCodebookMap = &(codebook_map[0]);
+    const Int *pGroup   = &(group[0]);
+    const Int *pFactors = &(factors[0]);
+
+    Int     tempInt;
+    Int32  *pWindow_Coef;
+
+
+    Int32   *spec;
+
+    Int partition;
+    Int win_indx;
+
+    tot_sfb = 0;
+
+    spec = spectral_coef;
+
+    /* PNS goes by group */
+    win_indx = 0;
+    partition = 0;
+    do
+    {
+        Int num_bands = pFrameInfo->sfb_per_win[partition];
+        pBand = pFrameInfo->win_sfb_top[partition];
+
+        /*----------------------------------------------------------
+        Partition is equal to the first window in the next group
+
+        { Group 0    }{      Group 1      }{    Group 2 }{Group 3}
+        [win 0][win 1][win 2][win 3][win 4][win 5][win 6][win 7]
+
+        pGroup[0] = 2
+        pGroup[1] = 5
+        pGroup[2] = 7
+        pGroup[3] = 8
+        -----------------------------------------------------------*/
+
+        partition = *pGroup++;      /* partition = index of last sbk in group */
+
+        do
+        {
+            Int band_start = 0;
+            for (sfb = 0; sfb < num_bands; sfb++)
+            {
+                band_stop = pBand[sfb]; /* band is offset table, band_stop is last coef in band */
+
+                Int band_length =  band_stop - band_start;
+                if (pCodebookMap[sfb] == NOISE_HCB)
+                {
+
+                    tempInt = sfb_prediction_used[tot_sfb] & ltp_data_present;
+
+                    if (tempInt == FALSE)
+                    {
+                        /* generate random noise */
+                        pWindow_Coef = spec + band_start;
+
+                        tempInt = pFactors[sfb];
+
+                        start_indx = tot_sfb++;
+
+                        /* reconstruct noise substituted values */
+                        /* generate random noise */
+
+                        q_format[start_indx] = gen_rand_vector(pWindow_Coef,
+                                                               band_length,
+                                                               pCurrentSeed,
+                                                               tempInt);
+
+                    }   /* if (sfb_prediction_used[tot_sfb] == FALSE) */
+
+                }   /* if (*(pCodebookMap++) == NOISE_HCB) */
+                else
+                {
+                    tot_sfb ++;     /*  update absolute sfb counter  */
+                }
+
+                band_start = band_stop;
+
+            }   /* for (sfb) */
+
+            spec += pFrameInfo->coef_per_win[win_indx++];
+            pFactors += num_bands;
+
+        }
+        while (win_indx < partition);
+
+        pCodebookMap += pFrameInfo->sfb_per_win[win_indx-1];
+
+    }
+    while (partition < pFrameInfo->num_win);
+
+
+    return;
+
+} /* pns */
diff --git a/media/libstagefright/codecs/aacdec/pns_left.h b/media/libstagefright/codecs/aacdec/pns_left.h
new file mode 100644
index 0000000..c44b13c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pns_left.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pns_left.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed #defines of LEFT and RIGHT, and the extra include
+ file "e_huffmanconst.h"
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Contains the function definition for pns_left.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PNS_LEFT_H
+#define PNS_LEFT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pns_left(
+        const FrameInfo *pFrameInfo,
+        const Int        group[],
+        const Int        codebook_map[],
+        const Int        factors[],
+        const Int        sfb_prediction_used[],
+        const Bool       ltp_data_present,
+        Int32      spectral_coef[],
+        Int        q_format[],
+        Int32     *pCurrentSeed);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.cpp b/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.cpp
new file mode 100644
index 0000000..48432f8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.cpp
@@ -0,0 +1,311 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_all_pass_filter_coeff.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Decorrelation is achieved by means of all-pass filtering
+
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "pv_audio_type_defs.h"
+#include    "s_ps_dec.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_all_pass_fract_delay_filter.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
+----------------------------------------------------------------------------*/
+
+
+const Int16 aRevLinkDecaySerCoeff[NO_ALLPASS_CHANNELS][NO_SERIAL_ALLPASS_LINKS] =
+{
+
+
+    { Qfmt15(0.74915491616071f),  Qfmt15(0.64942584030892f),  Qfmt15(0.56297290849050f) },
+    { Qfmt15(0.71658296328416f),  Qfmt15(0.62118993420853f),  Qfmt15(0.53849582551265f) },
+    { Qfmt15(0.68401101040761f),  Qfmt15(0.59295402810815f),  Qfmt15(0.51401874253480f) },
+    { Qfmt15(0.65143905753106f),  Qfmt15(0.56471812200776f),  Qfmt15(0.97908331911390f) },      /*  3  */
+    { Qfmt15(0.61886710465450f),  Qfmt15(0.53648221590737f),  Qfmt15(0.93012915315822f) },
+    { Qfmt15(0.58629515177795f),  Qfmt15(0.50824630980698f),  Qfmt15(0.88117498720252f) },
+    { Qfmt15(0.55372319890140f),  Qfmt15(0.48001040370660f),  Qfmt15(0.83222082124682f) },
+    { Qfmt15(0.52115124602484f),  Qfmt15(0.45177449760621f),  Qfmt15(0.78326665529112f) },
+    { Qfmt15(0.48857929314829f),  Qfmt15(0.42353859150582f),  Qfmt15(0.73431248933542f) },
+    { Qfmt15(0.45600734027174f),  Qfmt15(0.39530268540543f),  Qfmt15(0.68535832337974f) },
+    { Qfmt15(0.42343538739519f),  Qfmt15(0.36706677930504f),  Qfmt15(0.63640415742404f) },
+    { Qfmt15(0.39086343451863f),  Qfmt15(0.33883087320466f),  Qfmt15(0.58744999146834f) },
+    { Qfmt15(0.35829148164208f),  Qfmt15(0.31059496710427f),  Qfmt15(0.53849582551265f) },
+    { Qfmt15(0.32571952876553f),  Qfmt15(0.28235906100388f),  Qfmt15(0.48954165955695f) },
+    { Qfmt15(0.29314757588898f),  Qfmt15(0.25412315490349f),  Qfmt15(0.44058749360126f) },
+    { Qfmt15(0.26057562301242f),  Qfmt15(0.22588724880310f),  Qfmt15(0.39163332764556f) },
+    { Qfmt15(0.22800367013587f),  Qfmt15(0.19765134270272f),  Qfmt15(0.34267916168986f) },
+    { Qfmt15(0.19543171725932f),  Qfmt15(0.16941543660233f),  Qfmt15(0.29372499573418f) },
+    { Qfmt15(0.16285976438276f),  Qfmt15(0.14117953050194f),  Qfmt15(0.24477082977848f) },
+    { Qfmt15(0.13028781150621f),  Qfmt15(0.11294362440155f),  Qfmt15(0.19581666382278f) },
+    { Qfmt15(0.09771585862966f),  Qfmt15(0.08470771830116f),  Qfmt15(0.14686249786708f) },
+    { Qfmt15(0.06514390575311f),  Qfmt15(0.05647181220078f),  Qfmt15(0.09790833191140f) },
+    { Qfmt15(0.03257195287655f),  Qfmt15(0.02823590610039f),  Qfmt15(0.04895416595570f) }
+
+};
+
+
+
+
+
+const Char groupBorders[NO_IID_GROUPS + 1] =
+{
+    4,  5,  0,  1,  2,  3,  7,  6,   8,  9,  3,  4,
+    5,  6,  7,  8,  9,  11, 14, 18, 23, 35, 64
+};
+
+const Char bins2groupMap[NO_IID_GROUPS] =
+{
+    1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19
+};
+
+
+
+
+/*
+ *  q_phi = 0.39
+ *
+ *  cos(pi*([3:22]+0.5)*q_phi)
+ */
+
+
+/*
+ *  sin(-pi*([3:22]+0.5)*q_phi)
+ */
+
+
+const Int32 aFractDelayPhaseFactor[NO_QMF_ALLPASS_CHANNELS] =
+{
+    0xCB5474A9,  0x5BEC5914, 0x72F3C7B0, 0xF1F480C6, 0x8389E21E,
+    0xB9BA6AFC,  0x4CDB665C, 0x7A57DA5D, 0x06088024, 0x89BECF04,
+    0xA9DB5EAC,  0x3BE5711F, 0x7EB9EDF7, 0x19F582A9, 0x92DDBD1F,
+    0x9C1B5008,  0x29767919, 0x7FFC0203, 0x2D3F8843, 0x9EABACDF
+};
+
+/*
+ *  q(m) = { 0.43, 0.75, 0.347 }
+ *
+ *  cos(pi*([3:22]+0.5)*q(m))        cos(pi*([3:22]+0.5)'*q)
+ *
+ *  sin(-pi*([3:22]+0.5)*q(m))
+ *
+ */
+
+
+const Int32 aaFractDelayPhaseFactorSerQmf[NO_QMF_ALLPASS_CHANNELS][3] =
+{
+    { 0x02037FFC,  0xCF0489BE, 0x9BFB4FE0 },
+    { 0x7D5719F5,  0xCF047642, 0x18947D9E },
+    { 0x34AD8B57,  0x7642CF04, 0x7ABF244A },
+    { 0x99A4B325,  0x89BECF04, 0x58EFA3F1 },
+    { 0x9EAB5321,  0x30FC7642, 0xD77E8694 },
+    { 0x3BE5711F,  0x30FC89BE, 0x819CEBC7 },
+    { 0x7B77DE39,  0x89BE30FC, 0xB3A166B8 },
+    { 0xF9F88024,  0x764230FC, 0x37C57336 },
+    { 0x81E8E9FE,  0xCF0489BE, 0x7FF103D2 },
+    { 0xCF047642,  0xCF047642, 0x3E8B9052 },
+    { 0x68B9499A,  0x7642CF04, 0xB9E594E8 },
+    { 0x5EACA9DB,  0x89BECF04, 0x80A00CA5 },
+    { 0xC09590D1,  0x30FC7642, 0xD05276CA },
+    { 0x85A925A3,  0x30FC89BE, 0x53486134 },
+    { 0x0A0B7F9B,  0x89BE30FC, 0x7CB2E319 },
+    { 0x7EB91209,  0x764230FC, 0x20078412 },
+    { 0x2D3F8843,  0xCF0489BE, 0xA0ECAA4D },
+    { 0x9504B9BA,  0xCF047642, 0x880D2CAE },
+    { 0xA4145914,  0x7642CF04, 0xF0287F04 },
+    { 0x42E16D23,  0x89BECF04, 0x694C48C7 }
+};
+
+/*
+ *  Fractional delay vector
+ *
+ *  phi_fract(k) = exp(-j*pi*q_phi*f_center(k))       0<= k <= SUBQMF_GROUPS
+ *
+ *  q_phi = 0.39
+ *  f_center(k) frequency vector
+ *
+ *
+ *  f_center(k) = {0.5/4,  1.5/4,  2.5/4,  3.5/4,
+ *                -1.5/4, -0.5/4,
+ *                 3.5/2,  2.5/2,  4.5/2,  5.5/2};
+ */
+
+
+
+const Int32 aFractDelayPhaseFactorSubQmf[SUBQMF_GROUPS] =
+{
+    0x7E80EC79,  0x72BAC73D, 0x5C45A749, 0x3D398F97, 0x72BA38C3,
+    0x7E801387,  0xBA919478, 0x05068019, 0x895DCFF2, 0x834E1CE7,
+};
+
+
+
+
+
+/*
+ *  Fractional delay length matrix
+ *
+ *  Q_fract(k,m) = exp(-j*pi*q(m)*f_center(k))
+ *
+ *  q(m) = { 0.43, 0.75, 0.347 }
+ *  f_center(k) frequency vector
+ *
+ *
+ *  f_center(k) = { 0.5/4,  1.5/4,  2.5/4,  3.5/4,
+ *                 -1.5/4, -0.5/4,
+ *                  3.5/2,  2.5/2,  4.5/2,  5.5/2};
+ */
+
+const Int32 aaFractDelayPhaseFactorSerSubQmf[SUBQMF_GROUPS][3] =
+{
+
+    { 0x7E2EEA7D,  0x7A7DDAD8, 0x7ED0EE9D },
+    { 0x6FEDC1E5,  0x51349D0E, 0x7574CD1E },
+    { 0x5506A052,  0x0C8C809E, 0x636CAF62 },
+    { 0x3085898D,  0xC3A98F1D, 0x4A0D9799 },
+    { 0x6FED3E1B,  0x513462F2, 0x757432E2 },
+    { 0x7E2E1583,  0x7A7D2528, 0x7ED01163 },
+    { 0xA4C8A634,  0xB8E36A6E, 0xD5AF8732 },
+    { 0xF0F580E3,  0x8276E707, 0x1A7382C3 },
+    { 0x80ABF2F4,  0x471D6A6E, 0x9D2FAEA4 },
+    { 0x9478456F,  0x7D8AE707, 0x8152EDAB }
+};
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.h b/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.h
new file mode 100644
index 0000000..0358acb
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_all_pass_filter_coeff.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_all_pass_filter_coeff.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for all pass filter coefficients
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_ALL_PASS_FILTER_COEFF_H
+#define PS_ALL_PASS_FILTER_COEFF_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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 Char groupBorders[NO_IID_GROUPS + 1];
+extern const Int16 aRevLinkDecaySerCoeff[NO_ALLPASS_CHANNELS][NO_SERIAL_ALLPASS_LINKS];
+extern const Int32  aRevLinkDelaySer[];
+extern const Int16 aFractDelayPhaseFactorReQmf[NO_QMF_ALLPASS_CHANNELS];
+extern const Int16 aFractDelayPhaseFactorImQmf[NO_QMF_ALLPASS_CHANNELS];
+/* the old center frequencies (found in "else") were too small (factor 1/2) */
+extern const Int16 aFractDelayPhaseFactorReSubQmf[SUBQMF_GROUPS];
+extern const Int16 aFractDelayPhaseFactorImSubQmf[SUBQMF_GROUPS];
+extern const Int32 aFractDelayPhaseFactorSubQmf[SUBQMF_GROUPS];
+extern const Int32 aFractDelayPhaseFactor[NO_QMF_ALLPASS_CHANNELS];
+extern const Int32 aaFractDelayPhaseFactorSerQmf[NO_QMF_ALLPASS_CHANNELS][3];
+extern const Int32 aaFractDelayPhaseFactorSerSubQmf[SUBQMF_GROUPS][3];
+extern const Char bins2groupMap[NO_IID_GROUPS];
+extern const Int32 aaFractDelayPhaseFactorSerReQmf[NO_QMF_ALLPASS_CHANNELS][3];
+extern const Int32 aaFractDelayPhaseFactorSerImQmf[NO_QMF_ALLPASS_CHANNELS][3];
+extern const Int32 aaFractDelayPhaseFactorSerReSubQmf[SUBQMF_GROUPS][3];
+extern const Int32 aaFractDelayPhaseFactorSerImSubQmf[SUBQMF_GROUPS][3];
+
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_ALL_PASS_FILTER_COEFF_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.cpp b/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.cpp
new file mode 100644
index 0000000..81761a6
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.cpp
@@ -0,0 +1,391 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_all_pass_fract_delay_filter.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Decorrelation
+  Decorrelation is achieved by means of all-pass filtering and delaying
+  Sub-band samples s_k(n) are converted into de-correlated sub-bands samples
+  d_k(n). k index for frequency, n time index
+
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+  Delay is introduced to compensate QMF bands not passed through Hybrid
+  Analysis
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "pv_audio_type_defs.h"
+#include    "ps_decorrelate.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_pwr_transient_detection.h"
+#include    "ps_all_pass_fract_delay_filter.h"
+#include    "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*
+ *  For lower subbands
+ *  Apply all-pass filtering
+ *
+ */
+
+
+void ps_all_pass_fract_delay_filter_type_I(UInt32 *delayBufIndex,
+        Int32 sb_delay,
+        const Int32 *ppFractDelayPhaseFactorSer,
+        Int32 ***pppRealDelayRBufferSer,
+        Int32 ***pppImagDelayRBufferSer,
+        Int32 *rIn,
+        Int32 *iIn)
+{
+
+    Int32 cmplx;
+    Int16 rTmp0;
+    Int32 rTmp;
+    Int32 iTmp;
+    Int32 *pt_rTmp;
+    Int32 *pt_iTmp;
+
+
+
+    /*
+     *  All pass filters
+     *                         2
+     *                        ___  Q_fract(k,m)*z^(-d(m))  -  a(m)*g_decay_slope(k)
+     *   z^(-2)*phi_fract(k)* | |  ------------------------------------------------
+     *                        m=0  1  - a(m)*g_decay_slope(k)*Q_fract(k,m)*z^(-d(m))
+     *
+     *
+     *    Fractional delay matrix:
+     *
+     *    Q_fract(k,m) = exp(-j*pi*q(m)*f_center(k))       0<= k <= SUBQMF_GROUPS
+     *
+     *    Vectors: a(m), q(m), d(m) are constants
+     *
+     *    m                              m     0       1       2
+     *                                 -------------------------------
+     *    delay length                 d(m) == 3       4       5      (Fs > 32 KHz)
+     *    fractional delay length      q(m) == 0.43    0.75    0.347
+     *    filter coefficient           a(m) == 0.65144 0.56472 0.48954
+     *
+     *             g_decay_slope(k) is given
+     */
+
+
+    Int32 tmp_r;
+    Int32 tmp_i;
+
+    pt_rTmp = &pppRealDelayRBufferSer[0][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[0][*(delayBufIndex++)][sb_delay];
+
+    cmplx  = *(ppFractDelayPhaseFactorSer++);        /* Q_fract(k,m)  */
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = Qfmt15(0.65143905753106f);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+
+
+    iTmp     =  fxp_mac32_by_16(-*iIn << 1, rTmp0, iTmp);  /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp << 1, rTmp0, *iIn);   /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn << 1, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp << 1, rTmp0, *rIn);
+
+    *rIn = rTmp;
+
+    pt_rTmp = &pppRealDelayRBufferSer[1][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[1][*(delayBufIndex++)][sb_delay];
+
+
+
+    cmplx  = *(ppFractDelayPhaseFactorSer++);        /* Q_fract(k,m)  */
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = Qfmt15(0.56471812200776f);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+
+
+    iTmp     =  fxp_mac32_by_16(-*iIn << 1, rTmp0, iTmp);  /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp << 1, rTmp0, *iIn);   /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn << 1, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp << 1, rTmp0, *rIn);
+    *rIn = rTmp;
+
+    pt_rTmp = &pppRealDelayRBufferSer[2][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[2][*(delayBufIndex)][sb_delay];
+
+
+    cmplx  = *(ppFractDelayPhaseFactorSer);        /* Q_fract(k,m)  */
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = Qfmt15(0.97908331911390f);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+
+
+    iTmp     =  fxp_mac32_by_16(-*iIn, rTmp0, iTmp);    /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp, rTmp0, *iIn);     /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp << 2;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp, rTmp0, *rIn);
+    *rIn = rTmp << 2;
+}
+
+
+void ps_all_pass_fract_delay_filter_type_II(UInt32 *delayBufIndex,
+        Int32 sb_delay,
+        const Int32 *ppFractDelayPhaseFactorSer,
+        Int32 ***pppRealDelayRBufferSer,
+        Int32 ***pppImagDelayRBufferSer,
+        Int32 *rIn,
+        Int32 *iIn,
+        Int32 decayScaleFactor)
+{
+
+    Int32 cmplx;
+    Int16 rTmp0;
+    Int32 rTmp;
+    Int32 iTmp;
+    Int32 *pt_rTmp;
+    Int32 *pt_iTmp;
+    const Int16 *pt_delay;
+
+
+
+    /*
+     *  All pass filters
+     *                         2
+     *                        ___  Q_fract(k,m)*z^(-d(m))  -  a(m)*g_decay_slope(k)
+     *   z^(-2)*phi_fract(k)* | |  ------------------------------------------------
+     *                        m=0  1  - a(m)*g_decay_slope(k)*Q_fract(k,m)*z^(-d(m))
+     *
+     *
+     *    Fractional delay matrix:
+     *
+     *    Q_fract(k,m) = exp(-j*pi*q(m)*f_center(k))       0<= k <= SUBQMF_GROUPS
+     *
+     *    Vectors: a(m), q(m), d(m) are constants
+     *
+     *    m                              m     0       1       2
+     *                                 -------------------------------
+     *    delay length                 d(m) == 3       4       5      (Fs > 32 KHz)
+     *    fractional delay length      q(m) == 0.43    0.75    0.347
+     *    filter coefficient           a(m) == 0.65144 0.56472 0.48954
+     *
+     *             g_decay_slope(k) is given
+     */
+
+
+    Int32 tmp_r;
+    Int32 tmp_i;
+
+    pt_rTmp = &pppRealDelayRBufferSer[0][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[0][*(delayBufIndex++)][sb_delay];
+
+    cmplx  = *(ppFractDelayPhaseFactorSer++);        /* Q_fract(k,m)  */
+    pt_delay = aRevLinkDecaySerCoeff[decayScaleFactor];
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = *(pt_delay++);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+
+
+    iTmp     =  fxp_mac32_by_16(-*iIn << 1, rTmp0, iTmp);  /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp << 1, rTmp0, *iIn);   /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn << 1, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp << 1, rTmp0, *rIn);
+    *rIn = rTmp;
+
+    pt_rTmp = &pppRealDelayRBufferSer[1][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[1][*(delayBufIndex++)][sb_delay];
+
+
+    cmplx  = *(ppFractDelayPhaseFactorSer++);        /* Q_fract(k,m)  */
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = *(pt_delay++);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+    iTmp     =  fxp_mac32_by_16(-*iIn << 1, rTmp0, iTmp);  /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp << 1, rTmp0, *iIn);   /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn << 1, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp << 1, rTmp0, *rIn);
+    *rIn = rTmp;
+
+    pt_rTmp = &pppRealDelayRBufferSer[2][*(delayBufIndex)][sb_delay];
+    pt_iTmp = &pppImagDelayRBufferSer[2][*(delayBufIndex)][sb_delay];
+
+
+    cmplx  = *(ppFractDelayPhaseFactorSer);        /* Q_fract(k,m)  */
+    tmp_r = *pt_rTmp << 1;
+    tmp_i = *pt_iTmp << 1;
+
+    rTmp = cmplx_mul32_by_16(tmp_r, -tmp_i,  cmplx);
+    rTmp0  = *(pt_delay);
+    iTmp = cmplx_mul32_by_16(tmp_i,  tmp_r,  cmplx);
+
+
+    iTmp     =  fxp_mac32_by_16(-*iIn, rTmp0, iTmp);    /* Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n) */
+    *pt_iTmp =  fxp_mac32_by_16(iTmp, rTmp0, *iIn);     /* y(n) = x(n) + a(m)*g_decay_slope(k)*( Q_fract(k,m)*y(n-1) - a(m)*g_decay_slope(k)*x(n)) */
+    *iIn = iTmp << 2;
+
+    rTmp     =  fxp_mac32_by_16(-*rIn, rTmp0, rTmp);
+    *pt_rTmp =  fxp_mac32_by_16(rTmp, rTmp0, *rIn);
+    *rIn = rTmp << 2;
+
+}
+
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.h b/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.h
new file mode 100644
index 0000000..b4e9876
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_all_pass_fract_delay_filter.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_all_pass_fract_delay_filter.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_all_pass_fract_delay_filter()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_ALL_PASS_FRACT_DELAY_FILTER_H
+#define PS_ALL_PASS_FRACT_DELAY_FILTER_H
+
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define R_SHIFT     29
+#define Q29_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void ps_all_pass_fract_delay_filter_type_I(UInt32 *delayBufIndex,
+    Int32 sb_delay,
+    const Int32 *ppFractDelayPhaseFactorSer,
+    Int32 ***pppRealDelayRBufferSer,
+    Int32 ***pppImagDelayRBufferSer,
+    Int32 *rIn,
+    Int32 *iIn);
+
+
+    void ps_all_pass_fract_delay_filter_type_II(UInt32 *delayBufIndex,
+            Int32 sb_delay,
+            const Int32 *ppFractDelayPhaseFactorSer,
+            Int32 ***pppRealDelayRBufferSer,
+            Int32 ***pppImagDelayRBufferSer,
+            Int32 *rIn,
+            Int32 *iIn,
+            Int32 decayScaleFactor);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_ALL_PASS_FRACT_DELAY_FILTER_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_allocate_decoder.cpp b/media/libstagefright/codecs/aacdec/ps_allocate_decoder.cpp
new file mode 100644
index 0000000..ab15651
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_allocate_decoder.cpp
@@ -0,0 +1,341 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_allocate_decoder.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Reuses AAC+ HQ right channel, which is not used when PS is enabled
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef HQ_SBR
+
+#ifdef PARAMETRICSTEREO
+
+#include    "s_sbr_channel.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_hybrid_filter_bank_allocation.h"
+#include    "s_ps_dec.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_allocate_decoder.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     30
+#define Q30_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const Int32  aRevLinkDelaySer[] = {3,  4,  5};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int32 ps_allocate_decoder(SBRDECODER_DATA *self,
+                          UInt32  noSubSamples)
+{
+    Int32 i, j;
+    Int32 status;
+
+    Int32 *ptr1;
+    Int32 *ptr2;
+    Int32 *ptr3;
+    Int32 *ptr4;
+    Int32 *ptr5;
+    Int32 *ptr6;
+    Int32 *ptr7;
+
+    const Int32 pHybridResolution[] = { HYBRID_8_CPLX,
+                                        HYBRID_2_REAL,
+                                        HYBRID_2_REAL
+                                      };
+
+    STRUCT_PS_DEC *h_ps_dec = self->hParametricStereoDec;
+
+    /* initialisation */
+    h_ps_dec->noSubSamples = noSubSamples;
+
+    h_ps_dec->invNoSubSamples = Q30_fmt(1.0f) / noSubSamples;
+
+    /*
+     *  Reuse AAC+ HQ right channel, which is not used when PS is enabled
+     */
+    ptr1 = (Int32 *)(self->SbrChannel[1].frameData.codecQmfBufferReal[0]);   /*  reuse un-used right channel QMF_FILTER Synthesis buffer */
+
+    ptr2 = (&ptr1[658]);  /*  reuse un-used right channel QMF_FILTER Synthesis buffer */
+    /* 1162 - 658 = 504
+     *            = NO_QMF_ALLPASS_CHANNELS*2 (Re&Im)*( 3 + 4 + 5) + ( 3 + 4 + 5)*2 (Re&Im)
+     */
+
+    ptr3 = (&ptr1[1162]);  /*  reuse un-used right channel QMF_FILTER Synthesis buffer */
+    /* 1426 - 1162 = 264
+     *            = SUBQMF_GROUPS*2 (Re&Im)*( 3 + 4 + 5) + ( 3 + 4 + 5)*2 (Re&Im)
+     */
+
+    ptr4 = (&ptr1[1426]);  /*  high freq generation buffers */
+
+    ptr5 = (&ptr1[1490]);  /*  high freq generation buffers */
+
+    ptr6 = (&ptr1[1618]);  /*  high freq generation buffers */
+
+    ptr7 = (&ptr1[1810]);  /*  high freq generation buffers */
+
+    /*  whole allocation requires 1871 words, sbrQmfBufferImag has 1920 words */
+
+
+    h_ps_dec->aPeakDecayFast =  ptr1;
+    ptr1 += NO_BINS;
+
+    h_ps_dec->aPrevNrg =  ptr1;
+    ptr1 += NO_BINS;
+
+    h_ps_dec->aPrevPeakDiff = ptr1;
+    ptr1 += NO_BINS;
+
+
+
+    status = ps_hybrid_filter_bank_allocation(&h_ps_dec->hHybrid,
+             NO_QMF_CHANNELS_IN_HYBRID,
+             pHybridResolution,
+             &ptr1);
+    h_ps_dec->mHybridRealLeft = ptr1;
+    ptr1 += SUBQMF_GROUPS;
+
+    h_ps_dec->mHybridImagLeft = ptr1;
+    ptr1 += SUBQMF_GROUPS;
+
+    h_ps_dec->mHybridRealRight = ptr1;
+    ptr1 += SUBQMF_GROUPS;
+
+    h_ps_dec->mHybridImagRight = ptr1;
+    ptr1 += SUBQMF_GROUPS;
+
+
+    h_ps_dec->delayBufIndex   = 0;
+
+
+
+    for (i = 0 ; i < NO_DELAY_CHANNELS ; i++)   /* 41  */
+    {
+        if (i < SHORT_DELAY_START)              /* 12  */
+        {
+            h_ps_dec->aNoSampleDelay[i] = LONG_DELAY;
+        }
+        else
+        {
+            h_ps_dec->aNoSampleDelay[i] = SHORT_DELAY;
+        }
+    }
+
+
+    h_ps_dec->aaRealDelayBufferQmf = (Int32 **)ptr6;
+    ptr6 += NO_QMF_ICC_CHANNELS * sizeof(Int32 *) / sizeof(Int32);
+
+    h_ps_dec->aaImagDelayBufferQmf = (Int32 **)ptr7;
+    ptr7 += NO_QMF_ICC_CHANNELS * sizeof(Int32 *) / sizeof(Int32);
+
+    h_ps_dec->aaRealDelayBufferSubQmf = (Int32 **)ptr1;
+    ptr1 += SUBQMF_GROUPS * sizeof(Int32 *) / sizeof(Int32);
+
+    h_ps_dec->aaImagDelayBufferSubQmf = (Int32 **)ptr1;
+    ptr1 += SUBQMF_GROUPS * sizeof(Int32 *) / sizeof(Int32);
+
+    for (i = 0; i < NO_QMF_ICC_CHANNELS; i++)   /* 61 */
+    {
+        int delay;
+
+        if (i < NO_QMF_ALLPASS_CHANNELS)    /* 20 */
+        {
+            delay = 2;
+            h_ps_dec->aaRealDelayBufferQmf[i] = (Int32 *)ptr4;
+            ptr4 += delay;
+
+            h_ps_dec->aaImagDelayBufferQmf[i] = (Int32 *)ptr5;
+            ptr5 += delay;
+        }
+        else
+        {
+
+            if (i >= (NO_QMF_ALLPASS_CHANNELS + SHORT_DELAY_START))
+            {
+                delay = SHORT_DELAY;
+            }
+            else
+            {
+                delay = LONG_DELAY;
+            }
+
+            h_ps_dec->aaRealDelayBufferQmf[i] = (Int32 *)ptr1;
+            ptr1 += delay;
+
+            h_ps_dec->aaImagDelayBufferQmf[i] = (Int32 *)ptr1;
+            ptr1 += delay;
+        }
+    }
+
+    for (i = 0; i < SUBQMF_GROUPS; i++)
+    {
+        h_ps_dec->aaRealDelayBufferSubQmf[i] = (Int32 *)ptr1;
+        ptr1 += DELAY_ALLPASS;
+
+        h_ps_dec->aaImagDelayBufferSubQmf[i] = (Int32 *)ptr1;
+        ptr1 += DELAY_ALLPASS;
+
+    }
+
+    for (i = 0 ; i < NO_SERIAL_ALLPASS_LINKS ; i++) /*  NO_SERIAL_ALLPASS_LINKS == 3 */
+    {
+
+        h_ps_dec->aDelayRBufIndexSer[i] = 0;
+
+        h_ps_dec->aaaRealDelayRBufferSerQmf[i] = (Int32 **)ptr2;
+        ptr2 += aRevLinkDelaySer[i];
+
+        h_ps_dec->aaaImagDelayRBufferSerQmf[i] = (Int32 **)ptr2;
+        ptr2 += aRevLinkDelaySer[i];
+
+        h_ps_dec->aaaRealDelayRBufferSerSubQmf[i] = (Int32 **)ptr3;
+        ptr3 += aRevLinkDelaySer[i];
+
+        h_ps_dec->aaaImagDelayRBufferSerSubQmf[i] = (Int32 **)ptr3;
+        ptr3 += aRevLinkDelaySer[i];
+
+        for (j = 0; j < aRevLinkDelaySer[i]; j++)
+        {
+            h_ps_dec->aaaRealDelayRBufferSerQmf[i][j] = ptr2;
+            ptr2 += NO_QMF_ALLPASS_CHANNELS;    /* NO_QMF_ALLPASS_CHANNELS == 20 */
+
+            h_ps_dec->aaaImagDelayRBufferSerQmf[i][j] = ptr2;
+            ptr2 += NO_QMF_ALLPASS_CHANNELS;
+
+            h_ps_dec->aaaRealDelayRBufferSerSubQmf[i][j] = ptr3;
+            ptr3 += SUBQMF_GROUPS;
+
+            h_ps_dec->aaaImagDelayRBufferSerSubQmf[i][j] = ptr3;
+            ptr3 += SUBQMF_GROUPS;
+
+        }
+    }
+
+
+    for (i = 0; i < NO_IID_GROUPS; i++)         /*  NO_IID_GROUPS == 22   */
+    {
+        h_ps_dec->h11Prev[i] = Q30_fmt(1.0f);
+        h_ps_dec->h12Prev[i] = Q30_fmt(1.0f);
+    }
+
+
+
+    return status;
+} /*END CreatePsDec*/
+#endif
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_allocate_decoder.h b/media/libstagefright/codecs/aacdec/ps_allocate_decoder.h
new file mode 100644
index 0000000..d5f152f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_allocate_decoder.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_allocate_decoder.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_allocate_decoder()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_ALLOCATE_DECODER_H
+#define PS_ALLOCATE_DECODER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int32 ps_allocate_decoder(SBRDECODER_DATA *self,
+    UInt32  noSubSamples);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_ALLOCATE_DECODER_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_applied.cpp b/media/libstagefright/codecs/aacdec/ps_applied.cpp
new file mode 100644
index 0000000..77fd8a7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_applied.cpp
@@ -0,0 +1,216 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_applied.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Applies Parametric Stereo Tool to a QMF-analized mono signal
+        providing a stereo image as output
+
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+#include    "aac_mem_funcs.h"
+#include    "ps_stereo_processing.h"
+#include    "ps_decorrelate.h"
+#include    "ps_hybrid_synthesis.h"
+#include    "ps_hybrid_analysis.h"
+#include    "ps_applied.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 ps_applied(STRUCT_PS_DEC *h_ps_dec,
+                Int32 rIntBufferLeft[][64],
+                Int32 iIntBufferLeft[][64],
+                Int32 *rIntBufferRight,
+                Int32 *iIntBufferRight,
+                Int32 scratch_mem[],
+                Int32 band)
+
+{
+
+    /*
+     *  Get higher frequency resolution in the lower QMF subbands
+     *  creating sub-subbands
+     */
+    ps_hybrid_analysis(rIntBufferLeft,
+                       iIntBufferLeft,
+                       h_ps_dec->mHybridRealLeft,
+                       h_ps_dec->mHybridImagLeft,
+                       h_ps_dec->hHybrid,
+                       scratch_mem,
+                       band);
+
+    /*
+     *  By means of delaying and all-pass filtering, sub-subbands of
+     *  left ch. are decorrelate to creates right ch. sub-subbands
+     */
+
+    ps_decorrelate(h_ps_dec,
+                   *rIntBufferLeft,
+                   *iIntBufferLeft,
+                   rIntBufferRight,
+                   iIntBufferRight,
+                   scratch_mem);
+
+    /*
+     *  sub-subbands of left and right ch. are processed according to
+     *  stereo clues.
+     */
+
+    ps_stereo_processing(h_ps_dec,
+                         *rIntBufferLeft,
+                         *iIntBufferLeft,
+                         rIntBufferRight,
+                         iIntBufferRight);
+
+    /*
+     *  Reconstruct stereo signals
+     */
+
+    ps_hybrid_synthesis((const Int32*)h_ps_dec->mHybridRealLeft,
+                        (const Int32*)h_ps_dec->mHybridImagLeft,
+                        *rIntBufferLeft,
+                        *iIntBufferLeft,
+                        h_ps_dec->hHybrid);
+
+    ps_hybrid_synthesis((const Int32*)h_ps_dec->mHybridRealRight,
+                        (const Int32*)h_ps_dec->mHybridImagRight,
+                        rIntBufferRight,
+                        iIntBufferRight,
+                        h_ps_dec->hHybrid);
+
+}/* END ps_applied */
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_applied.h b/media/libstagefright/codecs/aacdec/ps_applied.h
new file mode 100644
index 0000000..231d9c3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_applied.h
@@ -0,0 +1,101 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_applied.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions ps_applied()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_APPLIED_H
+#define PS_APPLIED_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_applied(STRUCT_PS_DEC *h_ps_dec,
+    Int32 rIntBufferLeft[][64],
+    Int32 iIntBufferLeft[][64],
+    Int32 *rIntBufferRight,
+    Int32 *iIntBufferRight,
+    Int32 scratch_mem[],
+    Int32 band);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_APPLIED_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_bstr_decoding.cpp b/media/libstagefright/codecs/aacdec/ps_bstr_decoding.cpp
new file mode 100644
index 0000000..c7ed60b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_bstr_decoding.cpp
@@ -0,0 +1,304 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_bstr_decoding.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Decodes parametric stereo
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include "pv_audio_type_defs.h"
+#include "aac_mem_funcs.h"
+#include "ps_bstr_decoding.h"
+#include "ps_decode_bs_utils.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
+----------------------------------------------------------------------------*/
+
+const Int32 aNoIidBins[3] = {NO_LOW_RES_IID_BINS, NO_IID_BINS, NO_HI_RES_BINS};
+const Int32 aNoIccBins[3] = {NO_LOW_RES_ICC_BINS, NO_ICC_BINS, NO_HI_RES_BINS};
+const Int32 aFixNoEnvDecode[4] = {0, 1, 2, 4};
+
+/*----------------------------------------------------------------------------
+; 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 ps_bstr_decoding(STRUCT_PS_DEC *ps_dec)
+{
+    UInt32 env;
+    Int32 noIidSteps;
+
+    if (!ps_dec->bPsDataAvail)
+    {
+        ps_dec->noEnv = 0;
+    }
+
+    noIidSteps = ps_dec->bFineIidQ ? NO_IID_STEPS_FINE : NO_IID_STEPS;
+
+    for (env = 0; env < ps_dec->noEnv; env++)
+    {
+        Int32 *aPrevIidIndex;
+        Int32 *aPrevIccIndex;
+        if (env == 0)
+        {
+            aPrevIidIndex = ps_dec->aIidPrevFrameIndex;
+            aPrevIccIndex = ps_dec->aIccPrevFrameIndex;
+        }
+        else
+        {
+            aPrevIidIndex = ps_dec->aaIidIndex[env-1];
+            aPrevIccIndex = ps_dec->aaIccIndex[env-1];
+        }
+
+        /*
+         * Differential Decoding of IID parameters over time/frequency
+         */
+        differential_Decoding(ps_dec->bEnableIid,
+                              ps_dec->aaIidIndex[env],
+                              aPrevIidIndex,
+                              ps_dec->abIidDtFlag[env],
+                              aNoIidBins[ps_dec->freqResIid],
+                              (ps_dec->freqResIid) ? 1 : 2,
+                              -noIidSteps,
+                              noIidSteps);
+
+        /*
+         * Differential Decoding of ICC parameters over time/frequency
+         */
+        differential_Decoding(ps_dec->bEnableIcc,
+                              ps_dec->aaIccIndex[env],
+                              aPrevIccIndex,
+                              ps_dec->abIccDtFlag[env],
+                              aNoIccBins[ps_dec->freqResIcc],
+                              (ps_dec->freqResIcc) ? 1 : 2,
+                              0,
+                              NO_ICC_STEPS - 1);
+
+
+    }   /* for (env=0; env<ps_dec->noEnv; env++) */
+
+    if (ps_dec->noEnv == 0)
+    {
+        ps_dec->noEnv = 1;
+
+        if (ps_dec->bEnableIid)
+        {   /*  NO_HI_RES_BINS == 34 */
+            pv_memmove(ps_dec->aaIidIndex[ps_dec->noEnv-1],
+                       ps_dec->aIidPrevFrameIndex,
+                       NO_HI_RES_BINS*sizeof(*ps_dec->aIidPrevFrameIndex));
+
+        }
+        else
+        {
+            pv_memset((void *)ps_dec->aaIidIndex[ps_dec->noEnv-1],
+                      0,
+                      NO_HI_RES_BINS*sizeof(**ps_dec->aaIidIndex));
+        }
+        if (ps_dec->bEnableIcc)
+        {
+            pv_memmove(ps_dec->aaIccIndex[ps_dec->noEnv-1],
+                       ps_dec->aIccPrevFrameIndex,
+                       NO_HI_RES_BINS*sizeof(*ps_dec->aIccPrevFrameIndex));
+        }
+        else
+        {
+            pv_memset((void *)ps_dec->aaIccIndex[ps_dec->noEnv-1],
+                      0,
+                      NO_HI_RES_BINS*sizeof(**ps_dec->aaIccIndex));
+        }
+    }
+
+    pv_memmove(ps_dec->aIidPrevFrameIndex,
+               ps_dec->aaIidIndex[ps_dec->noEnv-1],
+               NO_HI_RES_BINS*sizeof(*ps_dec->aIidPrevFrameIndex));
+
+    pv_memmove(ps_dec->aIccPrevFrameIndex,
+               ps_dec->aaIccIndex[ps_dec->noEnv-1],
+               NO_HI_RES_BINS*sizeof(*ps_dec->aIccPrevFrameIndex));
+
+    ps_dec->bPsDataAvail = 0;
+
+    if (ps_dec->bFrameClass == 0)
+    {
+        Int32 shift;
+
+        shift = ps_dec->noEnv >> 1;
+
+        ps_dec->aEnvStartStop[0] = 0;
+
+        for (env = 1; env < ps_dec->noEnv; env++)
+        {
+            ps_dec->aEnvStartStop[env] =
+                (env * ps_dec->noSubSamples) >> shift;
+        }
+
+        ps_dec->aEnvStartStop[ps_dec->noEnv] = ps_dec->noSubSamples;
+    }
+    else
+    {   /* if (ps_dec->bFrameClass != 0) */
+        ps_dec->aEnvStartStop[0] = 0;
+
+        if (ps_dec->aEnvStartStop[ps_dec->noEnv] < ps_dec->noSubSamples)
+        {
+            ps_dec->noEnv++;
+            ps_dec->aEnvStartStop[ps_dec->noEnv] = ps_dec->noSubSamples;
+
+            pv_memmove(ps_dec->aaIidIndex[ps_dec->noEnv],
+                       ps_dec->aaIidIndex[ps_dec->noEnv-1],
+                       NO_HI_RES_BINS*sizeof(**ps_dec->aaIidIndex));
+
+            pv_memmove(ps_dec->aaIccIndex[ps_dec->noEnv],
+                       ps_dec->aaIccIndex[ps_dec->noEnv-1],
+                       NO_HI_RES_BINS*sizeof(**ps_dec->aaIccIndex));
+        }
+
+        for (env = 1; env < ps_dec->noEnv; env++)
+        {
+            UInt32 thr;
+            thr = ps_dec->noSubSamples - ps_dec->noEnv + env;
+
+            if (ps_dec->aEnvStartStop[env] > thr)
+            {
+                ps_dec->aEnvStartStop[env] = thr;
+            }
+            else
+            {
+                thr = ps_dec->aEnvStartStop[env-1] + 1;
+
+                if (ps_dec->aEnvStartStop[env] < thr)
+                {
+                    ps_dec->aEnvStartStop[env] = thr;
+                }
+            }
+        }
+    }   /* if (ps_dec->bFrameClass == 0) ... else */
+
+    for (env = 0; env < ps_dec->noEnv; env++)
+    {
+        if (ps_dec->freqResIid == 2)
+        {
+            map34IndexTo20(ps_dec->aaIidIndex[env]);
+        }
+        if (ps_dec->freqResIcc == 2)
+        {
+            map34IndexTo20(ps_dec->aaIccIndex[env]);
+        }
+    }
+
+
+}
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_bstr_decoding.h b/media/libstagefright/codecs/aacdec/ps_bstr_decoding.h
new file mode 100644
index 0000000..5212bf8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_bstr_decoding.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_bstr_decoding.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions ps_bstr_decoding()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_BSTR_DECODING_H
+#define PS_BSTR_DECODING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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 Int32 aNoIidBins[3];
+extern const Int32 aNoIccBins[3];
+
+extern const Int32 aFixNoEnvDecode[4];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_bstr_decoding(STRUCT_PS_DEC *h_ps_dec);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_BSTR_DECODING_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_channel_filtering.cpp b/media/libstagefright/codecs/aacdec/ps_channel_filtering.cpp
new file mode 100644
index 0000000..03a53df
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_channel_filtering.cpp
@@ -0,0 +1,281 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_hybrid_analysis.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Does Hybrid analysis
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "s_hybrid.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_fft_rx8.h"
+#include    "ps_channel_filtering.h"
+#include    "pv_audio_type_defs.h"
+#include    "fxp_mul32.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define R_SHIFT     29
+#define Q29_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt31(a)   (Int32)(-a*((Int32)1<<31)  + (a>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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 two_ch_filtering(const Int32 *pQmf_r,
+                      const Int32 *pQmf_i,
+                      Int32 *mHybrid_r,
+                      Int32 *mHybrid_i)
+{
+
+    Int32 cum0;
+    Int32 cum1;
+    Int32 cum2;
+    Int32 tmp1;
+    Int32 tmp2;
+
+    tmp1 = pQmf_r[ 1] + pQmf_r[11];
+    tmp2 = pQmf_i[ 1] + pQmf_i[11];
+    cum1 =   fxp_mul32_Q31(Qfmt31(0.03798975052098f), tmp1);
+    cum2 =   fxp_mul32_Q31(Qfmt31(0.03798975052098f), tmp2);
+    tmp1 = pQmf_r[ 3] + pQmf_r[ 9];
+    tmp2 = pQmf_i[ 3] + pQmf_i[ 9];
+    cum1 =   fxp_msu32_Q31(cum1, Qfmt31(0.14586278335076f), tmp1);
+    cum2 =   fxp_msu32_Q31(cum2, Qfmt31(0.14586278335076f), tmp2);
+    tmp1 = pQmf_r[ 5] + pQmf_r[ 7];
+    tmp2 = pQmf_i[ 5] + pQmf_i[ 7];
+    cum1 =   fxp_mac32_Q31(cum1, Qfmt31(0.61193261090336f), tmp1);
+    cum2 =   fxp_mac32_Q31(cum2, Qfmt31(0.61193261090336f), tmp2);
+
+    cum0 = pQmf_r[HYBRID_FILTER_DELAY] >> 1;  /* HYBRID_FILTER_DELAY == 6 */
+
+    mHybrid_r[0] = (cum0 + cum1);
+    mHybrid_r[1] = (cum0 - cum1);
+
+    cum0 = pQmf_i[HYBRID_FILTER_DELAY] >> 1;  /* HYBRID_FILTER_DELAY == 6 */
+
+    mHybrid_i[0] = (cum0 + cum2);
+    mHybrid_i[1] = (cum0 - cum2);
+
+}
+
+
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void eight_ch_filtering(const Int32 *pQmfReal,
+                        const Int32 *pQmfImag,
+                        Int32 *mHybridReal,
+                        Int32 *mHybridImag,
+                        Int32 scratch_mem[])
+
+{
+
+    Int32 real;
+    Int32 imag;
+    Int32 tmp1;
+    Int32 tmp2;
+
+    real  = fxp_mul32_Q29(Q29_fmt(-0.06989827306334f), pQmfReal[ 4]);
+
+    real  = fxp_mac32_Q31(real, Qfmt31(0.01055120626280f), pQmfReal[12]);
+    imag  = fxp_mul32_Q29(Q29_fmt(-0.06989827306334f), pQmfImag[ 4]);
+
+    imag  = fxp_mac32_Q31(imag, Qfmt31(0.01055120626280f), pQmfImag[12]);
+
+    mHybridReal[2] = (imag - real);
+    mHybridImag[2] = -(imag + real);
+
+    real  = fxp_mul32_Q29(Q29_fmt(-0.07266113929591f), pQmfReal[ 3]);
+
+    real  = fxp_mac32_Q31(real, Qfmt31(0.04540841899650f), pQmfReal[11]);
+    imag  = fxp_mul32_Q29(Q29_fmt(-0.07266113929591f), pQmfImag[ 3]);
+
+    imag  = fxp_mac32_Q31(imag, Qfmt31(0.04540841899650f), pQmfImag[11]);
+
+    tmp1           =  fxp_mul32_Q29(Q29_fmt(-0.38268343236509f), real);
+    mHybridReal[3] =  fxp_mac32_Q29(Q29_fmt(0.92387953251129f), imag, tmp1);
+    tmp2           =  fxp_mul32_Q29(Q29_fmt(-0.92387953251129f), real);
+    mHybridImag[3] =  fxp_mac32_Q29(Q29_fmt(-0.38268343236509f), imag, tmp2);
+
+
+    mHybridImag[4] = fxp_mul32_Q31(Qfmt31(0.09093731860946f), (pQmfReal[ 2] - pQmfReal[10]));
+    mHybridReal[4] = fxp_mul32_Q31(Qfmt31(0.09093731860946f), (pQmfImag[10] - pQmfImag[ 2]));
+
+
+    real  = fxp_mul32_Q29(Q29_fmt(-0.02270420949825f), pQmfReal[ 1]);
+
+    real  = fxp_mac32_Q31(real, Qfmt31(0.14532227859182f), pQmfReal[ 9]);
+    imag  = fxp_mul32_Q29(Q29_fmt(-0.02270420949825f), pQmfImag[ 1]);
+
+    imag  = fxp_mac32_Q31(imag, Qfmt31(0.14532227859182f), pQmfImag[ 9]);
+
+    tmp1           =  fxp_mul32_Q29(Q29_fmt(0.92387953251129f), imag);
+
+    mHybridReal[5] =  fxp_mac32_Q31(tmp1, Qfmt31(0.76536686473018f), real);
+    tmp2           =  fxp_mul32_Q29(Q29_fmt(-0.92387953251129f), real);
+
+    mHybridImag[5] =  fxp_mac32_Q31(tmp2, Qfmt31(0.76536686473018f), imag);
+
+    real  = fxp_mul32_Q29(Q29_fmt(-0.00527560313140f), pQmfReal[ 0]);
+
+    real  = fxp_mac32_Q31(real, Qfmt31(0.13979654612668f), pQmfReal[ 8]);
+    imag  = fxp_mul32_Q29(Q29_fmt(-0.00527560313140f), pQmfImag[ 0]);
+
+    imag  = fxp_mac32_Q31(imag, Qfmt31(0.13979654612668f), pQmfImag[ 8]);
+
+    mHybridReal[6] = (imag + real);
+    mHybridImag[6] = (imag - real);
+
+
+    tmp1            =  fxp_mul32_Q31(Qfmt31(0.21791935610828f), pQmfReal[ 7]);
+    mHybridReal[7]  =  fxp_mac32_Q31(tmp1, Qfmt31(0.09026515280366f), pQmfImag[ 7]);
+
+    tmp2            =  fxp_mul32_Q29(Q29_fmt(-0.04513257640183f), pQmfReal[ 7]);
+
+    mHybridImag[7]  =  fxp_mac32_Q31(tmp2, Qfmt31(0.21791935610828f), pQmfImag[ 7]);
+
+    mHybridReal[0] = pQmfReal[HYBRID_FILTER_DELAY] >> 3;
+    mHybridImag[0] = pQmfImag[HYBRID_FILTER_DELAY] >> 3;
+
+    tmp1           =  fxp_mul32_Q29(Q29_fmt(-0.04513257640183f), pQmfImag[ 5]);
+
+    mHybridReal[1] =  fxp_mac32_Q31(tmp1, Qfmt31(0.21791935610828f), pQmfReal[ 5]);
+
+
+    tmp2            =  fxp_mul32_Q31(Qfmt31(0.21791935610828f), pQmfImag[ 5]);
+    mHybridImag[1]  =  fxp_mac32_Q31(tmp2, Qfmt31(0.09026515280366f), pQmfReal[ 5]);
+
+    /*
+     *  8*ifft
+     */
+
+    ps_fft_rx8(mHybridReal, mHybridImag, scratch_mem);
+
+}
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_channel_filtering.h b/media/libstagefright/codecs/aacdec/ps_channel_filtering.h
new file mode 100644
index 0000000..19cda79
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_channel_filtering.h
@@ -0,0 +1,104 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_channel_filtering.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions two_ch_filtering()
+ and  eight_ch_filtering()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_CHANNEL_FILTERING_H
+#define PS_CHANNEL_FILTERING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void two_ch_filtering(const Int32 *pQmf_r,
+    const Int32 *pQmf_i,
+    Int32 *mHybrid_r,
+    Int32 *mHybrid_i);
+
+
+    void eight_ch_filtering(const Int32 *pQmfReal,
+                            const Int32 *pQmfImag,
+                            Int32 *mHybridReal,
+                            Int32 *mHybridImag,
+                            Int32 scratch_mem[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_CHANNEL_FILTERING_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_constants.h b/media/libstagefright/codecs/aacdec/ps_constants.h
new file mode 100644
index 0000000..d5b2ad4
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_constants.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+*******************************************************************************/
+/*
+*/
+#ifndef PS_CONSTANTS_H
+#define PS_CONSTANTS_H
+
+
+#define NO_SUB_QMF_CHANNELS         12
+#define NO_QMF_CHANNELS_IN_HYBRID   3
+#define NO_QMF_CHANNELS             64
+#define NO_ALLPASS_CHANNELS         23
+#define NO_DELAY_CHANNELS           (NO_QMF_CHANNELS-NO_ALLPASS_CHANNELS)
+#define DELAY_ALLPASS               2
+#define SHORT_DELAY_START           12
+#define SHORT_DELAY                 1
+#define LONG_DELAY                  14
+#define NO_QMF_ALLPASS_CHANNELS    (NO_ALLPASS_CHANNELS-NO_QMF_CHANNELS_IN_HYBRID)
+#define NO_QMF_ICC_CHANNELS        (NO_QMF_ALLPASS_CHANNELS+NO_DELAY_CHANNELS)
+#define HYBRIDGROUPS                8
+#define DECAY_CUTOFF                3
+#define NO_SERIAL_ALLPASS_LINKS     3
+#define MAX_NO_PS_ENV               5
+#define NEGATE_IPD_MASK                 ( 0x00001000 )
+#define NO_BINS                         ( 20 )
+#define NO_HI_RES_BINS                  ( 34 )
+#define NO_LOW_RES_BINS                 ( NO_IID_BINS / 2 )
+#define NO_IID_BINS                     ( NO_BINS )
+#define NO_ICC_BINS                     ( NO_BINS )
+#define NO_LOW_RES_IID_BINS             ( NO_LOW_RES_BINS )
+#define NO_LOW_RES_ICC_BINS             ( NO_LOW_RES_BINS )
+#define SUBQMF_GROUPS                   ( 10 )
+#define QMF_GROUPS                      ( 12 )
+#define NO_IID_GROUPS                   ( SUBQMF_GROUPS + QMF_GROUPS )
+#define NO_IID_STEPS                    ( 7 )
+#define NO_IID_STEPS_FINE               ( 15 )
+#define NO_ICC_STEPS                    ( 8 )
+#define NO_IID_LEVELS                   ( 2 * NO_IID_STEPS + 1 )
+#define NO_IID_LEVELS_FINE              ( 2 * NO_IID_STEPS_FINE + 1 )
+#define NO_ICC_LEVELS                   ( NO_ICC_STEPS )
+
+
+
+#endif      /*  PS_CONSTANTS_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.cpp b/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.cpp
new file mode 100644
index 0000000..241da34
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.cpp
@@ -0,0 +1,274 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_decode_bs_utils.c
+
+  Functions:
+        GetNrBitsAvailable
+        differential_Decoding
+        map34IndexTo20
+        limitMinMax
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Decode bitstream parametric stereo's utilities
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include "aac_mem_funcs.h"
+#include "s_ps_dec.h"
+#include "ps_decode_bs_utils.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
+----------------------------------------------------------------------------*/
+
+Int32 GetNrBitsAvailable(HANDLE_BIT_BUFFER hBitBuf)
+{
+
+    return (hBitBuf->bufferLen - hBitBuf->nrBitsRead);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+;
+;   Differential Decoding of parameters over time/frequency
+----------------------------------------------------------------------------*/
+
+void differential_Decoding(Int32 enable,
+                           Int32 *aIndex,
+                           Int32 *aPrevFrameIndex,
+                           Int32 DtDf,
+                           Int32 nrElements,
+                           Int32 stride,
+                           Int32 minIdx,
+                           Int32 maxIdx)
+{
+    Int32 i;
+    Int32 *ptr_aIndex;
+
+    if (enable == 1)
+    {
+        ptr_aIndex = aIndex;
+
+        if (DtDf == 0)
+        {
+            *(ptr_aIndex) = limitMinMax(*ptr_aIndex, minIdx, maxIdx);
+            ptr_aIndex++;
+
+            for (i = 1; i < nrElements; i++)
+            {
+                *(ptr_aIndex) = limitMinMax(aIndex[i-1] + *ptr_aIndex, minIdx, maxIdx);
+                ptr_aIndex++;
+            }
+        }
+        else
+        {
+            if (stride == 1)
+            {
+                for (i = 0; i < nrElements; i++)
+                {
+                    *(ptr_aIndex) = limitMinMax(aPrevFrameIndex[i] + *ptr_aIndex, minIdx, maxIdx);
+                    ptr_aIndex++;
+                }
+            }
+            else
+            {
+                for (i = 0; i < nrElements; i++)
+                {
+                    *(ptr_aIndex) = limitMinMax(aPrevFrameIndex[(i<<1)] + *ptr_aIndex, minIdx, maxIdx);
+                    ptr_aIndex++;
+                }
+            }
+        }
+    }
+    else
+    {
+        pv_memset((void *)aIndex, 0, nrElements*sizeof(*aIndex));
+    }
+    if (stride == 2)
+    {
+        for (i = (nrElements << 1) - 1; i > 0; i--)
+        {
+            aIndex[i] = aIndex[(i>>1)];
+        }
+    }
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+        map34IndexTo20
+----------------------------------------------------------------------------*/
+
+void map34IndexTo20(Int32 *aIndex)
+{
+
+    aIndex[ 0] = ((aIndex[0] << 1) +  aIndex[1]) / 3;
+    aIndex[ 1] = (aIndex[1] + (aIndex[2] << 1)) / 3;
+    aIndex[ 2] = ((aIndex[3] << 1) +  aIndex[4]) / 3;
+    aIndex[ 3] = (aIndex[4] + (aIndex[5] << 1)) / 3;
+    aIndex[ 4] = (aIndex[ 6] +  aIndex[7]) >> 1;
+    aIndex[ 5] = (aIndex[ 8] +  aIndex[9]) >> 1;
+    aIndex[ 6] =   aIndex[10];
+    aIndex[ 7] =   aIndex[11];
+    aIndex[ 8] = (aIndex[12] +  aIndex[13]) >> 1;
+    aIndex[ 9] = (aIndex[14] +  aIndex[15]) >> 1;
+    aIndex[10] =   aIndex[16];
+    aIndex[11] =   aIndex[17];
+    aIndex[12] =   aIndex[18];
+    aIndex[13] =   aIndex[19];
+    aIndex[14] = (aIndex[20] +  aIndex[21]) >> 1;
+    aIndex[15] = (aIndex[22] +  aIndex[23]) >> 1;
+    aIndex[16] = (aIndex[24] +  aIndex[25]) >> 1;
+    aIndex[17] = (aIndex[26] +  aIndex[27]) >> 1;
+    aIndex[18] = (aIndex[28] +  aIndex[29] + aIndex[30] + aIndex[31]) >> 2;
+    aIndex[19] = (aIndex[32] +  aIndex[33]) >> 1;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+        limitMinMax
+----------------------------------------------------------------------------*/
+
+
+Int32 limitMinMax(Int32 i,
+                  Int32 min,
+                  Int32 max)
+{
+    if (i < max)
+    {
+        if (i > min)
+        {
+            return i;
+        }
+        else
+        {
+            return min;
+        }
+    }
+    else
+    {
+        return max;
+    }
+}
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.h b/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.h
new file mode 100644
index 0000000..a672d94
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_decode_bs_utils.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_decode_bs_utils.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions differential_Decoding(), limitMinMax(),
+                           GetNrBitsAvailable(), map34IndexTo20()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_DECODE_BS_UTILS_H
+#define PS_DECODE_BS_UTILS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+#include "s_bit_buffer.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void differential_Decoding(Int32 enable,
+    Int32 *aIndex,
+    Int32 *aPrevFrameIndex,
+    Int32 DtDf,
+    Int32 nrElements,
+    Int32 stride,
+    Int32 minIdx,
+    Int32 maxIdx);
+
+    Int32 limitMinMax(Int32 i,
+                      Int32 min,
+                      Int32 max);
+
+    Int32 GetNrBitsAvailable(HANDLE_BIT_BUFFER hBitBuf);
+
+    void map34IndexTo20(Int32 *aIndex);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_DECODE_BS_UTILS_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_decorrelate.cpp b/media/libstagefright/codecs/aacdec/ps_decorrelate.cpp
new file mode 100644
index 0000000..6776d6e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_decorrelate.cpp
@@ -0,0 +1,499 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_decorrelate.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Decorrelation
+  Decorrelation is achieved by means of all-pass filtering and delaying
+  Sub-band samples s_k(n) are converted into de-correlated sub-bands samples
+  d_k(n). k index for frequency, n time index
+
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+  Delay is introduced to compensate QMF bands not passed through Hybrid
+  Analysis
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+#include    "pv_audio_type_defs.h"
+#include    "ps_decorrelate.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_pwr_transient_detection.h"
+#include    "ps_all_pass_fract_delay_filter.h"
+#include    "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+#ifndef min
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+
+/*----------------------------------------------------------------------------
+; 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 ps_decorrelate(STRUCT_PS_DEC *h_ps_dec,
+                    Int32 *rIntBufferLeft,
+                    Int32 *iIntBufferLeft,
+                    Int32 *rIntBufferRight,
+                    Int32 *iIntBufferRight,
+                    Int32 scratch_mem[])
+{
+    Int32 sb;
+    Int32 maxsb;
+    Int32 gr;
+    Int32 sb_delay;
+    Int32 bin;
+
+
+
+
+    Int32 *aLeftReal;
+    Int32 *aLeftImag;
+    Int32 *aRightReal;
+    Int32 *aRightImag;
+
+    Int32 *aTransRatio = scratch_mem;   /* use  NO_BINS == 20 */
+
+
+    Int32 ***pppRealDelayRBufferSer;
+    Int32 ***pppImagDelayRBufferSer;
+
+    Int32 **ppRealDelayBuffer;
+    Int32 **ppImagDelayBuffer;
+
+    const Int32(*ppFractDelayPhaseFactorSer)[3];
+    /*
+     *  Power transient estimation and detection
+     */
+
+
+    ps_pwr_transient_detection(h_ps_dec,
+                               rIntBufferLeft,
+                               iIntBufferLeft,
+                               aTransRatio);
+
+
+    aLeftReal = h_ps_dec->mHybridRealLeft;
+    aLeftImag = h_ps_dec->mHybridImagLeft;
+    aRightReal = h_ps_dec->mHybridRealRight;
+    aRightImag = h_ps_dec->mHybridImagRight;
+
+    pppRealDelayRBufferSer = h_ps_dec->aaaRealDelayRBufferSerSubQmf;
+    pppImagDelayRBufferSer = h_ps_dec->aaaImagDelayRBufferSerSubQmf;
+
+    ppRealDelayBuffer = h_ps_dec->aaRealDelayBufferSubQmf;
+    ppImagDelayBuffer = h_ps_dec->aaImagDelayBufferSubQmf;
+
+
+
+    ppFractDelayPhaseFactorSer = aaFractDelayPhaseFactorSerSubQmf;
+
+
+    /*
+     *   NO_IID_GROUPS (SUBQMF_GROUPS (12) + QMF_GROUPS (10)) == 22
+     */
+
+    for (gr = 0; gr < SUBQMF_GROUPS; gr++)      /*  0 to 9 */
+    {
+        Int32 rIn;
+        Int32 iIn;
+        Int32 *pt_rTmp;
+        Int32 *pt_iTmp;
+        Int32 rTmp;
+        Int32 cmplx;
+        Int32 tmp1, tmp2;
+
+        /* sb = subQMF/QMF subband */
+
+        sb = groupBorders[gr];
+
+        /*
+         *  For lower subbands
+         *  Apply all-pass filtering
+         *
+         */
+        pt_rTmp = &ppRealDelayBuffer[sb][h_ps_dec->delayBufIndex];
+        pt_iTmp = &ppImagDelayBuffer[sb][h_ps_dec->delayBufIndex];
+
+        tmp1 = aLeftReal[sb];
+        tmp2 = aLeftImag[sb];
+        rIn = *pt_rTmp >> 1;
+        iIn = *pt_iTmp >> 1;
+
+
+        *pt_rTmp = tmp1;
+        *pt_iTmp = tmp2;
+
+        /*
+         *  Fractional delay vector
+         *
+         *  phi_fract(k) = exp(-j*pi*q_phi*f_center(k))       0<= k <= SUBQMF_GROUPS
+         *
+         *  q_phi = 0.39
+         *  f_center(k) frequency vector
+         */
+
+        cmplx =  aFractDelayPhaseFactorSubQmf[sb];
+
+        aRightReal[sb]  = cmplx_mul32_by_16(rIn, -iIn, cmplx);
+        aRightImag[sb]  = cmplx_mul32_by_16(iIn,  rIn, cmplx);
+
+        ps_all_pass_fract_delay_filter_type_I(h_ps_dec->aDelayRBufIndexSer,
+                                              sb,
+                                              ppFractDelayPhaseFactorSer[sb],
+                                              pppRealDelayRBufferSer,
+                                              pppImagDelayRBufferSer,
+                                              &aRightReal[sb],
+                                              &aRightImag[sb]);
+
+        bin = bins2groupMap[gr];
+        rTmp = aTransRatio[bin];
+
+        if (rTmp != 0x7FFFFFFF)
+        {
+            aRightReal[sb] = fxp_mul32_Q31(rTmp, aRightReal[sb]) << 1;
+            aRightImag[sb] = fxp_mul32_Q31(rTmp, aRightImag[sb]) << 1;
+        }
+
+
+    } /* gr */
+
+    aLeftReal = rIntBufferLeft;
+    aLeftImag = iIntBufferLeft;
+    aRightReal = rIntBufferRight;
+    aRightImag = iIntBufferRight;
+
+    pppRealDelayRBufferSer = h_ps_dec->aaaRealDelayRBufferSerQmf;
+    pppImagDelayRBufferSer = h_ps_dec->aaaImagDelayRBufferSerQmf;
+
+    ppRealDelayBuffer = h_ps_dec->aaRealDelayBufferQmf;
+    ppImagDelayBuffer = h_ps_dec->aaImagDelayBufferQmf;
+
+
+
+    ppFractDelayPhaseFactorSer = aaFractDelayPhaseFactorSerQmf;
+
+
+    for (gr = SUBQMF_GROUPS; gr < NO_BINS; gr++)     /* 10 to 20 */
+    {
+
+        maxsb = min(h_ps_dec->usb, groupBorders[gr+1]);
+
+        /* sb = subQMF/QMF subband */
+
+        for (sb = groupBorders[gr]; sb < maxsb; sb++)
+        {
+
+            Int32 rIn, iIn;
+            Int32 *pt_rTmp, *pt_iTmp;
+            Int32 cmplx;
+            Int32 tmp1, tmp2;
+            Int32 rTmp;
+
+
+            sb_delay = sb - NO_QMF_CHANNELS_IN_HYBRID;  /* NO_QMF_CHANNELS_IN_HYBRID == 3 */
+
+            /*
+             *  For lower subbands
+             *  Apply all-pass filtering
+             *
+             */
+            pt_rTmp = &ppRealDelayBuffer[sb_delay][h_ps_dec->delayBufIndex];
+            pt_iTmp = &ppImagDelayBuffer[sb_delay][h_ps_dec->delayBufIndex];
+
+            rIn = *pt_rTmp >> 1;
+            iIn = *pt_iTmp >> 1;
+
+            tmp1 = aLeftReal[sb];
+            tmp2 = aLeftImag[sb];
+            *pt_rTmp = tmp1;
+            *pt_iTmp = tmp2;
+
+            /*
+             *  Fractional delay vector
+             *
+             *  phi_fract(k) = exp(-j*pi*q_phi*f_center(k))       0<= k <= SUBQMF_GROUPS
+             *
+             *  q_phi = 0.39
+             *  f_center(k) frequency vector
+             */
+
+            cmplx =  aFractDelayPhaseFactor[sb_delay];
+            aRightReal[sb] = cmplx_mul32_by_16(rIn, -iIn, cmplx);
+            aRightImag[sb] = cmplx_mul32_by_16(iIn,  rIn, cmplx);
+
+            ps_all_pass_fract_delay_filter_type_II(h_ps_dec->aDelayRBufIndexSer,
+                                                   sb_delay,
+                                                   ppFractDelayPhaseFactorSer[sb_delay],
+                                                   pppRealDelayRBufferSer,
+                                                   pppImagDelayRBufferSer,
+                                                   &aRightReal[sb],
+                                                   &aRightImag[sb],
+                                                   sb);
+
+            rTmp = aTransRatio[gr-2];
+            if (rTmp != 0x7FFFFFFF)
+            {
+                aRightReal[sb] = fxp_mul32_Q31(rTmp, aRightReal[sb]) << 1;
+                aRightImag[sb] = fxp_mul32_Q31(rTmp, aRightImag[sb]) << 1;
+            }
+
+
+        } /* sb */
+
+    }
+
+
+    maxsb = min(h_ps_dec->usb, 35);  /*  35 == groupBorders[NO_BINS + 1] */
+
+    /* sb = subQMF/QMF subband */
+    {
+        Int32 factor = aTransRatio[NO_BINS-2];
+
+        for (sb = 23; sb < maxsb; sb++)    /*  23 == groupBorders[NO_BINS] */
+        {
+
+            Int32  tmp, tmp2;
+            Int32 *pt_rTmp, *pt_iTmp;
+
+            sb_delay = sb - NO_QMF_CHANNELS_IN_HYBRID;  /*  == 3 */
+
+            /*
+             *  For the Upper Bands apply delay only
+             *                          -D(k)
+             *  Apply Delay   H_k(z) = z         , D(k) == 1 or 14
+             *
+             */
+            Int32 k = sb - NO_ALLPASS_CHANNELS;  /* == 23 */
+
+
+            pt_rTmp = &ppRealDelayBuffer[sb_delay][h_ps_dec->aDelayBufIndex[ k]];
+            pt_iTmp = &ppImagDelayBuffer[sb_delay][h_ps_dec->aDelayBufIndex[ k]];
+
+            if (++h_ps_dec->aDelayBufIndex[ k] >= LONG_DELAY)     /* == 14 */
+            {
+                h_ps_dec->aDelayBufIndex[ k] = 0;
+            }
+
+
+            tmp  = *pt_rTmp;
+            tmp2 = *pt_iTmp;
+
+            if (aTransRatio[NO_BINS-2] < 0x7FFFFFFF)
+            {
+                aRightReal[sb] = fxp_mul32_Q31(factor, tmp) << 1;
+                aRightImag[sb] = fxp_mul32_Q31(factor, tmp2) << 1;
+            }
+            else
+            {
+                aRightReal[sb] = tmp;
+                aRightImag[sb] = tmp2;
+            }
+
+
+            tmp  = aLeftReal[sb];
+            tmp2 = aLeftImag[sb];
+            *pt_rTmp = tmp;
+            *pt_iTmp = tmp2;
+
+
+        } /* sb */
+    }
+
+
+    maxsb = min(h_ps_dec->usb, 64);     /*  64 == groupBorders[NO_BINS+2] */
+
+    /* sb = subQMF/QMF subband */
+
+    {
+
+        for (sb = 35; sb < maxsb; sb++)    /*  35 == groupBorders[NO_BINS+1] */
+        {
+
+            Int32 *pt_rTmp, *pt_iTmp;
+
+            sb_delay = sb - NO_QMF_CHANNELS_IN_HYBRID;  /*  == 3 */
+
+            /*
+             *  For the Upper Bands apply delay only
+             *                          -D(k)
+             *  Apply Delay   H_k(z) = z         , D(k) == 1 or 14
+             *
+             */
+
+            pt_rTmp = &ppRealDelayBuffer[sb_delay][0];
+            pt_iTmp = &ppImagDelayBuffer[sb_delay][0];
+
+            aRightReal[sb] = *pt_rTmp;
+            aRightImag[sb] = *pt_iTmp;
+
+
+            if (aTransRatio[NO_BINS-1] < 0x7FFFFFFF)
+            {
+                aRightReal[sb] = fxp_mul32_Q31(aTransRatio[NO_BINS-1], aRightReal[sb]) << 1;
+                aRightImag[sb] = fxp_mul32_Q31(aTransRatio[NO_BINS-1], aRightImag[sb]) << 1;
+            }
+
+            *pt_rTmp = aLeftReal[sb];
+            *pt_iTmp = aLeftImag[sb];
+
+
+        } /* sb */
+    }
+
+
+    if (++h_ps_dec->delayBufIndex >= DELAY_ALLPASS)
+    {
+        h_ps_dec->delayBufIndex = 0;
+    }
+
+    if (++h_ps_dec->aDelayRBufIndexSer[0] >= 3)
+    {
+        h_ps_dec->aDelayRBufIndexSer[0] = 0;
+    }
+    if (++h_ps_dec->aDelayRBufIndexSer[1] >= 4)
+    {
+        h_ps_dec->aDelayRBufIndexSer[1] = 0;
+    }
+    if (++h_ps_dec->aDelayRBufIndexSer[2] >= 5)
+    {
+        h_ps_dec->aDelayRBufIndexSer[2] = 0;
+    }
+
+
+} /* END deCorrelate */
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_decorrelate.h b/media/libstagefright/codecs/aacdec/ps_decorrelate.h
new file mode 100644
index 0000000..c2a025a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_decorrelate.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_decorrelate.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_decorrelate()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_DECORRELATE_H
+#define PS_DECORRELATE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_decorrelate(STRUCT_PS_DEC *h_ps_dec,
+    Int32 *rIntBufferLeft,
+    Int32 *iIntBufferLeft,
+    Int32 *rIntBufferRight,
+    Int32 *iIntBufferRight,
+    Int32 scratch_mem[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_DECORRELATE_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_fft_rx8.cpp b/media/libstagefright/codecs/aacdec/ps_fft_rx8.cpp
new file mode 100644
index 0000000..7669be3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_fft_rx8.cpp
@@ -0,0 +1,318 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: fft_rx8.c
+ Funtions: ps_fft_rx8
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Real     Vector of Real components size 8
+
+    Imag     Vector of Imag components size 8
+             type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+     scratch_mem size 32
+
+ Outputs:
+    In-place calculation of a 8-point FFT (radix-8)
+
+ Pointers and Buffers Modified:
+    calculation are done in-place and returned in Data
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    8-point DFT, radix 8 with Decimation in Frequency
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should provide a fixed point FFT for any input array
+    of size power of 8.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] Advance Digital Signal Processing, J. Proakis, C. Rader, F. Ling,
+        C. Nikias, Macmillan Pub. Co.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+   MODIFY( x[] )
+   RETURN( exponent )
+
+------------------------------------------------------------------------------
+ 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
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#ifdef PARAMETRICSTEREO
+
+
+#include "pv_audio_type_defs.h"
+#include "ps_fft_rx8.h"
+
+#include    "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define R_SHIFT     29
+#define Q29_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void ps_fft_rx8(Int32 Re[], Int32 Im[], Int32 scratch_mem[])
+
+/* scratch_mem size 32 */
+{
+
+    Int     i;
+    Int32   *Q = &scratch_mem[0];
+    Int32   *Z = &scratch_mem[16];
+    Int32   temp1;
+    Int32   temp2;
+    Int32   temp3;
+    Int32   temp4;
+    Int32   aux_r[2];
+    Int32   aux_i[2];
+    Int32   *pt_r1 = &Re[0];
+    Int32   *pt_r2 = &Re[4];
+    Int32   *pt_i1 = &Im[0];
+    Int32   *pt_i2 = &Im[4];
+
+    Int32   *pt_Q = Q;
+    Int32   *pt_Z = Z;
+
+
+    temp1 = *(pt_r1++); /*  Real */
+    temp2 = *(pt_r2++); /*  Real */
+    temp3 = *(pt_i1++); /*  Imag */
+    temp4 = *(pt_i2++); /*  Imag */
+    /*
+     *  Vector Q stores data as Real, Imag, Real, Imag,....
+     */
+
+    *(pt_Q++) = temp1 + temp2;  /* Q(0) =  v(0) + v(4) */
+    *(pt_Q++) = temp3 + temp4;
+    *(pt_Q++) = temp1 - temp2;  /* Q(1) =  v(0) - v(4) */
+    *(pt_Q++) = temp3 - temp4;
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_i1++);
+    temp4 = *(pt_i2++);
+
+    *(pt_Q++) = temp1 + temp2;  /*    Q(2) =  v(1) + v(5) */
+    *(pt_Q++) = temp3 + temp4;
+    aux_r[0]  = temp1 - temp2;  /* aux[0]  =  v(1) - v(5) */
+    aux_i[0]  = temp3 - temp4;
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_i1++);
+    temp4 = *(pt_i2++);
+
+    *(pt_Q++) = temp1 + temp2;  /*  Q(3) =  v(2) + v(6) */
+    *(pt_Q++) = temp3 + temp4;
+    *(pt_Q++) = temp4 - temp3;  /*  Q(4) = (v(2) - v(6))*j */
+    *(pt_Q++) = temp1 - temp2;
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_i1++);
+    temp4 = *(pt_i2++);
+
+
+    *(pt_Q++) = temp1 + temp2;  /*  Q(5)   = v(3) + v(7) */
+    *(pt_Q++) = temp3 + temp4;
+    aux_r[1]  = temp1 - temp2;  /*  aux[1] = v(3) - v(7) */
+    aux_i[1]  = temp3 - temp4;
+    /*  Q(6) =  (aux[0] - aux[1])/sqrt(2); */
+    *(pt_Q++) = fxp_mul32_Q29((aux_r[0] - aux_r[1]), Q29_fmt(0.70710678118655f));
+    *(pt_Q++) = fxp_mul32_Q29((aux_i[0] - aux_i[1]), Q29_fmt(0.70710678118655f));
+
+    /*  Q(7) =  (aux[0] + aux[1])*j/sqrt(2); */
+    *(pt_Q++) =  fxp_mul32_Q29((aux_i[0] + aux_i[1]), Q29_fmt(-0.70710678118655f));
+    *(pt_Q) =  fxp_mul32_Q29((aux_r[0] + aux_r[1]), Q29_fmt(0.70710678118655f));
+
+    pt_r1 = &Q[0];        /* reset pointer */
+    pt_r2 = &Q[6];        /* reset pointer */
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_r1++);
+    temp4 = *(pt_r2++);
+
+    /*
+     *  Vector Z stores data as Real, Imag, Real, Imag,....
+     */
+
+    *(pt_Z++) = temp1 + temp2;  /* Q(0) + Q(3) */
+    *(pt_Z++) = temp3 + temp4;
+    aux_r[0]  = temp1 - temp2;
+    aux_i[0]  = temp3 - temp4;
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_r1++);
+    temp4 = *(pt_r2++);
+
+    *(pt_Z++) = temp1 + temp2;  /* Q(1) + Q(4) */
+    *(pt_Z++) = temp3 + temp4;
+    *(pt_Z++) = aux_r[0];       /* Q(0) - Q(3) */
+    *(pt_Z++) = aux_i[0];
+    *(pt_Z++) = temp1 - temp2;  /* Q(1) - Q(4) */
+    *(pt_Z++) = temp3 - temp4;
+
+    temp1 = *(pt_r1++);
+    temp2 = *(pt_r2++);
+    temp3 = *(pt_r1);
+    temp4 = *(pt_r2++);
+
+    *(pt_Z++) = temp1 + temp2;  /* Q(2) + Q(5) */
+    *(pt_Z++) = temp3 + temp4;
+    aux_r[0]  = temp1 - temp2;
+    aux_i[0]  = temp3 - temp4;
+
+    temp1 = *(pt_r2++);
+    temp3 = *(pt_r2++);
+    temp2 = *(pt_r2++);
+    temp4 = *(pt_r2);
+
+    *(pt_Z++) = temp1 + temp2;  /* Q(6) + Q(7) */
+    *(pt_Z++) = temp3 + temp4;
+
+    *(pt_Z++) = -aux_i[0];      /* (Q(2) - Q(5))*j */
+    *(pt_Z++) =  aux_r[0];
+
+    *(pt_Z++) =  temp2 - temp1;  /* -Q(6) + Q(7) */
+    *(pt_Z) =  temp4 - temp3;
+
+    pt_Z = &Z[0];        /* reset pointer */
+    pt_Q = &Z[8];        /* reset pointer */
+
+    pt_r1 = &Re[0];
+    pt_r2 = &Re[4];
+    pt_i1 = &Im[0];
+    pt_i2 = &Im[4];
+
+
+    for (i = 4; i != 0; i--)
+    {
+        temp1 = *(pt_Z++);
+        temp2 = *(pt_Q++);
+        temp3 = *(pt_Z++);
+        temp4 = *(pt_Q++);
+
+        *(pt_r1++) = temp1 + temp2;  /* Z(n) + Z(n+4) */
+        *(pt_i1++) = temp3 + temp4;
+        *(pt_r2++) = temp1 - temp2;  /* Z(n) - Z(n+4) */
+        *(pt_i2++) = temp3 - temp4;
+    }
+
+}
+
+#endif  /* PARAMETRICSTEREO */
+
+
+#endif  /* AAC_PLUS */
diff --git a/media/libstagefright/codecs/aacdec/ps_fft_rx8.h b/media/libstagefright/codecs/aacdec/ps_fft_rx8.h
new file mode 100644
index 0000000..6c3482e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_fft_rx8.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_fft_rx8.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions ps_fft_rx8()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_FFT_RX8_H
+#define PS_FFT_RX8_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_fft_rx8(Int32 Re[], Int32 Im[], Int32 scratch_mem[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_FFT_RX4_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.cpp b/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.cpp
new file mode 100644
index 0000000..933b07e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.cpp
@@ -0,0 +1,285 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_hybrid_analysis.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Does Hybrid analysis:
+
+        Get higher frequency resolution in the lower QMF subbands
+        creating sub-subbands. This is done by low frequency filtering.
+        Lower QMF subbands are further split in order to obtain a higher
+        frequency resolution, enabling a proper stereo analysis and synthesis
+        for the lower frequencies.
+        Two hybrid are defined. Both filters have length 13 and a delay of 6.
+        In this implementation, the symmetry of the filters helps to simplify
+        the design.
+
+
+   Increase Freq. Resolution
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+
+          subband k             QMF channel
+             0   .................  0      -----------
+             1   .................  0
+             2   .................  0
+             3   .................  0
+             4   .................  0
+             5   .................  0        Sub-QMF  ( Increase Freq. Resolution)
+             6   .................  1
+             7   .................  1
+             8   .................  2
+             9   .................  2
+            10   .................  3      -----------
+            11   .................  4
+            12   .................  5
+            13   .................  6
+            14   .................  7
+            15   .................  8         QMF
+           16-17 .................  9-10
+           18-20 ................. 11-13
+           21-24 ................. 14-17
+           25-29 ................. 18-22
+           30-41 ................. 23-34
+           42-70 ................. 35-63   -----------
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "s_hybrid.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_channel_filtering.h"
+#include    "ps_hybrid_analysis.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 ps_hybrid_analysis(const Int32 mQmfReal[][64],
+                        const Int32 mQmfImag[][64],
+                        Int32 *mHybridReal,
+                        Int32 *mHybridImag,
+                        HYBRID *pHybrid,
+                        Int32 scratch_mem[],
+                        Int32 i)
+
+{
+
+    Int32 band;
+    HYBRID_RES hybridRes;
+    Int32  chOffset = 0;
+
+    Int32 *ptr_mHybrid_Re;
+    Int32 *ptr_mHybrid_Im;
+
+    Int32 *pt_mQmfBufferReal;
+    Int32 *pt_mQmfBufferImag;
+
+    pt_mQmfBufferReal = &scratch_mem[32 + i];
+
+    for (band = 0; band < pHybrid->nQmfBands; band++)
+    {
+        pt_mQmfBufferImag = pt_mQmfBufferReal + 44;
+
+
+        pt_mQmfBufferReal[HYBRID_FILTER_LENGTH_m_1] = mQmfReal[HYBRID_FILTER_DELAY][band];
+        pt_mQmfBufferImag[HYBRID_FILTER_LENGTH_m_1] = mQmfImag[HYBRID_FILTER_DELAY][band];
+
+
+        ptr_mHybrid_Re = &mHybridReal[ chOffset];
+        ptr_mHybrid_Im = &mHybridImag[ chOffset];
+
+        hybridRes = (HYBRID_RES)pHybrid->pResolution[band];
+        switch (hybridRes)
+        {
+                /*
+                 *  For QMF band = 1  and  2
+                 */
+
+            case HYBRID_2_REAL:
+
+                two_ch_filtering(pt_mQmfBufferReal,
+                                 pt_mQmfBufferImag,
+                                 ptr_mHybrid_Re,
+                                 ptr_mHybrid_Im);
+                chOffset += 2;
+
+                break;
+
+                /*
+                 *  For QMF band = 0
+                 */
+
+            case HYBRID_8_CPLX:
+
+                eight_ch_filtering(pt_mQmfBufferReal,
+                                   pt_mQmfBufferImag,
+                                   pHybrid->mTempReal,
+                                   pHybrid->mTempImag,
+                                   scratch_mem);
+
+                pv_memmove(ptr_mHybrid_Re, pHybrid->mTempReal, 4*sizeof(*pHybrid->mTempReal));
+
+                ptr_mHybrid_Re += 2;
+
+                *(ptr_mHybrid_Re++) +=  pHybrid->mTempReal[5];
+                *(ptr_mHybrid_Re++) +=  pHybrid->mTempReal[4];
+                *(ptr_mHybrid_Re++)  =  pHybrid->mTempReal[6];
+                *(ptr_mHybrid_Re)  =  pHybrid->mTempReal[7];
+
+                pv_memmove(ptr_mHybrid_Im, pHybrid->mTempImag, 4*sizeof(*pHybrid->mTempImag));
+                ptr_mHybrid_Im += 2;
+
+                *(ptr_mHybrid_Im++) +=  pHybrid->mTempImag[5];
+                *(ptr_mHybrid_Im++) +=  pHybrid->mTempImag[4];
+                *(ptr_mHybrid_Im++)  =  pHybrid->mTempImag[6];
+                *(ptr_mHybrid_Im)  =  pHybrid->mTempImag[7];
+
+                chOffset += 6;
+
+                break;
+
+            default:
+                ;
+        }
+
+        pt_mQmfBufferReal = pt_mQmfBufferImag + 44;
+
+    }
+
+
+}
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.h b/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.h
new file mode 100644
index 0000000..0140a1f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_analysis.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_hybrid_analysis.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_hybrid_analysis()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_HYBRID_ANALYSIS_H
+#define PS_HYBRID_ANALYSIS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_hybrid.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_hybrid_analysis(const Int32 mQmfReal[][64],
+    const Int32 mQmfImag[][64],
+    Int32 *mHybridReal,
+    Int32 *mHybridImag,
+    HYBRID *pHybrid,
+    Int32 scratch_mem[],
+    Int32 band);
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_HYBRID_ANALYSIS_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.cpp b/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.cpp
new file mode 100644
index 0000000..4ff2385
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.cpp
@@ -0,0 +1,213 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_hybrid_filter_bank_allocation.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Does Hybrid filter bank memory allocation
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+#include    "aac_mem_funcs.h"
+#include    "ps_hybrid_filter_bank_allocation.h"
+#include    "ps_all_pass_filter_coeff.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
+----------------------------------------------------------------------------*/
+
+Int32 ps_hybrid_filter_bank_allocation(HYBRID **phHybrid,
+                                       Int32 noBands,
+                                       const Int32 *pResolution,
+                                       Int32 **pPtr)
+{
+    Int32 i;
+    Int32 tmp;
+    Int32 maxNoChannels = 0;
+    HYBRID *hs;
+    Int32 *ptr = *pPtr;
+
+
+    *phHybrid = (HYBRID *)NULL;
+
+    hs = (HYBRID *)ptr;
+
+    ptr += sizeof(HYBRID) / sizeof(*ptr);
+
+    hs->pResolution = (Int32*)ptr;
+
+    ptr += noBands * sizeof(Int32) / sizeof(*ptr);
+
+    for (i = 0; i < noBands; i++)
+    {
+
+        hs->pResolution[i] = pResolution[i];
+
+        if (pResolution[i] != HYBRID_8_CPLX &&
+                pResolution[i] != HYBRID_2_REAL &&
+                pResolution[i] != HYBRID_4_CPLX)
+        {
+            return 1;
+        }
+
+        if (pResolution[i] > maxNoChannels)
+        {
+            maxNoChannels = pResolution[i];
+        }
+    }
+
+    hs->nQmfBands     = noBands;
+    hs->qmfBufferMove = HYBRID_FILTER_LENGTH - 1;
+
+    hs->mQmfBufferReal = (Int32 **)ptr;
+    ptr += noBands * sizeof(ptr) / sizeof(*ptr);
+
+    hs->mQmfBufferImag = (Int32 **)ptr;
+    ptr += noBands * sizeof(ptr) / sizeof(*ptr);
+
+    tmp = hs->qmfBufferMove;        /*  HYBRID_FILTER_LENGTH == 13 */
+
+    for (i = 0; i < noBands; i++)
+    {
+        hs->mQmfBufferReal[i] = ptr;
+        ptr += tmp;
+
+        hs->mQmfBufferImag[i] = ptr;
+        ptr += tmp;
+
+    }
+
+    hs->mTempReal = ptr;
+    ptr += maxNoChannels;
+
+
+    hs->mTempImag = ptr;
+    ptr += maxNoChannels;
+
+
+    *phHybrid = hs;
+    *pPtr = ptr;
+
+    return 0;
+}
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.h b/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.h
new file mode 100644
index 0000000..fbc0d80
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_filter_bank_allocation.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_hybrid_filter_bank_allocation.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for ps_hybrid_filter_bank_allocation
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_HYBRID_FILTER_BANK_ALLOCATION_H
+#define PS_HYBRID_FILTER_BANK_ALLOCATION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_hybrid.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int32 ps_hybrid_filter_bank_allocation(HYBRID **phHybrid,
+    Int32 noBands,
+    const Int32 *pResolution,
+    Int32 **pPtr);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_HYBRID_FILTER_BANK_ALLOCATION_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.cpp b/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.cpp
new file mode 100644
index 0000000..4fbd016
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_hybrid_synthesis.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Hybrid synthesis
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include "s_hybrid.h"
+#include "ps_hybrid_synthesis.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#ifndef min
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 ps_hybrid_synthesis(const Int32 *mHybridReal,
+                         const Int32 *mHybridImag,
+                         Int32 *mQmfReal,
+                         Int32 *mQmfImag,
+                         HYBRID *hHybrid)
+{
+    Int32  k;
+    Int32  band;
+    HYBRID_RES hybridRes;
+
+    Int32 real;
+    Int32 imag;
+    Int32 *ptr_mQmfReal = mQmfReal;
+    Int32 *ptr_mQmfImag = mQmfImag;
+    const Int32 *ptr_mHybrid_Re = mHybridReal;
+    const Int32 *ptr_mHybrid_Im = mHybridImag;
+
+    for (band = 0; band < hHybrid->nQmfBands; band++)
+    {
+        hybridRes = (HYBRID_RES)(min(hHybrid->pResolution[band], 6) - 2);
+
+        real  = *(ptr_mHybrid_Re++);
+        real += *(ptr_mHybrid_Re++);
+        imag  = *(ptr_mHybrid_Im++);
+        imag += *(ptr_mHybrid_Im++);
+
+        for (k = (hybridRes >> 1); k != 0; k--)    /*  hybridRes = { 2,4,6 }  */
+        {
+            real += *(ptr_mHybrid_Re++);
+            real += *(ptr_mHybrid_Re++);
+            imag += *(ptr_mHybrid_Im++);
+            imag += *(ptr_mHybrid_Im++);
+        }
+
+        *(ptr_mQmfReal++) = real;
+        *(ptr_mQmfImag++) = imag;
+    }
+}
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.h b/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.h
new file mode 100644
index 0000000..d7242dd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_hybrid_synthesis.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_hybrid_synthesis.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_hybrid_synthesis()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_HYBRID_SYNTHESIS_H
+#define PS_HYBRID_SYNTHESIS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_hybrid.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_hybrid_synthesis(const Int32 *mHybridReal,
+    const Int32 *mHybridImag,
+    Int32 *mQmfReal,
+    Int32 *mQmfImag,
+    HYBRID *hHybrid);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_HYBRID_SYNTHESIS_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.cpp b/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.cpp
new file mode 100644
index 0000000..7027b5c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.cpp
@@ -0,0 +1,496 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_init_stereo_mixing.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      initialize mixing procedure  type Ra, type Rb is not supported
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "pv_audio_type_defs.h"
+#include    "fxp_mul32.h"
+
+#include    "aac_mem_funcs.h"
+#include    "pv_sine.h"
+#include    "s_ps_dec.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_init_stereo_mixing.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
+----------------------------------------------------------------------------*/
+
+/*
+;
+;  c(b) = 10^(iid(b)/20)
+;
+;  Intensity differences
+;
+;                  sqrt(2)
+;   c_1(b) = ----------------
+;            sqrt( 1 + c^2(b))
+;
+;               sqrt(2)*c(b)
+;   c_2(b) = ----------------
+;            sqrt( 1 + c^2(b))
+;
+*/
+
+
+
+#define R_SHIFT     30
+#define Q30_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+const Int32 scaleFactors[NO_IID_LEVELS] =
+{
+    Q30_fmt(1.411983f),  Q30_fmt(1.403138f),  Q30_fmt(1.386877f),
+    Q30_fmt(1.348400f),  Q30_fmt(1.291249f),  Q30_fmt(1.196037f),
+    Q30_fmt(1.107372f),  Q30_fmt(1.000000f),  Q30_fmt(0.879617f),
+    Q30_fmt(0.754649f),  Q30_fmt(0.576780f),  Q30_fmt(0.426401f),
+    Q30_fmt(0.276718f),  Q30_fmt(0.176645f),  Q30_fmt(0.079402f)
+};
+
+const Int32 scaleFactorsFine[NO_IID_LEVELS_FINE] =
+{
+    Q30_fmt(1.414207f),  Q30_fmt(1.414191f),  Q30_fmt(1.414143f),
+    Q30_fmt(1.413990f),  Q30_fmt(1.413507f),  Q30_fmt(1.411983f),
+    Q30_fmt(1.409773f),  Q30_fmt(1.405395f),  Q30_fmt(1.396780f),
+    Q30_fmt(1.380053f),  Q30_fmt(1.348400f),  Q30_fmt(1.313920f),
+    Q30_fmt(1.264310f),  Q30_fmt(1.196037f),  Q30_fmt(1.107372f),
+    Q30_fmt(1.000000f),  Q30_fmt(0.879617f),  Q30_fmt(0.754649f),
+    Q30_fmt(0.633656f),  Q30_fmt(0.523081f),  Q30_fmt(0.426401f),
+    Q30_fmt(0.308955f),  Q30_fmt(0.221375f),  Q30_fmt(0.157688f),
+    Q30_fmt(0.111982f),  Q30_fmt(0.079402f),  Q30_fmt(0.044699f),
+    Q30_fmt(0.025145f),  Q30_fmt(0.014141f),  Q30_fmt(0.007953f),
+    Q30_fmt(0.004472f)
+};
+
+
+/*
+ *  alphas ranged between 0 and pi/2
+ *  alpha(b) = (1/2)*arccos( gamma(b))
+ *
+ *    b   0    1      2        3        4      5        6     7
+ *  gamma 1 0.937  0.84118  0.60092  0.36764   0    -0.589   -1
+ *
+ */
+
+
+
+const Int32 scaled_alphas[NO_ICC_LEVELS] =
+{
+    Q30_fmt(0.00000000000000f),  Q30_fmt(0.12616764875355f),
+    Q30_fmt(0.20199707286122f),  Q30_fmt(0.32744135137762f),
+    Q30_fmt(0.42225800677370f),  Q30_fmt(0.55536025173035f),
+    Q30_fmt(0.77803595530059f),  Q30_fmt(1.11072050346071f)
+};
+
+const Int32 cos_alphas[NO_ICC_LEVELS] =
+{
+    Q30_fmt(1.00000000000000f),  Q30_fmt(0.98412391153249f),
+    Q30_fmt(0.95947390717984f),  Q30_fmt(0.89468446298319f),
+    Q30_fmt(0.82693418207478f),  Q30_fmt(0.70710689672598f),
+    Q30_fmt(0.45332071670080f),  Q30_fmt(0.00000032679490f)
+};
+
+const Int32 sin_alphas[NO_ICC_LEVELS] =
+{
+    Q30_fmt(0.00000000000000f),  Q30_fmt(0.17748275057029f),
+    Q30_fmt(0.28179748302823f),  Q30_fmt(0.44669868110000f),
+    Q30_fmt(0.56229872711603f),  Q30_fmt(0.70710666564709f),
+    Q30_fmt(0.89134747871404f),  Q30_fmt(1.00000000000000f)
+};
+
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int32 ps_init_stereo_mixing(STRUCT_PS_DEC *pms,
+                            Int32 env,
+                            Int32 usb)
+{
+    Int32   group;
+    Int32   bin;
+    Int32   noIidSteps;
+    Int32   tmp;
+
+    Int32   invEnvLength;
+    const Int32  *pScaleFactors;
+    Int32   scaleR;
+    Int32   scaleL;
+    Int32   cos_alpha;
+    Int32   sin_alpha;
+    Int32   beta;
+    Int32   cos_beta;
+    Int32   sin_beta;
+    Int32   temp1;
+    Int32   temp2;
+    Int32   *ptr_tmp;
+    Int32   h11;
+    Int32   h12;
+    Int32   h21;
+    Int32   h22;
+
+    if (pms->bFineIidQ)
+    {
+        noIidSteps = NO_IID_STEPS_FINE;     /*  NO_IID_STEPS_FINE == 15  */
+        pScaleFactors = scaleFactorsFine;
+    }
+    else
+    {
+        noIidSteps = NO_IID_STEPS;          /*  NO_IID_STEPS == 7   */
+        pScaleFactors = scaleFactors;
+    }
+
+    if (env == 0)
+    {
+        pms->lastUsb = pms->usb;
+        pms->usb = usb;
+        if (usb != pms->lastUsb && pms->lastUsb != 0)
+        {
+            return(-1);
+
+        }
+    }
+
+    invEnvLength =  pms->aEnvStartStop[env + 1] - pms->aEnvStartStop[env];
+
+    if (invEnvLength == (Int32) pms->noSubSamples)
+    {
+        invEnvLength = pms->invNoSubSamples;
+    }
+    else
+    {
+        invEnvLength = Q30_fmt(1.0f) / invEnvLength;
+    }
+
+    if (invEnvLength == 32)     /*  more likely value  */
+    {
+        for (group = 0; group < NO_IID_GROUPS; group++)      /* == 22 */
+        {
+            bin = bins2groupMap[group];
+
+            /*
+             *  c(b) = 10^(iid(b)/20)
+             */
+
+            tmp = pms->aaIidIndex[env][bin];
+
+            /*
+             *  Intensity differences
+             *
+             *                  sqrt(2)
+             *   c_1(b) = ----------------
+             *            sqrt( 1 + c^2(b))
+             *
+             */
+            scaleR = pScaleFactors[noIidSteps + tmp];
+
+            /*
+             *               sqrt(2)*c(b)
+             *   c_2(b) = ----------------
+             *            sqrt( 1 + c^2(b))
+             *
+             */
+
+            scaleL = pScaleFactors[noIidSteps - tmp];
+
+
+            /*
+             *  alpha(b) = (1/2)*arccos( gamma(b))
+             */
+            tmp = pms->aaIccIndex[env][bin];
+
+            cos_alpha = cos_alphas[ tmp];
+            sin_alpha = sin_alphas[ tmp];
+
+            /*
+             *   beta(b) = alpha(b)/sqrt(2)*( c_1(b) - c_2(b))
+             */
+
+            beta   = fxp_mul32_Q30(scaled_alphas[ tmp], (scaleR - scaleL));
+
+            cos_beta = pv_cosine(beta);
+            sin_beta = pv_sine(beta);
+
+            temp1 = fxp_mul32_Q30(cos_beta, cos_alpha);
+            temp2 = fxp_mul32_Q30(sin_beta, sin_alpha);
+
+
+            /*
+             *  h11(b) = cos( alpha(b) +  beta(b))* c_2(b)
+             *  h12(b) = cos(  beta(b) - alpha(b))* c_1(b)
+             */
+
+            h11 = fxp_mul32_Q30(scaleL, (temp1 - temp2));
+            h12 = fxp_mul32_Q30(scaleR, (temp1 + temp2));
+
+            temp1 = fxp_mul32_Q30(sin_beta, cos_alpha);
+            temp2 = fxp_mul32_Q30(cos_beta, sin_alpha);
+
+            /*
+             *  h21(b) = sin( alpha(b) +  beta(b))* c_2(b)
+             *  h22(b) = sin(  beta(b) - alpha(b))* c_1(b)
+             */
+
+            h21 = fxp_mul32_Q30(scaleL, (temp1 + temp2));
+            h22 = fxp_mul32_Q30(scaleR, (temp1 - temp2));
+
+
+            /*
+             *   Linear interpolation
+             *
+             *                                       Hij(k, n_e+1) - Hij(k, n_e)
+             *    Hij(k,n) = Hij(k, n_e) + (n - n_e)*---------------------------
+             *                                              n_e+1 - n_e
+             */
+
+            ptr_tmp = &pms->h11Prev[group];
+            pms->H11[group]       = *ptr_tmp;
+            pms->deltaH11[group]  = (h11 - *ptr_tmp) >> 5;
+            *ptr_tmp              = h11;
+
+            ptr_tmp = &pms->h12Prev[group];
+            pms->H12[group]       = *ptr_tmp;
+            pms->deltaH12[group]  = (h12 - *ptr_tmp) >> 5;
+            *ptr_tmp              = h12;
+
+            ptr_tmp = &pms->h21Prev[group];
+            pms->H21[group]       = *ptr_tmp;
+            pms->deltaH21[group]  = (h21 - *ptr_tmp) >> 5;
+            *ptr_tmp              = h21;
+
+            ptr_tmp = &pms->h22Prev[group];
+            pms->H22[group]       = *ptr_tmp;
+            pms->deltaH22[group]  = (h22 - *ptr_tmp) >> 5;
+            *ptr_tmp              = h22;
+
+
+        } /* groups loop */
+    }
+    else
+    {
+
+        for (group = 0; group < NO_IID_GROUPS; group++)      /* == 22 */
+        {
+            bin = bins2groupMap[group];
+
+            /*
+             *  c(b) = 10^(iid(b)/20)
+             */
+
+            tmp = pms->aaIidIndex[env][bin];
+
+            /*
+             *  Intensity differences
+             *
+             *                  sqrt(2)
+             *   c_1(b) = ----------------
+             *            sqrt( 1 + c^2(b))
+             *
+             */
+            scaleR = pScaleFactors[noIidSteps + tmp];
+
+            /*
+             *               sqrt(2)*c(b)
+             *   c_2(b) = ----------------
+             *            sqrt( 1 + c^2(b))
+             *
+             */
+
+            scaleL = pScaleFactors[noIidSteps - tmp];
+
+
+            /*
+             *  alpha(b) = (1/2)*arccos( gamma(b))
+             */
+            tmp = pms->aaIccIndex[env][bin];
+
+            cos_alpha = cos_alphas[ tmp];
+            sin_alpha = sin_alphas[ tmp];
+
+            /*
+             *   beta(b) = alpha(b)/sqrt(2)*( c_1(b) - c_2(b))
+             */
+
+            beta   = fxp_mul32_Q30(scaled_alphas[ tmp], (scaleR - scaleL));
+
+            cos_beta = pv_cosine(beta);
+            sin_beta = pv_sine(beta);
+
+            temp1 = fxp_mul32_Q30(cos_beta, cos_alpha);
+            temp2 = fxp_mul32_Q30(sin_beta, sin_alpha);
+
+
+            /*
+             *  h11(b) = cos( alpha(b) +  beta(b))* c_2(b)
+             *  h12(b) = cos(  beta(b) - alpha(b))* c_1(b)
+             */
+
+            h11 = fxp_mul32_Q30(scaleL, (temp1 - temp2));
+            h12 = fxp_mul32_Q30(scaleR, (temp1 + temp2));
+
+            temp1 = fxp_mul32_Q30(sin_beta, cos_alpha);
+            temp2 = fxp_mul32_Q30(cos_beta, sin_alpha);
+
+            /*
+             *  h21(b) = sin( alpha(b) +  beta(b))* c_2(b)
+             *  h22(b) = sin(  beta(b) - alpha(b))* c_1(b)
+             */
+
+            h21 = fxp_mul32_Q30(scaleL, (temp1 + temp2));
+            h22 = fxp_mul32_Q30(scaleR, (temp1 - temp2));
+
+
+            /*
+             *   Linear interpolation
+             *
+             *                                       Hij(k, n_e+1) - Hij(k, n_e)
+             *    Hij(k,n) = Hij(k, n_e) + (n - n_e)*---------------------------
+             *                                              n_e+1 - n_e
+             */
+
+            ptr_tmp = &pms->h11Prev[group];
+            pms->deltaH11[group]  = fxp_mul32_Q30((h11 - *ptr_tmp), invEnvLength);
+            pms->H11[group]       = *ptr_tmp;
+            *ptr_tmp              = h11;
+
+            ptr_tmp = &pms->h12Prev[group];
+            pms->deltaH12[group]  = fxp_mul32_Q30((h12 - *ptr_tmp), invEnvLength);
+            pms->H12[group]       = *ptr_tmp;
+            *ptr_tmp              = h12;
+
+            ptr_tmp = &pms->h21Prev[group];
+            pms->deltaH21[group]  = fxp_mul32_Q30((h21 - *ptr_tmp), invEnvLength);
+            pms->H21[group]       = *ptr_tmp;
+            *ptr_tmp              = h21;
+
+            ptr_tmp = &pms->h22Prev[group];
+            pms->deltaH22[group]  = fxp_mul32_Q30((h22 - *ptr_tmp), invEnvLength);
+            pms->H22[group]       = *ptr_tmp;
+            *ptr_tmp              = h22;
+
+
+        } /* groups loop */
+    }
+
+
+    return (0);
+
+} /* END ps_init_stereo_mixing */
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.h b/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.h
new file mode 100644
index 0000000..6c30781
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_init_stereo_mixing.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_init_stereo_mixing.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions ps_init_stereo_mixing()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_INIT_STEREO_MIXING_H
+#define PS_INIT_STEREO_MIXING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int32 ps_init_stereo_mixing(STRUCT_PS_DEC *pms,
+    Int32 env,
+    Int32 usb);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_INIT_STEREO_MIXING_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.cpp b/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.cpp
new file mode 100644
index 0000000..a0e8c38
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.cpp
@@ -0,0 +1,340 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_pwr_transient_detection.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Decorrelation
+  Decorrelation is achieved by means of all-pass filtering and delaying
+  Sub-band samples s_k(n) are converted into de-correlated sub-bands samples
+  d_k(n). k index for frequency, n time index
+
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+  To handle transients and other fast time-envelopes, the output of the all
+  pass filters has to be attenuated at those signals.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "pv_audio_type_defs.h"
+#include    "s_ps_dec.h"
+#include    "aac_mem_funcs.h"
+#include    "ps_all_pass_filter_coeff.h"
+#include    "ps_pwr_transient_detection.h"
+
+#include    "fxp_mul32.h"
+#include    "pv_div.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+#ifndef min
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     29
+#define Q29_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Qfmt31(a)   (Int32)(-a*((Int32)1<<31) - 1 + (a>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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 ps_pwr_transient_detection(STRUCT_PS_DEC *h_ps_dec,
+                                Int32 *rIntBufferLeft,
+                                Int32 *iIntBufferLeft,
+                                Int32 aTransRatio[])
+{
+
+    Int32 sb;
+    Int32 maxsb;
+    Int32 gr;
+    Int32 bin;
+
+
+
+    Int32 *aLeftReal;
+    Int32 *aLeftImag;
+    Int32   temp_r;
+    Int32   temp_i;
+    Int32   accu;
+    Int32 *aPower = aTransRatio;
+    Quotient result;
+
+    Int32 nrg;
+    Int32 *ptr_aPrevNrg;
+    Int32 peakDiff;
+    Int32 *ptr_PrevPeakDiff;
+
+
+    aLeftReal = rIntBufferLeft;
+    aLeftImag = iIntBufferLeft;
+
+    /*
+     *  Input Power Matrix
+     *                            2
+     *  Power(i,n) = SUM | s_k(n)|
+     *                i
+     */
+
+    for (gr = SUBQMF_GROUPS; gr < NO_IID_GROUPS; gr++) /* 10 to 22  */
+    {
+        maxsb = min(h_ps_dec->usb, groupBorders[ gr+1]);
+
+        accu = 0;
+
+        for (sb = groupBorders[gr]; sb < maxsb; sb++)
+        {
+
+            temp_r = aLeftReal[sb];
+            temp_i = aLeftImag[sb];
+            accu =  fxp_mac32_Q31(accu, temp_r, temp_r);
+            accu =  fxp_mac32_Q31(accu, temp_i, temp_i);
+
+        } /* sb */
+        aPower[gr - 2] = accu >> 1;
+    } /* gr */
+
+    aLeftReal = h_ps_dec->mHybridRealLeft;
+    aLeftImag = h_ps_dec->mHybridImagLeft;
+
+
+    temp_r = aLeftReal[0];
+    temp_i = aLeftImag[0];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    accu  = fxp_mac32_Q31(accu, temp_i, temp_i);
+    temp_r = aLeftReal[5];
+    temp_i = aLeftImag[5];
+    accu   = fxp_mac32_Q31(accu, temp_r, temp_r);
+    aPower[0]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[1];
+    temp_i = aLeftImag[1];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    accu  = fxp_mac32_Q31(accu, temp_i, temp_i);
+    temp_r = aLeftReal[4];
+    temp_i = aLeftImag[4];
+    accu   = fxp_mac32_Q31(accu, temp_r, temp_r);
+    aPower[1]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[2];
+    temp_i = aLeftImag[2];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[2]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[3];
+    temp_i = aLeftImag[3];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[3]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+
+
+    temp_r = aLeftReal[6];
+    temp_i = aLeftImag[6];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[5]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[7];
+    temp_i = aLeftImag[7];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[4]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[8];
+    temp_i = aLeftImag[8];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[6]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+    temp_r = aLeftReal[9];
+    temp_i = aLeftImag[9];
+    accu   = fxp_mul32_Q31(temp_r, temp_r);
+    aPower[7]  = fxp_mac32_Q31(accu, temp_i, temp_i) >> 1;
+
+
+    /*
+     *  Power transient detection
+     */
+
+    ptr_aPrevNrg = h_ps_dec->aPrevNrg;
+
+    ptr_PrevPeakDiff = h_ps_dec->aPrevPeakDiff;
+
+    for (bin = 0; bin < NO_BINS; bin++) /* NO_BINS = 20  */
+    {
+
+        peakDiff  = *ptr_PrevPeakDiff;
+
+
+        /* PEAK_DECAY_FACTOR  0.765928338364649f @ 48 KHz  for Fs > 32 Khz */
+        accu = h_ps_dec->aPeakDecayFast[bin];
+        peakDiff -= peakDiff >> 2;
+
+        accu  = fxp_mul32_Q31(accu, Qfmt31(0.765928338364649f)) << 1;
+
+        if (accu < *aPower)
+        {
+            accu = *aPower;
+        }
+        else
+        {
+            peakDiff += ((accu - *aPower) >> 2);
+        }
+
+        h_ps_dec->aPeakDecayFast[bin] = accu;
+
+        *(ptr_PrevPeakDiff++) = peakDiff;
+
+        nrg =   *ptr_aPrevNrg + ((*aPower - *ptr_aPrevNrg) >> 2);
+
+        *(ptr_aPrevNrg++) = nrg;
+
+        peakDiff += peakDiff >> 1;         /* transient impact factor == 1.5 */
+
+        if (peakDiff <= nrg)
+        {
+            *(aPower++) = 0x7FFFFFFF;    /* in Q31  */
+        }
+        else
+        {
+            pv_div(nrg, peakDiff, &result);
+            *(aPower++) = (result.quotient >> (result.shift_factor)) << 1;    /* in Q31  */
+        }
+
+    } /* bin */
+
+}
+
+
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.h b/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.h
new file mode 100644
index 0000000..80a73a8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_pwr_transient_detection.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_pwr_transient_detection.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_pwr_transient_detection()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_PWR_TRANSIENT_DETECTION_H
+#define PS_PWR_TRANSIENT_DETECTION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_pwr_transient_detection(STRUCT_PS_DEC *h_ps_dec,
+    Int32 *rIntBufferLeft,
+    Int32 *iIntBufferLeft,
+    Int32 aTransRatio[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_PWR_TRANSIENT_DETECTION_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_read_data.cpp b/media/libstagefright/codecs/aacdec/ps_read_data.cpp
new file mode 100644
index 0000000..c49eb3d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_read_data.cpp
@@ -0,0 +1,388 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_read_data.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Decodes parametric stereo
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include    "pv_audio_type_defs.h"
+#include    "buf_getbits.h"
+#include    "s_bit_buffer.h"
+#include    "s_huffman.h"
+#include    "aac_mem_funcs.h"
+#include    "s_ps_dec.h"
+#include    "sbr_decode_huff_cw.h"
+#include    "ps_decode_bs_utils.h"
+#include    "ps_bstr_decoding.h"
+#include    "ps_read_data.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
+----------------------------------------------------------------------------*/
+
+/* IID & ICC Huffman codebooks */
+const Char aBookPsIidTimeDecode[28][2] =
+{
+    { -64,   1 },    { -65,   2 },    { -63,   3 },    { -66,   4 },
+    { -62,   5 },    { -67,   6 },    { -61,   7 },    { -68,   8 },
+    { -60,   9 },    { -69,  10 },    { -59,  11 },    { -70,  12 },
+    { -58,  13 },    { -57,  14 },    { -71,  15 },    {  16,  17 },
+    { -56, -72 },    {  18,  21 },    {  19,  20 },    { -55, -78 },
+    { -77, -76 },    {  22,  25 },    {  23,  24 },    { -75, -74 },
+    { -73, -54 },    {  26,  27 },    { -53, -52 },    { -51, -50 }
+};
+
+const Char aBookPsIidFreqDecode[28][2] =
+{
+    { -64,   1 },    {   2,   3 },    { -63, -65 },    {   4,   5 },
+    { -62, -66 },    {   6,   7 },    { -61, -67 },    {   8,   9 },
+    { -68, -60 },    { -59,  10 },    { -69,  11 },    { -58,  12 },
+    { -70,  13 },    { -71,  14 },    { -57,  15 },    {  16,  17 },
+    { -56, -72 },    {  18,  19 },    { -55, -54 },    {  20,  21 },
+    { -73, -53 },    {  22,  24 },    { -74,  23 },    { -75, -78 },
+    {  25,  26 },    { -77, -76 },    { -52,  27 },    { -51, -50 }
+};
+
+const Char aBookPsIccTimeDecode[14][2] =
+{
+    { -64,   1 },    { -63,   2 },    { -65,   3 },    { -62,   4 },
+    { -66,   5 },    { -61,   6 },    { -67,   7 },    { -60,   8 },
+    { -68,   9 },    { -59,  10 },    { -69,  11 },    { -58,  12 },
+    { -70,  13 },    { -71, -57 }
+};
+
+const Char aBookPsIccFreqDecode[14][2] =
+{
+    { -64,   1 },    { -63,   2 },    { -65,   3 },    { -62,   4 },
+    { -66,   5 },    { -61,   6 },    { -67,   7 },    { -60,   8 },
+    { -59,   9 },    { -68,  10 },    { -58,  11 },    { -69,  12 },
+    { -57,  13 },    { -70, -71 }
+};
+
+const Char aBookPsIidFineTimeDecode[60][2] =
+{
+    {   1, -64 },    { -63,   2 },    {   3, -65 },    {   4,  59 },
+    {   5,   7 },    {   6, -67 },    { -68, -60 },    { -61,   8 },
+    {   9,  11 },    { -59,  10 },    { -70, -58 },    {  12,  41 },
+    {  13,  20 },    {  14, -71 },    { -55,  15 },    { -53,  16 },
+    {  17, -77 },    {  18,  19 },    { -85, -84 },    { -46, -45 },
+    { -57,  21 },    {  22,  40 },    {  23,  29 },    { -51,  24 },
+    {  25,  26 },    { -83, -82 },    {  27,  28 },    { -90, -38 },
+    { -92, -91 },    {  30,  37 },    {  31,  34 },    {  32,  33 },
+    { -35, -34 },    { -37, -36 },    {  35,  36 },    { -94, -93 },
+    { -89, -39 },    {  38, -79 },    {  39, -81 },    { -88, -40 },
+    { -74, -54 },    {  42, -69 },    {  43,  44 },    { -72, -56 },
+    {  45,  52 },    {  46,  50 },    {  47, -76 },    { -49,  48 },
+    { -47,  49 },    { -87, -41 },    { -52,  51 },    { -78, -50 },
+    {  53, -73 },    {  54, -75 },    {  55,  57 },    {  56, -80 },
+    { -86, -42 },    { -48,  58 },    { -44, -43 },    { -66, -62 }
+};
+
+const Char aBookPsIidFineFreqDecode[60][2] =
+{
+    {   1, -64 },    {   2,   4 },    {   3, -65 },    { -66, -62 },
+    { -63,   5 },    {   6,   7 },    { -67, -61 },    {   8,   9 },
+    { -68, -60 },    {  10,  11 },    { -69, -59 },    {  12,  13 },
+    { -70, -58 },    {  14,  18 },    { -57,  15 },    {  16, -72 },
+    { -54,  17 },    { -75, -53 },    {  19,  37 },    { -56,  20 },
+    {  21, -73 },    {  22,  29 },    {  23, -76 },    {  24, -78 },
+    {  25,  28 },    {  26,  27 },    { -85, -43 },    { -83, -45 },
+    { -81, -47 },    { -52,  30 },    { -50,  31 },    {  32, -79 },
+    {  33,  34 },    { -82, -46 },    {  35,  36 },    { -90, -89 },
+    { -92, -91 },    {  38, -71 },    { -55,  39 },    {  40, -74 },
+    {  41,  50 },    {  42, -77 },    { -49,  43 },    {  44,  47 },
+    {  45,  46 },    { -86, -42 },    { -88, -87 },    {  48,  49 },
+    { -39, -38 },    { -41, -40 },    { -51,  51 },    {  52,  59 },
+    {  53,  56 },    {  54,  55 },    { -35, -34 },    { -37, -36 },
+    {  57,  58 },    { -94, -93 },    { -84, -44 },    { -80, -48 }
+};
+
+
+
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Int32 ps_read_data(STRUCT_PS_DEC *ps_dec,
+                   BIT_BUFFER * hBitBuf,
+                   Int32 nBitsLeft)
+
+{
+    Int     gr;
+    UInt32     env;
+    UInt32     dtFlag;
+    Int32     startbits;
+    SbrHuffman CurrentTable;
+
+    if (!ps_dec)
+    {
+        return 0;
+    }
+
+    startbits = GetNrBitsAvailable(hBitBuf);
+
+    if (buf_get_1bit(hBitBuf))  /*  Enable Header */
+    {
+        ps_dec->bEnableIid = buf_get_1bit(hBitBuf);
+
+        if (ps_dec->bEnableIid)
+        {
+            ps_dec->freqResIid = buf_getbits(hBitBuf, 3);
+
+            if (ps_dec->freqResIid > 2)
+            {
+                ps_dec->bFineIidQ = 1;
+                ps_dec->freqResIid -= 3;
+            }
+            else
+            {
+                ps_dec->bFineIidQ = 0;
+            }
+        }
+
+        ps_dec->bEnableIcc = buf_get_1bit(hBitBuf);
+        if (ps_dec->bEnableIcc)
+        {
+            ps_dec->freqResIcc = buf_getbits(hBitBuf, 3);
+
+            if (ps_dec->freqResIcc > 2)
+            {
+                ps_dec->freqResIcc -= 3;
+            }
+        }
+        ps_dec->bEnableExt = buf_get_1bit(hBitBuf);
+    }
+
+    ps_dec->bFrameClass = buf_get_1bit(hBitBuf);
+    if (ps_dec->bFrameClass == 0)
+    {
+        ps_dec->noEnv = aFixNoEnvDecode[ buf_getbits(hBitBuf, 2)];
+    }
+    else
+    {
+        ps_dec->noEnv = 1 + buf_getbits(hBitBuf, 2);
+        for (env = 1; env < ps_dec->noEnv + 1; env++)
+        {
+            ps_dec->aEnvStartStop[env] = (buf_getbits(hBitBuf, 5)) + 1;
+        }
+    }
+
+    if ((ps_dec->freqResIid > 2) || (ps_dec->freqResIcc > 2))
+    {
+
+        ps_dec->bPsDataAvail = 0;
+
+        nBitsLeft -= startbits - GetNrBitsAvailable(hBitBuf);
+        while (nBitsLeft)
+        {
+            int i = nBitsLeft;
+            if (i > 8)
+            {
+                i = 8;
+            }
+            buf_getbits(hBitBuf, i);
+            nBitsLeft -= i;
+        }
+        return (startbits - GetNrBitsAvailable(hBitBuf));
+    }
+
+    if (ps_dec->bEnableIid)
+    {
+        for (env = 0; env < ps_dec->noEnv; env++)
+        {
+            dtFlag = buf_get_1bit(hBitBuf);
+
+            if (!dtFlag)
+            {
+                if (ps_dec->bFineIidQ)
+                {
+                    CurrentTable = aBookPsIidFineFreqDecode;
+                }
+                else
+                {
+                    CurrentTable = aBookPsIidFreqDecode;
+                }
+            }
+            else
+            {
+                if (ps_dec->bFineIidQ)
+                {
+                    CurrentTable = aBookPsIidFineTimeDecode;
+                }
+                else
+                {
+                    CurrentTable = aBookPsIidTimeDecode;
+                }
+            }
+
+            for (gr = 0; gr < aNoIidBins[ps_dec->freqResIid]; gr++)
+            {
+                ps_dec->aaIidIndex[env][gr] = sbr_decode_huff_cw(CurrentTable, hBitBuf);
+            }
+
+            ps_dec->abIidDtFlag[env] = dtFlag;
+        }
+    }
+
+    if (ps_dec->bEnableIcc)
+    {
+        for (env = 0; env < ps_dec->noEnv; env++)
+        {
+            dtFlag = buf_get_1bit(hBitBuf);
+            if (!dtFlag)
+            {
+                CurrentTable = aBookPsIccFreqDecode;
+            }
+            else
+            {
+                CurrentTable = aBookPsIccTimeDecode;
+            }
+            for (gr = 0; gr < aNoIccBins[ps_dec->freqResIcc]; gr++)
+            {
+                ps_dec->aaIccIndex[env][gr] = sbr_decode_huff_cw(CurrentTable, hBitBuf);
+            }
+
+            ps_dec->abIccDtFlag[env] = dtFlag;
+        }
+    }
+
+    if (ps_dec->bEnableExt)
+    {
+
+        int cnt;
+
+        cnt = (int)buf_getbits(hBitBuf, 4);
+
+        if (cnt == 15)
+        {
+            cnt += (int)buf_getbits(hBitBuf, 8);
+        }
+
+        hBitBuf->nrBitsRead += (cnt << 3);
+    }
+
+    ps_dec->bPsDataAvail = 1;
+
+    return (startbits - GetNrBitsAvailable(hBitBuf));
+}
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_read_data.h b/media/libstagefright/codecs/aacdec/ps_read_data.h
new file mode 100644
index 0000000..e2fec53
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_read_data.h
@@ -0,0 +1,100 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_read_data.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for functions ps_read_data()
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_READ_DATA_H
+#define PS_READ_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+#define EXTENSION_ID_PS_CODING   2
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int32 ps_read_data(STRUCT_PS_DEC *ps_dec,
+    BIT_BUFFER * hBitBuf,
+    Int32 nBitsLeft);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_READ_DATA_H */
diff --git a/media/libstagefright/codecs/aacdec/ps_stereo_processing.cpp b/media/libstagefright/codecs/aacdec/ps_stereo_processing.cpp
new file mode 100644
index 0000000..813b55d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_stereo_processing.cpp
@@ -0,0 +1,372 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: ps_stereo_processing.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Stereo Process or reconstruction
+
+           l_k(n) = H11(k,n)*s_k(n) + H21(k,n)*d_k(n)
+
+           r_k(n) = H12(k,n)*s_k(n) + H22(k,n)*d_k(n)
+
+     _______                                              ________
+    |       |                                  _______   |        |
+  ->|Hybrid | LF ----                         |       |->| Hybrid |-->
+    | Anal. |        |                        |       |  | Synth  |   QMF -> L
+     -------         o----------------------->|       |   --------    Synth
+QMF                  |                s_k(n)  |Stereo |-------------->
+Anal.              -------------------------->|       |
+     _______       | |                        |       |   ________
+    |       | HF --o |   -----------          |Process|  |        |
+  ->| Delay |      |  ->|           |-------->|       |->| Hybrid |-->
+     -------       |    |decorrelate| d_k(n)  |       |  | Synth  |   QMF -> R
+                   ---->|           |-------->|       |   --------    Synth
+                         -----------          |_______|-------------->
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+#include    "pv_audio_type_defs.h"
+#include    "ps_stereo_processing.h"
+#include    "fxp_mul32.h"
+#include    "ps_all_pass_filter_coeff.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+#ifndef min
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 ps_stereo_processing(STRUCT_PS_DEC  *pms,
+                          Int32          *qmfLeftReal,
+                          Int32          *qmfLeftImag,
+                          Int32          *qmfRightReal,
+                          Int32          *qmfRightImag)
+{
+    Int32     group;
+    Int32     subband;
+    Int32     maxSubband;
+    Int32     usb;
+    Char     index;
+
+
+    Int32  *hybrLeftReal;
+    Int32  *hybrLeftImag;
+    Int32  *hybrRightReal;
+    Int32  *hybrRightImag;
+    Int32  *ptr_hybrLeftReal;
+    Int32  *ptr_hybrLeftImag;
+    Int32  *ptr_hybrRightReal;
+    Int32  *ptr_hybrRightImag;
+
+
+    Int16   h11;
+    Int16   h12;
+    Int16   h21;
+    Int16   h22;
+
+    Int32   temp1;
+    Int32   temp2;
+    Int32   temp3;
+
+    usb = pms->usb;
+
+    /*
+     *   Complete Linear interpolation
+     */
+
+    hybrLeftReal  = pms->mHybridRealLeft;
+    hybrLeftImag  = pms->mHybridImagLeft;
+    hybrRightReal = pms->mHybridRealRight;
+    hybrRightImag = pms->mHybridImagRight;
+
+    for (group = 0; group < SUBQMF_GROUPS; group++)     /* SUBQMF_GROUPS == 10 */
+    {
+
+        temp1 = pms->deltaH11[group];
+        temp2 = pms->deltaH12[group];
+
+        pms->H11[group]  += temp1;
+        h11  = (Int16)(pms->H11[group] >> 16);
+        pms->H12[group]  += temp2;
+        h12  = (Int16)(pms->H12[group] >> 16);
+
+        temp1 = pms->deltaH21[group];
+        temp2 = pms->deltaH22[group];
+
+        pms->H21[group]  += temp1;
+        h21  = (Int16)(pms->H21[group] >> 16);
+        pms->H22[group]  += temp2;
+        h22  = (Int16)(pms->H22[group] >> 16);
+
+        index = groupBorders[group];
+
+        /*
+         *  Reconstruction of Stereo sub-band signal
+         *
+         *  l_k(n) = H11(k,n)*s_k(n) + H21(k,n)*d_k(n)
+         *
+         *  r_k(n) = H12(k,n)*s_k(n) + H22(k,n)*d_k(n)
+         */
+        ptr_hybrLeftReal  = &hybrLeftReal[  index];
+        ptr_hybrRightReal = &hybrRightReal[ index];
+
+        temp1 = *(ptr_hybrLeftReal) << 1;
+        temp2 = *(ptr_hybrRightReal) << 1;
+
+        temp3 = fxp_mul32_by_16(temp1, h11);
+        *(ptr_hybrLeftReal)  = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+        temp3 = fxp_mul32_by_16(temp1, h12);
+        *(ptr_hybrRightReal) = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+
+
+        ptr_hybrLeftImag  = &hybrLeftImag[  index];
+        ptr_hybrRightImag = &hybrRightImag[ index];
+
+        temp1 = *(ptr_hybrLeftImag) << 1;
+        temp2 = *(ptr_hybrRightImag) << 1;
+
+        temp3 = fxp_mul32_by_16(temp1, h11);
+        *(ptr_hybrLeftImag)  = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+        temp3 = fxp_mul32_by_16(temp1, h12);
+        *(ptr_hybrRightImag) = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+
+
+    } /* groups loop */
+
+    temp1 = pms->deltaH11[SUBQMF_GROUPS];
+    temp2 = pms->deltaH12[SUBQMF_GROUPS];
+
+    pms->H11[SUBQMF_GROUPS]  += temp1;
+    h11  = (Int16)(pms->H11[SUBQMF_GROUPS] >> 16);
+    pms->H12[SUBQMF_GROUPS]  += temp2;
+    h12  = (Int16)(pms->H12[SUBQMF_GROUPS] >> 16);
+
+    temp1 = pms->deltaH21[SUBQMF_GROUPS];
+    temp2 = pms->deltaH22[SUBQMF_GROUPS];
+
+    pms->H21[SUBQMF_GROUPS]  += temp1;
+    h21  = (Int16)(pms->H21[SUBQMF_GROUPS] >> 16);
+    pms->H22[SUBQMF_GROUPS]  += temp2;
+    h22  = (Int16)(pms->H22[SUBQMF_GROUPS] >> 16);
+
+
+    ptr_hybrLeftReal  = &qmfLeftReal[  3];
+    ptr_hybrRightReal = &qmfRightReal[ 3];
+
+    /*
+     *  Reconstruction of Stereo sub-band signal
+     *
+     *  l_k(n) = H11(k,n)*s_k(n) + H21(k,n)*d_k(n)
+     *
+     *  r_k(n) = H12(k,n)*s_k(n) + H22(k,n)*d_k(n)
+     */
+    temp1 = *(ptr_hybrLeftReal) << 1;
+    temp2 = *(ptr_hybrRightReal) << 1;
+
+
+    temp3 = fxp_mul32_by_16(temp1, h11);
+    *(ptr_hybrLeftReal)  = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+    temp3 = fxp_mul32_by_16(temp1, h12);
+    *(ptr_hybrRightReal)  = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+
+    ptr_hybrLeftImag  = &qmfLeftImag[  3];
+    ptr_hybrRightImag = &qmfRightImag[ 3];
+
+
+    temp1 = *(ptr_hybrLeftImag) << 1;
+    temp2 = *(ptr_hybrRightImag) << 1;
+
+    temp3 = fxp_mul32_by_16(temp1, h11);
+    *(ptr_hybrLeftImag)  = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+    temp3 = fxp_mul32_by_16(temp1, h12);
+    *(ptr_hybrRightImag)  = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+
+
+    for (group = SUBQMF_GROUPS + 1; group < NO_IID_GROUPS; group++)   /* 11 to NO_IID_GROUPS == 22 */
+    {
+        temp1 = pms->deltaH11[group];
+        temp2 = pms->deltaH12[group];
+
+        pms->H11[group]  += temp1;
+        h11  = (Int16)(pms->H11[group] >> 16);
+        pms->H12[group]  += temp2;
+        h12  = (Int16)(pms->H12[group] >> 16);
+
+        temp1 = pms->deltaH21[group];
+        temp2 = pms->deltaH22[group];
+
+        pms->H21[group]  += temp1;
+        h21  = (Int16)(pms->H21[group] >> 16);
+        pms->H22[group]  += temp2;
+        h22  = (Int16)(pms->H22[group] >> 16);
+
+        index = groupBorders[group];
+        maxSubband = groupBorders[group + 1];
+        maxSubband = min(usb, maxSubband);
+
+        /*
+         *  Reconstruction of Stereo sub-band signal
+         *
+         *  l_k(n) = H11(k,n)*s_k(n) + H21(k,n)*d_k(n)
+         *
+         *  r_k(n) = H12(k,n)*s_k(n) + H22(k,n)*d_k(n)
+         */
+
+        ptr_hybrLeftReal  = &qmfLeftReal[  index];
+        ptr_hybrRightReal = &qmfRightReal[ index];
+
+        for (subband = index; subband < maxSubband; subband++)
+        {
+            temp1 = *(ptr_hybrLeftReal) << 1;
+            temp2 = *(ptr_hybrRightReal) << 1;
+            temp3 = fxp_mul32_by_16(temp1, h11);
+            *(ptr_hybrLeftReal++)   = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+            temp3 = fxp_mul32_by_16(temp1, h12);
+            *(ptr_hybrRightReal++)  = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+        }
+
+        ptr_hybrLeftImag  = &qmfLeftImag[  index];
+        ptr_hybrRightImag = &qmfRightImag[ index];
+
+        for (subband = index; subband < maxSubband; subband++)
+        {
+            temp1 = *(ptr_hybrLeftImag) << 1;
+            temp2 = *(ptr_hybrRightImag) << 1;
+            temp3 = fxp_mul32_by_16(temp1, h11);
+            *(ptr_hybrLeftImag++)   = fxp_mac32_by_16(temp2, h21, temp3) << 1;
+
+            temp3 = fxp_mul32_by_16(temp1, h12);
+            *(ptr_hybrRightImag++)  = fxp_mac32_by_16(temp2, h22, temp3) << 1;
+
+        } /* subband loop */
+
+    } /* groups loop */
+
+} /* END ps_stereo_processing */
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/ps_stereo_processing.h b/media/libstagefright/codecs/aacdec/ps_stereo_processing.h
new file mode 100644
index 0000000..58b025a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/ps_stereo_processing.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ps_stereo_processing.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for function ps_stereo_processing()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PS_STEREO_PROCESSING_H
+#define PS_STEREO_PROCESSING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_ps_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void ps_stereo_processing(STRUCT_PS_DEC  *pms,
+    Int32          *qmfLeftReal,
+    Int32          *qmfLeftImag,
+    Int32          *qmfRightReal,
+    Int32          *qmfRightImag);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* PS_STEREO_PROCESSING_H */
diff --git a/media/libstagefright/codecs/aacdec/pulse_nc.cpp b/media/libstagefright/codecs/aacdec/pulse_nc.cpp
new file mode 100644
index 0000000..87b264d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pulse_nc.cpp
@@ -0,0 +1,298 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pulse_nc.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Modified to pass variables by reference to eliminate use
+               of global variables.
+
+ Description:  Modified to bring code in-line with PV standards.
+
+ Description: Pass in max as input argument.
+
+ Description: Went back to the if-statement to check for max.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    coef[]         =  Array of quantized spectral coefficents.
+                      (Int [])
+
+    pPulseInfo     =  Pointer to structure which contains noiseless
+                      encoding info, includes information about the pulse data,
+                      pulse amplitude, etc.
+                      (const PulseInfo *)
+
+    pLongFrameInfo =  Pointer to structure that holds information about
+                      each group. (long block flag, number of windows,
+                      scalefactor bands per group, etc.)
+
+                      Variable is named (pLongFrameInfo) because this function
+                      is only used for LONG windows.
+                      (FrameInfo *)
+    max             = Pointer to the maximum value of coef[]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coef[]  =  coefficient contents are modified by the encoded pulse
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function adds pulses to defined ranges of coefficients in the window,
+ for the case of LONG windows.  The pulses are unsigned, so
+ negative coefficients subtract the pulse, and positive coefficients add it.
+ (The ampltiude of the coefficient is always increased by the pulse)
+
+ A maximum of 4 coefficients may be modified by a pulse, and these
+ coefficients must all occur in the same scalefactor band.
+
+ The number of pulse-encoded coefficients to be processed by this function
+ is communicated to this function via pPulseInfo->number_pulse
+
+ This value is equal to the actual number of pulses - 1.
+ (e.g if pPulseInfo->number_pulse == 0, one pulse is assumed)
+ This function must not be called if no pulse encoded data exists.
+ The function assumes that at least one pulse exists.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This module shall correctly add transmitted pulse(s) to the correct
+ coefficients in a LONG window.
+
+------------------------------------------------------------------------------
+ REFERENCES
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.3.3 Decoding Process
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    index = pLongFrameInfo->win_sfb_top[0][pPulseInfo->pulse_start_sfb];
+
+    pPulseOffset = &(pPulseInfo->pulse_offset[0]);
+
+    pPulseAmp    = &(pPulseInfo->pulse_amp[0]);
+
+    pCoef        = &(Coef[index]);
+
+    FOR (index = pPulseInfo->number_pulse; index >= 0; index--)
+
+        pCoef   = pCoef + *(pPulseOffset);
+        pPulseOffset = pPulseOffset + 1;
+
+        IF (*pCoef > 0)
+            *(pCoef) = *(pCoef) + *(pPulseAmp);
+            pPulseAmp     = pPulseAmp + 1;
+        ELSE
+            *(pCoef) = *(pCoef) - *(pPulseAmp);
+            pPulseAmp     = pPulseAmp + 1;
+        ENDIF
+
+    ENDFOR
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+#include "s_pulseinfo.h"
+#include "pulse_nc.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 pulse_nc(
+    Int16      coef[],
+    const PulseInfo  *pPulseInfo,
+    const FrameInfo  *pLongFrameInfo,
+    Int      *max)
+{
+    Int index;
+
+    Int16 *pCoef;
+    Int temp;
+
+    const Int *pPulseOffset;
+    const Int *pPulseAmp;
+
+    /*--- Find the scalefactor band where pulse-encoded data starts ---*/
+
+    if (pPulseInfo->pulse_start_sfb > 0)
+    {
+        index = pLongFrameInfo->win_sfb_top[0][pPulseInfo->pulse_start_sfb - 1];
+    }
+    else
+    {
+        index = 0;
+    }
+
+    /*-------------------------------------------------------------------------
+      Each pulse index is stored as an offset from the previous pulse
+
+      Example - here we have a sfb that is 20 coefficients in length:
+
+      [0][1][2][3][4][5][6][7][8][9][10][11][12][13][14][15][16][17][18][19]
+      [ ][ ][ ][ ][ ][P][P][ ][ ][ ][  ][  ][  ][  ][  ][ P][  ][  ][  ][ P]
+
+      The array pointed to by pPulseOffset == [5][1][9][4]
+
+      pPulseAmp is of the same length as pPulseOffset, and contains
+      an individual pulse amplitude for each coefficient.
+    --------------------------------------------------------------------------*/
+
+    pCoef        = &(coef[index]);
+
+    pPulseOffset = &(pPulseInfo->pulse_offset[0]);
+
+    pPulseAmp    = &(pPulseInfo->pulse_amp[0]);
+
+    for (index = pPulseInfo->number_pulse; index > 0; index--)
+    {
+        pCoef  += *pPulseOffset++;
+
+        temp = *pCoef;
+
+        if (temp > 0)
+        {
+            temp += *(pPulseAmp++);
+            *pCoef = (Int16)temp;
+            if (temp > *max)
+            {
+                *max = temp;
+            }
+        }
+        else
+        {
+            temp -= *(pPulseAmp++);
+            *pCoef = (Int16)temp;
+            if (-temp > *max)
+            {
+                *max = -temp;
+            }
+        }
+
+    } /* for() */
+
+    return;
+
+} /* pulse_nc */
diff --git a/media/libstagefright/codecs/aacdec/pulse_nc.h b/media/libstagefright/codecs/aacdec/pulse_nc.h
new file mode 100644
index 0000000..8181dd0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pulse_nc.h
@@ -0,0 +1,104 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pulse_nc.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Pass in max as input argument.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the global function declaration for pulse_nc
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PULSE_NC_H
+#define PULSE_NC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+#include "s_pulseinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pulse_nc(
+        Int16        coef[],
+        const PulseInfo  *pPulseInfo,
+        const FrameInfo  *pLongFrameInfo,
+        Int      *max);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pv_audio_type_defs.h b/media/libstagefright/codecs/aacdec/pv_audio_type_defs.h
new file mode 100644
index 0000000..dee66bc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_audio_type_defs.h
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ Pathname: ./c/include/pv_audio_type_defs.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Removed errant semicolons from #define statements
+
+ Description:
+        1. Modified ifndef STD_TYPE_DEFS_H with
+           #ifndef PV_AUDIO_TYPE_DEFS_H to avoid double definition
+               if file was already included
+        2. Merged cai if-def structures and C++ definition
+            3. Updated copyright notice
+
+ Description:  Added dependency on OSCL libraries
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file was derived from a number of standards bodies. The type
+ definitions below were created from some of the best practices observed
+ in the standards bodies.
+
+ This file is dependent on limits.h for defining the bit widths. In an
+ ANSI C environment limits.h is expected to always be present and contain
+ the following definitions:
+
+     SCHAR_MIN
+     SCHAR_MAX
+     UCHAR_MAX
+
+     INT_MAX
+     INT_MIN
+     UINT_MAX
+
+     SHRT_MIN
+     SHRT_MAX
+     USHRT_MAX
+
+     LONG_MIN
+     LONG_MAX
+     ULONG_MAX
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_AUDIO_TYPE_DEFS_H
+#define PV_AUDIO_TYPE_DEFS_H
+
+#include <stdint.h>
+
+typedef int8_t        Char;
+
+typedef uint8_t       UChar;
+
+
+
+/*----------------------------------------------------------------------------
+; Define generic signed and unsigned int
+----------------------------------------------------------------------------*/
+#ifndef Int
+typedef signed int  Int;
+#endif
+
+#ifndef UInt
+typedef unsigned int    UInt;
+#endif
+
+
+/*----------------------------------------------------------------------------
+; Define 16 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+
+#ifndef Int16
+typedef int16_t       Int16;
+#endif
+
+#ifndef INT16_MIN
+#define INT16_MIN   (-32768)
+#endif
+
+#ifndef INT16_MAX
+#define INT16_MAX   32767
+#endif
+
+#ifndef UInt16
+typedef uint16_t      UInt16;
+
+#endif
+
+
+/*----------------------------------------------------------------------------
+; Define 32 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+
+#ifndef Int32
+typedef int32_t       Int32;
+#endif
+
+#ifndef INT32_MIN
+#define INT32_MIN   (-2147483647 - 1)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX   2147483647
+#endif
+
+#ifndef UInt32
+typedef uint32_t      UInt32;
+#endif
+
+#ifndef UINT32_MIN
+#define UINT32_MIN  0
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX  0xffffffff
+#endif
+
+
+/*----------------------------------------------------------------------------
+; Define 64 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Define boolean type
+----------------------------------------------------------------------------*/
+#ifndef Bool
+typedef Int     Bool;
+#endif
+#ifndef FALSE
+#define FALSE       0
+#endif
+
+#ifndef TRUE
+#define TRUE        1
+#endif
+
+#ifndef OFF
+#define OFF     0
+#endif
+#ifndef ON
+#define ON      1
+#endif
+
+#ifndef NO
+#define NO      0
+#endif
+#ifndef YES
+#define YES     1
+#endif
+
+#ifndef SUCCESS
+#define SUCCESS     0
+#endif
+
+#ifndef  NULL
+#define  NULL       0
+#endif
+
+
+#endif  /* PV_AUDIO_TYPE_DEFS_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_div.cpp b/media/libstagefright/codecs/aacdec/pv_div.cpp
new file mode 100644
index 0000000..86d2487
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_div.cpp
@@ -0,0 +1,188 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_div.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer numerator
+    Int32 y             32-bit integer denominator
+    Quotient *result    structure that hold result and shift factor
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement division of two Int32 numbers, provides back quotient and a
+    shift factor
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+
+#include "pv_audio_type_defs.h"
+#include "fxp_mul32.h"
+#include "pv_div.h"
+#include "pv_normalize.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 pv_div(Int32 x, Int32 y, Quotient *result)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Int32 quotient;
+    Int32 i;
+    Int32 j;
+    Int32 y_ov_y_hi;
+    Int32 flag = 0;     /* carries negative sign, if any  */
+
+
+    result->shift_factor = 0;   /* default  */
+
+    if (y == 0)
+    {
+        x = 0;   /* this will return 0 for any div/0 */
+    }
+    /*
+     *  make sure x and y are both positive
+     */
+
+    if (y < 0)
+    {
+        y = -y;
+        flag ^= 1;
+    }
+
+
+    if (x < 0)
+    {
+        x = -x;
+        flag ^= 1;
+    }
+
+    if (x != 0)
+    {
+        /*----------------------------------------------------------------------------
+        ; Scale the input to get maximum precision for x
+        ----------------------------------------------------------------------------*/
+
+        i = pv_normalize(x);
+
+        x <<= i;
+
+
+        /*----------------------------------------------------------------------------
+        ; Scale the input to get maximum precision for y
+        ----------------------------------------------------------------------------*/
+
+        j = pv_normalize(y);
+
+        y <<= j;
+
+        result->shift_factor = i - j;
+
+        /*----------------------------------------------------------------------------
+        ; Function body here
+        ----------------------------------------------------------------------------*/
+        /*---------------------------------------------------------------
+         ; take the inverse of the 16 MSB of y
+         ---------------------------------------------------------------*/
+
+        quotient = (0x40000000 / (y >> 15));
+
+        y_ov_y_hi = fxp_mul32_Q15(y, quotient);            /*  y*(1/y_hi)     */
+
+        y_ov_y_hi = 0x7FFFFFFF - y_ov_y_hi;                 /*  2 - y*(1/y_hi) */
+        y_ov_y_hi = fxp_mul32_Q14(quotient,  y_ov_y_hi);
+        i  = fxp_mul32_Q31(y_ov_y_hi,  x) << 1;
+
+        result->quotient = flag ? -i : i;
+    }
+    else
+    {
+        result->quotient = 0;
+    }
+
+
+
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pv_div.h b/media/libstagefright/codecs/aacdec/pv_div.h
new file mode 100644
index 0000000..2dfa8a0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_div.h
@@ -0,0 +1,74 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pv_div.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_DIV_H
+#define PV_DIV_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    struct intg_div
+    {
+        Int32 quotient;
+        Int32 shift_factor;
+    };
+    typedef struct intg_div Quotient;
+
+
+    void pv_div(Int32 x, Int32 y, Quotient *quotient);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PV_DIV_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_log2.cpp b/media/libstagefright/codecs/aacdec/pv_log2.cpp
new file mode 100644
index 0000000..69cbe91
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_log2.cpp
@@ -0,0 +1,168 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_log2.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer input
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement the logarithm base 2 of a number
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "pv_log2.h"
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     20
+#define Q_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+const Int32 log_table[9] =
+{
+    Q_fmt(-0.00879832091331F),  Q_fmt(0.12022974263833F),
+    Q_fmt(-0.72883958314294F),  Q_fmt(2.57909824242332F),
+    Q_fmt(-5.90041216630330F),  Q_fmt(9.15023342527264F),
+    Q_fmt(-9.90616619500413F),  Q_fmt(8.11228968755409F),
+    Q_fmt(-3.41763474309898F)
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+
+Int32 pv_log2(Int32 z)
+{
+    const Int32 *pt_table = log_table;
+    Int32 y;
+    Int32 i;
+
+    Int32 int_log2 = 0;
+
+    if (z > Q_fmt(2.0f))
+    {
+        while (z > Q_fmt(2.0f))
+        {
+            z >>= 1;
+            int_log2++;
+        }
+    }
+    else if (z < Q_fmt(1.0f))
+    {
+        {
+            while (z < Q_fmt(1.0f))
+            {
+                z <<= 1;
+                int_log2--;
+            }
+        }
+    }
+
+    /*
+     *  at this point, input limited to 1<x<2
+     */
+
+    if (z != Q_fmt(1.0f))
+    {
+        y  = fxp_mul32_Q20(*(pt_table++), z);
+
+        for (i = 7; i != 0; i--)
+        {
+            y += *(pt_table++);
+            y  = fxp_mul32_Q20(y, z);
+        }
+
+        y += *(pt_table++);
+    }
+    else
+    {
+        y = 0;
+    }
+
+
+    return (y + (int_log2 << 20));         /* Q20 */
+}
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/pv_log2.h b/media/libstagefright/codecs/aacdec/pv_log2.h
new file mode 100644
index 0000000..4834e82
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_log2.h
@@ -0,0 +1,69 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pv_log2.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_LOG2_H
+#define PV_LOG2_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    Int32 pv_log2(Int32 z);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PV_LOG2_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_normalize.cpp b/media/libstagefright/codecs/aacdec/pv_normalize.cpp
new file mode 100644
index 0000000..365b5ad
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_normalize.cpp
@@ -0,0 +1,167 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_normalize.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    Int32 x             32-bit integer non-zero input
+Returns
+    Int32 i             number of leading zeros on x
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns number of leading zeros on the non-zero input
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+#include "pv_normalize.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
+----------------------------------------------------------------------------*/
+
+#if defined(_ARM)
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+/* function is inlined in header file */
+
+
+#else
+
+Int pv_normalize(Int32 x)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Int i;
+
+
+    if (x > 0x0FFFFFFF)
+    {
+        i = 0;  /* most likely case */
+    }
+    else if (x > 0x00FFFFFF)
+    {
+        i = 3;  /* second most likely case */
+    }
+    else if (x > 0x0000FFFF)
+    {
+        i  = x > 0x000FFFFF ?  7 :  11;
+    }
+    else
+    {
+        if (x > 0x000000FF)
+        {
+            i  = x > 0x00000FFF ?  15 :  19;
+        }
+        else
+        {
+            i  = x > 0x0000000F ?  23 :  27;
+        }
+    }
+
+
+    x <<= i;
+
+    switch (x & 0x78000000)
+    {
+        case 0x08000000:
+            i += 3;
+            break;
+
+        case 0x18000000:
+        case 0x10000000:
+            i += 2;
+            break;
+        case 0x28000000:
+        case 0x20000000:
+        case 0x38000000:
+        case 0x30000000:
+            i++;
+
+        default:
+            ;
+    }
+
+    return i;
+
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/pv_normalize.h b/media/libstagefright/codecs/aacdec/pv_normalize.h
new file mode 100644
index 0000000..dce080e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_normalize.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Pathname: pv_normalize.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_NORMALIZE_H
+#define PV_NORMALIZE_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+#if defined(_ARM)
+
+__inline Int pv_normalize(Int32 x)
+{
+    Int32 y;
+    __asm
+    {
+        clz y, x;
+        sub y, y, #1
+    }
+    return (y);
+}
+
+
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+__inline Int pv_normalize(Int32 x)
+{
+    register Int32 y;
+    register Int32 ra = x;
+
+
+    asm volatile(
+        "clz %0, %1\n\t"
+        "sub %0, %0, #1"
+    : "=&r*i"(y)
+                : "r"(ra));
+    return (y);
+
+}
+
+#else
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int pv_normalize(Int32 x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
+
+#endif  /* PV_NORMALIZE_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_pow2.cpp b/media/libstagefright/codecs/aacdec/pv_pow2.cpp
new file mode 100644
index 0000000..8dfca23
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_pow2.cpp
@@ -0,0 +1,170 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_pow2.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    Int32 x             32-bit integer input  Q27
+
+Output
+    Int32               32-bit integer in Q25
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement the power base 2 for positive numbers lesser than 5.999999
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+#ifdef AAC_PLUS
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_pow2.h"
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+#define POW_2_TABLE_LENGTH          6
+#define POW_2_TABLE_LENGTH_m_2      (POW_2_TABLE_LENGTH - 2)
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     29
+#define Q_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+#define Q27fmt(x)   (Int32)(x*((Int32)1<<27) + (x>=0?0.5F:-0.5F))
+
+const Int32 pow2_table[6] =
+{
+    Q_fmt(0.00224510927441F),   Q_fmt(0.00777943379416F),
+    Q_fmt(0.05737929218747F),   Q_fmt(0.23918017179889F),
+    Q_fmt(0.69345251849351F),   Q_fmt(0.99996347120248F)
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/*
+ *      z in Q27 format
+ */
+
+Int32 pv_pow2(Int32 z)
+{
+    const Int32 *pt_table = pow2_table;
+    Int32 multiplier = 0;
+    Int32 shift_factor;
+    Int32 i;
+    Int32 v_q;
+    Int32 y;
+
+
+    if (z > Q27fmt(1.0f))
+    {
+        v_q = z - (z & 0xF8000000);
+        shift_factor =   z >> 27;
+    }
+    else
+    {
+        v_q = z;
+        shift_factor = 0;
+    }
+
+    if (v_q < Q27fmt(0.5f))
+    {
+        v_q += Q27fmt(0.5f);
+        multiplier = Q_fmt(0.70710678118655F);
+    }
+
+    v_q = v_q << 2;
+
+    y  = fxp_mul32_Q29(*(pt_table++), v_q);
+
+    for (i = POW_2_TABLE_LENGTH_m_2; i != 0; i--)
+    {
+        y += *(pt_table++);
+        y  = fxp_mul32_Q29(y, v_q);
+    }
+    y += *(pt_table++);
+
+    if (multiplier)
+    {
+        y = fxp_mul32_Q29(y, multiplier);
+    }
+
+    /*
+     *  returns number on Q25
+     */
+    return (y >> (4 - shift_factor));
+
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/pv_pow2.h b/media/libstagefright/codecs/aacdec/pv_pow2.h
new file mode 100644
index 0000000..04bfe93
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_pow2.h
@@ -0,0 +1,68 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pv_pow2.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_POW2_H
+#define PV_POW2_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    Int32 pv_pow2(Int32 z);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PV_POW2_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_sine.cpp b/media/libstagefright/codecs/aacdec/pv_sine.cpp
new file mode 100644
index 0000000..54319b1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_sine.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_sine.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer angle (in Q30) between 0 and pi/2
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Find the sine of a number between 0 and pi/2
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+#ifdef PARAMETRICSTEREO
+
+#include "pv_audio_type_defs.h"
+#include "fxp_mul32.h"
+#include "pv_sine.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
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     30
+
+#define Q_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+const Int32 sin_table[9] =
+{
+    Q_fmt(0.00001724684028), Q_fmt(-0.00024606242846),
+    Q_fmt(0.00007297328923), Q_fmt(0.00826706596417),
+    Q_fmt(0.00003585160465), Q_fmt(-0.16667772526248),
+    Q_fmt(0.00000174197440), Q_fmt(0.99999989138797),
+    Q_fmt(0.00000000110513)
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+Int32 pv_sine(Int32 z)
+{
+    Int32 sine;
+    Int32 i;
+    const Int32 *pt_table = sin_table;
+    Int32 sign = 0;
+
+    if (z < 0)
+    {
+        z = -z;
+        sign = 1;
+    }
+
+    if (z > Q_fmt(0.0015))
+    {
+        sine  = fxp_mul32_Q30(*(pt_table++), z);
+
+        for (i = 7; i != 0; i--)
+        {
+            sine += *(pt_table++);
+            sine  = fxp_mul32_Q30(sine, z);
+        }
+
+    }
+    else
+    {
+        sine = z;  /*  better approximation in this range */
+    }
+
+    if (sign)
+    {
+        sine = -sine;
+    }
+
+    return sine;
+}
+
+
+
+Int32 pv_cosine(Int32 z)
+{
+    Int32 cosine;
+
+    if (z < 0)
+    {
+        z = -z;     /* sign does not play a role in cosine */
+    }
+
+    if (z > Q_fmt(0.0015))
+    {
+        z = Q_fmt(1.57079632679490) - z;   /* pi/2 - z */
+
+        cosine  = pv_sine(z);
+    }
+    else
+    {   /*  better approximation in this range  */
+        cosine = Q_fmt(0.99999999906868) - (fxp_mul32_Q30(z, z) >> 1);
+    }
+
+    return cosine;
+}
+
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pv_sine.h b/media/libstagefright/codecs/aacdec/pv_sine.h
new file mode 100644
index 0000000..145013a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_sine.h
@@ -0,0 +1,68 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pv_sine.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_SINE_H
+#define PV_SINE_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    Int32 pv_sine(Int32 x);
+    Int32 pv_cosine(Int32 x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PV_SINE_H */
diff --git a/media/libstagefright/codecs/aacdec/pv_sqrt.cpp b/media/libstagefright/codecs/aacdec/pv_sqrt.cpp
new file mode 100644
index 0000000..065fa38
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_sqrt.cpp
@@ -0,0 +1,218 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: pv_sqrt.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 x             32-bit integer
+
+    Int32 y             32-bit integer
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement root squared of a number
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "pv_audio_type_defs.h"
+
+#include "fxp_mul32.h"
+#include "pv_sqrt.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
+----------------------------------------------------------------------------*/
+#define R_SHIFT     28
+#define Q_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+
+const Int32 sqrt_table[9] =
+{
+    Q_fmt(-0.13829740941110F),  Q_fmt(0.95383399963991F),
+    Q_fmt(-2.92784603873353F),  Q_fmt(5.27429191920042F),
+    Q_fmt(-6.20272445821478F),  Q_fmt(5.04717433019620F),
+    Q_fmt(-3.03362807640415F),  Q_fmt(1.86178814410910F),
+    Q_fmt(0.16540758699193F)
+};
+
+/*----------------------------------------------------------------------------
+; 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 pv_sqrt(Int32 man, Int32 exp, Root_sq *result, Int32 *sqrt_cache)
+{
+
+    Int32   y;
+    Int32   xx;
+    Int32   nn;
+    Int32   i;
+    const Int32 *pt_table = sqrt_table;
+
+
+    if (sqrt_cache[0] == man && sqrt_cache[1] == exp)
+    {
+        result->root         =        sqrt_cache[2];
+        result->shift_factor = (Int16)sqrt_cache[3];
+    }
+    else
+    {
+
+        sqrt_cache[0] = man;
+        sqrt_cache[1] = exp;
+
+
+        if (man > 0)
+        {
+            xx =  man;
+            if (man >= Q_fmt(1.0f))
+            {
+                nn = exp + 1;
+                while ((xx >>= 1) > Q_fmt(1.0f))
+                {
+                    nn++;
+                }
+            }
+            else if (man < Q_fmt(0.5f))
+            {
+                nn = exp - 1;
+                while ((xx <<= 1) < Q_fmt(0.5f))
+                {
+                    nn--;
+                }
+            }
+            else
+            {
+                nn = exp;
+            }
+
+
+            y  = fxp_mul32_Q28(*(pt_table++), xx);
+
+            for (i = 3; i != 0; i--)
+            {
+                y += *(pt_table++);
+                y  = fxp_mul32_Q28(y, xx);
+                y += *(pt_table++);
+                y  = fxp_mul32_Q28(y, xx);
+            }
+            y += *(pt_table++);
+            y  = fxp_mul32_Q28(y, xx) + *(pt_table++);
+
+            if (nn >= 0)
+            {
+                if (nn&1)
+                {
+                    y = fxp_mul32_Q29(y, Q_fmt(1.41421356237310F));
+                    result->shift_factor = (nn >> 1) - 28;
+                }
+                else
+                {
+                    result->shift_factor = (nn >> 1) - 29;
+                }
+            }
+            else
+            {
+                if (nn&1)
+                {
+                    y = fxp_mul32_Q28(y, Q_fmt(0.70710678118655F));
+                }
+
+                result->shift_factor = -((-nn) >> 1) - 29;
+            }
+
+            result->root = y;
+
+        }
+        else
+        {
+            result->root = 0;
+            result->shift_factor = 0;
+        }
+
+    }
+
+    sqrt_cache[2] = result->root;
+    sqrt_cache[3] = result->shift_factor;
+
+}
+
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/pv_sqrt.h b/media/libstagefright/codecs/aacdec/pv_sqrt.h
new file mode 100644
index 0000000..45d6f52
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pv_sqrt.h
@@ -0,0 +1,74 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pv_sqrt.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_SQRT_H
+#define PV_SQRT_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    struct intg_sqrt
+    {
+        Int32 root;
+        Int32 shift_factor;
+    };
+    typedef struct intg_sqrt Root_sq;
+
+    void pv_sqrt(Int32 man, Int32 exp, Root_sq *result, Int32 *sqrt_cache);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* PV_SQRT_H */
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecoder_api.h b/media/libstagefright/codecs/aacdec/pvmp4audiodecoder_api.h
new file mode 100644
index 0000000..7806f88
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecoder_api.h
@@ -0,0 +1,376 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Name: PVMP4AudioDecoder_API.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change buffer type to UChar
+
+ Description: Update comments
+
+ Description: Updated a comment that MT did not get around to
+ before the end of his contract.
+
+ Description: add a new API to decode audioSpecificConfig separately, the same
+              change has been made on 32-bits version (element \main\2)
+
+ Description: add a new API to reset history buffer, the same change has been
+              made on a 32-bits version(element \nd.e0352.wjin\1)
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Main header file for the Packet Video MP4/AAC audio decoder library. The
+ constants, structures, and functions defined within this file, along with
+ a basic data types header file, is all that is needed to use and communicate
+ with the library. The internal data structures within the library are
+ purposely hidden.
+
+ ---* Need description of the input buffering. *-------
+
+ ---* Need an example of calling the library here *----
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (Normally header files do not have a reference section)
+
+  ISO/EIC 14496-3:(1999) Document titled
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP4AUDIODECODER_API_H
+#define PVMP4AUDIODECODER_API_H
+
+#include "pv_audio_type_defs.h"  /* Basic data types used within the lib */
+
+#include "e_tmp4audioobjecttype.h"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*
+     * This constant is the guaranteed-to-work buffer size, specified in bytes,
+     * for the input buffer for 2 audio channels to decode one frame of data,
+     * as specified by the MPEG-2 or MPEG-4 standard.
+     * The standard, and this constant, do not take into account that lower
+     * bitrates will use less data per frame. Note that the number of bits
+     * used per frame is variable, and only that the average value will be the
+     * bit rate specified during encoding. The standard does not specify
+     * over how many frames the average must be maintained.
+     *
+     * The constant value is 6144 * 2 channels / 8 bits per byte
+     */
+
+
+#define PVMP4AUDIODECODER_INBUFSIZE  1536
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*
+     * This enumeration is used for the structure element outputFormat. It
+     * specifies how the output data is to be formatted. Presently only 16-bit
+     * PCM data is supported, and this enum informs how the single output
+     * buffer should be for two-channel stereo data.
+     * Grouped format stores all the left channel values, then right:
+     * "LLLL...LLRRRR...RR"
+     * Interleave format store left, then right audio samples:
+     * "LRLRLRLR...."
+     */
+    typedef enum ePVMP4AudioDecoderOutputFormat
+    {
+        OUTPUTFORMAT_16PCM_GROUPED = 0,
+        OUTPUTFORMAT_16PCM_INTERLEAVED = 1
+
+    } tPVMP4AudioDecoderOutputFormat;
+
+    /*
+     * This enumeration holds the possible return values for the main decoder
+     * function, PVMP4AudioDecodeFrame. The plan was to easily distinguish
+     * whether an error was recoverable (streaming mode) or not. Presently no
+     * errors are recoverable, which is a result of not supporting ADTS in
+     * this release.
+     */
+    typedef enum ePVMP4AudioDecoderErrorCode
+    {
+        MP4AUDEC_SUCCESS           =  0,
+        MP4AUDEC_INVALID_FRAME     = 10,
+        MP4AUDEC_INCOMPLETE_FRAME  = 20,
+        MP4AUDEC_LOST_FRAME_SYNC   = 30     /* Cannot happen since no ADTS */
+    } tPVMP4AudioDecoderErrorCode;
+
+
+    /*
+     * This enumeration holds the possible return values for stream type
+     * being decoded
+     */
+    typedef enum
+    {
+        AAC = 0,
+        AACPLUS,
+        ENH_AACPLUS
+    } STREAMTYPE;
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*
+     * This structure is used to communicate information in to and out of the
+     * AAC decoder.
+     */
+
+    typedef struct
+#ifdef __cplusplus
+                tPVMP4AudioDecoderExternal  // To allow forward declaration of this struct in C++
+#endif
+    {
+        /*
+         * INPUT:
+         * Pointer to the input buffer that contains the encoded bistream data.
+         * The data is filled in such that the first bit transmitted is
+         * the most-significant bit (MSB) of the first array element.
+         * The buffer is accessed in a linear fashion for speed, and the number of
+         * bytes consumed varies frame to frame.
+         * The calling environment can change what is pointed to between calls to
+         * the decode function, library, as long as the inputBufferCurrentLength,
+         * and inputBufferUsedLength are updated too. Also, any remaining bits in
+         * the old buffer must be put at the beginning of the new buffer.
+         */
+        UChar  *pInputBuffer;
+
+        /*
+         * INPUT:
+         * Number of valid bytes in the input buffer, set by the calling
+         * function. After decoding the bitstream the library checks to
+         * see if it when past this value; it would be to prohibitive to
+         * check after every read operation. This value is not modified by
+         * the AAC library.
+         */
+        Int     inputBufferCurrentLength;
+
+        /*
+         * INPUT:
+         * The actual size of the buffer.
+         * This variable is not used by the library, but is used by the
+         * console test application. This parameter could be deleted
+         * if this value was passed into these function. The helper functions are
+         * not part of the library and are not used by the Common Audio Decoder
+         * Interface.
+         */
+        Int     inputBufferMaxLength;
+
+        /*
+         * INPUT:
+         * Enumerated value the output is to be interleaved left-right-left-right.
+         * For further information look at the comments for the enumeration.
+         */
+        tPVMP4AudioDecoderOutputFormat  outputFormat;
+
+        /*
+         * INPUT: (but what is pointed to is an output)
+         * Pointer to the output buffer to hold the 16-bit PCM audio samples.
+         * If the output is stereo, both left and right channels will be stored
+         * in this one buffer. Presently it must be of length of 2048 points.
+         * The format of the buffer is set by the parameter outputFormat.
+         */
+        Int16  *pOutputBuffer;
+
+        /*
+         * INPUT: (but what is pointed to is an output)
+         * Pointer to the output buffer to hold the 16-bit PCM AAC-plus audio samples.
+         * If the output is stereo, both left and right channels will be stored
+         * in this one buffer. Presently it must be of length of 2048 points.
+         * The format of the buffer is set by the parameter outputFormat.
+         */
+        Int16  *pOutputBuffer_plus;     /* Used in AAC+ and enhanced AAC+  */
+
+        /*
+         * INPUT:
+         * AAC Plus Upsampling Factor. Normally set to 2 when Spectrum Band
+         * Replication (SBR) is used
+         */
+        Int32  aacPlusUpsamplingFactor; /* Used in AAC+ and enhanced AAC+  */
+
+        /*
+         * INPUT:
+         * AAC Plus enabler. Deafaults to be ON, unless run time conditions
+         * require the SBR and PS tools disabled
+         */
+        bool    aacPlusEnabled;
+        /*
+         * INPUT:
+         * (Currently not being used inside the AAC library.)
+         * This flag is set to TRUE when the playback position has been changed,
+         * for example, rewind or fast forward. This informs the AAC library to
+         * take an appropriate action, which has yet to be determined.
+         */
+        Bool    repositionFlag;
+
+        /*
+         * INPUT:
+         * Number of requested output audio channels. This relieves the calling
+         * environment from having to perform stereo-to-mono or mono-to-stereo
+         * conversions.
+         */
+        Int     desiredChannels;
+
+        /*
+         * INPUT/OUTPUT:
+         * Number of elements used by the library, initially set to zero by
+         * the function PVMP4AudioDecoderInitLibrary, and modified by each
+         * call to PVMP4AudioDecodeFrame.
+         */
+        Int     inputBufferUsedLength;
+
+        /*
+         * INPUT/OUTPUT:
+         * Number of bits left over in the next buffer element,
+         * This value will always be zero, unless support for ADTS is added.
+         */
+        Int32    remainderBits;
+
+        /*
+         * OUTPUT:
+         * The sampling rate decoded from the bitstream, in units of
+         * samples/second. For this release of the library this value does
+         * not change from frame to frame, but future versions will.
+         */
+        Int32   samplingRate;
+
+        /*
+         * OUTPUT:
+         * This value is the bitrate in units of bits/second. IT
+         * is calculated using the number of bits consumed for the current frame,
+         * and then multiplying by the sampling_rate, divided by points in a frame.
+         * This value can changes frame to frame.
+         */
+        Int32   bitRate;
+
+        /*
+         * OUTPUT:
+         * The number of channels decoded from the bitstream. The output data
+         * will have be the amount specified in the variable desiredChannels,
+         * this output is informative only, and can be ignored.
+         */
+        Int     encodedChannels;
+
+        /*
+         * OUTPUT:
+         * This value is the number of output PCM samples per channel.
+         * It is presently hard-coded to 1024, but may change in the future.
+         * It will not change frame to frame, and would take on
+         * one of these four values: 1024, 960, 512, or 480. If an error occurs
+         * do not rely on this value.
+         */
+        Int     frameLength;
+
+        /*
+        * This value is audio object type as defined in struct tMP4AudioObjectType
+        * in file e_tMP4AudioObjectType.h
+        */
+        Int     audioObjectType;
+
+        /*
+        * This value is extended audio object type as defined in struct tMP4AudioObjectType
+        * in file e_tMP4AudioObjectType.h. It carries the output Audio Object Type
+        */
+        Int     extendedAudioObjectType;
+
+
+    } tPVMP4AudioDecoderExternal;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    OSCL_IMPORT_REF UInt32 PVMP4AudioDecoderGetMemRequirements(void);
+
+    OSCL_IMPORT_REF Int PVMP4AudioDecoderInitLibrary(
+        tPVMP4AudioDecoderExternal  *pExt,
+        void                        *pMem);
+
+    OSCL_IMPORT_REF Int PVMP4AudioDecodeFrame(
+        tPVMP4AudioDecoderExternal  *pExt,
+        void                        *pMem);
+
+    OSCL_IMPORT_REF Int PVMP4AudioDecoderConfig(
+        tPVMP4AudioDecoderExternal  *pExt,
+        void                        *pMem);
+
+    OSCL_IMPORT_REF void PVMP4AudioDecoderResetBuffer(
+        void                        *pMem);
+
+    OSCL_IMPORT_REF void PVMP4AudioDecoderDisableAacPlus(
+        tPVMP4AudioDecoderExternal  *pExt,
+        void                        *pMem);
+
+    Int PVMP4SetAudioConfig(
+        tPVMP4AudioDecoderExternal  *pExt,
+        void                        *pMem,
+        Int                         upsamplingFactor,
+        Int                         samp_rate,
+        int                         num_ch,
+        tMP4AudioObjectType         audioObjectType);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* PVMP4AUDIODECODER_API_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecoderconfig.cpp b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderconfig.cpp
new file mode 100644
index 0000000..9208fa8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderconfig.cpp
@@ -0,0 +1,285 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: PVMP4AudioDecoderConfig
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) Modified to decode AudioSpecificConfig for any frame number
+                  pVars->bno
+              (2) Update the input and output descriptions
+
+ Description: Eliminated search for ADIF header
+
+ Description: Added support for AAC+
+
+ Who:                                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pExt = pointer to the external interface structure. See the file
+           PVMP4AudioDecoder_API.h for a description of each field.
+           Data type of pointer to a tPVMP4AudioDecoderExternal
+           structure.
+
+           pExt->pInputBuffer: pointer to input buffer containing input
+                               bitstream
+
+           pExt->inputBufferCurrentLength: number of bytes in the input buffer
+
+           pExt->inputBufferUsedLength: number of bytes already consumed in
+                                        input buffer
+
+           pExt->remainderBits: number of bits consumed in addition to
+                                pExt->inputBufferUsedLength
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tDec_Int_File structure. This structure
+           contains information that needs to persist between calls to
+           this function, or is too big to be placed on the stack, even
+           though the data is only needed during execution of this function
+           Data type void pointer, internally pointer to a tDec_Int_File
+           structure.
+
+ Local Stores/Buffers/Pointers Needed: None
+           (The memory set aside in pMem performs this task)
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+     status = 0                       if no error occurred
+              MP4AUDEC_NONRECOVERABLE if a non-recoverable error occurred
+              MP4AUDEC_RECOVERABLE    if a recoverable error occurred.
+              Presently a recoverable error does not exist, but this
+              was a requirement.
+
+
+ Pointers and Buffers Modified:
+    pMem contents are modified.
+    pExt: (more detail in the file PVMP4AudioDecoder_API.h)
+    inputBufferUsedLength - number of array elements used up by the stream.
+    remainderBits - remaining bits in the next UInt32 buffer
+    samplingRate - sampling rate in samples per sec
+    encodedChannels - channels found on the file (informative)
+    frameLength - length of the frame
+
+ Local Stores Modified: None.
+
+ Global Stores Modified: None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ PacketVideo Document # CCC-AUD-AAC-ERS-0003
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3: 1999(E)
+      subclause 1.6
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+#include "ibstream.h"           /* where #define INBUF_ARRAY_INDEX_SHIFT */
+#include "sfb.h"                   /* Where samp_rate_info[] is declared */
+
+#include "get_audio_specific_config.h"
+#include "pvmp4audiodecoder_api.h"   /* Where this function is declared */
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+OSCL_EXPORT_REF Int PVMP4AudioDecoderConfig(
+    tPVMP4AudioDecoderExternal  *pExt,
+    void                        *pMem)
+{
+
+    UInt           initialUsedBits;  /* Unsigned for C55x */
+    tDec_Int_File *pVars;           /* Helper pointer */
+
+    Int            status = MP4AUDEC_INCOMPLETE_FRAME;
+
+    /*
+     * Initialize "helper" pointers to existing memory.
+     */
+    pVars = (tDec_Int_File *)pMem;
+    /*
+     * Translate input buffer variables.
+     */
+    pVars->inputStream.pBuffer = pExt->pInputBuffer;
+
+    pVars->inputStream.inputBufferCurrentLength =
+        (UInt)pExt->inputBufferCurrentLength;
+
+    pVars->inputStream.availableBits =
+        (UInt)(pExt->inputBufferCurrentLength << INBUF_ARRAY_INDEX_SHIFT);
+
+    initialUsedBits =
+        (UInt)((pExt->inputBufferUsedLength << INBUF_ARRAY_INDEX_SHIFT) +
+               pExt->remainderBits);
+
+    pVars->inputStream.usedBits = initialUsedBits;
+
+    if (initialUsedBits <= pVars->inputStream.availableBits)
+    {
+
+        /*
+         * Buffer is not overrun, then
+         * decode the AudioSpecificConfig() structure
+         */
+
+        pVars->aacConfigUtilityEnabled = false;  /* set aac dec mode */
+
+        status = get_audio_specific_config(pVars);
+
+    }
+
+    byte_align(&pVars->inputStream);
+
+
+    if (status == SUCCESS)
+    {
+
+        pVars->bno++;
+
+        /*
+         * A possible improvement would be to set these values only
+         * when they change.
+         */
+        pExt->samplingRate =
+            samp_rate_info[pVars->prog_config.sampling_rate_idx].samp_rate;
+
+        /*
+         *  we default to 2 channel, even for mono files, (where channels have same content)
+         *  this is done to ensure support for enhanced aac+ with implicit signalling
+         */
+        pExt->aacPlusEnabled = pVars->aacPlusEnabled;
+
+//        pExt->encodedChannels = pVars->mc_info.nch;
+
+        pExt->encodedChannels = 2;
+
+        pExt->frameLength = pVars->frameLength;
+#ifdef AAC_PLUS
+        pExt->aacPlusUpsamplingFactor = pVars->mc_info.upsamplingFactor;
+#endif
+
+    }
+    else
+    {
+        /*
+         *  Default to nonrecoverable error status unless there is a Buffer overrun
+         */
+        status = MP4AUDEC_INVALID_FRAME;
+
+        if (pVars->inputStream.usedBits > pVars->inputStream.availableBits)
+        {
+            /* all bits were used but were not enough to complete parsing */
+            pVars->inputStream.usedBits = pVars->inputStream.availableBits;
+
+            status = MP4AUDEC_INCOMPLETE_FRAME; /* audio config too small */
+        }
+
+    }
+
+    /*
+     * Translate from units of bits back into units of words.
+     */
+
+    pExt->inputBufferUsedLength =
+        pVars->inputStream.usedBits >> INBUF_ARRAY_INDEX_SHIFT;
+
+    pExt->remainderBits = pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK;
+
+    pVars->status = status;
+
+    return (status);
+
+} /* PVMP4AudioDecoderDecodeFrame */
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecoderframe.cpp b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderframe.cpp
new file mode 100644
index 0000000..7a279dc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderframe.cpp
@@ -0,0 +1,1458 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pvmp4audiodecodeframe
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Pulled in loop structure from console.c, so that this function
+               now decodes all frames in the file.
+
+               Original program used several global variables.  These have been
+               eliminated, except for situations in which the global variables
+               could be converted into const types.  Otherwise, they are passed
+               by reference through the functions.
+
+ Description:  Begin mods for file I/O removal
+
+ Description:  Merged trans4m_freq_2_time, trans4m_time_2_freq, etc.
+
+ Description:  Removing commented out sections of code.  This includes the
+               removal of unneeded functions init_lt_pred, reset_mc_info,
+
+ Description: Copied from aac_decode_frame.c and renamed file,
+              Made many changes.
+
+ Description: Prepare for code review
+
+ Description: Update per review comments:
+              1) Add comment about leaveGetLoop
+              2) Remove inverseTNSCoef array
+              3) fix wnd_shape_this_bk to wnd_shape_prev_bk in F to T
+              4) Clean up comments
+              5) Change call to long_term_synthesis
+
+ Description: Remove division for calculation of bitrate.
+
+ Description: Remove update of LTP buffers if not LTP audio object type.
+
+ Description: Add hasmask to call to right_ch_sfb_tools_ms
+
+ Description:
+ Modified to call ltp related routines on the left channel
+ before intensity is called on the right channel.  The previous version
+ was causing a problem when IS was used on the right channel and LTP
+ on the left channel for the same scalefactor band.
+
+ This fix required creating a new function, apply_ms_synt, deleting another
+ function (right_ch_sfb_tools_noms.c), and modifying the calling order of
+ the other functions.
+
+ Description: Made changes per review comments.
+
+ Description: Changed name of right_ch_sfb_tools_ms to pns_intensity_right
+
+ Description: Added cast, since pVars->inputStream.usedBits is UInt, and
+ pExt->remainderBits is Int.
+
+ pExt->remainderBits =
+    (Int)(pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK);
+
+ Description: Modified to pass a pointer to scratch memory into
+ tns_setup_filter.c
+
+ Description: Removed include of "s_TNSInfo.h"
+
+ Description: Removed call to "tns_setup_filter" which has been eliminated
+ by merging its functionality into "get_tns"
+
+ Description:  Passing in a pointer to a q-format array, rather than
+ the address of a single q-format, for the inverse filter case for
+ apply_tns.
+
+ Description:
+ (1) Added #include of "e_ElementId.h"
+     Previously, this function was relying on another include file
+     to include "e_ElementId.h"
+
+ (2) Updated the copyright header.
+
+ Description:
+ Per review comments, declared two temporary variables
+
+    pChLeftShare  = pChVars[LEFT]->pShareWfxpCoef;
+    pChRightShare = pChVars[RIGHT]->pShareWfxpCoef;
+
+ Description:
+    long_term_synthesis should have been invoked with max_sfb
+    as the 2nd parameter, rather than pFrameInfo->sfb_per_win[0].
+
+    Old
+                long_term_synthesis(
+                    pChVars[ch]->wnd,
+                    pFrameInfo->sfb_per_win[0] ...
+
+    Correction
+                long_term_synthesis(
+                    pChVars[ch]->wnd,
+                    pChVars[ch]->pShareWfxpCoef->max_sfb ...
+
+    This problem caused long_term_synthesis to read memory which
+    was not initialized in get_ics_info.c
+
+ Description:
+ (1) Utilize scratch memory for the scratch Prog_Config.
+
+ Description: (1) Modified to decode ID_END syntactic element after header
+
+ Description:
+ (1) Reconfigured LTP buffer as a circular buffer.  This saves
+     2048 Int16->Int16 copies per frame.
+
+ Description: Updated so ltp buffers are not used as a wasteful
+ intermediate buffer for LC streams.  Data is transferred directly
+ from the filterbank to the output stream.
+
+ Description: Decode ADIF header if frame count is zero.
+              The AudioSpecificConfig is decoded by a separate API.
+
+ Description: Added comments explaining how the ltp_buffer_state
+ variable is updated.
+
+
+ Description: Modified code to take advantage of new trans4m_freq_2_time_fxp,
+ which writes the output directly into a 16-bit output buffer.  This
+ improvement allows faster operation by reducing the amount of memory
+ transfers.  Speed can be further improved on most platforms via use of a
+ DMA transfer in the function write_output.c
+
+ Description: perChan[] is an array of structures in tDec_Int_File. Made
+              corresponding changes.
+
+ Description: Included changes in interface for q_normalize() and
+              trans4m_freq_2_time_fxp.
+
+ Description: Included changes in interface for long_term_prediction.
+
+ Description: Added support for DSE (Data Streaming Channel). Added
+              function get_dse() and included file get_dse.h
+
+ Description: Added support for the ill-case when a raw data block contains
+              only a terminator <ID_END>. This is illegal but is added
+              for convinience
+
+ Description: Added support for empty audio frames, such the one containing
+              only DSE or FILL elements. A trap was added to stop processing
+              when no audio information was sent.
+
+ Description: Added support for adts format files. Added saturation to
+              floating point version of aac+ decoding
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pExt = pointer to the external interface structure. See the file
+           PVMP4AudioDecoder_API.h for a description of each field.
+           Data type of pointer to a tPVMP4AudioDecoderExternal
+           structure.
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tDec_Int_File structure. This structure
+           contains information that needs to persist between calls to
+           this function, or is too big to be placed on the stack, even
+           though the data is only needed during execution of this function
+           Data type void pointer, internally pointer to a tDec_Int_File
+           structure.
+
+ Local Stores/Buffers/Pointers Needed: None
+           (The memory set aside in pMem performs this task)
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+     status = 0                       if no error occurred
+              MP4AUDEC_NONRECOVERABLE if a non-recoverable error occurred
+              MP4AUDEC_RECOVERABLE    if a recoverable error occurred.
+              Presently a recoverable error does not exist, but this
+              was a requirement.
+
+
+ Pointers and Buffers Modified:
+    pMem contents are modified.
+    pExt: (more detail in the file PVMP4AudioDecoder_API.h)
+    inputBufferUsedLength - number of array elements used up by the stream.
+    remainderBits - remaining bits in the next UInt32 buffer
+    samplingRate - sampling rate in samples per sec
+    bitRate - bit rate in bits per second, varies frame to frame.
+    encodedChannels - channels found on the file (informative)
+    frameLength - length of the frame
+
+ Local Stores Modified: None.
+
+ Global Stores Modified: None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Decodes one frame of an MPEG-2/MPEG-4 encoded audio bitstream.
+
+ This function calls the various components of the decoder in the proper order.
+
+
+         Left Channel                                    Right Channel
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+ #1 ____________________                           #2 ____________________
+    |                  |                              |                  |
+    | Huffman Decoding |                              | Huffman Decoding |
+    |__________________|                              |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                                |
+ #3 ____________________                                       |
+    |                  |                                       |
+    |     PNS LEFT     |                                       |
+    |__________________|                                       |
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+ #4 ______________________________________________________________________
+    |                                                                    |
+    |                          Apply MS_Synt                             |
+    |____________________________________________________________________|
+             |                                                 |
+             |                                                 |
+            \|/                                                |
+ #5 ____________________                                       |
+    |                  |                                       W
+    |       LTP        |                                       A
+    |__________________|                                       I
+             |                                                 T
+             |                                                 |
+             |                                                 F
+            \|/                                                O
+ #6 ____________________                                       R
+    |                  |                                       |
+    |   Time -> Freq   |                                       L
+    |__________________|                                       E
+             |                                                 F
+             |                                                 T
+             |                                                 |
+            \|/                                                C
+ #7 ____________________                                       H
+    |                  |                                       A
+    |    TNS Inverse   |                                       N
+    |__________________|                                       N
+             |                                                 E
+             |                                                 L
+             |                                                 |
+            \|/                                                |
+ #8 ____________________                                       |
+    |                  |                                       |
+    | Long Term Synth  |                                       |
+    |__________________|                                       |
+             |                                                 |
+             |                                                \|/
+             |                                     #9 ____________________
+             |                                        |                  |
+             |--DATA ON LEFT CHANNEL MAY BE USED----->| PNS/Intensity Rt |
+             |                                        |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                \|/
+             |                                    #10 ____________________
+             W                                        |                  |
+             A                                        |       LTP        |
+             I                                        |__________________|
+             T                                                 |
+             |                                                 |
+             F                                                 |
+             O                                                \|/
+             R                                    #11 ____________________
+             |                                        |                  |
+             R                                        |   Time -> Freq   |
+             I                                        |__________________|
+             G                                                 |
+             H                                                 |
+             T                                                 |
+             |                                                \|/
+             C                                    #12 ____________________
+             H                                        |                  |
+             A                                        |    TNS Inverse   |
+             N                                        |__________________|
+             N                                                 |
+             E                                                 |
+             L                                                 |
+             |                                                \|/
+             |                                    #13 ____________________
+             |                                        |                  |
+             |                                        | Long Term Synth  |
+             |                                        |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+#14 ____________________                          #18 ____________________
+    |                  |                              |                  |
+    |       TNS        |                              |       TNS        |
+    |__________________|                              |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+#15 ____________________                          #19 ____________________
+    |                  |                              |                  |
+    |   qFormatNorm    |                              |   qFormatNorm    |
+    |__________________|                              |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+#16 ____________________                          #20 ____________________
+    |                  |                              |                  |
+    |   Freq / Time    |                              |   Freq / Time    |
+    |__________________|                              |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+#17 ____________________                          #21 ____________________
+    |                  |                              |                  |
+    |   Limit Buffer   |                              |   Limit Buffer   |
+    |__________________|                              |__________________|
+             |                                                 |
+             |                                                 |
+             |                                                 |
+            \|/                                               \|/
+#22 ______________________________________________________________________
+    |                                                                    |
+    |                           Write Output                             |
+    |____________________________________________________________________|
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ PacketVideo Document # CCC-AUD-AAC-ERS-0003
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+
+#include "s_tdec_int_chan.h"
+#include "s_tdec_int_file.h"
+#include "aac_mem_funcs.h"
+#include "sfb.h"                   /* Where samp_rate_info[] is declared */
+#include "e_tmp4audioobjecttype.h"
+#include "e_elementid.h"
+
+
+#include "get_adif_header.h"
+#include "get_adts_header.h"
+#include "get_audio_specific_config.h"
+#include "ibstream.h"           /* where getbits is declared */
+
+#include "huffman.h"            /* where huffdecode is declared */
+#include "get_prog_config.h"
+#include "getfill.h"
+#include "pns_left.h"
+
+#include "apply_ms_synt.h"
+#include "pns_intensity_right.h"
+#include "q_normalize.h"
+#include "long_term_prediction.h"
+#include "long_term_synthesis.h"
+#include "ltp_common_internal.h"
+#include "apply_tns.h"
+
+#include "window_block_fxp.h"
+
+#include "write_output.h"
+
+#include "pvmp4audiodecoder_api.h"   /* Where this function is declared */
+#include "get_dse.h"
+
+#include "sbr_applied.h"
+#include "sbr_open.h"
+#include "get_sbr_bitstream.h"
+#include "e_sbr_element_id.h"
+
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define LEFT (0)
+#define RIGHT (1)
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+void InitSbrSynFilterbank(bool bDownSampleSBR);
+
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+OSCL_EXPORT_REF Int PVMP4AudioDecodeFrame(
+    tPVMP4AudioDecoderExternal  *pExt,
+    void                        *pMem)
+{
+    Int            frameLength;      /* Helper variable */
+    Int            ch;
+    Int            id_syn_ele;
+    UInt           initialUsedBits;  /* Unsigned for C55x */
+    Int            qFormatNorm;
+    Int            qPredictedSamples;
+    Bool           leaveGetLoop;
+    MC_Info       *pMC_Info;        /* Helper pointer */
+    FrameInfo     *pFrameInfo;      /* Helper pointer */
+    tDec_Int_File *pVars;           /* Helper pointer */
+    tDec_Int_Chan *pChVars[Chans];  /* Helper pointer */
+
+    per_chan_share_w_fxpCoef *pChLeftShare;  /* Helper pointer */
+    per_chan_share_w_fxpCoef *pChRightShare; /* Helper pointer */
+
+    Int            status = MP4AUDEC_SUCCESS;
+
+
+    Bool empty_frame;
+
+#ifdef AAC_PLUS
+
+    SBRDECODER_DATA *sbrDecoderData;
+    SBR_DEC         *sbrDec;
+    SBRBITSTREAM    *sbrBitStream;
+
+#endif
+    /*
+     * Initialize "helper" pointers to existing memory.
+     */
+    pVars = (tDec_Int_File *)pMem;
+
+    pMC_Info = &pVars->mc_info;
+
+    pChVars[LEFT]  = &pVars->perChan[LEFT];
+    pChVars[RIGHT] = &pVars->perChan[RIGHT];
+
+    pChLeftShare = pChVars[LEFT]->pShareWfxpCoef;
+    pChRightShare = pChVars[RIGHT]->pShareWfxpCoef;
+
+
+#ifdef AAC_PLUS
+
+    sbrDecoderData = (SBRDECODER_DATA *) & pVars->sbrDecoderData;
+    sbrDec         = (SBR_DEC *) & pVars->sbrDec;
+    sbrBitStream   = (SBRBITSTREAM *) & pVars->sbrBitStr;
+
+#ifdef PARAMETRICSTEREO
+    sbrDecoderData->hParametricStereoDec = (HANDLE_PS_DEC) & pVars->sbrDecoderData.ParametricStereoDec;
+#endif
+
+#endif
+    /*
+     * Translate input buffer variables.
+     */
+    pVars->inputStream.pBuffer = pExt->pInputBuffer;
+
+    pVars->inputStream.inputBufferCurrentLength = (UInt)pExt->inputBufferCurrentLength;
+
+    pVars->inputStream.availableBits =
+        (UInt)(pExt->inputBufferCurrentLength << INBUF_ARRAY_INDEX_SHIFT);
+
+    initialUsedBits =
+        (UInt)((pExt->inputBufferUsedLength << INBUF_ARRAY_INDEX_SHIFT) +
+               pExt->remainderBits);
+
+    pVars->inputStream.usedBits = initialUsedBits;
+
+    if (initialUsedBits > pVars->inputStream.availableBits)
+    {
+        status = MP4AUDEC_INVALID_FRAME;
+    }
+    else if (pVars->bno == 0)
+    {
+        /*
+         * Attempt to read in ADIF format first because it is easily identified.
+         * If its not an ADIF bitstream, get_adif_header rewinds the "pointer"
+         * (actually usedBits).
+         */
+        status =
+            get_adif_header(
+                pVars,
+                &(pVars->scratch.scratch_prog_config));
+
+        byte_align(&pVars->inputStream);
+
+        if (status == SUCCESS)
+        {
+            pVars->prog_config.file_is_adts = FALSE;
+        }
+        else  /* we've tried simple audio config, adif, then it should be adts */
+        {
+            pVars->prog_config.file_is_adts = TRUE;
+        }
+    }
+    else if ((pVars->bno == 1) && (pVars->prog_config.file_is_adts == FALSE))
+    {
+
+        /*
+         * There might be an ID_END element following immediately after the
+         * AudioSpecificConfig header. This syntactic element should be read
+         * and byte_aligned before proceeds to decode "real" AAC raw data.
+         */
+        id_syn_ele = (Int)getbits(LEN_SE_ID, &pVars->inputStream) ;
+
+        if (id_syn_ele == ID_END)
+        {
+
+            byte_align(&pVars->inputStream);
+
+            pExt->inputBufferUsedLength =
+                pVars->inputStream.usedBits >> INBUF_ARRAY_INDEX_SHIFT;
+
+            pExt->remainderBits = pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK;
+
+            pVars->bno++;
+
+            return(status);
+        }
+        else
+        {
+            /*
+             * Rewind bitstream pointer so that the syntactic element can be
+             * read when decoding raw bitstream
+             */
+            pVars->inputStream.usedBits -= LEN_SE_ID;
+        }
+
+    }
+
+    if (pVars->prog_config.file_is_adts == TRUE)
+    {
+        /*
+         *  If file is adts format, let the decoder handle only on data raw
+         *  block at the time, once the last (or only) data block has been
+         *  processed, then synch on the next header
+         */
+        if (pVars->prog_config.headerless_frames)
+        {
+            pVars->prog_config.headerless_frames--;  /* raw data block counter  */
+        }
+        else
+        {
+            status =  get_adts_header(pVars,
+                                      &(pVars->syncword),
+                                      &(pVars->invoke),
+                                      3);     /*   CorrectlyReadFramesCount  */
+
+            if (status != SUCCESS)
+            {
+                status = MP4AUDEC_LOST_FRAME_SYNC;    /*  we lost track of header */
+            }
+        }
+    }
+    else
+    {
+        byte_align(&pVars->inputStream);
+    }
+
+#ifdef AAC_PLUS
+    sbrBitStream->NrElements = 0;
+    sbrBitStream->NrElementsCore = 0;
+
+#endif
+
+    /*
+     * The variable leaveGetLoop is used to signal that the following
+     * loop can be left, which retrieves audio syntatic elements until
+     * an ID_END is found, or an error occurs.
+     */
+    leaveGetLoop = FALSE;
+    empty_frame  = TRUE;
+
+    while ((leaveGetLoop == FALSE) && (status == SUCCESS))
+    {
+        /* get audio syntactic element */
+        id_syn_ele = (Int)get9_n_lessbits(LEN_SE_ID, &pVars->inputStream);
+
+        /*
+         *  As fractional frames are a possible input, check that parsing does not
+         *  go beyond the available bits before parsing the syntax.
+         */
+        if (pVars->inputStream.usedBits > pVars->inputStream.availableBits)
+        {
+            status = MP4AUDEC_INCOMPLETE_FRAME; /* possible EOF or fractional frame */
+            id_syn_ele = ID_END;           /* quit while-loop */
+        }
+
+        switch (id_syn_ele)
+        {
+            case ID_END:        /* terminator field */
+                leaveGetLoop = TRUE;
+                break;
+
+            case ID_SCE:        /* single channel */
+            case ID_CPE:        /* channel pair */
+                empty_frame = FALSE;
+                status =
+                    huffdecode(
+                        id_syn_ele,
+                        &(pVars->inputStream),
+                        pVars,
+                        pChVars);
+
+#ifdef AAC_PLUS
+                if (id_syn_ele == ID_SCE)
+                {
+                    sbrBitStream->sbrElement[sbrBitStream->NrElements].ElementID = SBR_ID_SCE;
+                }
+                else if (id_syn_ele == ID_CPE)
+                {
+                    sbrBitStream->sbrElement[sbrBitStream->NrElements].ElementID = SBR_ID_CPE;
+                }
+                sbrBitStream->NrElementsCore++;
+
+
+#endif
+
+                break;
+
+            case ID_PCE:        /* program config element */
+                /*
+                 * PCE are not accepted in the middle of a
+                 * raw_data_block. If found, a possible error may happen
+                 * If a PCE is encountered during the first 2 frames,
+                 * it will be read and accepted
+                 * if its tag matches the first, with no error checking
+                 * (inside of get_prog_config)
+                 */
+
+                if (pVars->bno <= 1)
+                {
+                    status = get_prog_config(pVars,
+                                             &(pVars->scratch.scratch_prog_config));
+                }
+                else
+                {
+                    status = MP4AUDEC_INVALID_FRAME;
+                }
+                break;
+
+            case ID_FIL:        /* fill element */
+#ifdef AAC_PLUS
+                get_sbr_bitstream(sbrBitStream, &pVars->inputStream);
+
+#else
+                getfill(&pVars->inputStream);
+#endif
+
+                break;
+
+            case ID_DSE:       /* Data Streaming element */
+                get_dse(pVars->share.data_stream_bytes,
+                        &pVars->inputStream);
+                break;
+
+            default: /* Unsupported element, including ID_LFE */
+                status = -1;  /* ERROR CODE needs to be updated */
+                break;
+
+        } /* end switch() */
+
+    } /* end while() */
+
+    byte_align(&pVars->inputStream);
+
+    /*
+     *   After parsing the first frame ( bno=0 (adif), bno=1 (raw))
+     *   verify if implicit signalling is forcing to upsample AAC with
+     *   no AAC+/eAAC+ content. If so, disable upsampling
+     */
+
+#ifdef AAC_PLUS
+    if (pVars->bno <= 1)
+    {
+        if ((pVars->mc_info.ExtendedAudioObjectType == MP4AUDIO_AAC_LC) &&
+                (!sbrBitStream->NrElements))
+        {
+            PVMP4AudioDecoderDisableAacPlus(pExt, pMem);
+        }
+    }
+#endif
+
+    /*
+     *   There might be an empty raw data block with only a
+     *   ID_END element or non audio ID_DSE, ID_FIL
+     *   This is an "illegal" condition but this trap
+     *   avoids any further processing
+     */
+
+    if (empty_frame == TRUE)
+    {
+        pExt->inputBufferUsedLength =
+            pVars->inputStream.usedBits >> INBUF_ARRAY_INDEX_SHIFT;
+
+        pExt->remainderBits = pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK;
+
+        pVars->bno++;
+
+        return(status);
+
+    }
+
+#ifdef AAC_PLUS
+
+    if (sbrBitStream->NrElements)
+    {
+        /* for every core SCE or CPE there must be an SBR element, otherwise sths. wrong */
+        if (sbrBitStream->NrElements != sbrBitStream->NrElementsCore)
+        {
+            status = MP4AUDEC_INVALID_FRAME;
+        }
+
+        if (pExt->aacPlusEnabled == false)
+        {
+            sbrBitStream->NrElements = 0;   /* disable aac processing  */
+        }
+    }
+    else
+    {
+        /*
+         *  This is AAC, but if aac+/eaac+ was declared in the stream, and there is not sbr content
+         *  something is wrong
+         */
+        if (pMC_Info->sbrPresentFlag || pMC_Info->psPresentFlag)
+        {
+            status = MP4AUDEC_INVALID_FRAME;
+        }
+    }
+#endif
+
+
+
+
+    /*
+     * Signal processing section.
+     */
+    frameLength = pVars->frameLength;
+
+    if (status == SUCCESS)
+    {
+        /*
+         *   PNS and INTENSITY STEREO and MS
+         */
+
+        pFrameInfo = pVars->winmap[pChVars[LEFT]->wnd];
+
+        pns_left(
+            pFrameInfo,
+            pChLeftShare->group,
+            pChLeftShare->cb_map,
+            pChLeftShare->factors,
+            pChLeftShare->lt_status.sfb_prediction_used,
+            pChLeftShare->lt_status.ltp_data_present,
+            pChVars[LEFT]->fxpCoef,
+            pChLeftShare->qFormat,
+            &(pVars->pns_cur_noise_state));
+
+        /*
+         * apply_ms_synt can only be ran for common windows.
+         * (where both the left and right channel share the
+         * same grouping, window length, etc.
+         *
+         * pVars->hasmask will be > 0 only if
+         * common windows are enabled for this frame.
+         */
+
+        if (pVars->hasmask > 0)
+        {
+            apply_ms_synt(
+                pFrameInfo,
+                pChLeftShare->group,
+                pVars->mask,
+                pChLeftShare->cb_map,
+                pChVars[LEFT]->fxpCoef,
+                pChVars[RIGHT]->fxpCoef,
+                pChLeftShare->qFormat,
+                pChRightShare->qFormat);
+        }
+
+        for (ch = 0; (ch < pMC_Info->nch); ch++)
+        {
+            pFrameInfo = pVars->winmap[pChVars[ch]->wnd];
+
+            /*
+             * Note: This MP4 library assumes that if there are two channels,
+             * then the second channel is right AND it was a coupled channel,
+             * therefore there is no need to check the "is_cpe" flag.
+             */
+
+            if (ch > 0)
+            {
+                pns_intensity_right(
+                    pVars->hasmask,
+                    pFrameInfo,
+                    pChRightShare->group,
+                    pVars->mask,
+                    pChRightShare->cb_map,
+                    pChLeftShare->factors,
+                    pChRightShare->factors,
+                    pChRightShare->lt_status.sfb_prediction_used,
+                    pChRightShare->lt_status.ltp_data_present,
+                    pChVars[LEFT]->fxpCoef,
+                    pChVars[RIGHT]->fxpCoef,
+                    pChLeftShare->qFormat,
+                    pChRightShare->qFormat,
+                    &(pVars->pns_cur_noise_state));
+            }
+
+            if (pChVars[ch]->pShareWfxpCoef->lt_status.ltp_data_present != FALSE)
+            {
+                /*
+                 * LTP - Long Term Prediction
+                 */
+
+                qPredictedSamples = long_term_prediction(
+                                        pChVars[ch]->wnd,
+                                        pChVars[ch]->pShareWfxpCoef->lt_status.
+                                        weight_index,
+                                        pChVars[ch]->pShareWfxpCoef->lt_status.
+                                        delay,
+                                        pChVars[ch]->ltp_buffer,
+                                        pVars->ltp_buffer_state,
+                                        pChVars[ch]->time_quant,
+                                        pVars->share.predictedSamples,      /* Scratch */
+                                        frameLength);
+
+                trans4m_time_2_freq_fxp(
+                    pVars->share.predictedSamples,
+                    pChVars[ch]->wnd,
+                    pChVars[ch]->wnd_shape_prev_bk,
+                    pChVars[ch]->wnd_shape_this_bk,
+                    &qPredictedSamples,
+                    pVars->scratch.fft);   /* scratch memory for FFT */
+
+
+                /*
+                 * To solve a potential problem where a pointer tied to
+                 * the qFormat was being incremented, a pointer to
+                 * pChVars[ch]->qFormat is passed in here rather than
+                 * the address of qPredictedSamples.
+                 *
+                 * Neither values are actually needed in the case of
+                 * inverse filtering, but the pointer was being
+                 * passed (and incremented) regardless.
+                 *
+                 * So, the solution is to pass a space of memory
+                 * that a pointer can happily point to.
+                 */
+
+                /* This is the inverse filter */
+                apply_tns(
+                    pVars->share.predictedSamples,  /* scratch re-used for each ch */
+                    pChVars[ch]->pShareWfxpCoef->qFormat,     /* Not used by the inv_filter */
+                    pFrameInfo,
+                    &(pChVars[ch]->pShareWfxpCoef->tns),
+                    TRUE,                       /* TRUE is FIR */
+                    pVars->scratch.tns_inv_filter);
+
+                /*
+                 * For the next function long_term_synthesis,
+                 * the third param win_sfb_top[], and
+                 * the tenth param coef_per_win,
+                 * are used differently that in the rest of the project. This
+                 * is because originally the ISO code was going to have
+                 * these parameters change as the "short window" changed.
+                 * These are all now the same value for each of the eight
+                 * windows.  This is why there is a [0] at the
+                 * end of each of theses parameters.
+                 * Note in particular that win_sfb_top was originally an
+                 * array of pointers to arrays, but inside long_term_synthesis
+                 * it is now a simple array.
+                 * When the rest of the project functions are changed, the
+                 * structure FrameInfo changes, and the [0]'s are removed,
+                 * this comment could go away.
+                 */
+                long_term_synthesis(
+                    pChVars[ch]->wnd,
+                    pChVars[ch]->pShareWfxpCoef->max_sfb,
+                    pFrameInfo->win_sfb_top[0], /* Look above */
+                    pChVars[ch]->pShareWfxpCoef->lt_status.win_prediction_used,
+                    pChVars[ch]->pShareWfxpCoef->lt_status.sfb_prediction_used,
+                    pChVars[ch]->fxpCoef,   /* input and output */
+                    pChVars[ch]->pShareWfxpCoef->qFormat,   /* input and output */
+                    pVars->share.predictedSamples,
+                    qPredictedSamples,       /* q format for previous aray */
+                    pFrameInfo->coef_per_win[0], /* Look above */
+                    NUM_SHORT_WINDOWS,
+                    NUM_RECONSTRUCTED_SFB);
+
+            } /* end if (pChVars[ch]->lt_status.ltp_data_present != FALSE) */
+
+        } /* for(ch) */
+
+        for (ch = 0; (ch < pMC_Info->nch); ch++)
+        {
+
+            pFrameInfo = pVars->winmap[pChVars[ch]->wnd];
+
+            /*
+             * TNS - Temporal Noise Shaping
+             */
+
+            /* This is the forward filter
+             *
+             * A special note:  Scratch memory is not used by
+             * the forward filter, but is passed in to maintain
+             * common interface for inverse and forward filter
+             */
+            apply_tns(
+                pChVars[ch]->fxpCoef,
+                pChVars[ch]->pShareWfxpCoef->qFormat,
+                pFrameInfo,
+                &(pChVars[ch]->pShareWfxpCoef->tns),
+                FALSE,                   /* FALSE is IIR */
+                pVars->scratch.tns_inv_filter);
+
+            /*
+             * Normalize the q format across all scale factor bands
+             * to one value.
+             */
+            qFormatNorm =
+                q_normalize(
+                    pChVars[ch]->pShareWfxpCoef->qFormat,
+                    pFrameInfo,
+                    pChVars[ch]->abs_max_per_window,
+                    pChVars[ch]->fxpCoef);
+
+            /*
+             *  filterbank - converts frequency coeficients to time domain.
+             */
+
+#ifdef AAC_PLUS
+            if (sbrBitStream->NrElements == 0 && pMC_Info->upsamplingFactor == 1)
+            {
+                trans4m_freq_2_time_fxp_2(
+                    pChVars[ch]->fxpCoef,
+                    pChVars[ch]->time_quant,
+                    pChVars[ch]->wnd,   /* window sequence */
+                    pChVars[ch]->wnd_shape_prev_bk,
+                    pChVars[ch]->wnd_shape_this_bk,
+                    qFormatNorm,
+                    pChVars[ch]->abs_max_per_window,
+                    pVars->scratch.fft,
+                    &pExt->pOutputBuffer[ch]);
+                /*
+                 *  Update LTP buffers if needed
+                 */
+
+                if (pVars->mc_info.audioObjectType == MP4AUDIO_LTP)
+                {
+                    Int16 * pt = &pExt->pOutputBuffer[ch];
+                    Int16 * ptr = &(pChVars[ch]->ltp_buffer[pVars->ltp_buffer_state]);
+                    Int16  x, y;
+                    for (Int32 i = HALF_LONG_WINDOW; i != 0; i--)
+                    {
+                        x = *pt;
+                        pt += 2;
+                        y = *pt;
+                        pt += 2;
+                        *(ptr++) =  x;
+                        *(ptr++) =  y;
+                    }
+                }
+            }
+            else
+            {
+                trans4m_freq_2_time_fxp_1(
+                    pChVars[ch]->fxpCoef,
+                    pChVars[ch]->time_quant,
+                    &(pChVars[ch]->ltp_buffer[pVars->ltp_buffer_state + 288]),
+                    pChVars[ch]->wnd,   /* window sequence */
+                    pChVars[ch]->wnd_shape_prev_bk,
+                    pChVars[ch]->wnd_shape_this_bk,
+                    qFormatNorm,
+                    pChVars[ch]->abs_max_per_window,
+                    pVars->scratch.fft);
+
+            }
+#else
+
+            trans4m_freq_2_time_fxp_2(
+                pChVars[ch]->fxpCoef,
+                pChVars[ch]->time_quant,
+                pChVars[ch]->wnd,   /* window sequence */
+                pChVars[ch]->wnd_shape_prev_bk,
+                pChVars[ch]->wnd_shape_this_bk,
+                qFormatNorm,
+                pChVars[ch]->abs_max_per_window,
+                pVars->scratch.fft,
+                &pExt->pOutputBuffer[ch]);
+            /*
+             *  Update LTP buffers only if needed
+             */
+
+            if (pVars->mc_info.audioObjectType == MP4AUDIO_LTP)
+            {
+                Int16 * pt = &pExt->pOutputBuffer[ch];
+                Int16 * ptr = &(pChVars[ch]->ltp_buffer[pVars->ltp_buffer_state]);
+                Int16  x, y;
+                for (Int32 i = HALF_LONG_WINDOW; i != 0; i--)
+                {
+                    x = *pt;
+                    pt += 2;
+                    y = *pt;
+                    pt += 2;
+                    *(ptr++) =  x;
+                    *(ptr++) =  y;
+                }
+
+            }
+
+
+#endif
+
+
+            /* Update the window shape */
+            pChVars[ch]->wnd_shape_prev_bk = pChVars[ch]->wnd_shape_this_bk;
+
+        } /* end for() */
+
+
+        /*
+         * Copy to the final output buffer, taking into account the desired
+         * channels from the calling environment, the actual channels, and
+         * whether the data should be interleaved or not.
+         *
+         * If the stream had only one channel, write_output will not use
+         * the right channel data.
+         *
+         */
+
+
+        /* CONSIDER USE OF DMA OPTIMIZATIONS WITHIN THE write_output FUNCTION.
+         *
+         * It is presumed that the ltp_buffer will reside in internal (fast)
+         * memory, while the pExt->pOutputBuffer will reside in external
+         * (slow) memory.
+         *
+         */
+
+
+#ifdef AAC_PLUS
+
+        if (sbrBitStream->NrElements || pMC_Info->upsamplingFactor == 2)
+        {
+
+            if (pVars->bno <= 1)   /* allows console to operate with ADIF and audio config */
+            {
+                if (sbrDec->outSampleRate == 0) /* do it only once (disregarding of signaling type) */
+                {
+                    sbr_open(samp_rate_info[pVars->mc_info.sampling_rate_idx].samp_rate,
+                             sbrDec,
+                             sbrDecoderData,
+                             pVars->mc_info.bDownSampledSbr);
+                }
+
+            }
+            pMC_Info->upsamplingFactor =
+                sbrDecoderData->SbrChannel[0].frameData.sbr_header.sampleRateMode;
+
+
+            /* reuse right aac spectrum channel  */
+            {
+                Int16 *pt_left  =  &(pChVars[LEFT ]->ltp_buffer[pVars->ltp_buffer_state]);
+                Int16 *pt_right =  &(pChVars[RIGHT]->ltp_buffer[pVars->ltp_buffer_state]);
+
+                if (sbr_applied(sbrDecoderData,
+                                sbrBitStream,
+                                pt_left,
+                                pt_right,
+                                pExt->pOutputBuffer,
+                                sbrDec,
+                                pVars,
+                                pMC_Info->nch) != SBRDEC_OK)
+                {
+                    status = MP4AUDEC_INVALID_FRAME;
+                }
+            }
+
+
+        }  /*  if( pExt->aacPlusEnabled == FALSE) */
+#endif
+
+        /*
+         * Copied mono data in both channels or just leave it as mono,
+         * according with desiredChannels (default is 2)
+         */
+
+        if (pExt->desiredChannels == 2)
+        {
+
+#if defined(AAC_PLUS)
+#if defined(PARAMETRICSTEREO)&&defined(HQ_SBR)
+            if (pMC_Info->nch != 2 && pMC_Info->psPresentFlag != 1)
+#else
+            if (pMC_Info->nch != 2)
+#endif
+#else
+            if (pMC_Info->nch != 2)
+#endif
+            {
+                /* mono */
+
+
+                Int16 * pt  = &pExt->pOutputBuffer[0];
+                Int16 * pt2 = &pExt->pOutputBuffer[1];
+                Int i;
+                if (pMC_Info->upsamplingFactor == 2)
+                {
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2 = *pt;
+                        pt += 2;
+                        pt2 += 2;
+                    }
+                    pt  = &pExt->pOutputBuffer_plus[0];
+                    pt2 = &pExt->pOutputBuffer_plus[1];
+
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2 = *pt;
+                        pt += 2;
+                        pt2 += 2;
+                    }
+                }
+                else
+                {
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2 = *pt;
+                        pt += 2;
+                        pt2 += 2;
+                    }
+                }
+
+            }
+
+#if defined(AAC_PLUS)
+#if defined(PARAMETRICSTEREO)&&defined(HQ_SBR)
+
+            else if (pMC_Info->psPresentFlag == 1)
+            {
+                Int32 frameSize = 0;
+                if (pExt->aacPlusEnabled == false)
+                {
+                    /*
+                     *  Decoding eaac+ when only aac is enabled, copy L into R
+                     */
+                    frameSize = 1024;
+                }
+                else if (sbrDecoderData->SbrChannel[0].syncState != SBR_ACTIVE)
+                {
+                    /*
+                     *  Decoding eaac+ when no PS data was found, copy upsampled L into R
+                     */
+                    frameSize = 2048;
+                }
+
+                Int16 * pt  = &pExt->pOutputBuffer[0];
+                Int16 * pt2 = &pExt->pOutputBuffer[1];
+                Int i;
+                for (i = 0; i < frameSize; i++)
+                {
+                    *pt2 = *pt;
+                    pt += 2;
+                    pt2 += 2;
+                }
+            }
+#endif
+#endif
+
+        }
+        else
+        {
+
+#if defined(AAC_PLUS)
+#if defined(PARAMETRICSTEREO)&&defined(HQ_SBR)
+            if (pMC_Info->nch != 2 && pMC_Info->psPresentFlag != 1)
+#else
+            if (pMC_Info->nch != 2)
+#endif
+#else
+            if (pMC_Info->nch != 2)
+#endif
+            {
+                /* mono */
+                Int16 * pt  = &pExt->pOutputBuffer[0];
+                Int16 * pt2 = &pExt->pOutputBuffer[0];
+                Int i;
+
+                if (pMC_Info->upsamplingFactor == 2)
+                {
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2++ = *pt;
+                        pt += 2;
+                    }
+
+                    pt  = &pExt->pOutputBuffer_plus[0];
+                    pt2 = &pExt->pOutputBuffer_plus[0];
+
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2++ = *pt;
+                        pt += 2;
+                    }
+                }
+                else
+                {
+                    for (i = 0; i < 1024; i++)
+                    {
+                        *pt2++ = *pt;
+                        pt += 2;
+                    }
+                }
+
+            }
+
+        }
+
+
+
+
+        /* pVars->ltp_buffer_state cycles between 0 and 1024.  The value
+         * indicates the location of the data corresponding to t == -2.
+         *
+         * | t == -2 | t == -1 |  pVars->ltp_buffer_state == 0
+         *
+         * | t == -1 | t == -2 |  pVars->ltp_buffer_state == 1024
+         *
+         */
+
+#ifdef AAC_PLUS
+        if (sbrBitStream->NrElements == 0 && pMC_Info->upsamplingFactor == 1)
+        {
+            pVars->ltp_buffer_state ^= frameLength;
+        }
+        else
+        {
+            pVars->ltp_buffer_state ^= (frameLength + 288);
+        }
+#else
+        pVars->ltp_buffer_state ^= frameLength;
+#endif
+
+
+        if (pVars->bno <= 1)
+        {
+            /*
+             * to set these values only during the second call
+             * when they change.
+             */
+            pExt->samplingRate =
+                samp_rate_info[pVars->mc_info.sampling_rate_idx].samp_rate;
+
+            pVars->mc_info.implicit_channeling = 0; /* disable flag, as this is allowed
+                                                      * only the first time
+                                                      */
+
+
+#ifdef AAC_PLUS
+
+            if (pMC_Info->upsamplingFactor == 2)
+            {
+                pExt->samplingRate *= pMC_Info->upsamplingFactor;
+                pExt->aacPlusUpsamplingFactor = pMC_Info->upsamplingFactor;
+            }
+
+#endif
+
+            pExt->extendedAudioObjectType = pMC_Info->ExtendedAudioObjectType;
+            pExt->audioObjectType = pMC_Info->audioObjectType;
+
+            pExt->encodedChannels = pMC_Info->nch;
+            pExt->frameLength = pVars->frameLength;
+        }
+
+        pVars->bno++;
+
+
+        /*
+         * Using unit analysis, the bitrate is a function of the sampling rate, bits,
+         * points in a frame
+         *
+         *     bits        samples                frame
+         *     ----  =    --------- *  bits  *   -------
+         *     sec           sec                  sample
+         *
+         * To save a divide, a shift is used. Presently only the value of
+         * 1024 is used by this library, so make it the most accurate for that
+         * value. This may need to be updated later.
+         */
+
+        pExt->bitRate = (pExt->samplingRate *
+                         (pVars->inputStream.usedBits - initialUsedBits)) >> 10;  /*  LONG_WINDOW  1024 */
+
+        pExt->bitRate >>= (pMC_Info->upsamplingFactor - 1);
+
+
+    } /* end if (status == SUCCESS) */
+
+
+    if (status != MP4AUDEC_SUCCESS)
+    {
+        /*
+         *  A non-SUCCESS decoding could be due to an error on the bitstream or
+         *  an incomplete frame. As access to the bitstream beyond frame boundaries
+         *  are not allowed, in those cases the bitstream reading routine return a 0
+         *  Zero values guarantees that the data structures are filled in with values
+         *  that eventually will signal an error (like invalid parameters) or that allow
+         *  completion of the parsing routine. Either way, the partial frame condition
+         *  is verified at this time.
+         */
+        if (pVars->prog_config.file_is_adts == TRUE)
+        {
+            status = MP4AUDEC_LOST_FRAME_SYNC;
+            pVars->prog_config.headerless_frames = 0; /* synchronization forced */
+        }
+        else
+        {
+            /*
+             *  Check if the decoding error was due to buffer overrun, if it was,
+             *  update status
+             */
+            if (pVars->inputStream.usedBits > pVars->inputStream.availableBits)
+            {
+                /* all bits were used but were not enough to complete decoding */
+                pVars->inputStream.usedBits = pVars->inputStream.availableBits;
+
+                status = MP4AUDEC_INCOMPLETE_FRAME; /* possible EOF or fractional frame */
+            }
+        }
+    }
+
+    /*
+     * Translate from units of bits back into units of words.
+     */
+
+    pExt->inputBufferUsedLength =
+        pVars->inputStream.usedBits >> INBUF_ARRAY_INDEX_SHIFT;
+
+    pExt->remainderBits = (Int)(pVars->inputStream.usedBits & INBUF_BIT_MODULO_MASK);
+
+
+
+    return (status);
+
+} /* PVMP4AudioDecoderDecodeFrame */
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecodergetmemrequirements.cpp b/media/libstagefright/codecs/aacdec/pvmp4audiodecodergetmemrequirements.cpp
new file mode 100644
index 0000000..7cdecd0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecodergetmemrequirements.cpp
@@ -0,0 +1,157 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: PVMP4AudioDecoderGetMemRequirements.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Copied from aac_decode_frame
+
+ Description: Cleaned up.
+
+ Description: (1) use UInt32 to replace size_t type
+              (2) memory of tDec_Int_File is splitted into 3 pieces,
+                  sizeof(tDec_Int_File) is only part of the total memory
+                  required. The additional memory required to decode per
+                  channel information is allocated by a DPI call outside this
+                  API
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs: None
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+    size = amount of memory needed to be allocated by the calling
+        environment.
+
+ Pointers and Buffers Modified: None
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function returns the amount of internal memory needed by the library.
+ Presently this is a constant value, but could later be more sophisticated
+ by taking into account mono or stereo, and whether LTP is to be used.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    size = sizeof(tDec_Int_File);
+
+ RETURN (size)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+#include "pvmp4audiodecoder_api.h" /* Where this function is declared */
+
+/*----------------------------------------------------------------------------
+; 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 FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+OSCL_EXPORT_REF UInt32 PVMP4AudioDecoderGetMemRequirements(void)
+{
+    UInt32 size;
+
+    size = (UInt32) sizeof(tDec_Int_File);
+
+    return (size);
+
+} /* PVMP4AudioDecoderGetMemRequirements() */
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecoderinitlibrary.cpp b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderinitlibrary.cpp
new file mode 100644
index 0000000..146ba0f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderinitlibrary.cpp
@@ -0,0 +1,418 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: PVMP4AudioDecoderInitLibrary.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Copied from aac_decode_frame
+
+ Description:  Clean up.
+
+ Description:  Update per review comments
+
+ Description:  Add frame_length, fix mistake in pseudo-code.
+               Change frame_length to frameLength, to matcht the API,
+               look more professional, etc.
+
+ Description:
+ (1) Added #include of "e_ProgConfigConst.h"
+     Previously, this function was relying on another include file
+     to include "e_ProgConfigConst.h"
+
+ (2) Updated the copyright header.
+
+ Description:
+ (1) Modified to initialize pointers for shared memory techniques.
+
+ Description: Since memory will be allocated continuously, it is initialized
+              in one spot
+
+ Description: Added field aacPlusUpsamplingFactor (default == 1) to have a
+              common interface for all AAC variations
+
+ Description: Added PVMP4AudioDecoderDisableAacPlus to disable sbr decoding
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pExt = pointer to the external application-program interface (API)
+           structure that a client program uses to communicate information
+           with this library. Among the items in this structure is a pointer
+           to the input and output buffers, data for handling the input buffer
+           and output information. Look in PVMP4AudioDecoder_API.h for all the
+           fields to this structure. Data type pointer to a
+           tPVMP4AudioDecoderExternal structure.
+
+   pMem =  pointer to allocated memory, of the size returned by the function
+           PVMP4AudioDecoderGetMemRequirements. This is a void pointer for
+           two reasons:
+           1) So the external program does not need all of the header files
+              for all of the fields in the structure tDec_Int_File
+           2) To hide data and the implementation of the program. Even knowing
+              how data is stored can help in reverse engineering software.
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+    status = 0 (SUCCESS). Presently there is no error checking in this
+    function.
+
+ Pointers and Buffers Modified: None
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Initializes the internal memory for the MP4 Audio Decoder library.
+ Also sets relevant values for the external interface structure, clears
+ the bit rate, channel count, sampling rate, and number of used buffer
+ elements.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pVars = pMem;
+
+    CALL pv_memset(
+           to = pVars,
+           c  = 0,
+           n  = sizeof(tDec_Int_File))
+    MODIFYING(*pVars = 0)
+    RETURNING(nothing)
+
+    pVars->current_program = -1
+    pVars->mc_info.sampling_rate_idx = Fs_44
+    pVars->frameLength = LONG_WINDOW
+
+
+    pVars->winmap[ONLY_LONG_SEQUENCE]   = &pVars->longFrameInfo;
+    pVars->winmap[LONG_START_SEQUENCE]  = &pVars->longFrameInfo;
+    pVars->winmap[EIGHT_SHORT_SEQUENCE] = &pVars->shortFrameInfo;
+    pVars->winmap[LONG_STOP_SEQUENCE]   = &pVars->longFrameInfo;
+
+    CALL infoinit(
+        samp_rate_indx = pVars->mc_info.sampling_rate_idx,
+        ppWin_seq_info = pVars->winmap,
+        pSfbwidth128   = pVars->SFBWidth128)
+    MODIFYING(ppWinSeq_info)
+    MODIFYING(pSfbwidth128)
+    RETURNING(nothing)
+
+    pExt->bitRate = 0;
+    pExt->encodedChannels = 0;
+    pExt->samplingRate = 0;
+    pExt->inputBufferUsedLength = 0;
+
+    MODIFY(pExt)
+    MODIFY(pMem)
+    RETURN(SUCCESS)
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+#include "e_progconfigconst.h"
+
+#include "huffman.h"               /* For the definition of infoinit        */
+#include "aac_mem_funcs.h"         /* For pv_memset                         */
+#include "pvmp4audiodecoder_api.h" /* Where this function is declared       */
+#include "s_tdec_int_chan.h"
+#include "sfb.h"                   /* samp_rate_info[] is declared here     */
+
+/*----------------------------------------------------------------------------
+; 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 FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+OSCL_EXPORT_REF Int PVMP4AudioDecoderInitLibrary(
+    tPVMP4AudioDecoderExternal  *pExt,
+    void                        *pMem)
+{
+    tDec_Int_File *pVars;
+
+    pVars = (tDec_Int_File *)pMem;
+
+    /*
+     * Initialize all memory. The pointers to channel memory will be
+     * set to zero also.
+     */
+    pv_memset(
+        pVars,
+        0,
+        sizeof(tDec_Int_File));
+
+    /*
+     * Pick default values for the library.
+     */
+    pVars->perChan[0].fxpCoef = pVars->fxpCoef[0];
+    pVars->perChan[1].fxpCoef = pVars->fxpCoef[1];
+
+    /* Here, the "shared memory" pointer is set to point
+     * at the 1024th element of fxpCoef, because those spaces
+     * in memory are not used until the filterbank is called.
+     *
+     * Therefore, any variables that are only used before
+     * the filterbank can occupy this same space in memory.
+     */
+
+    pVars->perChan[0].pShareWfxpCoef = (per_chan_share_w_fxpCoef *)
+                                       & (pVars->perChan[0].fxpCoef[1024]);
+
+    pVars->perChan[1].pShareWfxpCoef = (per_chan_share_w_fxpCoef *)
+                                       & (pVars->perChan[1].fxpCoef[1024]);
+
+    /*
+     * This next line informs the function get_prog_config that no
+     * configuration has been found thus far, so it is a default
+     * configuration.
+     */
+
+    pVars->current_program = -1;
+    pVars->mc_info.sampling_rate_idx = Fs_44; /* Fs_44 = 4, 44.1kHz */
+
+    /*
+     * In the future, the frame length will change with MP4 file format.
+     * Presently this variable is used to simply the unit test for
+     * the function PVMP4AudioDecodeFrame() .. otherwise the test would
+     * have to pass around 1024 length arrays.
+     */
+    pVars->frameLength = LONG_WINDOW; /* 1024*/
+
+    /*
+     * The window types ONLY_LONG_SEQUENCE, LONG_START_SEQUENCE, and
+     * LONG_STOP_SEQUENCE share the same information. The only difference
+     * between the windows is accounted for in the "filterbank", in
+     * the function trans4m_freq_2_time_fxp()
+     */
+
+    pVars->winmap[ONLY_LONG_SEQUENCE]   /* 0 */ = &pVars->longFrameInfo;
+    pVars->winmap[LONG_START_SEQUENCE]  /* 1 */ = &pVars->longFrameInfo;
+    pVars->winmap[EIGHT_SHORT_SEQUENCE] /* 2 */ = &pVars->shortFrameInfo;
+    pVars->winmap[LONG_STOP_SEQUENCE]   /* 3 */ = &pVars->longFrameInfo;
+
+    infoinit(
+        pVars->mc_info.sampling_rate_idx,
+        (FrameInfo   **)pVars->winmap,
+        pVars->SFBWidth128);
+
+
+    /*
+     * Clear out external output values. These values are set later at the end
+     * of PVMP4AudioDecodeFrames()
+     */
+    pExt->bitRate = 0;
+    pExt->encodedChannels = 0;
+    pExt->samplingRate = 0;
+    pExt->aacPlusUpsamplingFactor = 1;  /*  Default for regular AAC */
+    pVars->aacPlusEnabled = pExt->aacPlusEnabled;
+
+
+#if defined(AAC_PLUS)
+    pVars->sbrDecoderData.setStreamType = 1;        /* Enable Lock for AAC stream type setting  */
+#endif
+
+    /*
+     * Initialize input buffer variable.
+     */
+
+    pExt->inputBufferUsedLength = 0;
+
+    return (MP4AUDEC_SUCCESS);
+
+}  /* PVMP4AudioDecoderInitLibrary */
+
+
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pExt = pointer to the external application-program interface (API)
+           structure that a client program uses to communicate information
+           with this library. Among the items in this structure is a pointer
+           to the input and output buffers, data for handling the input buffer
+           and output information. Look in PVMP4AudioDecoder_API.h for all the
+           fields to this structure. Data type pointer to a
+           tPVMP4AudioDecoderExternal structure.
+
+   pMem =  pointer to allocated memory, of the size returned by the function
+           PVMP4AudioDecoderGetMemRequirements. This is a void pointer for
+           two reasons:
+           1) So the external program does not need all of the header files
+              for all of the fields in the structure tDec_Int_File
+           2) To hide data and the implementation of the program. Even knowing
+              how data is stored can help in reverse engineering software.
+
+ Local Stores/Buffers/Pointers Needed: None
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+    status = 0 (SUCCESS). Presently there is no error checking in this
+    function.
+
+ Pointers and Buffers Modified: None
+
+ Local Stores Modified: None
+
+ Global Stores Modified: None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Disable SBR decoding functionality and set parameters accordingly
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+OSCL_EXPORT_REF void PVMP4AudioDecoderDisableAacPlus(
+    tPVMP4AudioDecoderExternal  *pExt,
+    void                        *pMem)
+{
+    tDec_Int_File *pVars;
+
+    pVars = (tDec_Int_File *)pMem;
+
+    if ((pVars->aacPlusEnabled == true) && (pExt->aacPlusEnabled == true))
+    {
+        // disable only when makes sense
+        pVars->aacPlusEnabled = false;
+        pExt->aacPlusEnabled = false;
+
+#if defined(AAC_PLUS)
+        pVars->mc_info.upsamplingFactor = 1;
+        pVars->mc_info.psPresentFlag  = 0;
+        pVars->mc_info.sbrPresentFlag = 0;
+        pVars->prog_config.sampling_rate_idx += 3;
+        pVars->sbrDecoderData.SbrChannel[0].syncState = SBR_NOT_INITIALIZED;
+        pVars->sbrDecoderData.SbrChannel[1].syncState = SBR_NOT_INITIALIZED;
+
+
+        pExt->samplingRate = samp_rate_info[pVars->prog_config.sampling_rate_idx].samp_rate;
+        pExt->aacPlusUpsamplingFactor = 1;
+#endif
+    }
+}  /* PVMP4AudioDecoderDisableAacPlus */
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4audiodecoderresetbuffer.cpp b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderresetbuffer.cpp
new file mode 100644
index 0000000..c10423b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4audiodecoderresetbuffer.cpp
@@ -0,0 +1,354 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: PVMP4AudioDecoderResetBuffer.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) add more comments (2) set pVars->bno = 1
+
+ Description: perChan[] is an array of structures in tDec_Int_File. Made
+              corresponding changes.
+
+ Who:                                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tDec_Int_File structure. This structure
+           contains information that needs to persist between calls to
+           PVMP4AudioDecodeFrame
+           Data type void pointer, internally pointer to a tDec_Int_File
+           structure.
+
+ Local Stores/Buffers/Pointers Needed: None
+           (The memory set aside in pMem performs this task)
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs: None
+
+ Pointers and Buffers Modified:
+    pMem contents are modified.
+    pMem->perChan[0].time_quant[0-1023]: contents are set to zero
+    pMem->perChan[1].time_quant[0-1023]: contents are set to zero
+    pMem->bno = 1
+
+ Local Stores Modified: None.
+
+ Global Stores Modified: None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  This function is called when the same audio clip will be played again from
+  the begining. This situation happens when the "stop" button is pressed or
+  the "loop-mode" is selected on PVPlayer. Since it is the same audio clip to
+  be played again, the decoder does not need to reset the audioSpecificInfo.
+  However, the overlap-and-add buffer of the filterbank output needs to be
+  cleared, so that the decoder can re-start properly from the begining of
+  the audio. The frame number counter, pVars->bno, is set to 1 because the
+  audioSpecificInfo is decoded on pVars->bno==0
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ PacketVideo Document # CCC-AUD-AAC-ERS-0003
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3: 1999(E)
+      subclause 1.6
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+#include "pvmp4audiodecoder_api.h"   /* Where this function is declared */
+#include "aac_mem_funcs.h"
+
+#ifdef AAC_PLUS
+#include    "s_sbr_frame_data.h"
+#endif
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LEFT  (0)
+#define RIGHT (1)
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+OSCL_EXPORT_REF void PVMP4AudioDecoderResetBuffer(void  *pMem)
+{
+
+    tDec_Int_File *pVars;           /* Helper pointer */
+
+#ifdef AAC_PLUS
+    SBR_FRAME_DATA * hFrameData_1;
+    SBR_FRAME_DATA * hFrameData_2;
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+    SBRDECODER_DATA *sbrDecoderData;
+#endif
+#endif
+
+#endif
+    /*
+     * Initialize "helper" pointers to existing memory.
+     */
+    pVars = (tDec_Int_File *)pMem;
+
+    /*
+     * Clear the overlap-and-add buffer of filterbank output. The audio
+     * clip will be played again from the beginning.
+     */
+    pv_memset(pVars->perChan[LEFT].time_quant,
+              0,
+              LONG_WINDOW*sizeof(pVars->perChan[LEFT].time_quant[0]));
+
+    pv_memset(pVars->perChan[RIGHT].time_quant,
+              0,
+              LONG_WINDOW*sizeof(pVars->perChan[RIGHT].time_quant[0]));
+
+
+#ifdef AAC_PLUS
+
+    if (!pVars->sbrDecoderData.setStreamType)  /* reset only when stream type is defined */
+    {
+        if (pVars->aacPlusEnabled == true)  /* clear buffer only if they were used */
+        {
+
+            hFrameData_1   = (SBR_FRAME_DATA *) & pVars->sbrDecoderData.SbrChannel[LEFT].frameData;
+            hFrameData_2   = (SBR_FRAME_DATA *) & pVars->sbrDecoderData.SbrChannel[RIGHT].frameData;
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+            sbrDecoderData = (SBRDECODER_DATA *) & pVars->sbrDecoderData;
+            sbrDecoderData->hParametricStereoDec = (HANDLE_PS_DEC) & pVars->sbrDecoderData.ParametricStereoDec;
+#endif
+#endif
+
+
+            pv_memset(&pVars->perChan[LEFT].ltp_buffer[0],
+                      0,
+                      288*sizeof(pVars->perChan[LEFT].ltp_buffer[0]));
+            pv_memset(&pVars->perChan[LEFT].ltp_buffer[1024 + 288],
+                      0,
+                      288*sizeof(pVars->perChan[LEFT].ltp_buffer[0]));
+            pv_memset(hFrameData_1->V,
+                      0,
+                      1152*sizeof(hFrameData_1->V[0]));
+            pv_memset(hFrameData_1->prevNoiseLevel_man,
+                      0,
+                      MAX_NUM_NOISE_VALUES*sizeof(hFrameData_1->prevNoiseLevel_man[0]));
+
+
+            pv_memset(&pVars->perChan[RIGHT].ltp_buffer[0],
+                      0,
+                      288*sizeof(pVars->perChan[RIGHT].ltp_buffer[0]));
+            pv_memset(&pVars->perChan[RIGHT].ltp_buffer[1024 + 288],
+                      0,
+                      288*sizeof(pVars->perChan[RIGHT].ltp_buffer[0]));
+            pv_memset(hFrameData_2->V,
+                      0,
+                      1152*sizeof(hFrameData_2->V[0]));
+
+            pv_memset(hFrameData_2->prevNoiseLevel_man,
+                      0,
+                      MAX_NUM_NOISE_VALUES*sizeof(hFrameData_2->prevNoiseLevel_man[0]));
+
+
+            int i;
+            for (i = 0; i < 8; i++)
+            {
+                pv_memset((void *)&hFrameData_1->codecQmfBufferReal[i],
+                          0,
+                          sizeof(**hFrameData_1->codecQmfBufferReal) << 5);
+            }
+
+
+            /* ---- */
+            pv_memset((void *)hFrameData_1->BwVectorOld,
+                      0,
+                      sizeof(*hFrameData_1->BwVectorOld)*MAX_NUM_PATCHES);
+
+#ifdef HQ_SBR
+
+            for (i = 0; i < 5; i++)
+            {
+                pv_memset((void *)&hFrameData_1->fBuffer_man[i],
+                          0,
+                          sizeof(**hFrameData_1->fBuffer_man)*64);
+                pv_memset((void *)&hFrameData_1->fBufferN_man[i],
+                          0,
+                          sizeof(**hFrameData_1->fBufferN_man)*64);
+            }
+#endif
+
+
+            /* ---- */
+
+
+
+            pv_memset((void *)hFrameData_1->HistsbrQmfBufferReal,
+                      0,
+                      sizeof(*hFrameData_1->HistsbrQmfBufferReal)*6*SBR_NUM_BANDS);
+
+#ifdef HQ_SBR
+            pv_memset((void *)hFrameData_1->HistsbrQmfBufferImag,
+                      0,
+                      sizeof(*hFrameData_1->HistsbrQmfBufferImag)*6*SBR_NUM_BANDS);
+#endif
+
+            if (pVars->sbrDec.LC_aacP_DecoderFlag == 1)  /* clear buffer only for LC decoding */
+            {
+
+                for (i = 0; i < 8; i++)
+                {
+                    pv_memset((void *)&hFrameData_2->codecQmfBufferReal[i],
+                              0,
+                              sizeof(**hFrameData_1->codecQmfBufferReal) << 5);
+                }
+
+                pv_memset((void *)hFrameData_2->HistsbrQmfBufferReal,
+                          0,
+                          sizeof(*hFrameData_2->HistsbrQmfBufferReal)*6*SBR_NUM_BANDS);
+
+
+                pv_memset((void *)hFrameData_2->BwVectorOld,
+                          0,
+                          sizeof(*hFrameData_2->BwVectorOld)*MAX_NUM_PATCHES);
+
+#ifdef HQ_SBR
+
+                for (i = 0; i < 5; i++)
+                {
+                    pv_memset((void *)&hFrameData_2->fBuffer_man[i],
+                              0,
+                              sizeof(**hFrameData_2->fBuffer_man)*64);
+                    pv_memset((void *)&hFrameData_2->fBufferN_man[i],
+                              0,
+                              sizeof(**hFrameData_2->fBufferN_man)*64);
+                }
+#endif
+
+            }
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+            else if (pVars->mc_info.psPresentFlag == 1)
+            {
+                for (i = 0; i < 3; i++)
+                {
+                    pv_memset(sbrDecoderData->hParametricStereoDec->hHybrid->mQmfBufferReal[i],
+                              0,
+                              HYBRID_FILTER_LENGTH_m_1*sizeof(*sbrDecoderData->hParametricStereoDec->hHybrid->mQmfBufferReal));
+                    pv_memset(sbrDecoderData->hParametricStereoDec->hHybrid->mQmfBufferImag[i],
+                              0,
+                              HYBRID_FILTER_LENGTH_m_1*sizeof(*sbrDecoderData->hParametricStereoDec->hHybrid->mQmfBufferImag));
+                }
+            }
+#endif
+#endif
+
+            /*
+             *  default to UPSAMPLING, as if the file is SBR_ACTIVE, this will be fine and will be
+             *  fixed onced the new sbr header is found
+             *  SBR headers contain SBT freq. range as well as control signals that do not require
+             *  frequent changes.
+             *  For streaming, the SBR header is sent twice per second. Also, an SBR header can be
+             *  inserted at any time, if a change of parameters is needed.
+             */
+
+            pVars->sbrDecoderData.SbrChannel[LEFT].syncState = UPSAMPLING;
+            pVars->sbrDecoderData.SbrChannel[RIGHT].syncState = UPSAMPLING;
+
+        }
+    }
+#endif      /*  #ifdef AAC_PLUS */
+
+    /* reset frame count to 1 */
+    pVars->bno = 1;
+
+    return ;
+
+} /* PVMP4AudioDecoderDecodeFrame */
+
diff --git a/media/libstagefright/codecs/aacdec/pvmp4setaudioconfig.cpp b/media/libstagefright/codecs/aacdec/pvmp4setaudioconfig.cpp
new file mode 100644
index 0000000..d183d84
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/pvmp4setaudioconfig.cpp
@@ -0,0 +1,368 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: pvmp4setaudioconfigg
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pExt = pointer to the external interface structure. See the file
+           PVMP4AudioDecoder_API.h for a description of each field.
+           Data type of pointer to a tPVMP4AudioDecoderExternal
+           structure.
+
+           pExt->pInputBuffer: pointer to input buffer containing input
+                               bitstream
+
+           pExt->inputBufferCurrentLength: number of bytes in the input buffer
+
+           pExt->inputBufferUsedLength: number of bytes already consumed in
+                                        input buffer
+
+           pExt->remainderBits: number of bits consumed in addition to
+                                pExt->inputBufferUsedLength
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tDec_Int_File structure. This structure
+           contains information that needs to persist between calls to
+           this function, or is too big to be placed on the stack, even
+           though the data is only needed during execution of this function
+           Data type void pointer, internally pointer to a tDec_Int_File
+           structure.
+
+ Local Stores/Buffers/Pointers Needed: None
+           (The memory set aside in pMem performs this task)
+
+ Global Stores/Buffers/Pointers Needed: None
+
+ Outputs:
+     status = 0                       if no error occurred
+              MP4AUDEC_NONRECOVERABLE if a non-recoverable error occurred
+              MP4AUDEC_RECOVERABLE    if a recoverable error occurred.
+              Presently a recoverable error does not exist, but this
+              was a requirement.
+
+
+ Pointers and Buffers Modified:
+    pMem contents are modified.
+    pExt: (more detail in the file PVMP4AudioDecoder_API.h)
+    inputBufferUsedLength - number of array elements used up by the stream.
+    remainderBits - remaining bits in the next UInt32 buffer
+    samplingRate - sampling rate in samples per sec
+    encodedChannels - channels found on the file (informative)
+    frameLength - length of the frame
+
+ Local Stores Modified: None.
+
+ Global Stores Modified: None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ PacketVideo Document # CCC-AUD-AAC-ERS-0003
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+#include "ibstream.h"           /* where #define INBUF_ARRAY_INDEX_SHIFT */
+#include "sfb.h"                   /* Where samp_rate_info[] is declared */
+
+#include "get_audio_specific_config.h"
+#include "pvmp4audiodecoder_api.h"   /* Where this function is declared */
+#include "set_mc_info.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
+----------------------------------------------------------------------------*/
+
+Int PVMP4SetAudioConfig(
+    tPVMP4AudioDecoderExternal  *pExt,
+    void                        *pMem,
+    Int                         upsamplingFactor,
+    Int                         samp_rate,
+    Int                         num_ch,
+    tMP4AudioObjectType         audioObjectType)
+
+{
+
+    tDec_Int_File *pVars;           /* Helper pointer */
+
+    Int            status = MP4AUDEC_INCOMPLETE_FRAME;
+
+    /*
+     * Initialize "helper" pointers to existing memory.
+     */
+    pVars = (tDec_Int_File *)pMem;
+    /*
+     * Translate input buffer variables.
+     */
+    pVars->inputStream.pBuffer = pExt->pInputBuffer;
+
+    pVars->inputStream.availableBits = 0;
+
+    pVars->inputStream.usedBits = 0;
+
+
+
+    /*
+     *  get sampling rate index
+     */
+
+    switch (samp_rate)
+    {
+        case 96000:
+            pVars->prog_config.sampling_rate_idx = 0;
+            break;
+        case 88200:
+            pVars->prog_config.sampling_rate_idx = 1;
+            break;
+        case 64000:
+            pVars->prog_config.sampling_rate_idx = 2;
+            break;
+        case 48000:
+            pVars->prog_config.sampling_rate_idx = 3;
+            break;
+        case 44100:
+            pVars->prog_config.sampling_rate_idx = 4;
+            break;
+        case 32000:
+            pVars->prog_config.sampling_rate_idx = 5;
+            break;
+        case 24000:
+            pVars->prog_config.sampling_rate_idx = 6;
+            break;
+        case 22050:
+            pVars->prog_config.sampling_rate_idx = 7;
+            break;
+        case 16000:
+            pVars->prog_config.sampling_rate_idx = 8;
+            break;
+        case 12000:
+            pVars->prog_config.sampling_rate_idx = 9;
+            break;
+        case 11025:
+            pVars->prog_config.sampling_rate_idx = 10;
+            break;
+        case 8000:
+            pVars->prog_config.sampling_rate_idx = 11;
+            break;
+        case 7350:
+            pVars->prog_config.sampling_rate_idx = 12;
+            break;
+        default:
+            status = -1;
+
+            break;
+    }
+
+    pVars->mc_info.sbrPresentFlag = 0;
+    pVars->mc_info.psPresentFlag = 0;
+#ifdef AAC_PLUS
+    pVars->mc_info.bDownSampledSbr = 0;
+#endif
+    pVars->mc_info.implicit_channeling = 0;
+    pVars->mc_info.nch = num_ch;
+    pVars->mc_info.upsamplingFactor = upsamplingFactor;
+
+
+    /*
+     *  Set number of channels
+     */
+
+    if (num_ch == 2)
+    {
+        pVars->prog_config.front.ele_is_cpe[0] = 1;
+    }
+    else if (num_ch == 1)
+    {
+        pVars->prog_config.front.ele_is_cpe[0] = 0;
+    }
+    else
+    {
+        status = -1; /* do not support more than two channels */
+        pVars->status = status;
+        return (status);
+    }
+
+
+    /*
+     *  Set AAC bitstream
+     */
+
+    if ((audioObjectType == MP4AUDIO_AAC_LC)        ||
+            (audioObjectType == MP4AUDIO_LTP))
+    {
+        pVars->aacPlusEnabled = false;
+
+        status = set_mc_info(&(pVars->mc_info),
+                             audioObjectType, /* previously profile */
+                             pVars->prog_config.sampling_rate_idx,
+                             pVars->prog_config.front.ele_tag[0],
+                             pVars->prog_config.front.ele_is_cpe[0],
+                             pVars->winmap, /*pVars->pWinSeqInfo,*/
+                             pVars->SFBWidth128);
+    }
+    else if ((audioObjectType == MP4AUDIO_SBR)        ||
+             (audioObjectType == MP4AUDIO_PS))
+    {
+        pVars->aacPlusEnabled = true;
+
+
+        status = set_mc_info(&(pVars->mc_info),
+                             MP4AUDIO_AAC_LC,
+                             pVars->prog_config.sampling_rate_idx,
+                             pVars->prog_config.front.ele_tag[0],
+                             pVars->prog_config.front.ele_is_cpe[0],
+                             pVars->winmap, /*pVars->pWinSeqInfo,*/
+                             pVars->SFBWidth128);
+
+        pVars->mc_info.sbrPresentFlag = 1;
+        if (audioObjectType == MP4AUDIO_PS)
+        {
+            pVars->mc_info.psPresentFlag = 1;
+        }
+
+        if (upsamplingFactor == 1)
+        {
+#ifdef AAC_PLUS
+            pVars->mc_info.bDownSampledSbr = 1;
+#endif
+
+            /*
+             *  Disable SBR decoding for any sbr-downsampled file whose SF is >= 24 KHz
+             */
+            if (pVars->prog_config.sampling_rate_idx < 6)
+            {
+                pVars->aacPlusEnabled = false;
+            }
+        }
+
+    }
+    else
+    {
+        status = -1;
+    }
+
+
+    /*
+     * Translate from units of bits back into units of words.
+     */
+    pExt->inputBufferUsedLength = 0;
+
+    pExt->remainderBits = 0;
+
+    pVars->bno++;
+
+    pExt->samplingRate = samp_rate * upsamplingFactor;
+
+    pExt->aacPlusEnabled = pVars->aacPlusEnabled;
+
+    /*
+     *  we default to 2 channel, even for mono files, (where channels have same content)
+     *  this is done to ensure support for enhanced aac+ with implicit signalling
+     */
+
+    pExt->encodedChannels = 2;
+
+    pExt->frameLength = 1024;
+#ifdef AAC_PLUS
+    pExt->aacPlusUpsamplingFactor = upsamplingFactor;
+#endif
+
+    pVars->status = status;
+
+    return (status);
+
+} /* PVMP4AudioDecoderDecodeFrame */
diff --git a/media/libstagefright/codecs/aacdec/q_normalize.cpp b/media/libstagefright/codecs/aacdec/q_normalize.cpp
new file mode 100644
index 0000000..5266966
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/q_normalize.cpp
@@ -0,0 +1,388 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: q_normalize.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Modify to include search over the scalefactor bands to insure
+     that the data is using all 31 data-bits.
+
+ Description:
+ (1) Modify to remove search over the scalefactor bands to insure
+     that the data is using all 31 data-bits.
+     (Pushed out into separate function)
+ (2) Change variable "k" to more descriptive "shift_amt"
+ (3) Update pseudocode to reflect removed code.
+ (4) Add PV Copyright notice.
+
+ Description:
+ (1) Modified to protect q-normalize from shifting by amounts >= 32.
+
+ Description:
+ (1) Delete local variable idx_count.
+
+ Description:
+ (1) Included search for max in each frame, modified interface.
+
+ Description:
+ (1) unrolled loop based on the fact that the size of each scale band
+     is always an even number.
+
+ Description:Check shift, if zero, do not shift.
+
+ Description: Eliminated warning: non use variable "i" and memset function
+    definition
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    qFormat[] = Array of qFormats, one per scalefactor band. [ Int ]
+
+    pFrameInfo = Pointer to structure that holds information about each group.
+                 (long block flag, number of windows, scalefactor bands, etc.)
+                 [const FrameInfo]
+
+    coef[]    = Array of the spectral coefficients for one channel. [ Int32 ]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    min_q = The common q-format for the entire frame. [Int]
+
+ Pointers and Buffers Modified:
+    coef[]    = Array of spectral data, now normalized to one q-format.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module first scans every scalefactor band for the frame, insuring that
+ at least one element in that scalefactor band is using all available bits.
+ If not, the elements in the scalefactor band are shifted up to use all 31
+ data bits.  The q-format is adjusted accordingly.
+
+ This module then scans the q-formats for each scalefactor band.
+ Upon finding the minimum q-format in the frame, the coefficients in each
+ scalefactor band are normalized to the minimum q-format.
+ The minimum q-format is then returned to the calling function, which is now
+ the q-format for the entire frame.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    nwin = pFrameInfo->num_win;
+
+    pQformat   = &(qFormat[0]);
+    pSfbPerWin = &(pFrameInfo->sfb_per_win[0]);
+    pCoef      = &(coef[0]);
+
+    FOR (win = nwin; win > 0; win--)
+
+        nsfb = *(pSfbPerWin++);
+
+        FOR (sfb = nsfb; sfb > 0; sfb--)
+
+            IF ( *(pQformat) < min_q)
+                min_q = *(pQformat);
+            ENDIF
+
+            pQformat++;
+
+        ENDFOR
+
+    ENDFOR
+
+    pQformat   = &(qFormat[0]);
+    pSfbPerWin = &(pFrameInfo->sfb_per_win[0]);
+    pCoef      = &(coef[0]);
+
+    FOR (win = 0; win < nwin; win++)
+
+        stop_idx = 0;
+
+        nsfb   = *(pSfbPerWin++);
+
+        pWinSfbTop = &(pFrameInfo->win_sfb_top[win][0]);
+
+        FOR (sfb = nsfb; sfb > 0; sfb--)
+
+            sfbWidth  = *(pWinSfbTop++) - stop_idx;
+
+            stop_idx += sfbWidth;
+
+            k = *(pQformat++) - min_q;
+
+            IF (k < 32)
+            THEN
+                FOR (; sfbWidth > 0; sfbWidth--)
+                    *(pCoef++) >>= k;
+                ENDFOR
+            ELSE
+                FOR (; sfbWidth > 0; sfbWidth--)
+                    *(pCoef++) = 0;
+                ENDFOR
+            ENDIF
+
+        ENDFOR
+
+    ENDFOR
+
+    return min_q;
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+#include "q_normalize.h"
+#include "aac_mem_funcs.h"         /* For pv_memset                         */
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int q_normalize(
+    Int        qFormat[],
+    const FrameInfo *pFrameInfo,
+    Int32      abs_max_per_window[],
+    Int32      coef[])
+{
+    Int    sfb;
+    Int    nsfb;
+    Int    win;
+    Int    nwin;
+    Int    sfbWidth;
+
+    Int    shift_amt;
+
+    /* Initialize min_q to a very large value */
+    Int    min_q = 1000;
+
+    Int stop_idx  = 0;
+
+    const Int   *pSfbPerWin;
+    const Int16 *pWinSfbTop;
+
+    Int   *pQformat;
+    Int32 *pCoef;
+
+    nwin = pFrameInfo->num_win;
+
+    /* Find the minimum q format */
+    pQformat   = &(qFormat[0]);
+    pSfbPerWin = &(pFrameInfo->sfb_per_win[0]);
+
+    for (win = nwin; win != 0; win--)
+    {
+
+        nsfb = *(pSfbPerWin++);
+
+        if (nsfb < 0 || nsfb > MAXBANDS)
+        {
+            break;  /* avoid any processing on error condition */
+        }
+
+        for (sfb = nsfb; sfb != 0; sfb--)
+        {
+            Int qformat = *(pQformat++);
+            if (qformat < min_q)
+            {
+                min_q = qformat;
+            }
+        }
+
+    } /* for(win) */
+
+    /* Normalize the coefs in each scalefactor band to one q-format */
+    pQformat   = &(qFormat[0]);
+    pSfbPerWin = &(pFrameInfo->sfb_per_win[0]);
+    pCoef      = &(coef[0]);
+
+    for (win = 0; win < nwin; win++)
+    {
+
+        Int32 max = 0;
+        stop_idx = 0;
+
+        nsfb   = *(pSfbPerWin++);
+
+        if (nsfb < 0 || nsfb > MAXBANDS)
+        {
+            break;  /* avoid any processing on error condition */
+        }
+
+        pWinSfbTop = &(pFrameInfo->win_sfb_top[win][0]);
+
+        for (sfb = nsfb; sfb != 0; sfb--)
+        {
+            Int tmp1, tmp2;
+            tmp1 = *(pWinSfbTop++);
+            tmp2 = *(pQformat++);
+            sfbWidth  = tmp1 - stop_idx;
+
+            if (sfbWidth < 2)
+            {
+                break;  /* will lead to error condition */
+            }
+
+            stop_idx += sfbWidth;
+
+            shift_amt = tmp2 - min_q;
+
+            if (shift_amt == 0)
+            {
+                Int32 tmp1, tmp2;
+                tmp1 = *(pCoef++);
+                tmp2 = *(pCoef++);
+                /*
+                 *  sfbWidth is always an even number
+                 *  (check tables in pg.66 IS0 14496-3)
+                 */
+                for (Int i = (sfbWidth >> 1) - 1; i != 0; i--)
+                {
+                    max  |= (tmp1 >> 31) ^ tmp1;
+                    max  |= (tmp2 >> 31) ^ tmp2;
+                    tmp1 = *(pCoef++);
+                    tmp2 = *(pCoef++);
+                }
+                max  |= (tmp1 >> 31) ^ tmp1;
+                max  |= (tmp2 >> 31) ^ tmp2;
+
+            }
+            else
+            {
+                if (shift_amt < 31)
+                {
+                    Int32 tmp1, tmp2;
+                    tmp1 = *(pCoef++) >> shift_amt;
+                    tmp2 = *(pCoef--) >> shift_amt;
+                    /*
+                     *  sfbWidth is always an even number
+                     *  (check tables in pg.66 IS0 14496-3)
+                     */
+                    for (Int i = (sfbWidth >> 1) - 1; i != 0; i--)
+                    {
+                        *(pCoef++)   = tmp1;
+                        *(pCoef++)   = tmp2;
+
+                        max  |= (tmp1 >> 31) ^ tmp1;
+                        max  |= (tmp2 >> 31) ^ tmp2;
+                        tmp1 = *(pCoef++) >> shift_amt;
+                        tmp2 = *(pCoef--) >> shift_amt;
+
+                    }
+                    *(pCoef++)   = tmp1;
+                    *(pCoef++)   = tmp2;
+                    max  |= (tmp1 >> 31) ^ tmp1;
+                    max  |= (tmp2 >> 31) ^ tmp2;
+
+                }
+                else
+                {
+                    pv_memset(pCoef, 0, sizeof(Int32)*sfbWidth);
+                    pCoef += sfbWidth;
+                }
+            }
+
+            abs_max_per_window[win] = max;
+
+        }
+
+    } /* for (win) */
+
+    return min_q;
+
+} /* normalize() */
diff --git a/media/libstagefright/codecs/aacdec/q_normalize.h b/media/libstagefright/codecs/aacdec/q_normalize.h
new file mode 100644
index 0000000..63a9d53
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/q_normalize.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: q_normalize.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Added PV Copyright notice.
+ (2) Removed embedded TABS
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+  This file includes the function definition for q_normalize.h
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef Q_NORMALIZE_H
+#define Q_NORMALIZE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int q_normalize(
+        Int        qFormat[],
+        const FrameInfo *pFrameInfo,
+        Int32     abs_max_per_window[],
+        Int32      coef[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.cpp b/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.cpp
new file mode 100644
index 0000000..1164129
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.cpp
@@ -0,0 +1,319 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: qmf_filterbank_coeff.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+ Local Stores/Buffers/Pointers Needed:
+
+ Global Stores/Buffers/Pointers Needed:
+
+ Outputs:
+
+ Pointers and Buffers Modified:
+
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function defines the scalefactor bands for all sampling rates
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ 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
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "qmf_filterbank_coeff.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
+----------------------------------------------------------------------------*/
+
+
+
+const Int32 sbrDecoderFilterbankCoefficients[155] =
+{
+    /*  10/9*table */
+
+    0xFFEA0066,  0x020C09CF,  0x34F67965,  0xCE380A2F,  0xFE43005A,
+    0xFFEA006C,  0x02360998,  0x36907954,  0xCFCD0A57,  0xFE690054,
+    0xFFEC0072,  0x0262095B,  0x382B7937,  0xD1600A7A,  0xFE8E004F,
+    0xFFED0078,  0x028E0919,  0x39C6790F,  0xD2F00A98,  0xFEB20049,
+    0xFFED007E,  0x02BB08D0,  0x3B6378DB,  0xD47D0AB1,  0xFED50043,
+    0xFFEC0084,  0x02E90882,  0x3D00789B,  0xD6080AC6,  0xFEF6003E,
+    0xFFEB0089,  0x0318082F,  0x3E9D7851,  0xD78F0AD6,  0xFF160039,
+    0xFFEB008F,  0x034807D5,  0x403A77FB,  0xD9130AE2,  0xFF350033,
+    0xFFEA0095,  0x03790775,  0x41D7779A,  0xDA930AEA,  0xFF53002E,
+    0xFFE9009A,  0x03AB070E,  0x4373772D,  0xDC100AED,  0xFF6F0029,
+    0xFFE800A0,  0x03DE06A2,  0x450D76B6,  0xDD890AED,  0xFF8A0024,
+    0xFFE800A5,  0x0412062F,  0x46A77633,  0xDEFD0AE9,  0xFFA40020,
+    0xFFE700AA,  0x044705B6,  0x483F75A6,  0xE06D0AE2,  0xFFBD001C,
+    0xFFE600AF,  0x047B0537,  0x49D5750E,  0xE1D90AD7,  0xFFD40017,
+    0xFFE500B3,  0x04B104B0,  0x4B69746B,  0xE3400AC8,  0xFFEB0013,
+    0xFFE400B8,  0x04E70423,  0x4CFA73BE,  0xE4A20AB7,  0x0002000F,
+    0xFFE400BC,  0x051E0390,  0x4E897306,  0xE5FF0AA2,  0x0016000B,
+    0xFFE300BF,  0x055502F6,  0x50157244,  0xE7560A8A,  0x00280008,
+    0xFFE300C3,  0x058D0254,  0x519D7178,  0xE8A80A6F,  0x003A0004,
+    0xFFE300C6,  0x05C401AD,  0x532270A2,  0xE9F50A53,  0x004A0001,
+    0xFFE200C8,  0x05FC00FE,  0x54A36FC3,  0xEB3C0A33,  0x005AFFFC,
+    0xFFE200CA,  0x06340048,  0x56206EDA,  0xEC7D0A11,  0x0068FFF9,
+    0xFFE200CC,  0x066CFF8A,  0x57986DE8,  0xEDB809EC,  0x0075FFF7,
+    0xFFE200CD,  0x06A4FEC6,  0x590C6CEC,  0xEEED09C6,  0x0081FFF4,
+    0xFFE200CE,  0x06DCFDFC,  0x5A7B6BE7,  0xF01C099E,  0x008DFFF2,
+    0xFFE200CE,  0x0713FD2B,  0x5BE56ADA,  0xF1450973,  0x0097FFF0,
+    0xFFE300CD,  0x074BFC52,  0x5D4869C4,  0xF2680947,  0x00A0FFEE,
+    0xFFE300CC,  0x0781FB73,  0x5EA668A6,  0xF384091A,  0x00A8FFEC,
+    0xFFE400CA,  0x07B7FA8D,  0x5FFF6780,  0xF49908EB,  0x00B0FFEA,
+    0xFFE400C8,  0x07EDF9A0,  0x61506652,  0xF5A808BA,  0x00B6FFE9,
+    0xFFE500C5,  0x0822F8AC,  0x629B651C,  0xF6B00888,  0x00BCFFE7
+};
+
+
+const Int32 sbrDecoderFilterbankCoefficients_down_smpl[160] =
+{
+    0x0000FFEE,  0xFFF0FFEF, 0xFFEEFFED, 0xFFEBFFEA,
+    0xFFE9FFE8,  0xFFE7FFE6, 0xFFE6FFE7, 0xFFE7FFE8,
+    0xFFEAFFED,  0xFFEFFFF3, 0xFFF7FFFB, 0x00000007,
+    0x000D0014,  0x001C0025, 0x002E0037, 0x0041004B,
+    0x00560061,  0x006B0076, 0x0080008A, 0x0094009D,
+    0x00A500AC,  0x00B200B6, 0x00B800B9, 0x00B700B3,
+    0x00AD00A3,  0x00970087, 0x0074005D, 0x00420024,
+    0x0001FFDA,  0xFFAFFF7F, 0xFF4BFF12, 0xFED5FE93,
+    0x01B301FD,  0x024C029E, 0x02F4034D, 0x03A90408,
+    0x046904CC,  0x05300595, 0x05FA065E, 0x06C10722,
+    0x078007DA,  0x08300881, 0x08CB090F, 0x094A097C,
+    0x09A409C1,  0x09D209D5, 0x09CB09B2, 0x0988094D,
+    0x090108A2,  0x082F07A8, 0x070C0659, 0x059104B1,
+    0x03B902AA,  0x01810041, 0xFEE7FD74, 0xFBE9FA45,
+    0xF887F6B2,  0xF4C4F2BF, 0xF0A4EE72, 0xEC2AE9CF,
+    0xE760E4DE,  0xE24CDFA9, 0xDCF9DA3B, 0xD772D4A0,
+    0x2E3A311B,  0x33FF36E7, 0x39CE3CB4, 0x3F964273,
+    0x45484813,  0x4AD24D84, 0x502552B4, 0x55305795,
+    0x59E35C17,  0x5E2F602B, 0x620863C4, 0x655F66D7,
+    0x682B6959,  0x6A626B43, 0x6BFC6C8C, 0x6CF46D32,
+    0x6D476D32,  0x6CF46C8C, 0x6BFC6B43, 0x6A626959,
+    0x682B66D7,  0x655F63C4, 0x6208602B, 0x5E2F5C17,
+    0x59E35795,  0x553052B4, 0x50254D84, 0x4AD24813,
+    0x45484273,  0x3F963CB4, 0x39CE36E7, 0x33FF311B,
+    0xD1C6D4A0,  0xD772DA3B, 0xDCF9DFA9, 0xE24CE4DE,
+    0xE760E9CF,  0xEC2AEE72, 0xF0A4F2BF, 0xF4C4F6B2,
+    0xF887FA45,  0xFBE9FD74, 0xFEE70041, 0x018102AA,
+    0x03B904B1,  0x05910659, 0x070C07A8, 0x082F08A2,
+    0x0901094D,  0x098809B2, 0x09CB09D5, 0x09D209C1,
+    0x09A4097C,  0x094A090F, 0x08CB0881, 0x083007DA,
+    0x07800722,  0x06C1065E, 0x05FA0595, 0x053004CC,
+    0x04690408,  0x03A9034D, 0x02F4029E, 0x024C01FD,
+    0xFE4DFE93,  0xFED5FF12, 0xFF4BFF7F, 0xFFAFFFDA,
+    0x00010024,  0x0042005D, 0x00740087, 0x009700A3,
+    0x00AD00B3,  0x00B700B9, 0x00B800B6, 0x00B200AC,
+    0x00A5009D,  0x0094008A, 0x00800076, 0x006B0061,
+    0x0056004B,  0x00410037, 0x002E0025, 0x001C0014,
+    0x000D0007,  0x0000FFFB, 0xFFF7FFF3, 0xFFEFFFED,
+    0xFFEAFFE8,  0xFFE7FFE7, 0xFFE6FFE6, 0xFFE7FFE8,
+    0xFFE9FFEA,  0xFFEBFFED, 0xFFEEFFEF, 0xFFF0FFEE
+};
+
+const Int32 sbrDecoderFilterbankCoefficients_an_filt_LC[155] =
+{
+
+    Qfmt27(-0.00079446133872F), Qfmt27(0.02197766364781F), Qfmt27(0.54254182141522F), Qfmt27(-0.47923775873194F),
+    Qfmt27(-0.01574239605130F), Qfmt27(-0.00068946163857F), Qfmt27(0.02537571195384F), Qfmt27(0.57449847577240F),
+    Qfmt27(-0.44806230039026F), Qfmt27(-0.01291535202742F), Qfmt27(-0.00071286404460F), Qfmt27(0.02892516313544F),
+    Qfmt27(0.60657315615086F), Qfmt27(-0.41729436041451F), Qfmt27(-0.01026942774868F), Qfmt27(-0.00077308974337F),
+    Qfmt27(0.03262310249845F), Qfmt27(0.63865835544980F), Qfmt27(-0.38701849746199F), Qfmt27(-0.00782586328859F),
+    Qfmt27(-0.00083027488297F), Qfmt27(0.03646915244785F), Qfmt27(0.67068416485018F), Qfmt27(-0.35729827194706F),
+    Qfmt27(-0.00557215982767F), Qfmt27(-0.00089272089703F), Qfmt27(0.04045671426315F), Qfmt27(0.70254003810627F),
+    Qfmt27(-0.32819525024294F), Qfmt27(-0.00351102841332F), Qfmt27(-0.00095851011196F), Qfmt27(0.04455021764484F),
+    Qfmt27(0.73415149000395F), Qfmt27(-0.29977591877185F), Qfmt27(-0.00163598204794F), Qfmt27(-0.00101225729839F),
+    Qfmt27(0.04873676213679F), Qfmt27(0.76545064960593F), Qfmt27(-0.27208998714049F), Qfmt27(0.00003903936539F),
+    Qfmt27(-0.00105230782648F), Qfmt27(0.05300654158217F), Qfmt27(0.79631383686511F), Qfmt27(-0.24519750285673F),
+    Qfmt27(0.00154182229475F), Qfmt27(-0.00108630976316F), Qfmt27(0.05732502937107F), Qfmt27(0.82666485395476F),
+    Qfmt27(-0.21914753347432F), Qfmt27(0.00286720203220F), Qfmt27(-0.00110794157381F), Qfmt27(0.06167350555855F),
+    Qfmt27(0.85641712130638F), Qfmt27(-0.19396671004887F), Qfmt27(0.00402297937976F), Qfmt27(-0.00110360418081F),
+    Qfmt27(0.06602157445253F), Qfmt27(0.88547343436495F), Qfmt27(-0.16971665552213F), Qfmt27(0.00500649278750F),
+    Qfmt27(-0.00109714405326F), Qfmt27(0.07034096875232F), Qfmt27(0.91376152398903F), Qfmt27(-0.14641770628514F),
+    Qfmt27(0.00583386287581F), Qfmt27(-0.00106490281247F), Qfmt27(0.07461825625751F), Qfmt27(0.94117890777861F),
+    Qfmt27(-0.12410396326951F), Qfmt27(0.00651097277313F), Qfmt27(-0.00102041023958F), Qfmt27(0.07879625324269F),
+    Qfmt27(0.96765488212662F), Qfmt27(-0.10280530739363F), Qfmt27(0.00704839655425F), Qfmt27(-0.00094051141595F),
+    Qfmt27(0.08286099010631F), Qfmt27(0.99311573680798F), Qfmt27(-0.08254839941155F), Qfmt27(0.00745513427428F),
+    Qfmt27(-0.00084090835475F), Qfmt27(0.08675566213219F), Qfmt27(1.01745066253324F), Qfmt27(-0.06332944781672F),
+    Qfmt27(0.00774335382672F), Qfmt27(-0.00072769348801F), Qfmt27(0.09046949018457F), Qfmt27(1.04060828658052F),
+    Qfmt27(-0.04518854556363F), Qfmt27(0.00790787636150F), Qfmt27(-0.00057913742435F), Qfmt27(0.09395575430420F),
+    Qfmt27(1.06251808919053F), Qfmt27(-0.02811939233087F), Qfmt27(0.00797463714114F), Qfmt27(-0.00040969484059F),
+    Qfmt27(0.09716267023308F), Qfmt27(1.08310018709600F), Qfmt27(-0.01212147193047F), Qfmt27(0.00795079915733F),
+    Qfmt27(-0.00020454902123F), Qfmt27(0.10007381188066F), Qfmt27(1.10227871198194F), Qfmt27(0.00279527795884F),
+    Qfmt27(0.00784545014643F), Qfmt27(0.00001908481202F), Qfmt27(0.10262701466139F), Qfmt27(1.12001978353403F),
+    Qfmt27(0.01663452156443F), Qfmt27(0.00766458213130F), Qfmt27(0.00028892665922F), Qfmt27(0.10479373974558F),
+    Qfmt27(1.13624787143434F), Qfmt27(0.02941522773279F), Qfmt27(0.00741912981120F), Qfmt27(0.00056943874774F),
+    Qfmt27(0.10650970405576F), Qfmt27(1.15091404672203F), Qfmt27(0.04112872592057F), Qfmt27(0.00712664923329F),
+    Qfmt27(0.00088238158168F), Qfmt27(0.10776200996423F), Qfmt27(1.16395714324633F), Qfmt27(0.05181934748033F),
+    Qfmt27(0.00677868764313F), Qfmt27(0.00121741725989F), Qfmt27(0.10848340171661F), Qfmt27(1.17535833075364F),
+    Qfmt27(0.06148559051724F), Qfmt27(0.00639363830229F), Qfmt27(0.00159101288509F), Qfmt27(0.10864412991640F),
+    Qfmt27(1.18507099110810F), Qfmt27(0.07014197759039F), Qfmt27(0.00597707038378F), Qfmt27(0.00196610899088F),
+    Qfmt27(0.10819451041273F), Qfmt27(1.19306425909871F), Qfmt27(0.07784680399703F), Qfmt27(0.00554476792518F),
+    Qfmt27(0.00238550675072F), Qfmt27(0.10709920766553F), Qfmt27(1.19929775892826F), Qfmt27(0.08459352758522F),
+    Qfmt27(0.00509233837916F), Qfmt27(0.00280596092809F), Qfmt27(0.10531144797543F), Qfmt27(1.20377455661175F),
+    Qfmt27(0.09043115226911F), Qfmt27(0.00463008004888F), Qfmt27(0.00325513071185F), Qfmt27(0.10278145526768F),
+    Qfmt27(1.20646855283790F), Qfmt27(0.09539224314440F), Qfmt27(0.00416760958657F)
+};
+
+
+
+#ifdef HQ_SBR
+
+
+const Int32 sbrDecoderFilterbankCoefficients_an_filt[155] =
+{
+    Qfmt27(-0.000561769F),   Qfmt27(+ 0.015540555F),   Qfmt27(+ 0.383635001F),   Qfmt27(-0.338872269F),   Qfmt27(-0.011131555F),
+    Qfmt27(-0.000487523F),   Qfmt27(+ 0.017943338F),   Qfmt27(+ 0.406231768F),   Qfmt27(-0.316827891F),   Qfmt27(-0.009132533F),
+    Qfmt27(-0.000504071F),   Qfmt27(+ 0.020453179F),   Qfmt27(+ 0.428911992F),   Qfmt27(-0.295071672F),   Qfmt27(-0.007261582F),
+    Qfmt27(-0.000546657F),   Qfmt27(+ 0.023068017F),   Qfmt27(+ 0.451599654F),   Qfmt27(-0.273663404F),   Qfmt27(-0.005533721F),
+    Qfmt27(-0.000587093F),   Qfmt27(+ 0.025787585F),   Qfmt27(+ 0.474245321F),   Qfmt27(-0.252648031F),   Qfmt27(-0.003940112F),
+    Qfmt27(-0.000631249F),   Qfmt27(+ 0.028607217F),   Qfmt27(+ 0.496770825F),   Qfmt27(-0.232069087F),   Qfmt27(-0.002482672F),
+    Qfmt27(-0.000677769F),   Qfmt27(+ 0.031501761F),   Qfmt27(+ 0.519123497F),   Qfmt27(-0.211973585F),   Qfmt27(-0.001156814F),
+    Qfmt27(-0.000715774F),   Qfmt27(+ 0.034462095F),   Qfmt27(+ 0.541255345F),   Qfmt27(-0.192396675F),   Qfmt27(+ 0.000027605F),
+    Qfmt27(-0.000744094F),   Qfmt27(+ 0.037481285F),   Qfmt27(+ 0.563078914F),   Qfmt27(-0.173380817F),   Qfmt27(+ 0.001090233F),
+    Qfmt27(-0.000768137F),   Qfmt27(+ 0.040534917F),   Qfmt27(+ 0.584540324F),   Qfmt27(-0.154960707F),   Qfmt27(+ 0.002027418F),
+    Qfmt27(-0.000783433F),   Qfmt27(+ 0.043609754F),   Qfmt27(+ 0.605578354F),   Qfmt27(-0.137155176F),   Qfmt27(+ 0.002844676F),
+    Qfmt27(-0.000780366F),   Qfmt27(+ 0.046684303F),   Qfmt27(+ 0.626124270F),   Qfmt27(-0.120007798F),   Qfmt27(+ 0.003540125F),
+    Qfmt27(-0.000775798F),   Qfmt27(+ 0.049738576F),   Qfmt27(+ 0.646126970F),   Qfmt27(-0.103532953F),   Qfmt27(+ 0.004125164F),
+    Qfmt27(-0.000753000F),   Qfmt27(+ 0.052763075F),   Qfmt27(+ 0.665513988F),   Qfmt27(-0.087754754F),   Qfmt27(+ 0.004603953F),
+    Qfmt27(-0.000721539F),   Qfmt27(+ 0.055717365F),   Qfmt27(+ 0.684235329F),   Qfmt27(-0.072694330F),   Qfmt27(+ 0.004983969F),
+    Qfmt27(-0.000665042F),   Qfmt27(+ 0.058591568F),   Qfmt27(+ 0.702238872F),   Qfmt27(-0.058370533F),   Qfmt27(+ 0.005271576F),
+    Qfmt27(-0.000594612F),   Qfmt27(+ 0.061345517F),   Qfmt27(+ 0.719446263F),   Qfmt27(-0.044780682F),   Qfmt27(+ 0.005475378F),
+    Qfmt27(-0.000514557F),   Qfmt27(+ 0.063971590F),   Qfmt27(+ 0.735821176F),   Qfmt27(-0.031953127F),   Qfmt27(+ 0.005591713F),
+    Qfmt27(-0.000409512F),   Qfmt27(+ 0.066436751F),   Qfmt27(+ 0.751313746F),   Qfmt27(-0.019883413F),   Qfmt27(+ 0.005638920F),
+    Qfmt27(-0.000289698F),   Qfmt27(+ 0.068704383F),   Qfmt27(+ 0.765867487F),   Qfmt27(-0.008571175F),   Qfmt27(+ 0.005622064F),
+    Qfmt27(-0.000144638F),   Qfmt27(+ 0.070762871F),   Qfmt27(+ 0.779428752F),   Qfmt27(+ 0.001976560F),   Qfmt27(+ 0.005547571F),
+    Qfmt27(+ 0.000013495F),   Qfmt27(+ 0.072568258F),   Qfmt27(+ 0.791973584F),   Qfmt27(+ 0.011762383F),   Qfmt27(+ 0.005419678F),
+    Qfmt27(+ 0.000204302F),   Qfmt27(+ 0.074100364F),   Qfmt27(+ 0.803448575F),   Qfmt27(+ 0.020799707F),   Qfmt27(+ 0.005246117F),
+    Qfmt27(+ 0.000402654F),   Qfmt27(+ 0.075313734F),   Qfmt27(+ 0.813819127F),   Qfmt27(+ 0.029082401F),   Qfmt27(+ 0.005039302F),
+    Qfmt27(+ 0.000623938F),   Qfmt27(+ 0.076199248F),   Qfmt27(+ 0.823041989F),   Qfmt27(+ 0.036641812F),   Qfmt27(+ 0.004793256F),
+    Qfmt27(+ 0.000860844F),   Qfmt27(+ 0.076709349F),   Qfmt27(+ 0.831103846F),   Qfmt27(+ 0.043476878F),   Qfmt27(+ 0.004520985F),
+    Qfmt27(+ 0.001125016F),   Qfmt27(+ 0.076823001F),   Qfmt27(+ 0.837971734F),   Qfmt27(+ 0.049597868F),   Qfmt27(+ 0.004226427F),
+    Qfmt27(+ 0.001390249F),   Qfmt27(+ 0.076505072F),   Qfmt27(+ 0.843623828F),   Qfmt27(+ 0.055046003F),   Qfmt27(+ 0.003920743F),
+    Qfmt27(+ 0.001686808F),   Qfmt27(+ 0.075730576F),   Qfmt27(+ 0.848031578F),   Qfmt27(+ 0.059816657F),   Qfmt27(+ 0.003600827F),
+    Qfmt27(+ 0.001984114F),   Qfmt27(+ 0.074466439F),   Qfmt27(+ 0.851197152F),   Qfmt27(+ 0.063944481F),   Qfmt27(+ 0.003273961F),
+    Qfmt27(+ 0.002301725F),   Qfmt27(+ 0.072677464F),   Qfmt27(+ 0.853102095F),   Qfmt27(+ 0.067452502F),   Qfmt27(+ 0.002946945F)
+};
+
+
+
+#endif  /* HQ_SBR */
+
+
+#endif  /* AAC_PLUS */
diff --git a/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.h b/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.h
new file mode 100644
index 0000000..c8968cb
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/qmf_filterbank_coeff.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: qmf_filterbank_coeff.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ this file declares the scalefactor bands for all sampling rates
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef QMF_FILTERBANK_COEFF_H
+#define QMF_FILTERBANK_COEFF_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#define Qfmt(x)   (Int16)(x*(((Int32)1<<15)*1.11111111111111111F) + (x>=0?0.5F:-0.5F))
+
+
+#define Qfmt30(x)   (Int32)(x*((Int32)1<<30) + (x>=0?0.5F:-0.5F))
+#define Qfmt27(x)   (Int32)(x*(((Int32)1<<27)) + (x>=0?0.5F:-0.5F))
+
+extern const Int32 sbrDecoderFilterbankCoefficients[155];
+
+
+extern const Int32 sbrDecoderFilterbankCoefficients_down_smpl[160];
+extern const Int32 sbrDecoderFilterbankCoefficients_an_filt_LC[155];
+
+#ifdef HQ_SBR
+extern const Int32 sbrDecoderFilterbankCoefficients_an_filt[155];
+#endif
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_adif_header.h b/media/libstagefright/codecs/aacdec/s_adif_header.h
new file mode 100644
index 0000000..7fd49d3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_adif_header.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_ADIF_Header.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, ADIF_Header
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_ADIF_HEADER_H
+#define S_ADIF_HEADER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_adif_const.h"
+#include "e_rawbitstreamconst.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Char    adif_id[LEN_ADIF_ID+1];
+    Int     copy_id_present;
+    Char    copy_id[LEN_COPYRT_ID+1];
+    Int     original_copy;
+    Int     home;
+    Int     bitstream_type;
+    Int32   bitrate;
+    Int     num_pce;
+    Int     prog_tags[(1<<LEN_TAG)];
+} ADIF_Header;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/s_bit_buffer.h b/media/libstagefright/codecs/aacdec/s_bit_buffer.h
new file mode 100644
index 0000000..9f0dbda
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_bit_buffer.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_bit_buffer.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_BIT_BUFFER_H
+#define S_BIT_BUFFER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    UChar *char_ptr;
+    UInt32 buffered_bits;
+    UInt32 buffer_word;
+    UInt32 nrBitsRead;
+    UInt32 bufferLen;
+}
+BIT_BUFFER;
+
+typedef BIT_BUFFER *HANDLE_BIT_BUFFER;
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_bits.h b/media/libstagefright/codecs/aacdec/s_bits.h
new file mode 100644
index 0000000..cae69ad
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_bits.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_BITS.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Remove unused field.
+
+ Description: Change buffer type from UInt to UInt32, makes API much easier
+              to understand and describe, and getbits is faster on TI C55X
+              if the buffer is 32 bits instead of 16.
+
+ Description: Change buffer type from UInt32 to UChar.
+
+ Who:                                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, BITS
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef  S_BITS_H
+#define  S_BITS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+/*
+ * Name: BITS
+ * Description: Holds information for processing the input data buffer
+ *    as a "stream". The data is in packed format.
+ * Fields:
+ *    pBuffer - pointer to the beginning of the buffer. If the data type of
+ *        this changes, make sure to update the constants in ibstream.h
+ *    usedBits - number of bits read thus far from the buffer. Bit 0 is
+ *        the LSB of pBuffer[0].
+ *    availableBits - number of bits available in the buffer.
+ *    byteAlignOffset - used with ADTS in case sync word is not aligned
+                        on a boundary.
+ */
+typedef struct
+{
+    UChar    *pBuffer;
+    UInt      usedBits;      /* Keep this unsigned so can go to 65536 */
+    UInt      availableBits; /* Ditto */
+    UInt      inputBufferCurrentLength; /* Ditto */
+    Int      byteAlignOffset; /* Used in ADTS.  See find_adts_syncword() */
+} BITS;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/s_ch_info.h b/media/libstagefright/codecs/aacdec/s_ch_info.h
new file mode 100644
index 0000000..9fd259c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_ch_info.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_Ch_Info.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, Ch_Info
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_CH_INFO_H
+#define S_CH_INFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+//    Int present;    /* channel present */
+    Int tag;        /* element tag */
+    Int cpe;        /* 0 if single channel, 1 if channel pair */
+//    Int common_window;  /* 1 if common window for cpe */
+//    Int ch_is_left; /* 1 if left channel of cpe */
+//    Int paired_ch;  /* index of paired channel in cpe */
+//    Int widx;       /* window element index for this channel */
+    Int is_present; /* intensity stereo is used */
+    Int ncch;       /* number of coupling channels for this ch */
+    /* #if (CChans > 0) */
+    /*    int cch[CChans];*/    /* coupling channel idx */
+    /*    int cc_dom[CChans];*/ /* coupling channel domain */
+    /*    int cc_ind[CChans];*/ /* independently switched coupling channel flag */
+    /* #endif */
+    Char *fext;     /* filename extension */
+
+} Ch_Info;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/s_crc_buffer.h b/media/libstagefright/codecs/aacdec/s_crc_buffer.h
new file mode 100644
index 0000000..69250e7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_crc_buffer.h
@@ -0,0 +1,90 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_crc_buffer.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_CRC_BUFFER_H
+#define S_CRC_BUFFER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    unsigned short crcState;
+    unsigned short crcMask;
+    unsigned short crcPoly;
+}
+CRC_BUFFER;
+
+typedef CRC_BUFFER *HANDLE_CRC;
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_elelist.h b/media/libstagefright/codecs/aacdec/s_elelist.h
new file mode 100644
index 0000000..40b2f13
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_elelist.h
@@ -0,0 +1,90 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_EleList.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, EleList
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_ELELIST_H
+#define S_ELELIST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_rawbitstreamconst.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int num_ele;
+    Int ele_is_cpe[(1<<LEN_TAG)];
+    Int ele_tag[(1<<LEN_TAG)];
+} EleList;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/s_frameinfo.h b/media/libstagefright/codecs/aacdec/s_frameinfo.h
new file mode 100644
index 0000000..871ae83
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_frameinfo.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_frameinfo.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed name of bk_sfb_top to frame_sfb_top.
+ Included "interface.h" for defintion of MAX_WIN.  This
+ will hopefully be simplified when interface.h is broken up into smaller
+ include files.
+
+ Description: Eliminated the never used array, group_offs[8]
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, FrameInfo
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_FRAMEINFO_H
+#define S_FRAMEINFO_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_blockswitching.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    {
+        Int     islong;                 /* true if long block */
+        Int     num_win;                /* sub-blocks (SB) per block */
+        Int     coef_per_frame;         /* coef's per block */
+        Int     sfb_per_frame;          /* sfb per block */
+        Int     coef_per_win[MAX_WIN];  /* coef's per SB */
+        Int     sfb_per_win[MAX_WIN];   /* sfb per SB */
+        Int     sectbits[MAX_WIN];
+        Int16   *win_sfb_top[MAX_WIN];  /* top coef per sfb per SB */
+        Int     *sfb_width_128;         /* sfb width for short blocks */
+
+        Int     frame_sfb_top[MAXBANDS];    /* Only used in calc_gsfb_table() -
+                                      it is simply a cum version of
+                                      the above information */
+        Int     num_groups;
+        Int     group_len[8];
+
+    } FrameInfo;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_FRAMEINFO_H */
diff --git a/media/libstagefright/codecs/aacdec/s_hcb.h b/media/libstagefright/codecs/aacdec/s_hcb.h
new file mode 100644
index 0000000..6a64c27
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_hcb.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_Hcb.h
+
+     Date: 05/07/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description:
+ (1) LAV removed from structure definition, since it was never used.
+
+ Description: Huffman tables are stored as UInt16
+
+ Description: Modified the declaration of the structure so no pointers are
+              used in the structure.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ define the structure Hcb to store Huffman codebook information,
+ this structure was originally defined in all.h
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_HCB_H
+#define S_HCB_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_huffman.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
+    {
+        Int     n;
+        Int     dim;
+        Int     mod;
+        Int     off;
+        Int     signed_cb;
+    } Hcb;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_HCB_H */
+
diff --git a/media/libstagefright/codecs/aacdec/s_huffman.h b/media/libstagefright/codecs/aacdec/s_huffman.h
new file mode 100644
index 0000000..2db3dd9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_huffman.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_Huffman.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:   Changed "ulong" to "UInt32"
+
+ Description: add helper structure to speed up decode_huff_cw
+
+ Description: Remove the structure definition of Huffman
+
+ Description: Added definition for SBR Huffman, used for AAC plus
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, Huffman
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_HUFFMAN_H
+#define S_HUFFMAN_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 const Char(*SbrHuffman)[2];
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/s_hybrid.h b/media/libstagefright/codecs/aacdec/s_hybrid.h
new file mode 100644
index 0000000..3880d30
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_hybrid.h
@@ -0,0 +1,100 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_hybrid.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_HYBRID_H
+#define S_HYBRID_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "ps_constants.h"
+#include    "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define HYBRID_FILTER_LENGTH        13
+#define HYBRID_FILTER_LENGTH_m_1    12
+#define HYBRID_FILTER_DELAY         6
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+typedef enum
+{
+
+    HYBRID_2_REAL = 2,
+    HYBRID_4_CPLX = 4,
+    HYBRID_8_CPLX = 8
+
+} HYBRID_RES;
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+typedef struct
+{
+    Int32   nQmfBands;
+    Int32   *pResolution;
+    Int32   qmfBufferMove;
+
+    Int32 **mQmfBufferReal;
+    Int32 **mQmfBufferImag;
+    Int32 *mTempReal;
+    Int32 *mTempImag;
+
+
+} HYBRID;
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif      /*  S_HYBRID_H */
diff --git a/media/libstagefright/codecs/aacdec/s_lt_pred_status.h b/media/libstagefright/codecs/aacdec/s_lt_pred_status.h
new file mode 100644
index 0000000..4b5b56e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_lt_pred_status.h
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: LT_PRED_STATUS.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Merged in #defines from ltp_common.h, thereby eliminating that file.
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description: Moved large ltp_buffer up to s_tDec_Int_Chan.h, since this
+ move allowed for other elements in this structure to be shared with
+ the fxpCoef array.
+
+ Description: Decreased size of LTP buffers from 4096 to 3072.  The upper 1024
+ elements in the LTP buffers were never touched in the code.  This saves
+ 4 kilobytes in memory.
+
+ Description: Decreased size of LTP buffers again from 3072 to 2048.  This
+ time, I realized that 1024 elements were duplicated in the 32-bit array
+ pVars->pChVars[]->time_quant.  Rather than copy this data EVERY frame
+ from a 32-bit to a 16-bit LTP buffer, the data is accessed only
+ when it is needed.  This saves both MIPS and memory.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ define LT_PRED_STATUS structure for pulse data decoding.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_LT_PRED_STATUS_H
+#define S_LT_PRED_STATUS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_blockswitching.h"
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+    /*
+      Macro:    MAX_SHORT_WINDOWS
+      Purpose:  Number of short windows in one long window.
+      Explanation:  -  */
+#ifndef MAX_SHORT_WINDOWS
+#define MAX_SHORT_WINDOWS NSHORT
+#endif
+
+    /*
+      Macro:    MAX_SCFAC_BANDS
+      Purpose:  Maximum number of scalefactor bands in one frame.
+      Explanation:  -  */
+#ifndef MAX_SCFAC_BANDS
+#define MAX_SCFAC_BANDS MAXBANDS
+#endif
+
+    /*
+      Macro:    BLOCK_LEN_LONG
+      Purpose:  Length of one long window
+      Explanation:  -  */
+#ifndef BLOCK_LEN_LONG
+#define BLOCK_LEN_LONG LN2
+#endif
+
+
+    /*
+      Macro:    LTP_MAX_BLOCK_LEN_LONG
+      Purpose:  Informs the routine of the maximum block size used.
+      Explanation:  This is needed since the TwinVQ long window
+            is different from the AAC long window.  */
+#define LTP_MAX_BLOCK_LEN_LONG BLOCK_LEN_LONG //(2 * BLOCK_LEN_LONG) 
+
+    /*
+      Macro:    LT_BLEN
+      Purpose:  Length of the history buffer.
+      Explanation:  Has to hold 2 long windows of time domain data.  */
+#ifndef LT_BLEN
+#define LT_BLEN (2 * LTP_MAX_BLOCK_LEN_LONG)
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*
+      Type:     LT_PRED_STATUS
+      Purpose:  Type of the struct holding the LTP encoding parameters.
+      Explanation:  -  */
+    typedef struct
+    {
+        Int weight_index;
+        Int win_prediction_used[MAX_SHORT_WINDOWS];
+        Int sfb_prediction_used[MAX_SCFAC_BANDS];
+        Bool ltp_data_present;
+
+        Int delay[MAX_SHORT_WINDOWS];
+    }
+    LT_PRED_STATUS;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_LT_PRED_STATUS_H */
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_mc_info.h b/media/libstagefright/codecs/aacdec/s_mc_info.h
new file mode 100644
index 0000000..9006119
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_mc_info.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_MC_Info.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) use enum type for audioObjectType (2) update revision history
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, MC_Info
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_MC_INFO_H
+#define S_MC_INFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_rawbitstreamconst.h"
+#include "s_ch_info.h"
+#include "chans.h"
+#include "e_tmp4audioobjecttype.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int nch;        /* total number of audio channels */
+    Int nfsce;      /* number of front SCE's pror to first front CPE */
+    Int nfch;       /* number of front channels */
+    Int nsch;       /* number of side channels */
+    Int nbch;       /* number of back channels */
+    Int nlch;       /* number of lfe channels */
+    Int ncch;       /* number of valid coupling channels */
+    tMP4AudioObjectType audioObjectType;    /* Should eventually be called object */
+    Int sampling_rate_idx;
+
+    Int implicit_channeling;
+    Int  upsamplingFactor;
+#ifdef AAC_PLUS
+    bool bDownSampledSbr;
+    Int HE_AAC_level;
+#endif
+    /* All AAC content should be aware of these flag */
+    /*  AAC+ content Flag */
+    Int sbrPresentFlag;
+    /*  Enhanced AAC+ content Flag */
+    Int psPresentFlag;
+    tMP4AudioObjectType ExtendedAudioObjectType;    /* Should eventually be called object */
+
+    Ch_Info ch_info[Chans];
+} MC_Info;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/s_mixdown.h b/media/libstagefright/codecs/aacdec/s_mixdown.h
new file mode 100644
index 0000000..7f456d5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_mixdown.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_MIXdown.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, MIXdown
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_MIXDOWN_H
+#define S_MIXDOWN_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int present;
+    Int ele_tag;
+    Int pseudo_enab;
+} MIXdown;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/s_patch.h b/media/libstagefright/codecs/aacdec/s_patch.h
new file mode 100644
index 0000000..554fc2d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_patch.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_patch.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_PATCH_H
+#define S_PATCH_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define MAX_NUM_PATCHES   6
+
+#define     SBR_NUM_COLUMNS      38
+#define     SBR_NUM_BANDS        48
+#define     SBR_NUM_BANDS_OVR_4 (SBR_NUM_BANDS>>2)
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+struct PATCH
+{
+    Int32 noOfPatches;
+    Int32 targetStartBand[MAX_NUM_PATCHES];
+};
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_progconfig.h b/media/libstagefright/codecs/aacdec/s_progconfig.h
new file mode 100644
index 0000000..e58e5fc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_progconfig.h
@@ -0,0 +1,108 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_ProgConfig.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, ProgConfig
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_PROGCONFIG_H
+#define S_PROGCONFIG_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_mixdown.h"
+#include "s_elelist.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int     profile;
+    Int     sampling_rate_idx;
+    EleList front;
+    EleList side;
+    EleList back;
+    EleList lfe;
+    EleList data;
+    EleList coupling;
+    MIXdown mono_mix;
+    MIXdown stereo_mix;
+    MIXdown matrix_mix;
+
+    Char    comments[(1<<LEN_PC_COMM)+1]; /* TO BE DELETED */
+
+    Int32   buffer_fullness;    /* put this transport level info here */
+    Bool    file_is_adts;       /* For ADTS use only */
+    Int32   headerless_frames;  /* For ADTS use only */
+    Int32   frame_length;       /* For use by ADTS only */
+    Int32   CRC_absent;         /* For use by ADTS only */
+    UInt32  CRC_check;          /* For use by ADTS only */
+
+} ProgConfig;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/s_ps_dec.h b/media/libstagefright/codecs/aacdec/s_ps_dec.h
new file mode 100644
index 0000000..8b4391c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_ps_dec.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.
+ * -------------------------------------------------------------------
+ */
+/****************************************************************************
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2003.
+
+*******************************************************************************/
+
+#ifndef S_PS_DEC_H
+#define S_PS_DEC_H
+
+
+#include "s_hybrid.h"
+#include "s_patch.h"
+
+/****************************************************************
+  Type definitions
+ ****************************************************************/
+struct PS_DEC
+{
+
+    Int psDetected;
+    Int32 *R_ch_qmf_filter_history;
+    Int32 invNoSubSamples;
+
+    Int32 bForceMono;
+    UInt32 noSubSamples;
+    Int32 usb;
+    Int32 lastUsb;
+
+    Int32 bPsDataAvail;
+
+    UInt32 bEnableIid;
+    UInt32 bEnableIcc;
+
+    UInt32 bEnableExt;
+    Int32 bFineIidQ;
+
+    Int32 aIidPrevFrameIndex[NO_HI_RES_BINS];
+    Int32 aIccPrevFrameIndex[NO_HI_RES_BINS];
+
+    UInt32 freqResIid;
+    UInt32 freqResIcc;
+
+    UInt32 bFrameClass;
+    UInt32 noEnv;
+    UInt32 aEnvStartStop[MAX_NO_PS_ENV+1];
+
+    UInt32 abIidDtFlag[MAX_NO_PS_ENV];
+    UInt32 abIccDtFlag[MAX_NO_PS_ENV];
+
+    Int32   delayBufIndex;
+
+    UInt32 aDelayRBufIndexSer[NO_SERIAL_ALLPASS_LINKS];
+
+    Int32 **aaaRealDelayRBufferSerQmf[NO_SERIAL_ALLPASS_LINKS];
+    Int32 **aaaImagDelayRBufferSerQmf[NO_SERIAL_ALLPASS_LINKS];
+
+    Int32 **aaaRealDelayRBufferSerSubQmf[NO_SERIAL_ALLPASS_LINKS];
+    Int32 **aaaImagDelayRBufferSerSubQmf[NO_SERIAL_ALLPASS_LINKS];
+
+    Int32 **aaRealDelayBufferQmf;
+    Int32 **aaImagDelayBufferQmf;
+    Int32 **aaRealDelayBufferSubQmf;
+    Int32 **aaImagDelayBufferSubQmf;
+
+    Int32 *aPeakDecayFast;
+    Int32 *aPrevNrg;
+    Int32 *aPrevPeakDiff;
+
+    Int32 *mHybridRealLeft;
+    Int32 *mHybridImagLeft;
+    Int32 *mHybridRealRight;
+    Int32 *mHybridImagRight;
+
+
+    HYBRID *hHybrid;
+
+
+
+    Int32 h11Prev[NO_IID_GROUPS];
+    Int32 h12Prev[NO_IID_GROUPS];
+    Int32 h21Prev[NO_IID_GROUPS];
+    Int32 h22Prev[NO_IID_GROUPS];
+
+    Int32 H11[NO_IID_GROUPS];
+    Int32 H12[NO_IID_GROUPS];
+    Int32 H21[NO_IID_GROUPS];
+    Int32 H22[NO_IID_GROUPS];
+
+    Int32 deltaH11[NO_IID_GROUPS];
+    Int32 deltaH12[NO_IID_GROUPS];
+    Int32 deltaH21[NO_IID_GROUPS];
+    Int32 deltaH22[NO_IID_GROUPS];
+
+    Int32(*qmfBufferReal)[64];
+    Int32(*qmfBufferImag)[64];
+
+    Int32 aDelayBufIndex[NO_DELAY_CHANNELS];
+    Int32 aNoSampleDelay[NO_DELAY_CHANNELS];  /////
+    Int32 aaIidIndex[MAX_NO_PS_ENV+1][NO_HI_RES_BINS];
+    Int32 aaIccIndex[MAX_NO_PS_ENV+1][NO_HI_RES_BINS];
+
+};
+
+typedef struct PS_DEC STRUCT_PS_DEC;
+typedef struct PS_DEC * HANDLE_PS_DEC;
+
+
+
+#endif      /*  E_PS_DEC_H */
+
diff --git a/media/libstagefright/codecs/aacdec/s_pulseinfo.h b/media/libstagefright/codecs/aacdec/s_pulseinfo.h
new file mode 100644
index 0000000..a7ced04
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_pulseinfo.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_PulseInfo.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Comment out unused field.
+
+ Description:  Fix ARM warnings, update copyright.
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ define PulseInfo structure for pulse data decoding.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_PULSEINFO_H
+#define S_PULSEINFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_rawbitstreamconst.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int pulse_data_present;
+    Int number_pulse;
+    Int pulse_start_sfb;
+    Int pulse_offset[NUM_PULSE_LINES];
+    Int pulse_amp[NUM_PULSE_LINES];
+} PulseInfo;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbr_channel.h b/media/libstagefright/codecs/aacdec/s_sbr_channel.h
new file mode 100644
index 0000000..99e28dd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbr_channel.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbr_channel.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBR_CHANNEL_H
+#define S_SBR_CHANNEL_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "s_sbr_frame_data.h"
+#include    "e_sbr_sync_state.h"
+
+#ifdef PARAMETRICSTEREO
+#include "s_ps_dec.h"
+
+#endif
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define MAXNRELEMENTS 1
+#define MAXNRSBRCHANNELS (MAXNRELEMENTS*2)
+
+#ifdef PARAMETRICSTEREO
+#define MAXNRQMFCHANNELS MAXNRSBRCHANNELS
+#else
+#define MAXNRQMFCHANNELS MAXNRSBRCHANNELS
+#endif
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+typedef struct
+{
+    Int32 outFrameSize;
+    SBR_SYNC_STATE syncState;
+    SBR_FRAME_DATA frameData;
+
+} SBR_CHANNEL;
+
+typedef struct
+{
+    SBR_CHANNEL SbrChannel[MAXNRSBRCHANNELS];
+    Int32 setStreamType;
+#ifdef PARAMETRICSTEREO
+    HANDLE_PS_DEC hParametricStereoDec;
+    STRUCT_PS_DEC ParametricStereoDec;
+#endif
+
+} SBRDECODER_DATA;
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbr_dec.h b/media/libstagefright/codecs/aacdec/s_sbr_dec.h
new file mode 100644
index 0000000..810479c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbr_dec.h
@@ -0,0 +1,145 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbr_dec.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBR_DEC_H
+#define S_SBR_DEC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "s_sbr_frame_data.h"
+#include    "pv_audio_type_defs.h"
+#include    "s_patch.h"
+#include    "e_blockswitching.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int32 outSampleRate;
+    Int32 LC_aacP_DecoderFlag;  /* Low Complexity decoder flag  */
+
+    Int32 startIndexCodecQmf;
+    Int32 lowBandAddSamples;
+    Int32 noCols;
+    Int32 qmfBufLen;
+    Int32 bufWriteOffs;
+    Int32 bufReadOffs;
+
+    Int32 sbStopCodec;
+    Int   lowSubband;
+    Int   prevLowSubband;
+    Int32 highSubband;
+    Int32 noSubbands;
+
+    Int   FreqBandTable[2][MAX_FREQ_COEFFS + 1];
+    Int32 FreqBandTableNoise[MAX_NOISE_COEFFS + 1];
+    Int32 V_k_master[MAX_FREQ_COEFFS + 1];         /* Master BandTable which freqBandTable is derived from*/
+    Int32 NSfb[2];
+    Int32 NoNoiseBands;                            /* Number of noisebands */
+    Int32 Num_Master;                              /* Number of bands in V_k_master*/
+
+    struct PATCH Patch;                         /* Used by sbr_generate_high_freq */
+    /* Used by calc_sbr_envelope */
+    Int32 gateMode[4];
+    Int32 limSbc[4][12 + 1];                            /* Limiting bands */
+
+    Int32 sqrt_cache[8][4];                     /* cache memory for repeated sqrt() calculations */
+
+} SBR_DEC;
+
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbr_element_stream.h b/media/libstagefright/codecs/aacdec/s_sbr_element_stream.h
new file mode 100644
index 0000000..e9b6780
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbr_element_stream.h
@@ -0,0 +1,92 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbr_element_stream.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBR_ELEMENT_STREAM_H
+#define S_SBR_ELEMENT_STREAM_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+#define MAXSBRBYTES 1024
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+typedef struct
+{
+    Int32 ElementID;
+    Int32 ExtensionType;
+    Int32 Payload;
+    UChar Data[MAXSBRBYTES];
+}
+SBR_ELEMENT_STREAM;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbr_frame_data.h b/media/libstagefright/codecs/aacdec/s_sbr_frame_data.h
new file mode 100644
index 0000000..89d1bb1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbr_frame_data.h
@@ -0,0 +1,181 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbr_frame_data.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBR_FRAME_DATA_H
+#define S_SBR_FRAME_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sbr_header_data.h"
+#include    "e_invf_mode.h"
+#include    "e_coupling_mode.h"
+#include    "sbr_constants.h"
+#include    "s_patch.h"
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int32 nScaleFactors;            /* total number of scalefactors in frame */
+    Int32 nNoiseFactors;
+    Int32 crcCheckSum;
+    Int32 frameClass;
+    Int32 frameInfo[LENGTH_FRAME_INFO];
+    Int32 nSfb[2];
+    Int32 nNfb;
+    Int32 offset;
+    Int32 ampRes;
+    Int32 nNoiseFloorEnvelopes;
+    Int32 p;
+    Int32 prevEnvIsShort;
+
+    Int32 reset_flag;
+
+
+    SBR_HEADER_DATA sbr_header;
+
+
+    /* dynamic control signals */
+    Int32 domain_vec1[MAX_ENVELOPES];
+    Int32 domain_vec2[MAX_ENVELOPES];
+
+
+    INVF_MODE sbr_invf_mode[MAX_NUM_NOISE_VALUES];
+    INVF_MODE sbr_invf_mode_prev[MAX_NUM_NOISE_VALUES];
+
+    COUPLING_MODE coupling;               /*  3 possibilities: off, level, pan */
+
+
+    Int32 addHarmonics[MAX_NUM_ENVELOPE_VALUES];
+
+    /* Used by calc_sbr_envelope */
+    Int32 hFp[64];
+    Int32 harm_index;
+    Int32 phase_index;
+    Int32 sUp;
+
+    /*
+     *    envelope data
+     */
+
+    Int32 iEnvelope_man[MAX_NUM_ENVELOPE_VALUES]; /* mantissa */
+    Int32 iEnvelope_exp[MAX_NUM_ENVELOPE_VALUES]; /* exponent */
+    Int32 sfb_nrg_prev_man[MAX_FREQ_COEFFS];      /* mantissa */
+
+
+    /*
+     *    noise data
+     */
+
+    Int32 sbrNoiseFloorLevel_man[MAX_NUM_NOISE_VALUES]; /* mantissa */
+    Int32 sbrNoiseFloorLevel_exp[MAX_NUM_NOISE_VALUES]; /* exponent */
+    Int32 prevNoiseLevel_man[MAX_NUM_NOISE_VALUES]; /* mantissa */
+
+    Int32  BwVector[MAX_NUM_PATCHES];
+    Int32  BwVectorOld[MAX_NUM_PATCHES];
+    /* Both implement a pseudo circular buffer  */
+
+    /*
+     * 40 ==  Biggest of  autoCorrLength(38) + sbrDec->bufReadOffs (2)  and
+     *    sbrDec->noCols (32) + sbrDec->bufWriteOffs  (6)
+     */
+    Int32 codecQmfBufferReal[40][32];
+    Int32 *sbrQmfBufferReal;
+    Int32 HistsbrQmfBufferReal[6*SBR_NUM_BANDS];
+#ifdef HQ_SBR
+    Int32 codecQmfBufferImag[40][32];
+    Int32 *sbrQmfBufferImag;
+    Int32 HistsbrQmfBufferImag[6*SBR_NUM_BANDS];
+#endif
+    Int16  V[1152];     /* Used by calc_sbr_synfilterbank as freq. history buffer */
+
+
+    Int32 degreeAlias[64];
+
+
+#ifdef HQ_SBR
+
+    Int32 fBuffer_man[5][64];        /* smoothing history buffers */
+    Int32 fBufferN_man[5][64];
+    Int32 fBuffer_exp[5][64];        /* smoothing history buffers */
+    Int32 fBufferN_exp[5][64];
+
+    Int32 *fBuf_man[64];        /* pointer to smoothing history buffers */
+    Int32 *fBuf_exp[64];        /* pointer to smoothing history buffers */
+    Int32 *fBufN_man[64];
+    Int32 *fBufN_exp[64];
+
+
+#endif
+
+}
+SBR_FRAME_DATA;
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbr_header_data.h b/media/libstagefright/codecs/aacdec/s_sbr_header_data.h
new file mode 100644
index 0000000..7d7d746
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbr_header_data.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbr_header_data.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBR_HEADER_DATA_H
+#define S_SBR_HEADER_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "e_sbr_header_status.h"
+#include    "e_sbr_master_status.h"
+#include    "e_sr_mode.h"
+/*----------------------------------------------------------------------------
+; 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
+{
+    SBR_HEADER_STATUS status;      /* the current status of the header     */
+    SBR_MASTER_STATUS masterStatus;/* status of v_k_master freq table      */
+
+    /* Changes in these variables indicates an error */
+    Int32 crcEnable;
+    SR_MODE sampleRateMode;
+    Int32 ampResolution;
+
+    /* Changes in these variables causes a reset of the decoder */
+    Int32 startFreq;
+    Int32 stopFreq;
+    Int32 xover_band;
+    Int32 freqScale;
+    Int32 alterScale;
+    Int32 noise_bands;               /* noise bands per octave, read from bitstream */
+
+    /* Helper variable*/
+    Int32 noNoiseBands;              /* actual number of noise bands to read from the bitstream */
+
+    Int32 limiterBands;
+    Int32 limiterGains;
+    Int32 interpolFreq;
+    Int32 smoothingLength;
+}
+SBR_HEADER_DATA;
+
+typedef SBR_HEADER_DATA *HANDLE_SBR_HEADER_DATA;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sbrbitstream.h b/media/libstagefright/codecs/aacdec/s_sbrbitstream.h
new file mode 100644
index 0000000..609463a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sbrbitstream.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: s_sbrbitstream.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SBRBITSTREAM_H
+#define S_SBRBITSTREAM_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "s_sbr_element_stream.h"
+#include    "s_sbr_channel.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int32 NrElements;
+    Int32 NrElementsCore;
+    SBR_ELEMENT_STREAM sbrElement[MAXNRELEMENTS];
+}
+SBRBITSTREAM;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sectinfo.h b/media/libstagefright/codecs/aacdec/s_sectinfo.h
new file mode 100644
index 0000000..83dcc31
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sectinfo.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/s_SectInfo.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ defines a structre that holds the Huffman codebook index and section
+ boundary information for each Frame.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SECTINFO_H
+#define S_SECTINFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int   sect_cb;
+    Int   sect_end;
+} SectInfo;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/s_sr_info.h b/media/libstagefright/codecs/aacdec/s_sr_info.h
new file mode 100644
index 0000000..9b71003
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_sr_info.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_SR_info.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified the declaration of the structure so no pointers are
+              used in the structure.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, SR_Info
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_SR_INFO_H
+#define S_SR_INFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int32   samp_rate;
+    Int     nsfb1024;
+    Int     nsfb128;
+} SR_Info;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/s_tdec_int_chan.h b/media/libstagefright/codecs/aacdec/s_tdec_int_chan.h
new file mode 100644
index 0000000..f7a3602
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_tdec_int_chan.h
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_tDec_Int_Chan.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change data types of win
+
+ Description: Remove wnd_shape structure.
+
+ Description: Remove dependency on window_block.h, Fix header too.
+
+ Description:
+ Modified to utilize memory in the last 1024 elements in fxpCoef.
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description:
+ (1) Move temporary FrameInfo structure into the shared region with fxpCoef.
+ (2) Add more comments detailing the size of the shared structure.
+
+ Description:
+ (1) Changed time_quant from 2048 Int32 buffer to 1024 Int32 buffer.
+
+ Who:                                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, tDec_Int_Chan
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TDEC_INT_CHAN_H
+#define S_TDEC_INT_CHAN_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_rawbitstreamconst.h"
+#include "s_tns_frame_info.h"
+#include "s_wnd_shape.h"
+#include "s_lt_pred_status.h"
+#include "s_sectinfo.h"
+#include "s_frameinfo.h"
+#include "e_window_shape.h"
+#include "e_window_sequence.h"
+#include "window_block_fxp.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+    /* This structure was created with the specific goal in mind of sharing memory
+     * with the last 1024 data elements in fxpCoef.
+     *
+     * The size of this structure must NOT exceed 4 kilobytes
+     * Also, the size of the fxpCoef array cannot be less than 8 kilobytes
+     *
+     * The fxpCoef array is declared as an Int32, so its size should not vary
+     * from platform to platform.
+     *
+     * The shared structure is 3,640 bytes (3.55 KB), on a 32-bit platform,
+     * which represents the worst case.
+     */
+    typedef struct
+    {
+        TNS_frame_info       tns;
+
+        FrameInfo            frameInfo;
+
+        Int                  factors[MAXBANDS];
+        Int                  cb_map[MAXBANDS];
+        Int                  group[NSHORT];
+        Int                  qFormat[MAXBANDS];
+
+        Int                  max_sfb;
+        LT_PRED_STATUS       lt_status;
+
+    } per_chan_share_w_fxpCoef;
+
+    /*
+     * This structure contains one per channel.
+     */
+    typedef struct
+    {
+#ifdef AAC_PLUS
+        Int16                ltp_buffer[LT_BLEN + 2*288]; /* LT_BLEN  = 2048 + 2*288 */
+#else
+        Int16                ltp_buffer[LT_BLEN]; /* LT_BLEN  = 2048 */
+#endif
+
+
+        Int32                time_quant[LONG_WINDOW]; /*  1024 holds overlap&add */
+
+        Int32                *fxpCoef;         /* Spectrum coeff.*/
+
+        per_chan_share_w_fxpCoef * pShareWfxpCoef;
+
+        Int32                abs_max_per_window[NUM_SHORT_WINDOWS];
+
+        WINDOW_SEQUENCE      wnd;
+
+
+        WINDOW_SHAPE         wnd_shape_prev_bk;
+        WINDOW_SHAPE         wnd_shape_this_bk;
+
+    } tDec_Int_Chan;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_TDEC_INT_CHAN_H */
+
diff --git a/media/libstagefright/codecs/aacdec/s_tdec_int_file.h b/media/libstagefright/codecs/aacdec/s_tdec_int_file.h
new file mode 100644
index 0000000..d0ffb0b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_tdec_int_file.h
@@ -0,0 +1,277 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_tDec_Int_File.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Remove unneeded structure elements, clean up.
+
+ Description: Remove block.h, not needed, chains in other not needed files.
+
+ Description: Added declaration of scratch memory, scratchTnsDecCoefMem,
+ which will be utilized by tns_decode_coef().
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description: Per review comments...
+ (1) Removed declaration of unused variable, savedMCInfo
+ (2) Commented out ADTS related variables.
+ (3) Slight re-wording of comment for clarity.
+
+ Description:
+ (1) Moved scratch_prog_config into the scratch union.
+
+ Description:
+ (1) Added ltp state variable.
+
+ Description: Make tDec_Int_perChan an array of structures.
+              In the user applications, the malloc command will allocate a
+              continuous chunk of memory.
+
+ Description:
+           (1) Added the array data_stream_bytes[] to structure tDec_Int_File.
+               This to support Data Streaming Elements (DSE).
+           (2) Updated the copyright header.
+
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, tDec_Int_Chan
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TDEC_INT_FILE_H
+#define S_TDEC_INT_FILE_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_progconfig.h"
+#include "s_frameinfo.h"
+#include "s_mc_info.h"
+#include "s_adif_header.h"
+#include "s_tdec_int_chan.h"
+#include "s_pulseinfo.h"
+#include "s_bits.h"
+#include "s_hcb.h"
+#include "e_infoinitconst.h"
+
+#include "s_sbr_channel.h"
+#include "s_sbr_dec.h"
+#include "s_sbrbitstream.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+
+
+
+
+    /*
+     * Note: most of the names of the variables put into this structure were kept
+     * the same because the name is also used in called functions.
+     *
+     * bno - block number
+     *
+     */
+    typedef struct
+    {
+        UInt32         bno;
+        Int            status;  /* save the status */
+
+        bool           aacPlusEnabled;
+        bool           aacConfigUtilityEnabled;
+
+        Int            current_program;
+        Int            frameLength;
+        Int            adif_test;
+
+        BITS           inputStream;
+
+        ProgConfig     prog_config;
+
+        Int            SFBWidth128[(1<<LEN_MAX_SFBS)];
+
+        /*
+         * One of the two arrays should be deleted in the final version.
+         */
+        FrameInfo      longFrameInfo;
+        FrameInfo      shortFrameInfo;
+        FrameInfo     *winmap[NUM_WIN_SEQ];
+
+        /*
+         * Pns variables.
+         */
+        Int32          pns_cur_noise_state;
+
+        /*
+         *
+         */
+        MC_Info        mc_info;
+
+        Int            ltp_buffer_state;
+
+        /*
+         *  For eaac+, a scratch matrix is created with the rigth element ( perChan[1] is not used)
+         *  and the fxpCoef matrix. These  2 matrices are [2][38][64] == 4864 Int32
+         *    2349 coming from the perChan[1] plus 4096 coming from fxpCoef
+         */
+        tDec_Int_Chan  perChan[Chans];
+
+        Int32          fxpCoef[2][LN];         /* LN  = 2048     */
+
+
+
+#ifdef AAC_PLUS
+
+        SBRDECODER_DATA sbrDecoderData;/* allocates 2 SBR_CHANNEL, each has a SBR_FRAME_DATA */
+        SBR_DEC         sbrDec;
+        SBRBITSTREAM    sbrBitStr;
+
+#endif
+
+
+        /*
+         * If ADTS support is needed, the following variables will
+         * be required.
+         */
+        UInt32         syncword;
+        Int            invoke;
+
+        Int         mask[MAXBANDS];
+        Int         hasmask;
+
+
+        /*  SBR usage
+         *  These two unions are used for the SBR tool and used
+         *  as a single 2560 int32 continuous memory for circular
+         *  buffering the synthesis QMF's bank history
+         */
+
+        /* This union specifies memory for arrays which are used
+         * by only one function.  This is the simplest type of scratch
+         * memory to implement, since there are no worries about
+         * function interaction.
+         */
+        union scratch_memory
+        {
+            Int32  fft[LONG_WINDOW];    /* 1024, as needed by the FFT */
+            Int32  tns_inv_filter[TNS_MAX_ORDER];
+            Int32  tns_decode_coef[2*TNS_MAX_ORDER];
+            Int    huffbook_used[248];
+            Int16  tmp_spec[LN2];  /* Used in conjunction with quant_spec */
+
+            ADIF_Header    adif_header;
+
+            ProgConfig     scratch_prog_config;
+
+
+            Int32  scratch_mem[16][64];
+        } scratch;
+
+        /* This union tries to take advantage of the fact that
+         * some variables are only used before LTP, and
+         * the long array, predictedSamples, is only used after LTP.
+         */
+
+        /*
+         *  also used by the circular buffer scheme on aac+ (needs 4096 + 1152)
+         *  from scratch_mem[2] + 5248  (uses most of shared_memory).
+         *  For eaac+, shared memory is used by sbrQmfBufferReal which needs
+         *  1824 bytes
+         */
+        union shared_memory
+        {
+            Int32       predictedSamples[LONG_BLOCK1];  /* 2048 Int32 */
+
+            Char        data_stream_bytes[(1<<LEN_D_CNT)+1];
+
+            struct
+            {
+                Int16         quantSpec[LN2];
+                SectInfo    sect[MAXBANDS + 1];
+                PulseInfo   pulseInfo;
+            } a;
+
+        } share;
+
+
+    } tDec_Int_File;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_TDEC_INT_FILE_H */
diff --git a/media/libstagefright/codecs/aacdec/s_tns_frame_info.h b/media/libstagefright/codecs/aacdec/s_tns_frame_info.h
new file mode 100644
index 0000000..61af0ac
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_tns_frame_info.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_TNS_frame_info.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to eliminate triple-nested structure, which wasted
+ 2 KB of memory.
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Description:
+ (1) Changed hard coded size of arrays from "8" to "TNS_MAX_WIN"
+ (2) Moved elements from s_TNSinfo.h up to the level of TNS_frame_info
+ (3) Added Bool "tns_data_present" for future use.
+ (4) Moved lpc_coef up from s_TNSfilt.h (allowed for use of smaller array.)
+
+ Description:
+ (1) Removed the array "coef_res", which is now a local variable on the
+ stack inside get_tns.c
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, s_TNS_frame_info
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TNS_FRAME_INFO_H
+#define S_TNS_FRAME_INFO_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_tns_const.h"
+#include "s_tnsfilt.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    {
+        Bool tns_data_present;
+
+        /* Information about the number of filters for each window. */
+        Int n_filt[TNS_MAX_WIN];
+
+        /*
+         * Filter Information
+         *
+         * For short windows, there is a maximum of
+         * 1 filter per window (8 total)
+         *
+         * For long windows, there is a maximum of 3 filters
+         *
+         */
+        TNSfilt filt[TNS_MAX_WIN];
+
+        /*
+         * For short windows, there is a maximum of 8 filters,
+         * each of order 7 (requring 56 Ints)
+         *
+         * For long windows, there is a maximum of 3 filters,
+         * each of order 20 (requiring 60 Ints)
+         *
+         * So, 3*TNS_MAX_ORDER declares an array of sufficient
+         * size (60) for both cases.
+         */
+        Int32 lpc_coef[3*TNS_MAX_ORDER];
+
+    } TNS_frame_info;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_TNS_FRAME_INFO_H */
diff --git a/media/libstagefright/codecs/aacdec/s_tnsfilt.h b/media/libstagefright/codecs/aacdec/s_tnsfilt.h
new file mode 100644
index 0000000..c1d78af
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_tnsfilt.h
@@ -0,0 +1,132 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_TNSfilt.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added lpc, start, & size, so the data from
+ tns_inv_subblock can be shared with tns_decode_subblock.
+
+ Description: Removed lpc to save 2KB of memory (on 32-bit machines.)
+ This change requires tns_decode_coef.c to perform calculations in place.
+
+ Description: Removed start & size.  start_band and stop_band can simply
+ take on a new meaning after this function.  (coef index, rather than
+ scalefactor band index.)
+
+ Description: Had to add "start_coef" and "stop_coef" in order to preserve
+ values "start_band" and "stop_band."  This required a change to
+ tns_setup_filter.c also.
+
+ Description: Had to add element "q_lpc" to store the q-format of the lpc
+ coefficients passed via "coef."
+
+ Description: Moved lpc_coef array up to the s_TNS_frame_info.h structure.
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, s_TNSfilt
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TNSFILT_H
+#define S_TNSFILT_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_tns_const.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    {
+        Int start_band;
+        Int stop_band;
+        Int start_coef;
+        Int stop_coef;
+        UInt order;
+        Int direction;
+        Int q_lpc;
+
+    } TNSfilt;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* S_TNSFILT_H */
diff --git a/media/libstagefright/codecs/aacdec/s_wnd_shape.h b/media/libstagefright/codecs/aacdec/s_wnd_shape.h
new file mode 100644
index 0000000..c8a05c8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/s_wnd_shape.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: s_Wnd_Shape.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Change data type to Int
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, Wnd_Shape
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_WND_SHAPE_H
+#define S_WND_SHAPE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    Int    this_bk;
+    Int    prev_bk;
+} Wnd_Shape;
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.cpp b/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.cpp
new file mode 100644
index 0000000..efbab7d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.cpp
@@ -0,0 +1,366 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_aliasing_reduction.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+
+#include    "sbr_aliasing_reduction.h"
+#include    "pv_sqrt.h"
+
+#include    "aac_mem_funcs.h"
+
+#include    "pv_div.h"
+#include    "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Q30fmt(x)   (Int32)(x*((Int32)1<<30) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#include "pv_normalize.h"
+#include  "sbr_constants.h"
+
+/*******************************************************************************
+ Functionname:  sbr_aliasing_reduction
+ *******************************************************************************
+ Description:
+ Arguments:
+
+ Return:        none
+*******************************************************************************/
+void sbr_aliasing_reduction(Int32 *degreeAlias,
+                            Int32  * nrg_gain_man,
+                            Int32  * nrg_gain_exp,
+                            Int32  * nrg_est_man,
+                            Int32  * nrg_est_exp,
+                            Int32  * dontUseTheseGainValues,
+                            Int32    noSubbands,
+                            Int32    lowSubband,
+                            Int32  sqrt_cache[][4],
+                            Int32 * groupVector)
+{
+
+    Int32 temp1;
+    Int32 est_total;
+    Int32 ref_total_man;
+    Int32 ref_total_exp;
+    Int32 tmp_q1;
+    Int32 tmp_q2;
+    Int32 tmp_q3;
+    Int32 tmp_q4;
+    Int32 bst_man;
+    Int32 bst_exp;
+    struct intg_div   quotient;
+    struct intg_sqrt  root_sq;
+    Int32 group;
+    Int32 grouping = 0;
+    Int32 index = 0;
+    Int32 noGroups;
+    Int32 k;
+
+
+    /* Calculate grouping*/
+    for (k = 0; k < noSubbands - 1; k++)
+    {
+        if (degreeAlias[k + lowSubband + 1] && dontUseTheseGainValues[k] == 0)
+        {
+            if (grouping == 0)
+            {
+                groupVector[index] = k + lowSubband;
+                grouping = 1;
+                index++;
+            }
+        }
+        else
+        {
+            if (grouping)
+            {
+                groupVector[index] = k + lowSubband;
+
+                if (! dontUseTheseGainValues[k])
+                {
+                    (groupVector[index])++;
+                }
+                grouping = 0;
+                index++;
+            }
+        }
+    }
+
+    if (grouping)
+    {
+        groupVector[index] = noSubbands + lowSubband;
+        index++;
+    }
+    noGroups = (index >> 1);
+
+
+
+    /*Calculate new gain*/
+    for (group = 0; group < noGroups; group ++)
+    {
+
+        int startGroup = groupVector[(group<<1)] - lowSubband;
+        int stopGroup  = groupVector[(group<<1)+1] - lowSubband;
+
+
+        est_total = 0;
+        ref_total_man = 0;
+
+        tmp_q1 = -100;
+        tmp_q2 = -100;
+
+        for (k = startGroup; k < stopGroup; k++)
+        {
+            if (tmp_q1 < nrg_est_exp[k])
+            {
+                tmp_q1 = nrg_est_exp[k];    /* max */
+            }
+            if (tmp_q2 < (nrg_est_exp[k] + (nrg_gain_exp[k] << 1)))
+            {
+                tmp_q2 = (nrg_est_exp[k] + (nrg_gain_exp[k] << 1));  /* max */
+            }
+        }
+
+
+        k -= startGroup;        /*  number of element used in the addition */
+        /* adjust Q format */
+        tmp_q2 += 59 - pv_normalize(k);
+
+        for (k = startGroup; k < stopGroup; k++)
+        {
+            /*
+             *  est_total += nrg_est[k]
+             *  ref_total += nrg_est[k]*nrg_gain[k]*nrg_gain[k
+             */
+            est_total += nrg_est_man[k] >> (tmp_q1 - nrg_est_exp[k]);
+
+            if (tmp_q2 - (nrg_est_exp[k] + (nrg_gain_exp[k] << 1)) < 60)
+            {
+                nrg_gain_man[k] = fxp_mul32_Q28(nrg_gain_man[k], nrg_gain_man[k]);
+                nrg_gain_exp[k] = (nrg_gain_exp[k] << 1) + 28;
+                tmp_q3          = fxp_mul32_Q28(nrg_gain_man[k], nrg_est_man[k]);
+                ref_total_man    += tmp_q3 >> (tmp_q2 - (nrg_est_exp[k] + nrg_gain_exp[k]));
+            }
+        }
+
+        ref_total_exp = tmp_q2 + 28;
+
+        pv_div(ref_total_man, est_total, &quotient);
+
+        tmp_q2 += - tmp_q1 - quotient.shift_factor - 2;
+
+
+
+        for (k = startGroup; k < stopGroup; k++)
+        {
+            Int32 alpha;
+            temp1 = k + lowSubband;
+            if (k < noSubbands - 1)
+            {
+                alpha = degreeAlias[temp1 + 1] > degreeAlias[temp1 ] ?
+                        degreeAlias[temp1 + 1] : degreeAlias[temp1 ];
+            }
+            else
+            {
+                alpha = degreeAlias[temp1];
+            }
+
+            /*
+             *  nrg_gain[k] = alpha*newGain + (1.0f-alpha)*nrg_gain[k]*nrg_gain[k];
+             */
+
+            tmp_q1 = tmp_q2 > nrg_gain_exp[k] ? tmp_q2 : nrg_gain_exp[k];
+            tmp_q1++;
+
+            tmp_q3 = fxp_mul32_Q30(alpha, quotient.quotient);
+            tmp_q4 = fxp_mul32_Q30(Q30fmt(1.0f) - alpha, nrg_gain_man[k]);
+
+            nrg_gain_man[k] = (tmp_q3 >> (tmp_q1 - tmp_q2)) +
+                              (tmp_q4 >> (tmp_q1 - nrg_gain_exp[k]));
+
+            nrg_gain_exp[k] = tmp_q1;
+        }
+
+
+        bst_exp = -100;
+
+        for (k = startGroup; k < stopGroup; k++)
+        {
+            if (bst_exp < nrg_gain_exp[k] + nrg_est_exp[k])
+            {
+                bst_exp = nrg_gain_exp[k] + nrg_est_exp[k];    /* max */
+            }
+        }
+
+        k -= startGroup;        /*  number of element used in the addition */
+
+        while (k != 0)          /*  bit guard protection depends on log2(k)  */
+        {
+            k >>= 1;
+            bst_exp++;           /*  add extra bit-overflow-guard */
+        }
+
+        bst_man = 0;
+
+        for (k = startGroup; k < stopGroup; k++)
+        {
+            tmp_q2 =  fxp_mul32_Q28(nrg_gain_man[k], nrg_est_man[k]);
+            bst_man +=  tmp_q2 >> (bst_exp - nrg_gain_exp[k] - nrg_est_exp[k]);
+        }
+
+        bst_exp += 28;  /* compensate for shift down */
+
+        if (bst_man)
+        {
+            /*
+             *  bst = ref_total / bst
+             */
+
+            pv_div(ref_total_man, bst_man, &quotient);
+            bst_exp = ref_total_exp - bst_exp - quotient.shift_factor - 30;
+            bst_man = quotient.quotient;      /*  Q30 */
+
+            for (k = startGroup; k < stopGroup; k++)
+            {
+                tmp_q1 = fxp_mul32_Q30(bst_man, nrg_gain_man[k]);
+                pv_sqrt(tmp_q1, (bst_exp + nrg_gain_exp[k] + 60), &root_sq, sqrt_cache[0]);
+                nrg_gain_man[k] = root_sq.root;
+                nrg_gain_exp[k] = root_sq.shift_factor;
+            }
+        }
+        else
+        {
+            pv_memset((void *)&nrg_gain_man[startGroup],
+                      0,
+                      (stopGroup - startGroup)*sizeof(nrg_gain_man[0]));
+
+            pv_memset((void *)&nrg_gain_exp[startGroup],
+                      0,
+                      (stopGroup - startGroup)*sizeof(nrg_gain_exp[0]));
+
+        }
+
+    }
+}
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.h b/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.h
new file mode 100644
index 0000000..2ce99ec
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_aliasing_reduction.h
@@ -0,0 +1,92 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_aliasing_reduction.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_ALIASING_REDUCTION_H
+#define SBR_ALIASING_REDUCTION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 sbr_aliasing_reduction(Int32 *degreeAlias,
+                            Int32  * nrg_gain_man,
+                            Int32  * nrg_gain_exp,
+                            Int32  * nrg_est_man,
+                            Int32  * nrg_est_exp,
+                            Int32  * dontUseTheseGainValues,
+                            Int32    noSubbands,
+                            Int32    lowSubband,
+                            Int32  sqrt_cache[][4],
+                            Int32 * groupVector);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_applied.cpp b/media/libstagefright/codecs/aacdec/sbr_applied.cpp
new file mode 100644
index 0000000..c8b81b2
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_applied.cpp
@@ -0,0 +1,435 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Filename: sbr_applied.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    INPUT
+
+    SBRDECODER self,
+    SBRBITSTREAM * stream,
+    float *timeData,
+    int numChannels
+
+    OUTPUT
+
+    errorCode, noError if successful
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        sbr decoder processing, set up SBR decoder phase 2 in case of
+        different cotrol data
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+
+#include    "sbr_applied.h"
+#include    "sbr_read_data.h"
+
+#include    "sbr_decode_envelope.h"
+#include    "decode_noise_floorlevels.h"
+#include    "sbr_requantize_envelope_data.h"
+#include    "sbr_envelope_unmapping.h"
+#include    "sbr_dec.h"
+#include    "e_sbr_element_id.h"
+#include    "aac_mem_funcs.h"
+
+#ifdef PARAMETRICSTEREO
+#include    "ps_bstr_decoding.h"
+#include    "ps_allocate_decoder.h"
+
+#endif
+
+#include    "init_sbr_dec.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LEFT  (0)
+#define RIGHT (1)
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR  sbr_applied(SBRDECODER_DATA * self,
+                       SBRBITSTREAM * stream,
+                       Int16 *ch_left,
+                       Int16 *ch_right,
+                       Int16 *timeData,
+                       SBR_DEC *sbrDec,
+                       tDec_Int_File  *pVars,
+                       Int32 numChannels)
+{
+    SBR_ERROR err = SBRDEC_OK ;
+
+    Int32 eleChannels = 0;
+
+    SBR_CHANNEL *SbrChannel = self->SbrChannel;
+
+    /* Get SBR or PS Data only when available */
+    if (stream->NrElements)
+    {
+        /* read frame data from bitstream */
+
+        err = sbr_read_data(self,
+                            sbrDec,
+                            stream);
+
+        if (err != SBRDEC_OK)
+        {
+            /*
+             * This error condition disables any further SBR processing
+             */
+            self->SbrChannel[LEFT].syncState = UPSAMPLING;
+            if (eleChannels == 2)
+            {
+                self->SbrChannel[RIGHT].syncState = UPSAMPLING;
+            }
+        }
+
+        /*
+         *  Setting bistream and decoding type is only done once,
+         */
+        if (SbrChannel[LEFT].syncState == SBR_ACTIVE && self->setStreamType)
+        {
+            self->setStreamType = 0;  /* Disable Lock for AAC stream type setting  */
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+
+            Int sbrEnablePS = self->hParametricStereoDec->psDetected;
+
+            pVars->mc_info.psPresentFlag  = sbrEnablePS;
+
+            if (sbrEnablePS)   /* Initialize PS arrays */
+            {
+                pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_PS;
+                ps_allocate_decoder(self, 32);
+
+                /* Disable LC (or Enable HQ)  if PS is detected */
+                sbrDec->LC_aacP_DecoderFlag = OFF;
+            }
+            else
+            {
+                /*
+                 *  Do not downgrade stream type from eaac+, if it has been explicitly declared
+                 */
+                if (pVars->mc_info.ExtendedAudioObjectType != MP4AUDIO_PS)
+                {
+                    pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_SBR;
+
+                    if (pVars->mc_info.nch > 1)
+                    {
+                        sbrDec->LC_aacP_DecoderFlag = ON;    /* Enable LC for stereo */
+                    }
+                    else
+                    {
+                        sbrDec->LC_aacP_DecoderFlag = OFF;    /* Disable LC, Enable HQ for mono */
+                    }
+                }
+                else
+                {
+                    sbrEnablePS = 1;  /* Force this condition as it was explicititly declared */
+                    pVars->mc_info.psPresentFlag  = sbrEnablePS;
+
+                }
+            }
+#else
+
+            pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_SBR;
+
+            if (pVars->mc_info.nch > 1)
+            {
+                sbrDec->LC_aacP_DecoderFlag = ON;    /* Enable LC for stereo */
+            }
+            else
+            {
+                sbrDec->LC_aacP_DecoderFlag = OFF;    /* Disable LC, Enable HQ for mono */
+            }
+#endif
+
+#else
+            pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_SBR;
+
+            sbrDec->LC_aacP_DecoderFlag = ON;       /* Enable LC for all sbr decoding */
+
+#endif
+
+        }   /*   (SbrChannel[LEFT].syncState == SBR_ACTIVE && lock)  */
+        else
+        {
+            /*
+             *  Default setting for upsampler
+             */
+            if (pVars->mc_info.ExtendedAudioObjectType == MP4AUDIO_AAC_LC)
+            {
+                /*
+                 *  Change only in implicit signalling, otherwise keep original declaration
+                 */
+                pVars->mc_info.ExtendedAudioObjectType = MP4AUDIO_SBR;
+            }
+
+#ifdef HQ_SBR
+            if (pVars->mc_info.nch > 1)
+            {
+                sbrDec->LC_aacP_DecoderFlag = ON;    /* Enable LC for stereo */
+            }
+            else
+            {
+                sbrDec->LC_aacP_DecoderFlag = OFF;    /* Disable LC, Enable HQ for mono */
+            }
+#else
+            sbrDec->LC_aacP_DecoderFlag = ON;       /* Enable LC for all sbr decoding */
+
+#endif
+            /* mask error and let upsampler run */
+            err = SBRDEC_OK;
+
+        }
+
+        /* decoding */
+        eleChannels = (stream->sbrElement [LEFT].ElementID == SBR_ID_CPE) ? 2 : 1;
+
+        if (SbrChannel[LEFT].syncState == SBR_ACTIVE)
+        {
+
+            sbr_decode_envelope(&(SbrChannel[LEFT].frameData));
+
+            decode_noise_floorlevels(&(SbrChannel[LEFT].frameData));
+
+            if (! SbrChannel[LEFT].frameData.coupling)
+            {
+                sbr_requantize_envelope_data(&(SbrChannel[LEFT].frameData));
+            }
+
+            if (eleChannels == 2)
+            {
+
+                sbr_decode_envelope(&(SbrChannel[RIGHT].frameData));
+
+                decode_noise_floorlevels(&(SbrChannel[RIGHT].frameData));
+
+                if (SbrChannel[RIGHT].frameData.coupling)
+                {
+                    sbr_envelope_unmapping(&(SbrChannel[ LEFT].frameData),
+                                           &(SbrChannel[RIGHT].frameData));
+                }
+                else
+                {
+                    sbr_requantize_envelope_data(&(SbrChannel[RIGHT].frameData));
+                }
+            }
+        }
+        else            /* enable upsampling until valid SBR is obtained */
+        {
+            /*
+             *  Incomplete sbr frame, or disabled SBR section
+             *  Set the decoder to act as a regular upsampler
+             */
+
+            init_sbr_dec((sbrDec->outSampleRate >> 1),
+                         pVars->mc_info.upsamplingFactor,
+                         sbrDec,
+                         &(self->SbrChannel[LEFT].frameData));
+
+            if ((eleChannels == 2) && (SbrChannel[RIGHT].syncState != SBR_ACTIVE))
+            {
+                init_sbr_dec((sbrDec->outSampleRate >> 1),
+                             pVars->mc_info.upsamplingFactor,
+                             sbrDec,
+                             &(self->SbrChannel[RIGHT].frameData));
+
+            }
+
+        }
+
+    }
+
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+    if (pVars->mc_info.ExtendedAudioObjectType == MP4AUDIO_PS)
+    {
+        ps_bstr_decoding(self->hParametricStereoDec);
+        /* allocate pointer for rigth channel qmf filter history  */
+        Int16 *tempInt16Ptr = (Int16 *)SbrChannel[RIGHT].frameData.V;
+        self->hParametricStereoDec->R_ch_qmf_filter_history = (Int32 *)tempInt16Ptr;
+
+
+        /*
+         * 1824 (48*38) Int32 needed by each matrix sbrQmfBufferReal, sbrQmfBufferImag
+         * pVars->share.predictedSamples  has 2048 available
+         * pVars->fxpCoef[1]  has 2048 available
+         */
+        SbrChannel[LEFT].frameData.sbrQmfBufferReal = pVars->share.predictedSamples;
+        SbrChannel[LEFT].frameData.sbrQmfBufferImag = &pVars->fxpCoef[0][920];
+
+        sbr_dec(ch_left,
+                timeData,
+                &(SbrChannel[LEFT].frameData),
+                (SbrChannel[LEFT].syncState == SBR_ACTIVE),
+                sbrDec,
+                &timeData[RIGHT],
+                self->hParametricStereoDec,
+                pVars);
+    }
+    else
+    {
+#endif
+#endif
+
+        SbrChannel[LEFT].frameData.sbrQmfBufferReal = pVars->fxpCoef[LEFT];
+#ifdef HQ_SBR
+        SbrChannel[LEFT].frameData.sbrQmfBufferImag = pVars->fxpCoef[RIGHT];
+#endif
+
+        sbr_dec(ch_left,
+                timeData,
+                &(SbrChannel[LEFT].frameData),
+                (SbrChannel[LEFT].syncState == SBR_ACTIVE),
+                sbrDec,
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+                NULL,
+                NULL,
+#endif
+#endif
+                pVars);
+
+        if (numChannels == 2)
+        {
+            SbrChannel[RIGHT].frameData.sbrQmfBufferReal = pVars->fxpCoef[LEFT];
+#ifdef HQ_SBR
+            SbrChannel[RIGHT].frameData.sbrQmfBufferImag = pVars->fxpCoef[RIGHT];
+#endif
+
+            sbr_dec(ch_right,
+                    &timeData[RIGHT],
+                    &(SbrChannel[RIGHT].frameData),
+                    (SbrChannel[RIGHT].syncState == SBR_ACTIVE),
+                    sbrDec,
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+                    NULL,
+                    NULL,
+#endif
+#endif
+                    pVars);
+
+        }
+
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+    }
+#endif
+#endif
+
+    return err;
+}
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_applied.h b/media/libstagefright/codecs/aacdec/sbr_applied.h
new file mode 100644
index 0000000..6878537
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_applied.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_applied.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_APPLIED_H
+#define SBR_APPLIED_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "e_sbr_error.h"
+#include "s_sbr_channel.h"
+#include "s_sbrbitstream.h"
+#include "sbr_dec.h"
+#include "pv_audio_type_defs.h"
+#include "s_tdec_int_file.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define MAX_FRAME_SIZE  1024
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    SBR_ERROR  sbr_applied(SBRDECODER_DATA * self,
+    SBRBITSTREAM * stream,
+    Int16 *ch_left,
+    Int16 *ch_right,
+    Int16 *timeData,
+    SBR_DEC *sbrDec,
+    tDec_Int_File  *pVars,
+    Int32 numChannels);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.cpp b/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.cpp
new file mode 100644
index 0000000..9db3221
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.cpp
@@ -0,0 +1,403 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_code_book_envlevel.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include   "pv_audio_type_defs.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    /*******************************************************************************/
+    /* table       : envelope level, 1.5 dB                                        */
+    /* theor range : [-58,58], CODE_BOOK_SCF_LAV   = 58                            */
+    /* implem range: [-60,60], CODE_BOOK_SCF_LAV10 = 60                            */
+    /* raw stats   : envelopeLevel_00 (yes, wrong suffix in name)  KK 01-03-09     */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode3C2FIX.m/envelopeLevel_00T_cF.mat/m_hALC_cF
+       built by : FH 01-07-05 */
+
+    extern const Char bookSbrEnvLevel10T[120][2] =
+    {
+        {   1,   2 },    { -64, -65 },    {   3,   4 },    { -63, -66 },
+        {   5,   6 },    { -62, -67 },    {   7,   8 },    { -61, -68 },
+        {   9,  10 },    { -60, -69 },    {  11,  12 },    { -59, -70 },
+        {  13,  14 },    { -58, -71 },    {  15,  16 },    { -57, -72 },
+        {  17,  18 },    { -73, -56 },    {  19,  21 },    { -74,  20 },
+        { -55, -75 },    {  22,  26 },    {  23,  24 },    { -54, -76 },
+        { -77,  25 },    { -53, -78 },    {  27,  34 },    {  28,  29 },
+        { -52, -79 },    {  30,  31 },    { -80, -51 },    {  32,  33 },
+        { -83, -82 },    { -81, -50 },    {  35,  57 },    {  36,  40 },
+        {  37,  38 },    { -88, -84 },    { -48,  39 },    { -90, -85 },
+        {  41,  46 },    {  42,  43 },    { -49, -87 },    {  44,  45 },
+        { -89, -86 },    { -124, -123 },    {  47,  50 },    {  48,  49 },
+        { -122, -121 },    { -120, -119 },    {  51,  54 },    {  52,  53 },
+        { -118, -117 },    { -116, -115 },    {  55,  56 },    { -114, -113 },
+        { -112, -111 },    {  58,  89 },    {  59,  74 },    {  60,  67 },
+        {  61,  64 },    {  62,  63 },    { -110, -109 },    { -108, -107 },
+        {  65,  66 },    { -106, -105 },    { -104, -103 },    {  68,  71 },
+        {  69,  70 },    { -102, -101 },    { -100, -99 },    {  72,  73 },
+        { -98, -97 },    { -96, -95 },    {  75,  82 },    {  76,  79 },
+        {  77,  78 },    { -94, -93 },    { -92, -91 },    {  80,  81 },
+        { -47, -46 },    { -45, -44 },    {  83,  86 },    {  84,  85 },
+        { -43, -42 },    { -41, -40 },    {  87,  88 },    { -39, -38 },
+        { -37, -36 },    {  90, 105 },    {  91,  98 },    {  92,  95 },
+        {  93,  94 },    { -35, -34 },    { -33, -32 },    {  96,  97 },
+        { -31, -30 },    { -29, -28 },    {  99, 102 },    { 100, 101 },
+        { -27, -26 },    { -25, -24 },    { 103, 104 },    { -23, -22 },
+        { -21, -20 },    { 106, 113 },    { 107, 110 },    { 108, 109 },
+        { -19, -18 },    { -17, -16 },    { 111, 112 },    { -15, -14 },
+        { -13, -12 },    { 114, 117 },    { 115, 116 },    { -11, -10 },
+        {  -9,  -8 },    { 118, 119 },    {  -7,  -6 },    {  -5,  -4 }
+    };
+
+    /* direction: freq
+       raw table: HuffCode3C2FIX.m/envelopeLevel_00F_cF.mat/m_hALC_cF
+       built by : FH 01-07-05 */
+
+    extern const Char bookSbrEnvLevel10F[120][2] =
+    {
+        {   1,   2 },    { -64, -65 },    {   3,   4 },    { -63, -66 },
+        {   5,   6 },    { -67, -62 },    {   7,   8 },    { -68, -61 },
+        {   9,  10 },    { -69, -60 },    {  11,  13 },    { -70,  12 },
+        { -59, -71 },    {  14,  16 },    { -58,  15 },    { -72, -57 },
+        {  17,  19 },    { -73,  18 },    { -56, -74 },    {  20,  23 },
+        {  21,  22 },    { -55, -75 },    { -54, -53 },    {  24,  27 },
+        {  25,  26 },    { -76, -52 },    { -77, -51 },    {  28,  31 },
+        {  29,  30 },    { -50, -78 },    { -79, -49 },    {  32,  36 },
+        {  33,  34 },    { -48, -47 },    { -80,  35 },    { -81, -82 },
+        {  37,  47 },    {  38,  41 },    {  39,  40 },    { -83, -46 },
+        { -45, -84 },    {  42,  44 },    { -85,  43 },    { -44, -43 },
+        {  45,  46 },    { -88, -87 },    { -86, -90 },    {  48,  66 },
+        {  49,  56 },    {  50,  53 },    {  51,  52 },    { -92, -42 },
+        { -41, -39 },    {  54,  55 },    { -105, -89 },    { -38, -37 },
+        {  57,  60 },    {  58,  59 },    { -94, -91 },    { -40, -36 },
+        {  61,  63 },    { -20,  62 },    { -115, -110 },    {  64,  65 },
+        { -108, -107 },    { -101, -97 },    {  67,  89 },    {  68,  75 },
+        {  69,  72 },    {  70,  71 },    { -95, -93 },    { -34, -27 },
+        {  73,  74 },    { -22, -17 },    { -16, -124 },    {  76,  82 },
+        {  77,  79 },    { -123,  78 },    { -122, -121 },    {  80,  81 },
+        { -120, -119 },    { -118, -117 },    {  83,  86 },    {  84,  85 },
+        { -116, -114 },    { -113, -112 },    {  87,  88 },    { -111, -109 },
+        { -106, -104 },    {  90, 105 },    {  91,  98 },    {  92,  95 },
+        {  93,  94 },    { -103, -102 },    { -100, -99 },    {  96,  97 },
+        { -98, -96 },    { -35, -33 },    {  99, 102 },    { 100, 101 },
+        { -32, -31 },    { -30, -29 },    { 103, 104 },    { -28, -26 },
+        { -25, -24 },    { 106, 113 },    { 107, 110 },    { 108, 109 },
+        { -23, -21 },    { -19, -18 },    { 111, 112 },    { -15, -14 },
+        { -13, -12 },    { 114, 117 },    { 115, 116 },    { -11, -10 },
+        {  -9,  -8 },    { 118, 119 },    {  -7,  -6 },    {  -5,  -4 }
+    };
+
+    /*******************************************************************************/
+    /* table       : envelope balance, 1.5 dB                                      */
+    /* theor range : [-48,48], CODE_BOOK_SCF_LAV = 48                              */
+    /* implem range: same but mapped to [-24,24], CODE_BOOK_SCF_LAV_BALANCE10 = 24 */
+    /* raw stats   : envelopePan_00 (yes, wrong suffix in name)  KK 01-03-09       */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode3C.m/envelopePan_00T.mat/v_hALB
+       built by : FH 01-05-15 */
+
+    extern const Char bookSbrEnvBalance10T[48][2] =
+    {
+        { -64,   1 },    { -63,   2 },    { -65,   3 },    { -62,   4 },
+        { -66,   5 },    { -61,   6 },    { -67,   7 },    { -60,   8 },
+        { -68,   9 },    {  10,  11 },    { -69, -59 },    {  12,  13 },
+        { -70, -58 },    {  14,  28 },    {  15,  21 },    {  16,  18 },
+        { -57,  17 },    { -71, -56 },    {  19,  20 },    { -88, -87 },
+        { -86, -85 },    {  22,  25 },    {  23,  24 },    { -84, -83 },
+        { -82, -81 },    {  26,  27 },    { -80, -79 },    { -78, -77 },
+        {  29,  36 },    {  30,  33 },    {  31,  32 },    { -76, -75 },
+        { -74, -73 },    {  34,  35 },    { -72, -55 },    { -54, -53 },
+        {  37,  41 },    {  38,  39 },    { -52, -51 },    { -50,  40 },
+        { -49, -48 },    {  42,  45 },    {  43,  44 },    { -47, -46 },
+        { -45, -44 },    {  46,  47 },    { -43, -42 },    { -41, -40 }
+    };
+
+    /* direction: freq
+       raw table: HuffCode3C.m/envelopePan_00T.mat/v_hALB
+       built by : FH 01-05-15 */
+
+    extern const Char bookSbrEnvBalance10F[48][2] =
+    {
+        { -64,   1 },    { -65,   2 },    { -63,   3 },    { -66,   4 },
+        { -62,   5 },    { -61,   6 },    { -67,   7 },    { -68,   8 },
+        { -60,   9 },    {  10,  11 },    { -69, -59 },    { -70,  12 },
+        { -58,  13 },    {  14,  17 },    { -71,  15 },    { -57,  16 },
+        { -56, -73 },    {  18,  32 },    {  19,  25 },    {  20,  22 },
+        { -72,  21 },    { -88, -87 },    {  23,  24 },    { -86, -85 },
+        { -84, -83 },    {  26,  29 },    {  27,  28 },    { -82, -81 },
+        { -80, -79 },    {  30,  31 },    { -78, -77 },    { -76, -75 },
+        {  33,  40 },    {  34,  37 },    {  35,  36 },    { -74, -55 },
+        { -54, -53 },    {  38,  39 },    { -52, -51 },    { -50, -49 },
+        {  41,  44 },    {  42,  43 },    { -48, -47 },    { -46, -45 },
+        {  45,  46 },    { -44, -43 },    { -42,  47 },    { -41, -40 }
+    };
+
+    /*******************************************************************************/
+    /* table       : envelope level, 3.0 dB                                        */
+    /* theor range : [-29,29], CODE_BOOK_SCF_LAV   = 29                            */
+    /* implem range: [-31,31], CODE_BOOK_SCF_LAV11 = 31                            */
+    /* raw stats   : envelopeLevel_11  KK 00-02-03                                 */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode2.m
+       built by : FH 00-02-04 */
+
+    extern const Char bookSbrEnvLevel11T[62][2] =
+    {
+        { -64,   1 },    { -65,   2 },    { -63,   3 },    { -66,   4 },
+        { -62,   5 },    { -67,   6 },    { -61,   7 },    { -68,   8 },
+        { -60,   9 },    {  10,  11 },    { -69, -59 },    {  12,  14 },
+        { -70,  13 },    { -71, -58 },    {  15,  18 },    {  16,  17 },
+        { -72, -57 },    { -73, -74 },    {  19,  22 },    { -56,  20 },
+        { -55,  21 },    { -54, -77 },    {  23,  31 },    {  24,  25 },
+        { -75, -76 },    {  26,  27 },    { -78, -53 },    {  28,  29 },
+        { -52, -95 },    { -94,  30 },    { -93, -92 },    {  32,  47 },
+        {  33,  40 },    {  34,  37 },    {  35,  36 },    { -91, -90 },
+        { -89, -88 },    {  38,  39 },    { -87, -86 },    { -85, -84 },
+        {  41,  44 },    {  42,  43 },    { -83, -82 },    { -81, -80 },
+        {  45,  46 },    { -79, -51 },    { -50, -49 },    {  48,  55 },
+        {  49,  52 },    {  50,  51 },    { -48, -47 },    { -46, -45 },
+        {  53,  54 },    { -44, -43 },    { -42, -41 },    {  56,  59 },
+        {  57,  58 },    { -40, -39 },    { -38, -37 },    {  60,  61 },
+        { -36, -35 },    { -34, -33 }
+    };
+
+    /* direction: freq
+       raw table: HuffCode2.m
+       built by : FH 00-02-04 */
+
+    extern const Char bookSbrEnvLevel11F[62][2] =
+    {
+        { -64,   1 },    { -65,   2 },    { -63,   3 },    { -66,   4 },
+        { -62,   5 },    { -67,   6 },    {   7,   8 },    { -61, -68 },
+        {   9,  10 },    { -60, -69 },    {  11,  12 },    { -59, -70 },
+        {  13,  14 },    { -58, -71 },    {  15,  16 },    { -57, -72 },
+        {  17,  19 },    { -56,  18 },    { -55, -73 },    {  20,  24 },
+        {  21,  22 },    { -74, -54 },    { -53,  23 },    { -75, -76 },
+        {  25,  30 },    {  26,  27 },    { -52, -51 },    {  28,  29 },
+        { -77, -79 },    { -50, -49 },    {  31,  39 },    {  32,  35 },
+        {  33,  34 },    { -78, -46 },    { -82, -88 },    {  36,  37 },
+        { -83, -48 },    { -47,  38 },    { -86, -85 },    {  40,  47 },
+        {  41,  44 },    {  42,  43 },    { -80, -44 },    { -43, -42 },
+        {  45,  46 },    { -39, -87 },    { -84, -40 },    {  48,  55 },
+        {  49,  52 },    {  50,  51 },    { -95, -94 },    { -93, -92 },
+        {  53,  54 },    { -91, -90 },    { -89, -81 },    {  56,  59 },
+        {  57,  58 },    { -45, -41 },    { -38, -37 },    {  60,  61 },
+        { -36, -35 },    { -34, -33 }
+    };
+
+    /*******************************************************************************/
+    /* table       : envelope balance, 3.0 dB                                      */
+    /* theor range : [-24,24], CODE_BOOK_SCF_LAV = 24                              */
+    /* implem range: same but mapped to [-12,12], CODE_BOOK_SCF_LAV_BALANCE11 = 12 */
+    /* raw stats   : envelopeBalance_11  KK 00-02-03                               */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode3C.m/envelopeBalance_11T.mat/v_hALB
+       built by : FH 01-05-15 */
+
+    extern const Char bookSbrEnvBalance11T[24][2] =
+    {
+        { -64,   1 },    { -63,   2 },    { -65,   3 },    { -66,   4 },
+        { -62,   5 },    { -61,   6 },    { -67,   7 },    { -68,   8 },
+        { -60,   9 },    {  10,  16 },    {  11,  13 },    { -69,  12 },
+        { -76, -75 },    {  14,  15 },    { -74, -73 },    { -72, -71 },
+        {  17,  20 },    {  18,  19 },    { -70, -59 },    { -58, -57 },
+        {  21,  22 },    { -56, -55 },    { -54,  23 },    { -53, -52 }
+    };
+
+    /* direction: time (?)
+       raw table: HuffCode3C.m/envelopeBalance_11T.mat/v_hALB
+       built by : FH 01-05-15 */
+
+    extern const Char bookSbrEnvBalance11F[24][2] =
+    {
+        { -64,   1 },    { -65,   2 },    { -63,   3 },    { -66,   4 },
+        { -62,   5 },    { -61,   6 },    { -67,   7 },    { -68,   8 },
+        { -60,   9 },    {  10,  13 },    { -69,  11 },    { -59,  12 },
+        { -58, -76 },    {  14,  17 },    {  15,  16 },    { -75, -74 },
+        { -73, -72 },    {  18,  21 },    {  19,  20 },    { -71, -70 },
+        { -57, -56 },    {  22,  23 },    { -55, -54 },    { -53, -52 }
+    };
+
+    /*******************************************************************************/
+    /* table       : noise level, 3.0 dB                                           */
+    /* theor range : [-29,29], CODE_BOOK_SCF_LAV   = 29                            */
+    /* implem range: [-31,31], CODE_BOOK_SCF_LAV11 = 31                            */
+    /* raw stats   : noiseLevel_11  KK 00-02-03                                    */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode2.m
+       built by : FH 00-02-04 */
+
+    extern const Char bookSbrNoiseLevel11T[62][2] =
+    {
+        { -64,   1 },    { -63,   2 },    { -65,   3 },    { -66,   4 },
+        { -62,   5 },    { -67,   6 },    {   7,   8 },    { -61, -68 },
+        {   9,  30 },    {  10,  15 },    { -60,  11 },    { -69,  12 },
+        {  13,  14 },    { -59, -53 },    { -95, -94 },    {  16,  23 },
+        {  17,  20 },    {  18,  19 },    { -93, -92 },    { -91, -90 },
+        {  21,  22 },    { -89, -88 },    { -87, -86 },    {  24,  27 },
+        {  25,  26 },    { -85, -84 },    { -83, -82 },    {  28,  29 },
+        { -81, -80 },    { -79, -78 },    {  31,  46 },    {  32,  39 },
+        {  33,  36 },    {  34,  35 },    { -77, -76 },    { -75, -74 },
+        {  37,  38 },    { -73, -72 },    { -71, -70 },    {  40,  43 },
+        {  41,  42 },    { -58, -57 },    { -56, -55 },    {  44,  45 },
+        { -54, -52 },    { -51, -50 },    {  47,  54 },    {  48,  51 },
+        {  49,  50 },    { -49, -48 },    { -47, -46 },    {  52,  53 },
+        { -45, -44 },    { -43, -42 },    {  55,  58 },    {  56,  57 },
+        { -41, -40 },    { -39, -38 },    {  59,  60 },    { -37, -36 },
+        { -35,  61 },    { -34, -33 }
+    };
+
+    /*******************************************************************************/
+    /* table       : noise balance, 3.0 dB                                         */
+    /* theor range : [-24,24], CODE_BOOK_SCF_LAV = 24                              */
+    /* implem range: same but mapped to [-12,12], CODE_BOOK_SCF_LAV_BALANCE11 = 12 */
+    /* raw stats   : noiseBalance_11  KK 00-02-03                                  */
+    /*******************************************************************************/
+
+    /* direction: time
+       raw table: HuffCode3C.m/noiseBalance_11.mat/v_hALB
+       built by : FH 01-05-15 */
+
+    extern const Char bookSbrNoiseBalance11T[24][2] =
+    {
+        { -64,   1 },    { -65,   2 },    { -63,   3 },    {   4,   9 },
+        { -66,   5 },    { -62,   6 },    {   7,   8 },    { -76, -75 },
+        { -74, -73 },    {  10,  17 },    {  11,  14 },    {  12,  13 },
+        { -72, -71 },    { -70, -69 },    {  15,  16 },    { -68, -67 },
+        { -61, -60 },    {  18,  21 },    {  19,  20 },    { -59, -58 },
+        { -57, -56 },    {  22,  23 },    { -55, -54 },    { -53, -52 }
+    };
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.h b/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.h
new file mode 100644
index 0000000..3df0531
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_code_book_envlevel.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: sbr_code_book_envlevel.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ this file declares the scalefactor bands for all sampling rates
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_CODE_BOOK_ENVLEVEL_H
+#define SBR_CODE_BOOK_ENVLEVEL_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Char bookSbrEnvLevel10T[120][2];
+    extern const Char bookSbrEnvLevel10F[120][2];
+    extern const Char bookSbrEnvBalance10T[48][2];
+    extern const Char bookSbrEnvBalance10F[48][2];
+    extern const Char bookSbrEnvLevel11T[62][2];
+    extern const Char bookSbrEnvLevel11F[62][2];
+    extern const Char bookSbrEnvBalance11T[24][2];
+    extern const Char bookSbrEnvBalance11F[24][2];
+    extern const Char bookSbrNoiseLevel11T[62][2];
+    extern const Char bookSbrNoiseBalance11T[24][2];
+
+    /*----------------------------------------------------------------------------
+    ; 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/aacdec/sbr_constants.h b/media/libstagefright/codecs/aacdec/sbr_constants.h
new file mode 100644
index 0000000..d54a699
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_constants.h
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_constants.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_CONSTANTS_H
+#define SBR_CONSTANTS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+
+#define SBR_AMP_RES_1_5         0
+#define SBR_AMP_RES_3_0         1
+
+#define MAX_NOISE_ENVELOPES     2
+#define MAX_NOISE_COEFFS        5
+#define MAX_NUM_NOISE_VALUES     (MAX_NOISE_ENVELOPES * MAX_NOISE_COEFFS)
+
+#define MAX_ENVELOPES           5
+#define MAX_FREQ_COEFFS         58
+#define MAX_NUM_ENVELOPE_VALUES (MAX_ENVELOPES * MAX_FREQ_COEFFS)
+
+#define MAX_NUM_CHANNELS            2
+#define NOISE_FLOOR_OFFSET          6
+#define NOISE_FLOOR_OFFSET_PLUS_1   7
+
+#define LOW_RES                     0
+#define HIGH_RES                    1
+
+#define LO                          0
+#define HI                          1
+
+#define TIME                        1
+#define FREQ                        0
+
+#define LENGTH_FRAME_INFO           35
+
+#define SI_SBR_CRC_BITS             10
+
+#define SBR_FREQ_SCALE_DEFAULT      2
+#define SBR_ALTER_SCALE_DEFAULT     1
+#define SBR_NOISE_BANDS_DEFAULT     2
+
+#define SBR_LIMITER_BANDS_DEFAULT      2
+#define SBR_LIMITER_GAINS_DEFAULT      2
+#define SBR_INTERPOL_FREQ_DEFAULT      1
+#define SBR_SMOOTHING_LENGTH_DEFAULT   1
+
+/* header */
+#define SI_SBR_AMP_RES_BITS            1
+#define SI_SBR_START_FREQ_BITS         4
+#define SI_SBR_STOP_FREQ_BITS          4
+#define SI_SBR_XOVER_BAND_BITS         3
+#define SI_SBR_RESERVED_BITS_HDR       2
+#define SI_SBR_DATA_EXTRA_BITS         1
+#define SI_SBR_HEADER_EXTRA_1_BITS     1
+#define SI_SBR_HEADER_EXTRA_2_BITS     1
+
+#define SI_SBR_FREQ_SCALE_BITS         2
+#define SI_SBR_ALTER_SCALE_BITS        1
+#define SI_SBR_NOISE_BANDS_BITS        2
+
+#define SI_SBR_LIMITER_BANDS_BITS      2
+#define SI_SBR_LIMITER_GAINS_BITS      2
+#define SI_SBR_INTERPOL_FREQ_BITS      1
+#define SI_SBR_SMOOTHING_LENGTH_BITS   1
+
+
+/* data */
+#define SI_SBR_RESERVED_PRESENT        1
+#define SI_SBR_RESERVED_BITS_DATA      4
+
+#define SI_SBR_COUPLING_BITS           1
+
+#define SI_SBR_INVF_MODE_BITS          2
+
+#define SI_SBR_EXTENDED_DATA_BITS      1
+#define SI_SBR_EXTENSION_SIZE_BITS     4
+#define SI_SBR_EXTENSION_ESC_COUNT_BITS   8
+#define SI_SBR_EXTENSION_ID_BITS          2
+
+#define SI_SBR_NOISE_MODE_BITS         1
+#define SI_SBR_DOMAIN_BITS             1
+
+#define SI_SBR_START_ENV_BITS_AMP_RES_3_0           6
+#define SI_SBR_START_ENV_BITS_BALANCE_AMP_RES_3_0   5
+#define SI_SBR_START_NOISE_BITS_AMP_RES_3_0         5
+#define SI_SBR_START_NOISE_BITS_BALANCE_AMP_RES_3_0 5
+
+#define SI_SBR_START_ENV_BITS_AMP_RES_1_5           7
+#define SI_SBR_START_ENV_BITS_BALANCE_AMP_RES_1_5   6
+
+
+#define SBR_CLA_BITS  2
+#define SBR_ABS_BITS  2
+#define SBR_RES_BITS  1
+#define SBR_REL_BITS  2
+#define SBR_ENV_BITS  2
+#define SBR_NUM_BITS  2
+
+
+#define FIXFIX  0
+#define FIXVAR  1
+#define VARFIX  2
+#define VARVAR  3
+
+
+#define    LEN_EX_TYPE  (4)
+#define    LEN_NIBBLE   (4)
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_crc_check.cpp b/media/libstagefright/codecs/aacdec/sbr_crc_check.cpp
new file mode 100644
index 0000000..3bb4398
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_crc_check.cpp
@@ -0,0 +1,191 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_crc_check.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "sbr_crc_check.h"
+#include "s_crc_buffer.h"
+#include "buf_getbits.h"
+#include "sbr_constants.h"
+#include "check_crc.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
+----------------------------------------------------------------------------*/
+
+const unsigned short MAXCRCSTEP = 16;
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int32 sbr_crc_check(BIT_BUFFER * hBitBuf, UInt32 NrBits)
+{
+    Int32 crcResult = 1;
+    BIT_BUFFER BitBufferCRC;
+    UInt32 NrCrcBits;
+
+    UInt32 crcCheckSum;
+
+    Int32 i;
+    CRC_BUFFER CrcBuf;
+    UInt32 bValue;
+    Int32 CrcStep;
+    Int32 CrcNrBitsRest;
+
+    crcCheckSum = buf_getbits(hBitBuf, SI_SBR_CRC_BITS);
+
+
+    /*
+     *    Copy Bit buffer State
+     */
+
+    BitBufferCRC.char_ptr       = hBitBuf->char_ptr;
+    BitBufferCRC.buffer_word    = hBitBuf->buffer_word;
+    BitBufferCRC.buffered_bits  = hBitBuf->buffered_bits;
+    BitBufferCRC.nrBitsRead     = hBitBuf->nrBitsRead;
+    BitBufferCRC.bufferLen      = hBitBuf->bufferLen;
+
+
+    NrCrcBits = min(NrBits, BitBufferCRC.bufferLen - BitBufferCRC.nrBitsRead);
+
+
+    CrcStep = NrCrcBits / MAXCRCSTEP;
+    CrcNrBitsRest = (NrCrcBits - CrcStep * MAXCRCSTEP);
+
+    CrcBuf.crcState = CRCSTART;
+    CrcBuf.crcMask  = CRCMASK;
+    CrcBuf.crcPoly  = CRCPOLY;
+
+    for (i = 0; i < CrcStep; i++)
+    {
+        bValue = buf_getbits(&BitBufferCRC, MAXCRCSTEP);
+        check_crc(&CrcBuf, bValue, MAXCRCSTEP);
+    }
+
+    bValue = buf_getbits(&BitBufferCRC, CrcNrBitsRest);
+    check_crc(&CrcBuf, bValue, CrcNrBitsRest);
+
+    if ((UInt32)(CrcBuf.crcState & CRCRANGE) != crcCheckSum)
+    {
+        crcResult = 0;
+    }
+
+    return (crcResult);
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_crc_check.h b/media/libstagefright/codecs/aacdec/sbr_crc_check.h
new file mode 100644
index 0000000..9e6b1be
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_crc_check.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_crc_check.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_CRC_CHECK_H
+#define SBR_CRC_CHECK_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "s_bit_buffer.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define CRCPOLY  0x0233
+#define CRCMASK  0x0200
+#define CRCSTART 0x0000
+#define CRCRANGE 0x03FF
+
+#define SBR_EXTENSION      13 /* 1101 */
+#define SBR_EXTENSION_CRC  14 /* 1110 */
+
+
+
+#ifndef min
+#define min(a, b) ((a) < (b) ? (a) : (b))
+#endif
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int32 sbr_crc_check(BIT_BUFFER * hBitBuf,
+                    UInt32 NrBits);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.cpp b/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.cpp
new file mode 100644
index 0000000..9472ffc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.cpp
@@ -0,0 +1,253 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_create_limiter_bands.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_create_limiter_bands.h"
+#include    "shellsort.h"
+#include    "s_patch.h"
+#include    "pv_log2.h"
+
+#include "fxp_mul32.h"
+
+#define R_SHIFT     29
+#define Q_fmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+
+/*----------------------------------------------------------------------------
+; 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 sbr_create_limiter_bands(Int32 limSbc[][13],
+                              Int32 *gateMode,
+                              Int   *freqTable,
+                              struct PATCH Patch,
+                              const Int32 noBands)
+{
+    Int32 i;
+    Int32 j;
+    Int32 k;
+    Int isPatchBorder[2];
+    Int32 patchBorders[MAX_NUM_PATCHES + 1];
+    Int32 workLimiterBandTable[32 + MAX_NUM_PATCHES + 1];
+
+    Int32 nOctaves;
+    const Int32 limiterBandsPerOctave[4] =
+        {Q_fmt(0.0F), Q_fmt(1.2F),
+         Q_fmt(2.0F), Q_fmt(3.0F)
+        };
+
+    Int32 tmp_q1;
+
+    Int32 noPatches = Patch.noOfPatches;
+    Int32 lowSubband = freqTable[0];
+    Int32 highSubband = freqTable[noBands];
+
+
+    for (i = 0; i < noPatches; i++)
+    {
+        patchBorders[i] = Patch.targetStartBand[i] - lowSubband;
+    }
+    patchBorders[i] = highSubband - lowSubband;
+
+    /* First band: 1 limiter band. */
+    limSbc[0][0] = freqTable[0] - lowSubband;
+    limSbc[0][1] = freqTable[noBands] - lowSubband;
+    gateMode[0] = 1;
+
+    /* Next three bands: 1.2, 2, 3 limiter bands/octave plus bandborders at patchborders. */
+    for (i = 1; i < 4; i++)
+    {
+
+        for (k = 0; k <= noBands; k++)
+        {
+            workLimiterBandTable[k] = freqTable[k] - lowSubband;
+        }
+
+        for (k = 1; k < noPatches; k++)
+        {
+            workLimiterBandTable[noBands+k] = patchBorders[k];
+        }
+
+        gateMode[i] = noBands + noPatches - 1;
+        shellsort(workLimiterBandTable, gateMode[i] + 1);
+
+        for (j = 1; j <= gateMode[i]; j++)
+        {
+            tmp_q1 = ((workLimiterBandTable[j] + lowSubband) << 20) / (workLimiterBandTable[j-1] + lowSubband);
+
+            nOctaves = pv_log2(tmp_q1);
+
+            tmp_q1 = fxp_mul32_Q20(nOctaves, limiterBandsPerOctave[i]);
+            if (tmp_q1 < Q_fmt(0.49))
+            {
+                if (workLimiterBandTable[j] == workLimiterBandTable[j-1])
+                {
+                    workLimiterBandTable[j] = highSubband;
+                    shellsort(workLimiterBandTable, gateMode[i] + 1);
+                    gateMode[i]--;
+                    j--;
+                    continue;
+                }
+
+                isPatchBorder[0] = isPatchBorder[1] = 0;
+
+                for (k = 0; k <= noPatches; k++)
+                {
+                    if (workLimiterBandTable[j-1] == patchBorders[k])
+                    {
+                        isPatchBorder[0] = 1;
+                        break;
+                    }
+                }
+
+                for (k = 0; k <= noPatches; k++)
+                {
+                    if (workLimiterBandTable[j] == patchBorders[k])
+                    {
+                        isPatchBorder[1] = 1;
+                        break;
+                    }
+                }
+
+                if (!isPatchBorder[1])
+                {
+                    workLimiterBandTable[j] = highSubband;
+                    shellsort(workLimiterBandTable, gateMode[i] + 1);
+                    gateMode[i]--;
+                    j--;
+                }
+                else if (!isPatchBorder[0])
+                {
+                    workLimiterBandTable[j-1] = highSubband;
+                    shellsort(workLimiterBandTable, gateMode[i] + 1);
+                    gateMode[i]--;
+                    j--;
+                }
+            }
+        }
+        for (k = 0; k <= gateMode[i]; k++)
+        {
+            limSbc[i][k] = workLimiterBandTable[k];
+        }
+    }
+}
+
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.h b/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.h
new file mode 100644
index 0000000..7a53944
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_create_limiter_bands.h
@@ -0,0 +1,95 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_create_limiter_bands.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_CREATE_LIMITER_BANDS_H
+#define SBR_CREATE_LIMITER_BANDS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "sbr_generate_high_freq.h"
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void sbr_create_limiter_bands(Int32 limSbc[4][12 + 1],
+    Int32 gateMode[4],
+    Int   *freqTable,
+    struct PATCH Patch,
+    const Int32 noBands);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_dec.cpp b/media/libstagefright/codecs/aacdec/sbr_dec.cpp
new file mode 100644
index 0000000..8fcc3ce
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_dec.cpp
@@ -0,0 +1,942 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_dec.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    sbr decoder core function
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+
+#include    "s_sbr_frame_data.h"
+#include    "calc_sbr_synfilterbank.h"
+#include    "calc_sbr_anafilterbank.h"
+#include    "calc_sbr_envelope.h"
+#include    "sbr_generate_high_freq.h"
+#include    "sbr_dec.h"
+#include    "decode_noise_floorlevels.h"
+#include    "aac_mem_funcs.h"
+#include    "fxp_mul32.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
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+#ifdef PARAMETRICSTEREO
+
+#include   "ps_applied.h"
+#include   "ps_init_stereo_mixing.h"
+
+#endif
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void sbr_dec(Int16 *inPcmData,
+             Int16 *ftimeOutPtr,
+             SBR_FRAME_DATA * hFrameData,
+             int32_t applyProcessing,
+             SBR_DEC *sbrDec,
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+             Int16 * ftimeOutPtrPS,
+             HANDLE_PS_DEC hParametricStereoDec,
+#endif
+#endif
+             tDec_Int_File  *pVars)
+{
+    int32_t   i;
+    int32_t   j;
+    int32_t   m;
+
+    int32_t  *frameInfo = hFrameData->frameInfo;
+    Int  num_qmf_bands;
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+
+    int32_t env;
+
+    int32_t *qmf_PS_generated_Real;
+    int32_t *qmf_PS_generated_Imag;
+
+    int32_t *Sr_x;
+    int32_t *Si_x;
+
+
+#endif
+#endif
+
+    int32_t(*scratch_mem)[64];
+    Int16 *circular_buffer_s;
+
+    int32_t   k;
+    int32_t *Sr;
+    int32_t *Si;
+    int32_t *ptr_tmp1;
+    int32_t *ptr_tmp2;
+    scratch_mem = pVars->scratch.scratch_mem;
+
+
+    if (applyProcessing)
+    {
+        num_qmf_bands = sbrDec->lowSubband;
+    }
+    else
+    {
+        num_qmf_bands = 32;     /* becomes a resampler by 2  */
+    }
+
+    /* -------------------------------------------------- */
+    /*
+     *    Re-Load Buffers
+     */
+    pv_memmove(&hFrameData->sbrQmfBufferReal[0],
+               &hFrameData->HistsbrQmfBufferReal[0],
+               6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferReal));
+#ifdef HQ_SBR
+
+
+    if (sbrDec->LC_aacP_DecoderFlag == OFF)
+    {
+        pv_memmove(&hFrameData->sbrQmfBufferImag[0],
+                   &hFrameData->HistsbrQmfBufferImag[0],
+                   6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferImag));
+    }
+#endif
+    /* -------------------------------------------------- */
+
+
+    /*
+     *    low band codec signal subband filtering
+     */
+
+    for (i = 0; i < 32; i++)
+    {
+
+        if (sbrDec->LC_aacP_DecoderFlag == ON)
+        {
+
+            calc_sbr_anafilterbank_LC(hFrameData->codecQmfBufferReal[sbrDec->bufWriteOffs + i],
+                                      &inPcmData[319] + (i << 5),
+                                      scratch_mem,
+                                      num_qmf_bands);
+
+        }
+#ifdef HQ_SBR
+        else
+        {
+
+            calc_sbr_anafilterbank(hFrameData->codecQmfBufferReal[sbrDec->bufWriteOffs + i],
+                                   hFrameData->codecQmfBufferImag[sbrDec->bufWriteOffs + i],
+                                   &inPcmData[319] + (i << 5),
+                                   scratch_mem,
+                                   num_qmf_bands);
+        }
+#endif
+
+    }
+
+    if (pVars->ltp_buffer_state)
+    {
+        pv_memcpy(&inPcmData[-1024-288], &inPcmData[1024], 288*sizeof(*inPcmData));
+    }
+    else
+    {
+        pv_memcpy(&inPcmData[1024 + 288], &inPcmData[1024], 288*sizeof(*inPcmData));
+    }
+
+
+    if (applyProcessing)
+    {
+
+        /*
+         *  Inverse filtering of lowband + HF generation
+         */
+
+        if (sbrDec->LC_aacP_DecoderFlag == ON)
+        {
+
+            sbr_generate_high_freq((int32_t(*)[32])(hFrameData->codecQmfBufferReal + sbrDec->bufReadOffs),
+                                   NULL,
+                                   (int32_t *)(hFrameData->sbrQmfBufferReal),
+                                   NULL,
+                                   hFrameData->sbr_invf_mode,
+                                   hFrameData->sbr_invf_mode_prev,
+                                   &(sbrDec->FreqBandTableNoise[1]),
+                                   sbrDec->NoNoiseBands,
+                                   sbrDec->lowSubband,
+                                   sbrDec->V_k_master,
+                                   sbrDec->Num_Master,
+                                   sbrDec->outSampleRate,
+                                   frameInfo,
+                                   hFrameData->degreeAlias,
+                                   scratch_mem,
+                                   hFrameData->BwVector,/* */
+                                   hFrameData->BwVectorOld,
+                                   &(sbrDec->Patch),
+                                   sbrDec->LC_aacP_DecoderFlag,
+                                   &(sbrDec->highSubband));
+
+
+            /*
+             *      Adjust envelope of current frame.
+             */
+
+            calc_sbr_envelope(hFrameData,
+                              (int32_t *)(hFrameData->sbrQmfBufferReal),
+                              NULL,
+                              sbrDec->FreqBandTable,
+                              sbrDec->NSfb,
+                              sbrDec->FreqBandTableNoise,
+                              sbrDec->NoNoiseBands,
+                              hFrameData->reset_flag,
+                              hFrameData->degreeAlias,
+                              &(hFrameData->harm_index),
+                              &(hFrameData->phase_index),
+                              hFrameData->hFp,
+                              &(hFrameData->sUp),
+                              sbrDec->limSbc,
+                              sbrDec->gateMode,
+#ifdef HQ_SBR
+                              NULL,
+                              NULL,
+                              NULL,
+                              NULL,
+#endif
+                              scratch_mem,
+                              sbrDec->Patch,
+                              sbrDec->sqrt_cache,
+                              sbrDec->LC_aacP_DecoderFlag);
+        }
+#ifdef HQ_SBR
+        else
+        {
+
+            sbr_generate_high_freq((int32_t(*)[32])(hFrameData->codecQmfBufferReal + sbrDec->bufReadOffs),
+                                   (int32_t(*)[32])(hFrameData->codecQmfBufferImag + sbrDec->bufReadOffs),
+                                   (int32_t *)(hFrameData->sbrQmfBufferReal),
+                                   (int32_t *)(hFrameData->sbrQmfBufferImag),
+                                   hFrameData->sbr_invf_mode,
+                                   hFrameData->sbr_invf_mode_prev,
+                                   &(sbrDec->FreqBandTableNoise[1]),
+                                   sbrDec->NoNoiseBands,
+                                   sbrDec->lowSubband,
+                                   sbrDec->V_k_master,
+                                   sbrDec->Num_Master,
+                                   sbrDec->outSampleRate,
+                                   frameInfo,
+                                   NULL,
+                                   scratch_mem,
+                                   hFrameData->BwVector,
+                                   hFrameData->BwVectorOld,
+                                   &(sbrDec->Patch),
+                                   sbrDec->LC_aacP_DecoderFlag,
+                                   &(sbrDec->highSubband));
+
+            /*
+             *      Adjust envelope of current frame.
+             */
+
+            calc_sbr_envelope(hFrameData,
+                              (int32_t *)(hFrameData->sbrQmfBufferReal),
+                              (int32_t *)(hFrameData->sbrQmfBufferImag),
+                              sbrDec->FreqBandTable,
+                              sbrDec->NSfb,
+                              sbrDec->FreqBandTableNoise,
+                              sbrDec->NoNoiseBands,
+                              hFrameData->reset_flag,
+                              NULL,
+                              &(hFrameData->harm_index),
+                              &(hFrameData->phase_index),
+                              hFrameData->hFp,
+                              &(hFrameData->sUp),
+                              sbrDec->limSbc,
+                              sbrDec->gateMode,
+                              hFrameData->fBuf_man,
+                              hFrameData->fBuf_exp,
+                              hFrameData->fBufN_man,
+                              hFrameData->fBufN_exp,
+                              scratch_mem,
+                              sbrDec->Patch,
+                              sbrDec->sqrt_cache,
+                              sbrDec->LC_aacP_DecoderFlag);
+
+        }
+#endif
+
+
+    }
+    else   /*  else for applyProcessing */
+    {
+        /* no sbr, set high band buffers to zero */
+
+        for (i = 0; i < SBR_NUM_COLUMNS; i++)
+        {
+            pv_memset((void *)&hFrameData->sbrQmfBufferReal[i*SBR_NUM_BANDS],
+                      0,
+                      SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferReal));
+
+#ifdef HQ_SBR
+            pv_memset((void *)&hFrameData->sbrQmfBufferImag[i*SBR_NUM_BANDS],
+                      0,
+                      SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferImag));
+
+#endif
+        }
+
+    }
+
+
+    /*
+     *  Synthesis subband filtering.
+     */
+
+#ifdef HQ_SBR
+
+#ifdef PARAMETRICSTEREO
+
+
+    /*
+     * psPresentFlag set implies hParametricStereoDec !=NULL, second condition is
+     * is just here to prevent CodeSonar warnings.
+     */
+    if ((pVars->mc_info.psPresentFlag) && (applyProcessing) &&
+            (hParametricStereoDec != NULL))
+    {
+
+        /*
+         *  qmfBufferReal uses the rigth aac channel ( perChan[1] is not used)
+         *  followed by the buffer fxpCoef[2][2048]  which makes a total of
+         *  2349 + 2048*2 = 6445
+         *  These  2 matrices (qmfBufferReal & qmfBufferImag) are
+         *  [2][38][64] == 4864 int32_t
+         */
+
+
+        tDec_Int_Chan *tmpx = &pVars->perChan[1];
+        /*
+         *  dereferencing type-punned pointer avoid
+         *  breaking strict-aliasing rules
+         */
+        int32_t *tmp = (int32_t *)tmpx;
+        hParametricStereoDec->qmfBufferReal = (int32_t(*)[64]) tmp;
+
+        tmp = (int32_t *) & hParametricStereoDec->qmfBufferReal[38][0];
+        hParametricStereoDec->qmfBufferImag = (int32_t(*)[64]) tmp;
+
+        for (i = 0; i < 32; i++)
+        {
+            Int   xoverBand;
+
+            if (i < ((hFrameData->frameInfo[1]) << 1))
+            {
+                xoverBand = sbrDec->prevLowSubband;
+            }
+            else
+            {
+                xoverBand = sbrDec->lowSubband;
+            }
+
+            if (xoverBand > sbrDec->highSubband)
+            {
+                xoverBand = 32; /* error condition, default to upsampling mode */
+            }
+
+            m = sbrDec->bufReadOffs + i;    /*  2 + i */
+
+            Sr_x = hParametricStereoDec->qmfBufferReal[i];
+            Si_x = hParametricStereoDec->qmfBufferImag[i];
+
+
+
+            for (int32_t j = 0; j < xoverBand; j++)
+            {
+                Sr_x[j] = shft_lft_1(hFrameData->codecQmfBufferReal[m][j]);
+                Si_x[j] = shft_lft_1(hFrameData->codecQmfBufferImag[m][j]);
+            }
+
+
+
+
+            pv_memcpy(&Sr_x[xoverBand],
+                      &hFrameData->sbrQmfBufferReal[i*SBR_NUM_BANDS],
+                      (sbrDec->highSubband - xoverBand)*sizeof(*Sr_x));
+
+            pv_memcpy(&Si_x[xoverBand],
+                      &hFrameData->sbrQmfBufferImag[i*SBR_NUM_BANDS],
+                      (sbrDec->highSubband - xoverBand)*sizeof(*Si_x));
+
+            pv_memset((void *)&Sr_x[sbrDec->highSubband],
+                      0,
+                      (64 - sbrDec->highSubband)*sizeof(*Sr_x));
+
+            pv_memset((void *)&Si_x[sbrDec->highSubband],
+                      0,
+                      (64 - sbrDec->highSubband)*sizeof(*Si_x));
+
+
+        }
+
+        for (i = 32; i < 32 + 6; i++)
+        {
+            m = sbrDec->bufReadOffs + i;     /*  2 + i */
+
+            for (int32_t j = 0; j < 5; j++)
+            {
+                hParametricStereoDec->qmfBufferReal[i][j] = shft_lft_1(hFrameData->codecQmfBufferReal[m][j]);
+                hParametricStereoDec->qmfBufferImag[i][j] = shft_lft_1(hFrameData->codecQmfBufferImag[m][j]);
+            }
+
+        }
+
+
+        /*
+         *    Update Buffers
+         */
+        for (i = 0; i < sbrDec->bufWriteOffs; i++)     /* sbrDec->bufWriteOffs set to 8 and unchanged */
+        {
+            j = sbrDec->noCols + i;                    /* sbrDec->noCols set to 32 and unchanged */
+
+            pv_memmove(hFrameData->codecQmfBufferReal[i],         /* to    */
+                       hFrameData->codecQmfBufferReal[j],        /* from  */
+                       sizeof(*hFrameData->codecQmfBufferReal[i]) << 5);
+
+            pv_memmove(hFrameData->codecQmfBufferImag[i],
+                       hFrameData->codecQmfBufferImag[j],
+                       sizeof(*hFrameData->codecQmfBufferImag[i]) << 5);
+        }
+
+
+        pv_memmove(&hFrameData->HistsbrQmfBufferReal[0],
+                   &hFrameData->sbrQmfBufferReal[32*SBR_NUM_BANDS],
+                   6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferReal));
+
+        pv_memmove(&hFrameData->HistsbrQmfBufferImag[0],
+                   &hFrameData->sbrQmfBufferImag[32*SBR_NUM_BANDS],
+                   6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferImag));
+
+
+        /*
+         *   Needs whole QMF matrix formed before applying
+         *   Parametric stereo processing.
+         */
+
+        qmf_PS_generated_Real = scratch_mem[0];
+        qmf_PS_generated_Imag = scratch_mem[1];
+        env = 0;
+
+        /*
+         *  Set circular buffer for Left channel
+         */
+
+        circular_buffer_s = (Int16 *)scratch_mem[7];
+
+
+        if (pVars->mc_info.bDownSampledSbr)
+        {
+            pv_memmove(&circular_buffer_s[2048],
+                       hFrameData->V,
+                       640*sizeof(*circular_buffer_s));
+        }
+        else
+        {
+            pv_memmove(&circular_buffer_s[4096],
+                       hFrameData->V,
+                       1152*sizeof(*circular_buffer_s));
+
+        }
+
+
+        /*
+         *  Set Circular buffer for PS hybrid analysis
+         */
+        for (i = 0, j = 0; i < 3; i++)
+        {
+
+            pv_memmove(&scratch_mem[2][32 + j     ],
+                       hParametricStereoDec->hHybrid->mQmfBufferReal[i],
+                       HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferReal));
+            pv_memmove(&scratch_mem[2][32 + j + 44],
+                       hParametricStereoDec->hHybrid->mQmfBufferImag[i],
+                       HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferImag));
+            j += 88;
+        }
+
+        pv_memset((void *)&qmf_PS_generated_Real[hParametricStereoDec->usb],
+                  0,
+                  (64 - hParametricStereoDec->usb)*sizeof(*qmf_PS_generated_Real));
+
+        pv_memset((void *)&qmf_PS_generated_Imag[hParametricStereoDec->usb],
+                  0,
+                  (64 - hParametricStereoDec->usb)*sizeof(*qmf_PS_generated_Imag));
+
+
+        for (i = 0; i < 32; i++)
+        {
+            if (i == (Int)hParametricStereoDec-> aEnvStartStop[env])
+            {
+                ps_init_stereo_mixing(hParametricStereoDec, env, sbrDec->highSubband);
+                env++;
+            }
+
+
+            ps_applied(hParametricStereoDec,
+                       &hParametricStereoDec->qmfBufferReal[i],
+                       &hParametricStereoDec->qmfBufferImag[i],
+                       qmf_PS_generated_Real,
+                       qmf_PS_generated_Imag,
+                       scratch_mem[2],
+                       i);
+
+            /* Create time samples for regular mono channel */
+
+            if (pVars->mc_info.bDownSampledSbr)
+            {
+                calc_sbr_synfilterbank(hParametricStereoDec->qmfBufferReal[i],  /* realSamples  */
+                                       hParametricStereoDec->qmfBufferImag[i], /* imagSamples  */
+                                       ftimeOutPtr + (i << 6),
+                                       &circular_buffer_s[1984 - (i<<6)],
+                                       pVars->mc_info.bDownSampledSbr);
+            }
+            else
+            {
+                calc_sbr_synfilterbank(hParametricStereoDec->qmfBufferReal[i],  /* realSamples  */
+                                       hParametricStereoDec->qmfBufferImag[i], /* imagSamples  */
+                                       ftimeOutPtr + (i << 7),
+                                       &circular_buffer_s[3968 - (i<<7)],
+                                       pVars->mc_info.bDownSampledSbr);
+
+            }
+
+            pv_memmove(hParametricStereoDec->qmfBufferReal[i], qmf_PS_generated_Real, 64*sizeof(*qmf_PS_generated_Real));
+            pv_memmove(hParametricStereoDec->qmfBufferImag[i], qmf_PS_generated_Imag, 64*sizeof(*qmf_PS_generated_Real));
+
+        }
+
+
+        /*
+         *  Save Circular buffer history used on PS hybrid analysis
+         */
+
+        for (i = 0, j = 0; i < 3; i++)
+        {
+            pv_memmove(hParametricStereoDec->hHybrid->mQmfBufferReal[i],
+                       &scratch_mem[2][ 64 + j     ],
+                       HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferReal));
+
+            pv_memmove(hParametricStereoDec->hHybrid->mQmfBufferImag[i],
+                       &scratch_mem[2][ 64 + j + 44],
+                       HYBRID_FILTER_LENGTH_m_1*sizeof(*hParametricStereoDec->hHybrid->mQmfBufferImag));
+
+            j += 88;
+        }
+
+        pv_memmove(hFrameData->V, &circular_buffer_s[0], 1152*sizeof(*circular_buffer_s));
+
+        /*
+         *  Set circular buffer for Right channel
+         */
+
+        circular_buffer_s = (Int16 *)scratch_mem[5];
+
+        if (pVars->mc_info.bDownSampledSbr)
+        {
+            pv_memmove(&circular_buffer_s[2048],
+                       (int32_t *)hParametricStereoDec->R_ch_qmf_filter_history,
+                       640*sizeof(*circular_buffer_s));
+        }
+        else
+        {
+            pv_memmove(&circular_buffer_s[4096],
+                       (int32_t *)hParametricStereoDec->R_ch_qmf_filter_history,
+                       1152*sizeof(*circular_buffer_s));
+
+        }
+
+
+        for (i = 0; i < 32; i++)
+        {
+            if (pVars->mc_info.bDownSampledSbr)
+            {
+
+                calc_sbr_synfilterbank(hParametricStereoDec->qmfBufferReal[i],  /* realSamples  */
+                                       hParametricStereoDec->qmfBufferImag[i], /* imagSamples  */
+                                       ftimeOutPtrPS + (i << 6),
+                                       &circular_buffer_s[1984 - (i<<6)],
+                                       pVars->mc_info.bDownSampledSbr);
+            }
+            else
+            {
+                calc_sbr_synfilterbank(hParametricStereoDec->qmfBufferReal[i],  /* realSamples  */
+                                       hParametricStereoDec->qmfBufferImag[i], /* imagSamples  */
+                                       ftimeOutPtrPS + (i << 7),
+                                       &circular_buffer_s[3968 - (i<<7)],
+                                       pVars->mc_info.bDownSampledSbr);
+            }
+
+        }
+
+        if (pVars->mc_info.bDownSampledSbr)
+        {
+            pv_memmove((int32_t *)hParametricStereoDec->R_ch_qmf_filter_history, &circular_buffer_s[0], 640*sizeof(*circular_buffer_s));
+        }
+        else
+        {
+            pv_memmove((int32_t *)hParametricStereoDec->R_ch_qmf_filter_history, &circular_buffer_s[0], 1152*sizeof(*circular_buffer_s));
+        }
+
+
+
+
+
+    }
+    else    /*  else -- sbrEnablePS  */
+    {
+
+#endif      /*   PARAMETRICSTEREO */
+#endif      /*   HQ_SBR */
+
+        /*
+         *  Use shared aac memory as continuous buffer
+         */
+
+
+        Sr  = scratch_mem[0];
+        Si  = scratch_mem[1];
+
+        circular_buffer_s = (Int16*)scratch_mem[2];
+
+        if (pVars->mc_info.bDownSampledSbr)
+        {
+
+            pv_memmove(&circular_buffer_s[2048],
+                       hFrameData->V,
+                       640*sizeof(*circular_buffer_s));
+        }
+        else
+        {
+            pv_memmove(&circular_buffer_s[4096],
+                       hFrameData->V,
+                       1152*sizeof(*circular_buffer_s));
+        }
+
+        for (i = 0; i < 32; i++)
+        {
+            Int   xoverBand;
+
+            if (applyProcessing)
+            {
+                if (i < ((hFrameData->frameInfo[1]) << 1))
+                {
+                    xoverBand = sbrDec->prevLowSubband;
+
+                }
+                else
+                {
+                    xoverBand = sbrDec->lowSubband;
+                }
+
+                if (xoverBand > sbrDec->highSubband)
+                {
+                    xoverBand = 32; /* error condition, default to upsampling mode */
+                }
+            }
+            else
+            {
+                xoverBand = 32;
+                sbrDec->highSubband = 32;
+            }
+
+
+            m = sbrDec->bufReadOffs + i;    /* sbrDec->bufReadOffs == 2 */
+
+
+            ptr_tmp1 = (hFrameData->codecQmfBufferReal[m]);
+            ptr_tmp2 = Sr;
+
+            if (sbrDec->LC_aacP_DecoderFlag == ON)
+            {
+
+                for (k = (xoverBand >> 1); k != 0; k--)
+                {
+                    *(ptr_tmp2++) = (*(ptr_tmp1++)) >> 9;
+                    *(ptr_tmp2++) = (*(ptr_tmp1++)) >> 9;
+                }
+                if (xoverBand & 1)
+                {
+                    *(ptr_tmp2++) = (*(ptr_tmp1)) >> 9;
+                }
+
+                ptr_tmp1 = &hFrameData->sbrQmfBufferReal[i*SBR_NUM_BANDS];
+
+
+                for (k = xoverBand; k < sbrDec->highSubband; k++)
+                {
+                    *(ptr_tmp2++) = (*(ptr_tmp1++)) << 1;
+                }
+
+                pv_memset((void *)ptr_tmp2,
+                          0,
+                          (64 - sbrDec->highSubband)*sizeof(*ptr_tmp2));
+
+
+                if (pVars->mc_info.bDownSampledSbr)
+                {
+                    calc_sbr_synfilterbank_LC(Sr,               /* realSamples  */
+                                              ftimeOutPtr + (i << 6),
+                                              &circular_buffer_s[1984 - (i<<6)],
+                                              pVars->mc_info.bDownSampledSbr);
+                }
+                else
+                {
+                    calc_sbr_synfilterbank_LC(Sr,               /* realSamples  */
+                                              ftimeOutPtr + (i << 7),
+                                              &circular_buffer_s[3968 - (i<<7)],
+                                              pVars->mc_info.bDownSampledSbr);
+                }
+            }
+#ifdef HQ_SBR
+            else
+            {
+
+                for (k = xoverBand; k != 0; k--)
+                {
+                    *(ptr_tmp2++) = shft_lft_1(*(ptr_tmp1++));
+                }
+
+                ptr_tmp1 = &hFrameData->sbrQmfBufferReal[i*SBR_NUM_BANDS];
+                ptr_tmp2 = &Sr[xoverBand];
+
+
+                for (k = xoverBand; k < sbrDec->highSubband; k++)
+                {
+                    *(ptr_tmp2++) = (*(ptr_tmp1++));
+                }
+
+                pv_memset((void *)ptr_tmp2,
+                          0,
+                          (64 - sbrDec->highSubband)*sizeof(*ptr_tmp2));
+
+
+                ptr_tmp1 = (hFrameData->codecQmfBufferImag[m]);
+                ptr_tmp2 = Si;
+
+                for (k = (xoverBand >> 1); k != 0; k--)
+                {
+                    *(ptr_tmp2++) = shft_lft_1(*(ptr_tmp1++));
+                    *(ptr_tmp2++) = shft_lft_1(*(ptr_tmp1++));
+                }
+                if (xoverBand & 1)
+                {
+                    *(ptr_tmp2) = shft_lft_1(*(ptr_tmp1));
+                }
+
+                ptr_tmp1 = &hFrameData->sbrQmfBufferImag[i*SBR_NUM_BANDS];
+                ptr_tmp2 = &Si[xoverBand];
+
+                for (k = xoverBand; k < sbrDec->highSubband; k++)
+                {
+                    *(ptr_tmp2++) = (*(ptr_tmp1++));
+                }
+
+                pv_memset((void *)ptr_tmp2,
+                          0,
+                          (64 - sbrDec->highSubband)*sizeof(*ptr_tmp2));
+
+
+                if (pVars->mc_info.bDownSampledSbr)
+                {
+                    calc_sbr_synfilterbank(Sr,              /* realSamples  */
+                                           Si,             /* imagSamples  */
+                                           ftimeOutPtr + (i << 6),
+                                           &circular_buffer_s[1984 - (i<<6)],
+                                           pVars->mc_info.bDownSampledSbr);
+                }
+                else
+                {
+                    calc_sbr_synfilterbank(Sr,              /* realSamples  */
+                                           Si,             /* imagSamples  */
+                                           ftimeOutPtr + (i << 7),
+                                           &circular_buffer_s[3968 - (i<<7)],
+                                           pVars->mc_info.bDownSampledSbr);
+                }
+            }
+#endif
+
+        }
+
+        if (pVars->mc_info.bDownSampledSbr)
+        {
+            pv_memmove(hFrameData->V, &circular_buffer_s[0], 640*sizeof(*circular_buffer_s));
+        }
+        else
+        {
+            pv_memmove(hFrameData->V, &circular_buffer_s[0], 1152*sizeof(*circular_buffer_s));
+        }
+
+
+
+
+        /*
+         *    Update Buffers
+         */
+        for (i = 0; i < sbrDec->bufWriteOffs; i++)     /* sbrDec->bufWriteOffs set to 8 and unchanged */
+        {
+            j = sbrDec->noCols + i;                    /* sbrDec->noCols set to 32 and unchanged */
+
+            pv_memmove(hFrameData->codecQmfBufferReal[i],         /* to    */
+                       hFrameData->codecQmfBufferReal[j],        /* from  */
+                       sizeof(*hFrameData->codecQmfBufferReal[i]) << 5);
+        }
+
+
+        pv_memmove(&hFrameData->HistsbrQmfBufferReal[0],
+                   &hFrameData->sbrQmfBufferReal[32*SBR_NUM_BANDS],
+                   6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferReal));
+
+#ifdef HQ_SBR
+        if (sbrDec->LC_aacP_DecoderFlag == OFF)
+        {
+            for (i = 0; i < sbrDec->bufWriteOffs; i++)     /* sbrDec->bufWriteOffs set to 6 and unchanged */
+            {
+                j = sbrDec->noCols + i;                    /* sbrDec->noCols set to 32 and unchanged */
+
+
+                pv_memmove(hFrameData->codecQmfBufferImag[i],
+                           hFrameData->codecQmfBufferImag[j],
+                           sizeof(*hFrameData->codecQmfBufferImag[i]) << 5);
+
+            }
+
+            pv_memmove(&hFrameData->HistsbrQmfBufferImag[0],
+                       &hFrameData->sbrQmfBufferImag[32*SBR_NUM_BANDS],
+                       6*SBR_NUM_BANDS*sizeof(*hFrameData->sbrQmfBufferImag));
+        }
+#endif
+
+
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+    }
+#endif
+#endif
+
+
+    hFrameData->reset_flag = 0;
+    if (applyProcessing)
+    {
+        sbrDec->prevLowSubband = sbrDec->lowSubband;
+    }
+
+}
+
+
+#endif      /*  AAC_PLUS */
diff --git a/media/libstagefright/codecs/aacdec/sbr_dec.h b/media/libstagefright/codecs/aacdec/sbr_dec.h
new file mode 100644
index 0000000..ba7c1f3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_dec.h
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_dec.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_DEC_H
+#define SBR_DEC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "s_sbr_frame_data.h"
+#include    "pv_audio_type_defs.h"
+#include    "s_patch.h"
+#include    "e_blockswitching.h"
+#include    "s_sbr_dec.h"
+#include    "s_tdec_int_file.h"
+#ifdef PARAMETRICSTEREO
+#include    "s_ps_dec.h"
+#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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+
+    void sbr_dec(Int16 *inPcmData,
+    Int16 *ftimeOutPtr,
+    SBR_FRAME_DATA * hFrameData,
+    Int32 applyProcessing,
+    SBR_DEC *sbrDec,
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+    Int16 * ftimeOutPtrPS,
+    HANDLE_PS_DEC hParametricStereoDec,
+#endif
+#endif
+    tDec_Int_File  *pVars);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_decode_envelope.cpp b/media/libstagefright/codecs/aacdec/sbr_decode_envelope.cpp
new file mode 100644
index 0000000..771bb32
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_decode_envelope.cpp
@@ -0,0 +1,286 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_decode_envelope.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_decode_envelope.h"
+#include    "sbr_constants.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
+----------------------------------------------------------------------------*/
+void mapLowResEnergyVal(
+    Int32  currVal,
+    Int32 *prevData,
+    Int32 offset,
+    Int32 index,
+    Int32 res);
+
+Int32 indexLow2High(Int32 offset,
+                    Int32 index,
+                    Int32 res);
+
+/*----------------------------------------------------------------------------
+; 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 sbr_decode_envelope(SBR_FRAME_DATA * hFrameData)
+
+{
+    Int32 i;
+    Int32 no_of_bands;
+    Int32 band;
+    Int32 freqRes;
+    Int32 *iEnvelope    = hFrameData->iEnvelope_man;
+    Int32 *sfb_nrg_prev = hFrameData->sfb_nrg_prev_man;
+
+    Int32  offset       = hFrameData->offset;
+    Int32 *nSfb         = hFrameData->nSfb;
+    Int32 *domain_vec   = hFrameData->domain_vec1;
+    Int32 *frameInfo    = hFrameData->frameInfo;
+
+
+
+    for (i = 0; i < frameInfo[0]; i++)
+    {
+        freqRes = frameInfo[frameInfo[0] + i + 2];
+        no_of_bands = nSfb[freqRes];
+
+        if (domain_vec[i] == 0)
+        {
+            mapLowResEnergyVal(*iEnvelope,
+                               sfb_nrg_prev,
+                               offset,
+                               0,
+                               freqRes);
+            iEnvelope++;
+
+            for (band = 1; band < no_of_bands; band++)
+            {
+                *iEnvelope +=  *(iEnvelope - 1);
+
+                mapLowResEnergyVal(*iEnvelope,
+                                   sfb_nrg_prev,
+                                   offset,
+                                   band,
+                                   freqRes);
+                iEnvelope++;
+            }
+        }
+        else
+        {
+            for (band = 0; band < no_of_bands; band++)
+            {
+                *iEnvelope +=  sfb_nrg_prev[ indexLow2High(offset, band, freqRes)];
+
+                mapLowResEnergyVal(*iEnvelope,
+                                   sfb_nrg_prev,
+                                   offset,
+                                   band,
+                                   freqRes);
+                iEnvelope++;
+            }
+        }
+    }
+}
+
+
+
+void mapLowResEnergyVal(
+    Int32  currVal,
+    Int32 *prevData,
+    Int32  offset,
+    Int32  index,
+    Int32  res)
+{
+    Int32 tmp;
+
+    if (res == LO)
+    {
+        if (offset >= 0)
+        {
+            if (index < offset)
+            {
+                prevData[index] = currVal;
+            }
+            else
+            {
+                tmp = (index << 1) - offset;
+                prevData[tmp    ] = currVal;
+                prevData[tmp +1 ] = currVal;
+            }
+        }
+        else
+        {
+            offset = -offset;
+            if (index < offset)
+            {
+                tmp = (index << 1) + index;
+                prevData[tmp    ] = currVal;
+                prevData[tmp + 1] = currVal;
+                prevData[tmp + 2] = currVal;
+            }
+            else
+            {
+                tmp = (index << 1) + offset;
+                prevData[tmp    ] = currVal;
+                prevData[tmp + 1] = currVal;
+            }
+        }
+    }
+    else
+    {
+        prevData[index] = currVal;
+    }
+}
+
+
+Int32 indexLow2High(Int32 offset,
+                    Int32 index,
+                    Int32 res)
+{
+    if (res == LO)
+    {
+        if (offset >= 0)
+        {
+            if (index < offset)
+            {
+                return(index);
+            }
+            else
+            {
+                return((index << 1) - offset);
+            }
+        }
+        else
+        {
+            offset = -offset;
+            if (index < offset)
+            {
+                return((index << 1) + index);
+            }
+            else
+            {
+                return((index << 1) + offset);
+            }
+        }
+    }
+    else
+    {
+        return(index);
+    }
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_decode_envelope.h b/media/libstagefright/codecs/aacdec/sbr_decode_envelope.h
new file mode 100644
index 0000000..19c04a9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_decode_envelope.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_decode_envelope.h
+ Funtions:
+    decodeEnvelope
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_DECODE_ENVELOPE_H
+#define SBR_DECODE_ENVELOPE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void sbr_decode_envelope(SBR_FRAME_DATA * hFrameData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.cpp b/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.cpp
new file mode 100644
index 0000000..290fd18
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.cpp
@@ -0,0 +1,149 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_decode_huff_cw.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+        SbrHuffman          h,     pointer to huffman codebook table
+        BIT_BUFFER    * hBitBuf    pointer  to Bitbuffer
+
+    return    decoded value
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Decodes one huffman code word
+
+  Reads bits from the bitstream until a valid codeword is found.
+  The table entries are interpreted either as index to the next entry
+  or - if negative - as the codeword.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_decode_huff_cw.h"
+#include    "buf_getbits.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
+----------------------------------------------------------------------------*/
+
+Int32 sbr_decode_huff_cw(SbrHuffman h,
+                         BIT_BUFFER * hBitBuf)
+{
+    Int32 bits;
+    Char index = 0;
+
+    while (index >= 0)
+    {
+        bits = buf_get_1bit(hBitBuf);
+        index = h[index][bits];
+    }
+
+    return((Int32)index + 64); /* Add offset */
+}
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.h b/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.h
new file mode 100644
index 0000000..bfbdb67
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_decode_huff_cw.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_decode_huff_cw.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_DECODE_HUFF_CW_H
+#define SBR_DECODE_HUFF_CW_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_huffman.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int32 sbr_decode_huff_cw(SbrHuffman h,
+    BIT_BUFFER * hBitBuf);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.cpp b/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.cpp
new file mode 100644
index 0000000..c2b007a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_downsample_lo_res.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_downsample_lo_res.h"
+#include    "sbr_constants.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  sbr_downsample_lo_res(Int32 v_result[],
+                            Int32 num_result,
+                            Int   freqBandTableRef[],
+                            Int32 num_Ref)
+{
+    Int32 step;
+    Int32 i, j;
+    Int32 org_length;
+    Int32 result_length;
+    Int32 v_index[MAX_FREQ_COEFFS/2];
+
+    /* init */
+    org_length = num_Ref;
+    result_length = num_result;
+
+    v_index[0] = 0; /* Always use left border */
+    i = 0;
+    while (org_length > 0)  /* Create downsample vector */
+    {
+        i++;
+        step = org_length / result_length; /* floor; */
+        org_length = org_length - step;
+        result_length--;
+        v_index[i] = v_index[i-1] + step;
+    }
+
+    for (j = 0; j <= i; j++)   /* Use downsample vector to index LoResolution vector. */
+    {
+        v_result[j] = freqBandTableRef[ v_index[j]];
+    }
+
+}  /* End downSampleLoRes */
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.h b/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.h
new file mode 100644
index 0000000..2f49aea
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_downsample_lo_res.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_downsample_lo_res.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_DOWNSAMPLE_LO_RES_H
+#define SBR_DOWNSAMPLE_LO_RES_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void  sbr_downsample_lo_res(Int32 v_result[],
+    Int32 num_result,
+    Int   freqBandTableRef[],
+    Int32 num_Ref);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.cpp b/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.cpp
new file mode 100644
index 0000000..2ed76dd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.cpp
@@ -0,0 +1,424 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_envelope_calc_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_envelope_calc_tbl.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
+----------------------------------------------------------------------------*/
+#define Q30_fmt(x)   (Int32)(x*((Int32)1<<30) + (x>=0?0.5F:-0.5F))
+#define Qfmt15(x)    (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+
+const Int32 limGains[5] = { Q30_fmt(0.70795f), Q30_fmt(1.0f),
+                            Q30_fmt(1.41254f), Q30_fmt(1.16415321826935f), 33
+                          };
+
+const Int32 smoothLengths[2] = { 4, 0 };
+
+const Int16 rP_LCx[512] =
+{
+    Qfmt15(-0.99948153278296f), Qfmt15(0.97113454393991f), Qfmt15(0.14130051758487f), Qfmt15(-0.47005496701697f),
+    Qfmt15(0.80705063769351f), Qfmt15(-0.38981478896926f), Qfmt15(-0.01053049862020f), Qfmt15(-0.91266367957293f),
+    Qfmt15(0.54840422910309f), Qfmt15(0.40009252867955f), Qfmt15(-0.99867974711855f), Qfmt15(-0.95531076805040f),
+    Qfmt15(-0.45725933317144f), Qfmt15(-0.72929675029275f), Qfmt15(0.75622801399036f), Qfmt15(0.07069442601050f),
+    Qfmt15(0.74496252926055f), Qfmt15(-0.96440182703856f), Qfmt15(0.30424629369539f), Qfmt15(0.66565033746925f),
+    Qfmt15(0.91697008020594f), Qfmt15(-0.70774918760427f), Qfmt15(-0.70051415345560f), Qfmt15(-0.99496513054797f),
+    Qfmt15(0.98164490790123f), Qfmt15(-0.54671580548181f), Qfmt15(-0.01689629065389f), Qfmt15(-0.86110349531986f),
+    Qfmt15(-0.98892980586032f), Qfmt15(0.51756627678691f), Qfmt15(-0.99635026409640f), Qfmt15(-0.99969370862163f),
+    Qfmt15(0.55266258627194f), Qfmt15(0.34581177741673f), Qfmt15(0.62664209577999f), Qfmt15(-0.77149701404973f),
+    Qfmt15(-0.91592244254432f), Qfmt15(-0.76285492357887f), Qfmt15(0.79788337195331f), Qfmt15(0.54473080610200f),
+    Qfmt15(-0.85639281671058f), Qfmt15(-0.92882402971423f), Qfmt15(-0.11708371046774f), Qfmt15(0.21356749817493f),
+    Qfmt15(-0.76191692573909f), Qfmt15(0.98111043100884f), Qfmt15(-0.85913269895572f), Qfmt15(-0.93307242253692f),
+    Qfmt15(0.30485754879632f), Qfmt15(0.85289650925190f), Qfmt15(0.91328082618125f), Qfmt15(-0.05890199924154f),
+    Qfmt15(0.28398686150148f), Qfmt15(0.95258164539612f), Qfmt15(-0.78566324168507f), Qfmt15(-0.95789495447877f),
+    Qfmt15(0.82411158711197f), Qfmt15(-0.65185446735885f), Qfmt15(-0.93643603134666f), Qfmt15(0.91427159529618f),
+    Qfmt15(-0.70395684036886f), Qfmt15(0.00563771969365f), Qfmt15(0.89065051931895f), Qfmt15(-0.68683707712762f),
+    Qfmt15(0.72165342518718f), Qfmt15(-0.62928247730667f), Qfmt15(0.29938434065514f), Qfmt15(-0.91781958879280f),
+    Qfmt15(0.99298717043688f), Qfmt15(0.82368298622748f), Qfmt15(-0.98512833386833f), Qfmt15(-0.95915368242257f),
+    Qfmt15(-0.21411126572790f), Qfmt15(-0.68821476106884f), Qfmt15(0.91851997982317f), Qfmt15(-0.96062769559127f),
+    Qfmt15(0.51646184922287f), Qfmt15(0.61130721139669f), Qfmt15(0.47336129371299f), Qfmt15(0.90998308703519f),
+    Qfmt15(0.44844799194357f), Qfmt15(0.66614891079092f), Qfmt15(0.74922239129237f), Qfmt15(-0.99571588506485f),
+    Qfmt15(0.97401082477563f), Qfmt15(0.72683747733879f), Qfmt15(0.95432193457128f), Qfmt15(-0.72962208425191f),
+    Qfmt15(-0.85359479233537f), Qfmt15(-0.81412430338535f), Qfmt15(-0.87930772356786f), Qfmt15(-0.71573331064977f),
+    Qfmt15(0.83524300028228f), Qfmt15(-0.48086065601423f), Qfmt15(0.97139128574778f), Qfmt15(0.51992825347895f),
+    Qfmt15(-0.00848591195325f), Qfmt15(-0.70294374303036f), Qfmt15(-0.95894428168140f), Qfmt15(0.97079252950321f),
+    Qfmt15(-0.92404293670797f), Qfmt15(-0.69506469500450f), Qfmt15(0.26559203620024f), Qfmt15(0.28038443336943f),
+    Qfmt15(-0.74138124825523f), Qfmt15(-0.01752795995444f), Qfmt15(-0.55126773094930f), Qfmt15(0.97960898850996f),
+    Qfmt15(-0.99196309146936f), Qfmt15(-0.67684928085260f), Qfmt15(0.09140039465500f), Qfmt15(-0.71658965751996f),
+    Qfmt15(0.81014640078925f), Qfmt15(0.40616991671205f), Qfmt15(-0.67680188682972f), Qfmt15(0.86849774348749f),
+    Qfmt15(-0.99500381284851f), Qfmt15(0.84329189340667f), Qfmt15(-0.09215968531446f), Qfmt15(0.99956173327206f),
+    Qfmt15(-0.79732779473535f), Qfmt15(0.96349973642406f), Qfmt15(-0.79942778496547f), Qfmt15(-0.11566039853896f),
+    Qfmt15(-0.39922954514662f), Qfmt15(0.99089197565987f), Qfmt15(0.28631285179909f), Qfmt15(-0.83302725605608f),
+    Qfmt15(0.95404443402072f), Qfmt15(-0.06449863579434f), Qfmt15(-0.99575054486311f), Qfmt15(-0.65501142790847f),
+    Qfmt15(-0.81254441908887f), Qfmt15(-0.99646369485481f), Qfmt15(0.00287840603348f), Qfmt15(0.70176989408455f),
+    Qfmt15(0.96361882270190f), Qfmt15(-0.68883758192426f), Qfmt15(-0.34875585502238f), Qfmt15(0.91980081243087f),
+    Qfmt15(-0.99009048343881f), Qfmt15(0.68865791458395f), Qfmt15(-0.99484402129368f), Qfmt15(0.94214511408023f),
+    Qfmt15(-0.67414626793544f), Qfmt15(-0.47339353684664f), Qfmt15(0.14323651387360f), Qfmt15(-0.29268293575672f),
+    Qfmt15(0.43793861458754f), Qfmt15(-0.36345126374441f), Qfmt15(-0.08750604656825f), Qfmt15(-0.96495267812511f),
+    Qfmt15(0.55526940659947f), Qfmt15(0.73538215752630f), Qfmt15(-0.30889773919437f), Qfmt15(0.03574995626194f),
+    Qfmt15(0.98720684660488f), Qfmt15(-0.81689296271203f), Qfmt15(0.67866860118215f), Qfmt15(-0.15808569732583f),
+    Qfmt15(0.80723395114371f), Qfmt15(0.47788757329038f), Qfmt15(0.96367554763201f), Qfmt15(-0.99143875716818f),
+    Qfmt15(0.83081876925833f), Qfmt15(-0.58753191905341f), Qfmt15(0.95538108220960f), Qfmt15(-0.96490920476211f),
+    Qfmt15(-0.97327101028521f), Qfmt15(0.91400366022124f), Qfmt15(-0.99925837363824f), Qfmt15(-0.86875903507313f),
+    Qfmt15(-0.26240034795124f), Qfmt15(-0.24664412953388f), Qfmt15(0.02416275806869f), Qfmt15(0.82068619590515f),
+    Qfmt15(0.88547373760759f), Qfmt15(-0.18173078152226f), Qfmt15(0.09355476558534f), Qfmt15(-0.54668414224090f),
+    Qfmt15(0.37050990604091f), Qfmt15(-0.70373594262891f), Qfmt15(-0.34600785879594f), Qfmt15(-0.68774481731008f),
+    Qfmt15(-0.26843291251234f), Qfmt15(0.49072334613242f), Qfmt15(0.38975993093975f), Qfmt15(-0.97757125224150f),
+    Qfmt15(-0.17325552859616f), Qfmt15(0.99948035025744f), Qfmt15(-0.64946246527458f), Qfmt15(-0.12016920576437f),
+    Qfmt15(-0.58947456517751f), Qfmt15(-0.41815140454465f), Qfmt15(0.99885650204884f), Qfmt15(-0.56649614128386f),
+    Qfmt15(0.94138021032330f), Qfmt15(-0.75725076534641f), Qfmt15(0.20541973692630f), Qfmt15(0.99980371023351f),
+    Qfmt15(0.29078277605775f), Qfmt15(-0.62858772103030f), Qfmt15(0.43440904467688f), Qfmt15(-0.98298583762390f),
+    Qfmt15(0.19513029146934f), Qfmt15(-0.95476662400101f), Qfmt15(0.93379635304810f), Qfmt15(-0.85235410573336f),
+    Qfmt15(-0.86425093011245f), Qfmt15(0.38879779059045f), Qfmt15(0.92045124735495f), Qfmt15(0.89162532251878f),
+    Qfmt15(-0.36834336949252f), Qfmt15(0.93891760988045f), Qfmt15(0.99267657565094f), Qfmt15(-0.94063471614176f),
+    Qfmt15(0.99740224117019f), Qfmt15(-0.35899413170555f), Qfmt15(0.05237237274947f), Qfmt15(0.36703583957424f),
+    Qfmt15(0.91653180367913f), Qfmt15(0.69000803499316f), Qfmt15(-0.38658751133527f), Qfmt15(-0.29250814029851f),
+    Qfmt15(-0.60182204677608f), Qfmt15(-0.97418588163217f), Qfmt15(0.88461574003963f), Qfmt15(0.05198933055162f),
+    Qfmt15(-0.53499621979720f), Qfmt15(-0.49429560226497f), Qfmt15(-0.98935142339139f), Qfmt15(-0.98081380091130f),
+    Qfmt15(-0.27338148835532f), Qfmt15(0.06310802338302f), Qfmt15(-0.20461677199539f), Qfmt15(0.66223843141647f),
+    Qfmt15(-0.84764345483665f), Qfmt15(-0.89039863483811f), Qfmt15(0.95903308477986f), Qfmt15(0.73504123909879f),
+    Qfmt15(-0.31744434966056f), Qfmt15(-0.34110827591623f), Qfmt15(0.47803883714199f), Qfmt15(0.98299195879514f),
+    Qfmt15(-0.30963073129751f), Qfmt15(0.99992588229018f), Qfmt15(-0.93149731080767f), Qfmt15(0.99923472302773f),
+    Qfmt15(-0.26024169633417f), Qfmt15(-0.35712514743563f), Qfmt15(-0.99899084509530f), Qfmt15(0.86557171579452f),
+    Qfmt15(0.33408042438752f), Qfmt15(0.99010736374716f), Qfmt15(-0.66694269691195f), Qfmt15(0.64016792079480f),
+    Qfmt15(0.99570534804836f), Qfmt15(-0.63431466947340f), Qfmt15(-0.07706847005931f), Qfmt15(0.98590090577724f),
+    Qfmt15(0.80099335254678f), Qfmt15(0.78368131392666f), Qfmt15(0.08707806671691f), Qfmt15(-0.86811883080712f),
+    Qfmt15(-0.39466529740375f), Qfmt15(0.97875325649683f), Qfmt15(-0.95038560288864f), Qfmt15(0.17005239424212f),
+    Qfmt15(-0.76910792026848f), Qfmt15(0.99743281016846f), Qfmt15(0.95437383549973f), Qfmt15(0.99578905365569f),
+    Qfmt15(0.28058259829990f), Qfmt15(0.85256524470573f), Qfmt15(-0.50608540105128f), Qfmt15(-0.97210735183243f),
+    Qfmt15(0.95424048234441f), Qfmt15(-0.96926570524023f), Qfmt15(0.30872163214726f), Qfmt15(-0.24523839572639f),
+    Qfmt15(-0.33813265086024f), Qfmt15(-0.05826828420146f), Qfmt15(-0.22898461455054f), Qfmt15(-0.18509915019881f),
+    Qfmt15(-0.10488238045009f), Qfmt15(-0.71886586182037f), Qfmt15(0.99793873738654f), Qfmt15(0.57563307626120f),
+    Qfmt15(0.28909646383717f), Qfmt15(0.42188998312520f), Qfmt15(0.93335049681047f), Qfmt15(-0.97087374418267f),
+    Qfmt15(0.36722871286923f), Qfmt15(-0.81093025665696f), Qfmt15(-0.26240603062237f), Qfmt15(0.83996497984604f),
+    Qfmt15(-0.99909615720225f), Qfmt15(0.74649464155061f), Qfmt15(-0.74774595569805f), Qfmt15(0.95781667469567f),
+    Qfmt15(0.95472308713099f), Qfmt15(0.48708332746299f), Qfmt15(0.46332038247497f), Qfmt15(-0.76497004940162f),
+    Qfmt15(0.57397389364339f), Qfmt15(0.75374316974495f), Qfmt15(-0.59174397685714f), Qfmt15(0.75087906691890f),
+    Qfmt15(-0.98607857336230f), Qfmt15(-0.40761056640505f), Qfmt15(0.66929266740477f), Qfmt15(-0.97463695257310f),
+    Qfmt15(0.90145509409859f), Qfmt15(-0.87259289048043f), Qfmt15(-0.91529461447692f), Qfmt15(-0.03305738840705f),
+    Qfmt15(0.07223051368337f), Qfmt15(0.99498012188353f), Qfmt15(-0.74904939500519f), Qfmt15(0.04585228574211f),
+    Qfmt15(-0.89054954257993f), Qfmt15(-0.83782144651251f), Qfmt15(0.33454804933804f), Qfmt15(-0.99707579362824f),
+    Qfmt15(-0.22827527843994f), Qfmt15(0.67248046289143f), Qfmt15(-0.05146538187944f), Qfmt15(0.99947295749905f),
+    Qfmt15(0.66951124390363f), Qfmt15(-0.99602956559179f), Qfmt15(0.82104905483590f), Qfmt15(0.99186510988782f),
+    Qfmt15(-0.65284592392918f), Qfmt15(0.93885443798188f), Qfmt15(0.96735248738388f), Qfmt15(-0.22225968841114f),
+    Qfmt15(-0.44132783753414f), Qfmt15(-0.85694974219574f), Qfmt15(0.91783042091762f), Qfmt15(0.72556974415690f),
+    Qfmt15(-0.99711581834508f), Qfmt15(0.77638976371966f), Qfmt15(0.07717324253925f), Qfmt15(-0.56049829194163f),
+    Qfmt15(0.98398893639988f), Qfmt15(0.47546946844938f), Qfmt15(0.65675089314631f), Qfmt15(0.03273375457980f),
+    Qfmt15(-0.38684144784738f), Qfmt15(-0.97346267944545f), Qfmt15(-0.53282156061942f), Qfmt15(0.99817310731176f),
+    Qfmt15(-0.50254500772635f), Qfmt15(0.01995873238855f), Qfmt15(0.99930381973804f), Qfmt15(0.82907767600783f),
+    Qfmt15(-0.58660709669728f), Qfmt15(-0.17573736667267f), Qfmt15(0.83434292401346f), Qfmt15(0.05946491307025f),
+    Qfmt15(0.81505484574602f), Qfmt15(-0.44976380954860f), Qfmt15(-0.89746474625671f), Qfmt15(0.39677256130792f),
+    Qfmt15(-0.07588948563079f), Qfmt15(0.76343198951445f), Qfmt15(-0.74490104699626f), Qfmt15(0.64880119792759f),
+    Qfmt15(0.62319537462542f), Qfmt15(0.42215817594807f), Qfmt15(0.02704554141885f), Qfmt15(0.80001773566818f),
+    Qfmt15(-0.79351832348816f), Qfmt15(0.63872359151636f), Qfmt15(0.52890520960295f), Qfmt15(0.74238552914587f),
+    Qfmt15(0.99096131449250f), Qfmt15(-0.80412329643109f), Qfmt15(-0.64612616129736f), Qfmt15(0.11657770663191f),
+    Qfmt15(-0.95053182488101f), Qfmt15(-0.62228872928622f), Qfmt15(0.03004475787316f), Qfmt15(-0.97987214341034f),
+    Qfmt15(-0.99986980746200f), Qfmt15(0.89110648599879f), Qfmt15(0.10407960510582f), Qfmt15(0.95964737821728f),
+    Qfmt15(0.50843233159162f), Qfmt15(0.17006334670615f), Qfmt15(0.25872675063360f), Qfmt15(-0.01115998681937f),
+    Qfmt15(-0.79598702973261f), Qfmt15(-0.99264708948101f), Qfmt15(-0.99829663752818f), Qfmt15(-0.70801016548184f),
+    Qfmt15(-0.70467057786826f), Qfmt15(0.99846021905254f), Qfmt15(-0.63364968534650f), Qfmt15(-0.16258217500792f),
+    Qfmt15(-0.43645594360633f), Qfmt15(-0.99848471702976f), Qfmt15(-0.16796458968998f), Qfmt15(-0.87979225745213f),
+    Qfmt15(0.44183099021786f), Qfmt15(0.93310180125532f), Qfmt15(-0.93941931782002f), Qfmt15(-0.88590003188677f),
+    Qfmt15(0.99971463703691f), Qfmt15(-0.75376385639978f), Qfmt15(0.93887685615875f), Qfmt15(0.85126435782309f),
+    Qfmt15(0.39701421446381f), Qfmt15(-0.37024464187437f), Qfmt15(-0.36024828242896f), Qfmt15(-0.93388812549209f),
+    Qfmt15(-0.65298804552119f), Qfmt15(0.11960319006843f), Qfmt15(0.94292565553160f), Qfmt15(0.75081145286948f),
+    Qfmt15(0.56721979748394f), Qfmt15(0.46857766746029f), Qfmt15(0.97312313923635f), Qfmt15(-0.38299976567017f),
+    Qfmt15(0.41025800019463f), Qfmt15(0.09638062008048f), Qfmt15(-0.85283249275397f), Qfmt15(0.88866808958124f),
+    Qfmt15(-0.48202429536989f), Qfmt15(0.27572582416567f), Qfmt15(-0.65889129659168f), Qfmt15(0.98838086953732f),
+    Qfmt15(-0.20651349620689f), Qfmt15(-0.62126416356920f), Qfmt15(0.20320105410437f), Qfmt15(-0.97790548600584f),
+    Qfmt15(0.11112534735126f), Qfmt15(-0.41368337314182f), Qfmt15(0.24133038992960f), Qfmt15(-0.66393410674885f),
+    Qfmt15(-0.53697829178752f), Qfmt15(-0.97224737889348f), Qfmt15(0.87392477144549f), Qfmt15(0.19050361015753f),
+    Qfmt15(-0.46353441212724f), Qfmt15(-0.07064096339021f), Qfmt15(-0.92444085484466f), Qfmt15(-0.83822593578728f),
+    Qfmt15(0.75214681811150f), Qfmt15(-0.42102998829339f), Qfmt15(-0.72094786237696f), Qfmt15(0.78843311019251f),
+    Qfmt15(0.97394027897442f), Qfmt15(0.99206463477946f), Qfmt15(0.76789609461795f), Qfmt15(-0.82002421836409f),
+    Qfmt15(0.81924990025724f), Qfmt15(-0.26719850873357f), Qfmt15(-0.43311260380975f), Qfmt15(0.99194979673836f),
+    Qfmt15(-0.80692001248487f), Qfmt15(0.43080003649976f), Qfmt15(0.67709491937357f), Qfmt15(0.56151770568316f),
+    Qfmt15(0.10831862810749f), Qfmt15(0.91229417540436f), Qfmt15(-0.48972893932274f), Qfmt15(-0.89033658689697f),
+    Qfmt15(0.65269447475094f), Qfmt15(0.67439478141121f), Qfmt15(-0.47770832416973f), Qfmt15(-0.99715979260878f),
+    Qfmt15(-0.90889593602546f), Qfmt15(-0.06618622548177f), Qfmt15(0.99430266919728f), Qfmt15(0.97686402381843f),
+    Qfmt15(0.94813650221268f), Qfmt15(-0.95434497492853f), Qfmt15(-0.49104783137150f), Qfmt15(0.99881175120751f),
+    Qfmt15(0.50449166760303f), Qfmt15(0.47162891065108f), Qfmt15(-0.62081581361840f), Qfmt15(-0.43867015250812f),
+    Qfmt15(0.98630563232075f), Qfmt15(-0.61510362277374f), Qfmt15(-0.03841517601843f), Qfmt15(-0.30102157304644f),
+    Qfmt15(0.41881284182683f), Qfmt15(-0.86135454941237f), Qfmt15(0.67226861393788f), Qfmt15(-0.70737398842068f),
+    Qfmt15(0.94044946687963f), Qfmt15(-0.82386352534327f), Qfmt15(-0.32070666698656f), Qfmt15(0.57593163224487f),
+    Qfmt15(-0.36326018419965f), Qfmt15(0.99979044674350f), Qfmt15(-0.92366023326932f), Qfmt15(-0.44607178518598f),
+    Qfmt15(0.44226800932956f), Qfmt15(0.03671907158312f), Qfmt15(0.52175424682195f), Qfmt15(-0.94701139690956f),
+    Qfmt15(-0.98759606946049f), Qfmt15(0.87434794743625f), Qfmt15(-0.93412041758744f), Qfmt15(0.96063943315511f),
+    Qfmt15(0.97534253457837f), Qfmt15(0.99642466504163f), Qfmt15(-0.94705089665984f), Qfmt15(0.91599807087376f)
+};
+
+
+#ifdef HQ_SBR
+
+
+const Int32 fir_table[5][5] =
+{
+    { Q30_fmt(1.0f)},
+    { Q30_fmt(0.33333333333333f), Q30_fmt(0.66666666666666f)},
+    { Q30_fmt(0.12500000000000f), Q30_fmt(0.37500000000000f),
+      Q30_fmt(0.50000000000000f)},
+    { Q30_fmt(0.05857864376269f), Q30_fmt(0.20000000000000f),
+      Q30_fmt(0.34142135623731f), Q30_fmt(0.40000000000000f)},
+    { Q30_fmt(0.03183050093751f), Q30_fmt(0.11516383427084f),
+      Q30_fmt(0.21816949906249f), Q30_fmt(0.30150283239582f),
+      Q30_fmt(0.33333333333333f)}
+};
+
+
+
+const Int32 rPxx[512] =
+{
+
+    0x8010B3DB,  0x7C4DA98F, 0x12168648, 0xC3D4D033,
+    0x674D25F5,  0xCE1972A6, 0xFEA5AA4A, 0x8B2DF13E,
+    0x46326048,  0x3336815E, 0x802A8F2B, 0x85B7745C,
+    0xC577B766,  0xA2A5828C, 0x60CB1AD1, 0x090C9BD7,
+    0x5F5A8B4D,  0x848D86BB, 0x26F1C0B7, 0x553352C1,
+    0x755E166B,  0xA5674343, 0xA654C5F5, 0x80A48CB4,
+    0x7DA69CD8,  0xBA04FCB4, 0xFDD4005E, 0x91C63676,
+    0x816A8F82,  0x423F55AA, 0x8077B59E, 0x80097DE9,
+    0x46BD4C18,  0x2C437971, 0x5035A0C2, 0x9D3ED49F,
+    0x8AC204B8,  0x9E5A8B0A, 0x662088B9, 0x45B9F0BC,
+    0x9261364F,  0x891B23AD, 0xF1028040, 0x1B568BE1,
+    0x9E787FB3,  0x7D94854D, 0x92077A94, 0x88903F45,
+    0x2705A5B4,  0x6D2B3BDC, 0x74E58034, 0xF8745A8C,
+    0x24592C54,  0x79EDB9BB, 0x9B6E9F44, 0x8563E5DA,
+    0x697C7BB7,  0xAC8F8E6A, 0x88227FD5, 0x7506822F,
+    0xA5E34B42,  0x00B94F10, 0x72004390, 0xA814676E,
+    0x5C5EA758,  0xAF721171, 0x2652C50C, 0x8A84A142,
+    0x7F19343E,  0x696EA13B, 0x81E68008, 0x853980F9,
+    0xE4968869,  0xA7E7DD92, 0x75910BFA, 0x85092E35,
+    0x421BA4A3,  0x4E3F3C18, 0x3C97DD02, 0x74797BCB,
+    0x39667EFD,  0x55447BA2, 0x5FE68CF3, 0x808B4390,
+    0x7CABEA6B,  0x5D08C27A, 0x7A265820, 0xA29A9DF0,
+    0x92BC7195,  0x97CA8338, 0x8F725FAD, 0xA46281D3,
+    0x6AE86B23,  0xC2728178, 0x7C566684, 0x428C66B7,
+    0xFEE89DDB,  0xA60546DC, 0x8540C89D, 0x7C420BF0,
+    0x89B86D72,  0xA7077E3F, 0x21FF5DD7, 0x23E3129C,
+    0xA1197F1D,  0xFDC0963F, 0xB96F8168, 0x7D6387A6,
+    0x810655C8,  0xA95C102B, 0x0BB3E5B4, 0xA44682D4,
+    0x67B244C3,  0x33FDDE1D, 0xA95D78F5, 0x6F2AE887,
+    0x80A3FC9F,  0x6BF00D52, 0xF4325902, 0x7FF1F02C,
+    0x99F08AC5,  0x7B537BB2, 0x99AB5255, 0xF1302497,
+    0xCCE4787B,  0x7ED58A28, 0x24A68B79, 0x955EA9D0,
+    0x7A1D3EED,  0xF7BD0429, 0x808A3642, 0xAC2769A8,
+    0x97FDBDE9,  0x80736C25, 0x005E52E7, 0x59D3E5D0,
+    0x7B57341A,  0xA7D374E9, 0xD35A5B7B, 0x75BB5520,
+    0x81446DE8,  0x5825473E, 0x80A8E653, 0x78978062,
+    0xA9B43F6B,  0xC366920A, 0x1255877D, 0xDA88075F,
+    0x380E9AFF,  0xD1795309, 0xF4CB7D09, 0x847BBAED,
+    0x471364FA,  0x5E207B74, 0xD87498BF, 0x0493836B,
+    0x7E5C3DF6,  0x976F8BBC, 0x56DE680A, 0xEBC26D28,
+    0x6753E05B,  0x3D2BC4B0, 0x7B593143, 0x8118E010,
+    0x6A5786AD,  0xB4CA01A7, 0x7A49927C, 0x847DAE0C,
+    0x836B0FD8,  0x74FD4A34, 0x80175AFC, 0x90CBE605,
+    0xDE68A89E,  0xE06C8FD0, 0x031822CE, 0x690B9315,
+    0x71568D43,  0xE8BBDE85, 0x0BFA4633, 0xBA057ADA,
+    0x2F6CB34F,  0xA5EB74C5, 0xD3B480B6, 0xA7F7D94A,
+    0xDDA26A63,  0x3ED0C5EF, 0x31E37A42, 0x82DE06CB,
+    0xE9D18940,  0x7FEE4A9A, 0xACDD57DD, 0xF09CB6D9,
+    0xB48BD364,  0xCA7814D5, 0x7FDA0E41, 0xB77C8C2A,
+    0x787E2D29,  0x9F1144AC, 0x1A4B871E, 0x7FF96630,
+    0x25382D4D,  0xAF89319E, 0x379A81DB, 0x822D1AE8,
+    0x18FA875E,  0x85C97DE7, 0x7786A544, 0x92E5F550,
+    0x915FC560,  0x31C47C82, 0x75D0B014, 0x72204656,
+    0xD0D87B76,  0x782E8CD6, 0x7F0FFB2F, 0x879834E7,
+    0x7FAAEA73,  0xD20BC44E, 0x06B4DF2C, 0x2EFBCE84,
+    0x7550D8D7,  0x5851746A, 0xCE837F5C, 0xDA8D2FEE,
+    0xB2F66F13,  0x834D7B7A, 0x713A499C, 0x06A81B39,
+    0xBB847C77,  0xC0B97DAC, 0x815CCC7A, 0x8274A2BD,
+    0xDD007FEF,  0x0814BA2F, 0xE5CDEDCE, 0x54C45CD5,
+    0x937F0309,  0x8E0671BF, 0x7AC1623B, 0x5E15FB32,
+    0xD75CD0D9,  0xD4553378, 0x3D30CD88, 0x7DD2028C,
+    0xD85CE8DB,  0x7FFDDE5A, 0x88C48228, 0x7FE6996A,
+    0xDEAF9EB7,  0xD24818B4, 0x80205F8B, 0x6ECA4728,
+    0x2AC36E51,  0x7EBB05E4, 0xAAA08AB1, 0x51F01408,
+    0x7F723AAE,  0xAECD1AFB, 0xF6218D55, 0x7E3170F2,
+    0x6686D0D3,  0x644F3A3F, 0x0B256799, 0x90E0325D,
+    0xCD7AAA7B,  0x7D47A33C, 0x865972A3, 0x15C445FE,
+    0x9D8D84D3,  0x7FAB36A7, 0x7A287C29, 0x7F75BABD,
+    0x23EA92BC,  0x6D20AD59, 0xBF37ABB6, 0x8391E26E,
+    0x7A2480F8,  0x83EE5E6E, 0x27843523, 0xE09A50E7,
+    0xD4B6CE82,  0xF889F71C, 0xE2AF7C3A, 0xE84D3CE2,
+    0xF2918FA6,  0xA3FB63E0, 0x7FBB7340, 0x49AE8B79,
+    0x25017B45,  0x36003DA1, 0x7777C844, 0x83B96EE4,
+    0x2F015392,  0x98320B3C, 0xDE68893F, 0x6B834779,
+    0x801D8516,  0x5F8C0F8C, 0xA049DD90, 0x7A999AD0,
+    0x7A33F500,  0x3E587FFF, 0x3B4E0E09, 0x9E147230,
+    0x49772D2B,  0x607A7BC7, 0xB4408D8F, 0x601CDA17,
+    0x81C7200B,  0xCBD28CBD, 0x55AB7E3E, 0x833EFFC0,
+    0x73627FB7,  0x904E7F04, 0x8AD7EBE6, 0xFBC3D05F,
+    0x093F8E53,  0x7F5B7C47, 0xA01E7FFA, 0x05DE7FC2,
+    0x8E01D74D,  0x94C17CF9, 0x2AD2919F, 0x805F7757,
+    0xE2C61829,  0x5613FB53, 0xF9688978, 0x7FEE77D6,
+    0x55B27E98,  0x8081C6D6, 0x69177F69, 0x7EF45C30,
+    0xAC6E42CC,  0x782BA021, 0x7BD17457, 0xE38B491E,
+    0xC781895B,  0x924E71B8, 0x757BC4A8, 0x5CDF8020,
+    0x805E4A82,  0x636078BA, 0x09E14B0E, 0xB84069A0,
+    0x7DF23284,  0x3CDC57D2, 0x54101777, 0x0431A015,
+    0xCE7A41B6,  0x8365846A, 0xBBCB8AF9, 0x7FC34E40,
+    0xBFAB8E4B,  0x028E6D15, 0x7FE8790F, 0x6A1EF7E6,
+    0xB4E97BF4,  0xE980C257, 0x6ACBEF53, 0x079C1A41,
+    0x685386CC,  0xC66D3458, 0x8D1F7FCD, 0x32C9A02E,
+    0xF6475ED7,  0x61B7356F, 0xA0A6793F, 0x530B34E9,
+    0x4FC488D4,  0x3609F61F, 0x0376F90F, 0x6666752C,
+    0x9A6DD1A5,  0x51C10A67, 0x43B34CDC, 0x5F0605C0,
+    0x7ED7E718,  0x99118EB3, 0xAD4A5C69, 0x0EEC94E8,
+    0x865483EA,  0xB05769F0, 0x03D88055, 0x82932EC1,
+    0x8003D1E3,  0x720F82B1, 0x0D526304, 0x7AD5D2A3,
+    0x41147B04,  0x15C49D9F, 0x211E7FDC, 0xFE907E12,
+    0x9A1C7C55,  0x80F08095, 0x80370267, 0xA55F2B1C,
+    0xA5CC7763,  0x7FCD81A1, 0xAEE3EAE8, 0xEB2F8532,
+    0xC82186A5,  0x80317B31, 0xEA7E814B, 0x8F62A430,
+    0x388D883A,  0x776F801B, 0x87C0B7CA, 0x8E9A3CF5,
+    0x7FF6949E,  0x9F83010B, 0x782CF18C, 0x6CF54301,
+    0x32D168AD,  0xD09A908B, 0xD1E22C5C, 0x887593DE,
+    0xAC6AE864,  0x0F4F7FDE, 0x78B16A72, 0x601AD283,
+    0x489AE12D,  0x3BFAD96A, 0x7C8E8093, 0xCEF87E19,
+    0x348302B6,  0x0C5605A6, 0x92D57516, 0x71BF8056,
+    0xC24C8416,  0x234B4B0D, 0xABA84B4F, 0x7E827FFD,
+    0xE58F45E1,  0xB079B355, 0x1A0290CA, 0x82D37B40,
+    0x0E391B80,  0xCB0B241E, 0x1EE441A8, 0xAB03F56F,
+    0xBB438301,  0x838C1C43, 0x6FDCEF9D, 0x1862020D,
+    0xC4A98614,  0xF6F38710, 0x89ABF29B, 0x94B4FDD3,
+    0x6046800E,  0xCA1A7FA4, 0xA3B7D32F, 0x64EB43A6,
+    0x7CA9DDD3,  0x7EFBB705, 0x624A9E0D, 0x9708A1E0,
+    0x68DC7F9C,  0xDDCB5832, 0xC88E6D35, 0x7EF77599,
+    0x98B6D63B,  0x3724E3F0, 0x56AA85C9, 0x47DFA582,
+    0x0DDDF4F3,  0x74C5AB88, 0xC14F480C, 0x8E08A446,
+    0x538B545F,  0x56529770, 0xC2D9EA81, 0x805C883B,
+    0x8BA84F67,  0xF785E183, 0x7F441814, 0x7D09DB4D,
+    0x795C8330,  0x85D79A19, 0xC1242A1B, 0x7FD871E9,
+    0x409391EC,  0x3C5EE815, 0xB0885FFF, 0xC7D87FFE,
+    0x7E3EBB6A,  0xB1438D6B, 0xFB13A68A, 0xD976F62D,
+    0x359B02CD,  0x91BE7EA6, 0x560CEEB8, 0xA5739E04,
+    0x78600B8E,  0x968A0B6C, 0xD6F1402E, 0x49B88152,
+    0xD17F0986,  0x7FF8EDE8, 0x89C48295, 0xC6E6BA93,
+    0x389C5B4C,  0x04B3516A, 0x42C892B0, 0x86C7FDA8,
+    0x81956954,  0x6FEA726E, 0x886E34F5, 0x7AF57730,
+    0x7CD76E45,  0x7F8A59D7, 0x86C6DA22, 0x753F825E
+};
+
+
+#endif
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.h b/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.h
new file mode 100644
index 0000000..60e806d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_envelope_calc_tbl.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_envelope_calc_tbl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_ENVELOPE_CALC_TBL_H
+#define SBR_ENVELOPE_CALC_TBL_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 Int32 limGains[5];
+
+extern const Int32 smoothLengths[2];
+
+extern const Int16 rP_LCx[512];
+
+#ifdef HQ_SBR
+
+
+extern const Int32 fir_table[5][5];
+
+extern const Int32 rPxx[512];
+
+#endif
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.cpp b/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.cpp
new file mode 100644
index 0000000..7fce46b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.cpp
@@ -0,0 +1,427 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_envelope_unmapping.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_envelope_unmapping.h"
+#include    "sbr_constants.h"
+
+#include "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+#define R_SHIFT     30
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+/*
+ *  1./(1+2.^-[0:10])
+ */
+const Int32 one_over_one_plus_two_to_n[11] =
+{
+    Qfmt(0.50000000000000F), Qfmt(0.66666666666667F), Qfmt(0.80000000000000F),
+    Qfmt(0.88888888888889F), Qfmt(0.94117647058824F), Qfmt(0.96969696969697F),
+    Qfmt(0.98461538461538F), Qfmt(0.99224806201550F), Qfmt(0.99610894941634F),
+    Qfmt(0.99805068226121F), Qfmt(0.99902439024390F)
+};
+
+/*
+ *  1./(1+2.^[0.5:-1:-10.5])
+ */
+const Int32 one_over_one_plus_sq_2_by_two_to_n[12] =
+{
+    Qfmt(0.41421356237310F), Qfmt(0.58578643762690F), Qfmt(0.73879612503626F),
+    Qfmt(0.84977889517767F), Qfmt(0.91878969685839F), Qfmt(0.95767628767521F),
+    Qfmt(0.97838063800882F), Qfmt(0.98907219289563F), Qfmt(0.99450607818892F),
+    Qfmt(0.99724547251514F), Qfmt(0.99862083678608F), Qfmt(0.99930994254211F)
+};
+
+/*----------------------------------------------------------------------------
+; 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 sbr_envelope_unmapping(SBR_FRAME_DATA * hFrameData1,
+                            SBR_FRAME_DATA * hFrameData2)
+
+{
+    Int32 i;
+    Int32 tempLeft;
+    Int32 tempRight;
+
+    Int32 tmp;
+    Int32 *iEnvelopeLeft_man    = hFrameData1->iEnvelope_man;
+    Int32 *iEnvelopeLeft_exp    = hFrameData1->iEnvelope_exp;
+    Int32 *noiseFloorLeft_man   = hFrameData1->sbrNoiseFloorLevel_man;
+    Int32 *noiseFloorLeft_exp   = hFrameData1->sbrNoiseFloorLevel_exp;
+
+    Int32 *iEnvelopeRight_man   = hFrameData2->iEnvelope_man;
+    Int32 *iEnvelopeRight_exp   = hFrameData2->iEnvelope_exp;
+    Int32 *noiseFloorRight_man  = hFrameData2->sbrNoiseFloorLevel_man;
+    Int32 *noiseFloorRight_exp  = hFrameData2->sbrNoiseFloorLevel_exp;
+
+
+    if (hFrameData2->ampRes)
+    {
+        for (i = 0; i < hFrameData1->nScaleFactors; i++)
+        {
+            tempRight = iEnvelopeRight_man[i];
+            tempLeft  = iEnvelopeLeft_man[i];
+            /*  iEnvelope[i] always positive  6 bits max */
+
+            iEnvelopeLeft_exp[i] = tempLeft + 7;
+
+            iEnvelopeRight_exp[i] = tempRight - 12;
+            iEnvelopeRight_man[i] = Qfmt(1.000F);
+
+            /*
+             *  iEnvelopeRight[i] = tempLeft / (1 + tempRight);
+             *  iEnvelopeLeft[i]  = tempRight * iEnvelopeRight[i];
+             *
+             *
+             *   iEnvelopeRight[i] = k*2^n/(1+2^m) =  k*2^(n-m)/(1 + 2^-m);
+             *   where k = 1 or sqrt(2)
+             */
+            if (iEnvelopeRight_exp[i] >= 0)
+            {
+                if (iEnvelopeRight_exp[i] < 11)
+                {
+                    iEnvelopeRight_man[i] = one_over_one_plus_two_to_n[ iEnvelopeRight_exp[i]];
+                }
+                else        /*  1/(1+2^-m) == 1 - 2^-m ;  for m >= 10  */
+                {
+                    iEnvelopeRight_man[i] -= (Qfmt(1.000F) >> iEnvelopeRight_exp[i]);
+                }
+                iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i] - iEnvelopeRight_exp[i];
+            }
+            else
+            {
+                if (iEnvelopeRight_exp[i] > -11)
+                {
+                    iEnvelopeRight_man[i] -= one_over_one_plus_two_to_n[ -iEnvelopeRight_exp[i]];
+                    iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i] - iEnvelopeRight_exp[i];
+
+                }
+                else        /*  1/(1+2^m) == 2^-m ;  for m >= 10  */
+                {
+                    iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i];
+                    iEnvelopeLeft_exp[i] = 0;
+                }
+            }
+
+            iEnvelopeLeft_man[i]  = iEnvelopeRight_man[i];
+        }
+    }
+    else
+    {
+        for (i = 0; i < hFrameData1->nScaleFactors; i++)
+        {
+            /*  iEnvelope[i] always positive  7 bits max */
+            tempRight = iEnvelopeRight_man[i];
+            tempLeft  = iEnvelopeLeft_man[i];
+
+            iEnvelopeLeft_exp[i] = (tempLeft >> 1) + 7;
+            if (tempLeft & 0x1)   /*  odd */
+            {
+                iEnvelopeLeft_man[i] = Qfmt(1.41421356237310F);
+            }
+            else
+            {
+                iEnvelopeLeft_man[i] = Qfmt(1.000F);
+            }
+
+            iEnvelopeRight_exp[i] = (tempRight >> 1) - 12;
+            if (tempRight & 0x1)   /*  odd */
+            {
+                if (iEnvelopeRight_exp[i] > 0)
+                {
+                    iEnvelopeRight_man[i] = Qfmt(1.41421356237310F);
+                }
+                else
+                {
+                    iEnvelopeRight_man[i] = Qfmt(0.7071067811865F);
+                }
+            }
+            else
+            {
+                iEnvelopeRight_man[i] = Qfmt(1.000F);
+            }
+
+            if (iEnvelopeRight_man[i] == Qfmt(1.000F))
+            {
+
+                /*
+                 *  iEnvelopeRight[i] = tempLeft / (1 + tempRight);
+                 *  iEnvelopeLeft[i]  = tempRight * iEnvelopeRight[i];
+                 *
+                 *
+                 *   iEnvelopeRight[i] = k*2^n/(1+2^m) =  k*2^(n-m)/(1 + 2^-m);
+                 *   where k = 1 or sqrt(2)
+                 */
+                if (iEnvelopeRight_exp[i] >= 0)
+                {
+                    if (iEnvelopeRight_exp[i] < 11)
+                    {
+                        iEnvelopeRight_man[i] = one_over_one_plus_two_to_n[ iEnvelopeRight_exp[i]];
+                    }
+                    else        /*  1/(1+2^-m) == 1 - 2^-m ;  for m >= 10  */
+                    {
+                        iEnvelopeRight_man[i] -= (Qfmt(1.000F) >> iEnvelopeRight_exp[i]);
+                    }
+                    iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i] - iEnvelopeRight_exp[i];
+
+                }
+                else
+                {
+                    if (iEnvelopeRight_exp[i] > -11)
+                    {
+                        iEnvelopeRight_man[i] -= one_over_one_plus_two_to_n[ -iEnvelopeRight_exp[i]];
+                        iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i] - iEnvelopeRight_exp[i];
+                    }
+                    else        /*  1/(1+2^m) == 2^-m ;  for m >= 10  */
+                    {
+                        iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i];
+                        iEnvelopeLeft_exp[i]  = 0;
+                    }
+                }
+
+                /*
+                 *  apply "k" factor 1 or sqrt(2)
+                 *
+                 *   (2^m)*2*k*2^n/(1+2^m) =  k*2^(n+1)/(1 + 2^-m);
+                 *
+                 */
+                if (iEnvelopeLeft_man[i] != Qfmt(1.000F))
+                {
+                    iEnvelopeRight_man[i] = fxp_mul32_Q30(iEnvelopeLeft_man[i], iEnvelopeRight_man[i]);
+                }
+
+                iEnvelopeLeft_man[i]  = iEnvelopeRight_man[i];
+
+            }
+            else
+            {
+
+                /*
+                *  iEnvelopeRight[i] = tempLeft / (1 + tempRight);
+                *  iEnvelopeLeft[i]  = tempRight * iEnvelopeRight[i];
+                *
+                *
+                *   iEnvelopeRight[i] = k*2^n/(1+q2^m) =  k*2^(n-m)/(1 + q2^-m);
+                *   where k = 1 or sqrt(2)
+                *   and q = sqrt(2)
+                    */
+                if (iEnvelopeRight_exp[i] >= 0)
+                {
+                    if (iEnvelopeRight_exp[i] < 12)
+                    {
+                        iEnvelopeRight_man[i] = one_over_one_plus_sq_2_by_two_to_n[ iEnvelopeRight_exp[i]];
+                    }
+                    else        /*  1/(1+2^-m) == 1 - 2^-m ;  for m >= 11  */
+                    {
+                        iEnvelopeRight_man[i] = Qfmt(1.000F) - (Qfmt(1.000F) >> iEnvelopeRight_exp[i]);
+                    }
+                }
+                else
+                {
+                    if (iEnvelopeRight_exp[i] > -12)
+                    {
+                        iEnvelopeRight_man[i] = Qfmt(1.000F) - one_over_one_plus_sq_2_by_two_to_n[ -iEnvelopeRight_exp[i]];
+                    }
+                    else        /*  1/(1+2^m) == 2^-m ;  for m >= 11  */
+                    {
+                        iEnvelopeRight_man[i] = Qfmt(1.000F);
+                        iEnvelopeRight_exp[i] = 0;
+                    }
+                }
+
+                iEnvelopeRight_exp[i] = iEnvelopeLeft_exp[i] - iEnvelopeRight_exp[i];
+
+                /*
+                *  apply "k" factor 1 or sqrt(2)
+                *
+                *   Right ==    k*2^(n-m)/(1 + q2^-m)
+                *   Left  == (q2^m)*k*2^n/(1 + q2^m) =  qk*2^n/(1 + q2^-m);
+                */
+                if (iEnvelopeLeft_man[i] != Qfmt(1.000F))
+                {
+                    /*
+                    *   k/(1 + q2^-m);
+                        */
+                    tmp = iEnvelopeRight_man[i];
+                    iEnvelopeRight_man[i] = fxp_mul32_Q30(iEnvelopeLeft_man[i], iEnvelopeRight_man[i]);
+                    iEnvelopeLeft_man[i] = tmp;
+                    iEnvelopeLeft_exp[i] += 1;      /* extra one due to sqrt(2)^2 */
+                }
+                else
+                {
+                    iEnvelopeLeft_man[i]  = fxp_mul32_Q30(iEnvelopeRight_man[i], Qfmt(1.41421356237310F));
+                }
+
+            }       /*  end of     if (iEnvelopeRight_man[i] == Qfmt( 1.000F) )  */
+        }      /* end of for loop */
+    }     /*  end  if (hFrameData2->ampRes) */
+
+
+    for (i = 0; i < hFrameData1->nNoiseFactors; i++)
+    {
+
+        noiseFloorLeft_exp[i]  = NOISE_FLOOR_OFFSET_PLUS_1 - noiseFloorLeft_man[i];
+        noiseFloorRight_exp[i] = noiseFloorRight_man[i] - SBR_ENERGY_PAN_OFFSET_INT;
+
+
+        /*
+         *  noiseFloorRight[i] = tempLeft / (1.0f + tempRight);
+         *  noiseFloorLeft[i]  = tempRight*noiseFloorRight[i];
+         *
+         *
+         *   noiseFloorRight[i] = 2^n/(1+2^m) =  2^(n-m)/(1 + 2^-m);
+         */
+        if (noiseFloorRight_exp[i] >= 0)
+        {
+            if (noiseFloorRight_exp[i] < 11)
+            {
+                noiseFloorRight_man[i] = one_over_one_plus_two_to_n[ noiseFloorRight_exp[i]];
+            }
+            else        /*  1/(1+2^-m) == 1 - 2^-m ;  for m >= 10  */
+            {
+                noiseFloorRight_man[i] = Qfmt(1.000F) - (Qfmt(1.000F) >> noiseFloorRight_exp[i]);
+            }
+        }
+        else
+        {
+            if (noiseFloorRight_exp[i] > -11)
+            {
+                noiseFloorRight_man[i] = Qfmt(1.000F) - one_over_one_plus_two_to_n[ -noiseFloorRight_exp[i]];
+            }
+            else        /*  1/(1+2^m) == 2^-m ;  for m >= 10  */
+            {
+                noiseFloorRight_man[i] = Qfmt(1.000F);
+                noiseFloorRight_exp[i] = 0;
+            }
+        }
+
+        noiseFloorRight_exp[i] = noiseFloorLeft_exp[i] - noiseFloorRight_exp[i];
+
+        /*
+         *   (2^m)*2^n/(1+2^m) =  2^n/(1 + 2^-m);
+         */
+
+        noiseFloorLeft_man[i] = noiseFloorRight_man[i];
+        noiseFloorLeft_exp[i] = noiseFloorLeft_exp[i];
+
+    }
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.h b/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.h
new file mode 100644
index 0000000..b949830
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_envelope_unmapping.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_envelope_unmapping.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_ENVELOPE_UNMAPPING_H
+#define SBR_ENVELOPE_UNMAPPING_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+#define UNMAPPING_SCALE_INT         (-18)           /*  factor's 2-exponent */
+#define SBR_ENERGY_PAN_OFFSET_INT   12
+
+
+
+/*----------------------------------------------------------------------------
+; 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 sbr_envelope_unmapping(SBR_FRAME_DATA * hFrameData1,
+                            SBR_FRAME_DATA * hFrameData2);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.cpp b/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.cpp
new file mode 100644
index 0000000..92b22f7
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.cpp
@@ -0,0 +1,223 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_extract_extended_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    SBR_FRAME_DATA *hFrameData,     Destination for extracted data of left channel
+    SBR_FRAME_DATA *hFrameDataRight Destination for extracted data of right channel
+    BIT_BUFFER hBitBuf              pointer to bit buffer
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Reads extension data from the bitstream
+
+  The bitstream format allows up to 4 kinds of extended data element.
+  Extended data may contain several elements, each identified by a 2-bit-ID.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_extract_extended_data.h"
+#include    "buf_getbits.h"
+
+#ifdef PARAMETRICSTEREO
+#include    "ps_read_data.h"
+#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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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 sbr_extract_extended_data(BIT_BUFFER * hBitBuf
+#ifdef PARAMETRICSTEREO         /* Parametric Stereo Decoder */
+                               , HANDLE_PS_DEC hParametricStereoDec
+#endif
+                              )
+{
+    Int32 extended_data;
+    Int32 i;
+    Int32 nBitsLeft;
+    Int32 extension_id;
+
+    extended_data = buf_get_1bit(hBitBuf);    /*  SI_SBR_EXTENDED_DATA_BITS  */
+
+    if (extended_data)
+    {
+        Int32 cnt;
+
+        cnt = buf_getbits(hBitBuf, SI_SBR_EXTENSION_SIZE_BITS);
+        if (cnt == (1 << SI_SBR_EXTENSION_SIZE_BITS) - 1)
+        {
+            cnt += buf_getbits(hBitBuf, SI_SBR_EXTENSION_ESC_COUNT_BITS);
+        }
+
+        nBitsLeft = (cnt << 3);
+        while (nBitsLeft > 7)
+        {
+            extension_id = buf_getbits(hBitBuf, SI_SBR_EXTENSION_ID_BITS);
+            nBitsLeft -= SI_SBR_EXTENSION_ID_BITS;
+
+            switch (extension_id)
+            {
+#ifdef HQ_SBR
+#ifdef PARAMETRICSTEREO
+
+                    /*
+                     *  Parametric Coding supports the Transient, Sinusoidal, Noise, and
+                     *  Parametric Stereo tools (MPEG4).
+                     *  3GPP use aac+ hq along with ps for enhanced aac+
+                     *  The PS tool uses complex-value QMF data, therefore can not be used
+                     *  with low power version of aac+
+                     */
+                case EXTENSION_ID_PS_CODING:
+
+                    if (hParametricStereoDec != NULL)
+                    {
+                        if (!hParametricStereoDec->psDetected)
+                        {
+                            /* parametric stereo detected */
+                            hParametricStereoDec->psDetected = 1;
+                        }
+
+                        nBitsLeft -= ps_read_data(hParametricStereoDec,
+                                                  hBitBuf,
+                                                  nBitsLeft);
+
+                    }
+
+                    break;
+#endif
+#endif
+                case 0:
+
+                default:
+                    /*   An unknown extension id causes the remaining extension data
+                     *   to be skipped
+                     */
+                    cnt = nBitsLeft >> 3; /* number of remaining bytes */
+
+                    for (i = 0; i < cnt; i++)
+                    {
+                        buf_getbits(hBitBuf, 8);
+                    }
+
+                    nBitsLeft -= (cnt << 3);
+            }
+        }
+        /* read fill bits for byte alignment */
+        buf_getbits(hBitBuf, nBitsLeft);
+    }
+}
+
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.h b/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.h
new file mode 100644
index 0000000..bbca3b9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_extract_extended_data.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_extract_extended_data.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_EXTRACT_EXTENDED_DATA_H
+#define SBR_EXTRACT_EXTENDED_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+
+#ifdef PARAMETRICSTEREO
+#include    "s_ps_dec.h"
+#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 sbr_extract_extended_data(BIT_BUFFER * hBitBuf
+#ifdef PARAMETRICSTEREO         /* Parametric Stereo Decoder */
+                               , HANDLE_PS_DEC hParametricStereoDec
+#endif
+                              );
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.cpp b/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.cpp
new file mode 100644
index 0000000..fc3d38f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_find_start_andstop_band.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_find_start_andstop_band.h"
+#include    "get_sbr_startfreq.h"
+#include    "get_sbr_stopfreq.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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_find_start_andstop_band(const Int32 samplingFreq,
+                                      const Int32 startFreq,
+                                      const Int32 stopFreq,
+                                      Int   *lsbM,
+                                      Int   *usb)
+{
+    /* Update startFreq struct */
+    *lsbM = get_sbr_startfreq(samplingFreq, startFreq);
+
+    if (*lsbM == 0)
+    {
+        return(SBRDEC_ILLEGAL_SCFACTORS);
+    }
+
+    /*Update stopFreq struct */
+    if (stopFreq < 13)
+    {
+        *usb = get_sbr_stopfreq(samplingFreq, stopFreq);
+    }
+    else if (stopFreq == 13)
+    {
+        *usb = 64;
+    }
+    else if (stopFreq == 14)
+    {
+        *usb = (*lsbM) << 1;
+    }
+    else
+    {
+        *usb = 3 * *lsbM;
+    }
+
+    /* limit to Nyqvist */
+    if (*usb > 64)
+    {
+        *usb = 64;
+    }
+
+    /* test for invalid lsb, usb combinations */
+    if ((*usb - *lsbM) > 48)
+    {
+        /*
+         *  invalid SBR bitstream ?
+         */
+        return(SBRDEC_INVALID_BITSTREAM);
+    }
+
+    if ((samplingFreq == 44100) && ((*usb - *lsbM) > 35))
+    {
+        /*
+         *  invalid SBR bitstream ?
+         */
+        return(SBRDEC_INVALID_BITSTREAM);
+    }
+
+    if ((samplingFreq >= 48000) && ((*usb - *lsbM) > 32))
+    {
+        /*
+         *  invalid SBR bitstream ?
+         */
+        return(SBRDEC_INVALID_BITSTREAM);
+    }
+
+    return(SBRDEC_OK);
+
+}
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.h b/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.h
new file mode 100644
index 0000000..88283c6
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_find_start_andstop_band.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+ Filename: sbr_find_start_andstop_band.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_FIND_START_ANDSTOP_BAND_H
+#define SBR_FIND_START_ANDSTOP_BAND_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_sbr_error.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_find_start_andstop_band(const Int32 samplingFreq,
+                                      const Int32 startFreq,
+                                      const Int32 stopFreq,
+                                      Int *lsbM,
+                                      Int *usb);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.cpp b/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.cpp
new file mode 100644
index 0000000..2126e47
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.cpp
@@ -0,0 +1,1040 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_generate_high_freq.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    HF generator with built-in QMF bank inverse filtering function
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+
+
+#include    "sbr_generate_high_freq.h"
+#include    "calc_auto_corr.h"
+#include    "sbr_inv_filt_levelemphasis.h"
+#include    "pv_div.h"
+#include    "fxp_mul32.h"
+#include    "aac_mem_funcs.h"
+#include    "sbr_constants.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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void high_freq_coeff_LC(Int32 sourceBufferReal[][32],
+    Int32 *alphar[2],
+    Int32 *degreeAlias,
+    Int32 *v_k_master,
+    Int32 *scratch_mem);
+
+
+    void high_freq_generation_LC(Int32 sourceBufferReal[][32],
+                                 Int32 *targetBufferReal,
+                                 Int32 *alphar[2],
+                                 Int32 *degreeAlias,
+                                 Int32 *invFiltBandTable,
+                                 Int32 targetStopBand,
+                                 Int32 patchDistance,
+                                 Int32 numBandsInPatch,
+                                 Int32 startSample,
+                                 Int32 slopeLength,
+                                 Int32 stopSample,
+                                 Int32 *BwVector,
+                                 Int32 sbrStartFreqOffset);
+
+
+#ifdef HQ_SBR
+
+    void high_freq_coeff(Int32 sourceBufferReal[][32],
+                         Int32 sourceBufferImag[][32],
+                         Int32 *alphar[2],
+                         Int32 *alphai[2],
+                         Int32 *v_k_master);
+
+    void high_freq_generation(Int32 sourceBufferReal[][32],
+                              Int32 sourceBufferImag[][32],
+                              Int32 *targetBufferReal,
+                              Int32 *targetBufferImag,
+                              Int32 *alphar[2],
+                              Int32 *alphai[2],
+                              Int32 *invFiltBandTable,
+                              Int32 targetStopBand,
+                              Int32 patchDistance,
+                              Int32 numBandsInPatch,
+                              Int32 startSample,
+                              Int32 slopeLength,
+                              Int32 stopSample,
+                              Int32 *BwVector,
+                              Int32 sbrStartFreqOffset);
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 sbr_generate_high_freq(Int32 sourceBufferReal[][32],
+                            Int32 sourceBufferImag[][32],
+                            Int32 *targetBufferReal,
+                            Int32 *targetBufferImag,
+                            INVF_MODE *invFiltMode,
+                            INVF_MODE *prevInvFiltMode,
+                            Int32 *invFiltBandTable,
+                            Int32 noInvFiltBands,
+                            Int32 highBandStartSb,
+                            Int32  *v_k_master,
+                            Int32 numMaster,
+                            Int32 fs,
+                            Int32   *frameInfo,
+                            Int32 *degreeAlias,
+                            Int32  scratch_mem[][64],
+                            Int32  BwVector[MAX_NUM_PATCHES],
+                            Int32  BwVectorOld[MAX_NUM_PATCHES],
+                            struct PATCH *Patch,
+                            Int32 LC_flag,
+                            Int32 *highBandStopSb)
+{
+    Int32    i;
+    Int32    patch;
+    Int32    startSample;
+    Int32    stopSample;
+    Int32    goalSb;
+    Int32    targetStopBand;
+    Int32    sourceStartBand;
+    Int32    patchDistance;
+    Int32    numBandsInPatch;
+    Int32    sbrStartFreqOffset;
+
+    Int32  *alphar[2];
+    Int32  *alphai[2];
+
+    Int32    lsb = v_k_master[0];                           /* Lowest subband related to the synthesis filterbank */
+    Int32    usb = v_k_master[numMaster];                   /* Stop subband related to the synthesis filterbank */
+    Int32  xoverOffset = highBandStartSb - v_k_master[0]; /* Calculate distance in subbands between k0 and kx */
+
+
+
+    Int    slopeLength = 0;
+
+    Int32 firstSlotOffs = frameInfo[1];
+    Int32 lastSlotOffs  = frameInfo[frameInfo[0] + 1] - 16;
+
+
+    alphar[0] = scratch_mem[0];
+    alphar[1] = scratch_mem[1];
+    alphai[0] = scratch_mem[2];
+    alphai[1] = scratch_mem[3];
+
+
+    startSample = (firstSlotOffs << 1);
+    stopSample  = (lastSlotOffs << 1) + 32;
+
+
+    sbr_inv_filt_levelemphasis(invFiltMode,
+                               prevInvFiltMode,
+                               noInvFiltBands,
+                               BwVector,
+                               BwVectorOld);
+
+
+    if (LC_flag == ON)
+    {
+        /* Set subbands to zero  */
+
+        pv_memset((void *)&targetBufferReal[startSample*SBR_NUM_BANDS],
+                  0,
+                  (stopSample - startSample)*SBR_NUM_BANDS*sizeof(targetBufferReal[0]));
+
+        high_freq_coeff_LC(sourceBufferReal,
+                           alphar,
+                           degreeAlias,
+                           v_k_master,
+                           scratch_mem[4]);
+    }
+#ifdef HQ_SBR
+    else
+    {
+        /* Set subbands to zero  */
+
+        pv_memset((void *)&targetBufferReal[startSample*SBR_NUM_BANDS],
+                  0,
+                  (stopSample - startSample)*SBR_NUM_BANDS*sizeof(targetBufferReal[0]));
+        pv_memset((void *)&targetBufferImag[startSample*SBR_NUM_BANDS],
+                  0,
+                  (stopSample - startSample)*SBR_NUM_BANDS*sizeof(targetBufferImag[0]));
+
+        high_freq_coeff(sourceBufferReal,
+                        sourceBufferImag,
+                        alphar,
+                        alphai,
+                        v_k_master);
+
+    }
+#endif     /*  #ifdef HQ_SBR */
+
+
+
+
+    /*
+     * Initialize the patching parameter
+     */
+    switch (fs)
+
+    {
+            /*
+             *  goalSb = (int)( 2.048e6f / fs + 0.5f );
+             */
+        case 48000:
+            goalSb = 43;  /* 16 kHz band */
+            break;
+        case 32000:
+            goalSb = 64;  /* 16 kHz band */
+            break;
+        case 24000:
+            goalSb = 85;  /* 16 kHz band */
+            break;
+        case 22050:
+            goalSb = 93;  /* 16 kHz band */
+            break;
+        case 16000:
+            goalSb = 128;  /* 16 kHz band */
+            break;
+        case 44100:
+        default:
+            goalSb = 46;  /* 16 kHz band */
+            break;
+    }
+
+    i = 0;
+
+    if (goalSb > v_k_master[0])
+    {
+        if (goalSb < v_k_master[numMaster])
+        {
+            while (v_k_master[i] < goalSb)
+            {
+                i++;
+            }
+        }
+        else
+        {
+            i = numMaster;
+        }
+    }
+
+    goalSb =  v_k_master[i];
+
+    /* First patch */
+    sourceStartBand = xoverOffset + 1;
+    targetStopBand = lsb + xoverOffset;
+
+    /* even (odd) numbered channel must be patched to even (odd) numbered channel */
+    patch = 0;
+
+
+    sbrStartFreqOffset = targetStopBand;
+
+    while (targetStopBand < usb)
+    {
+        Patch->targetStartBand[patch] = targetStopBand;
+
+        numBandsInPatch = goalSb - targetStopBand;                   /* get the desired range of the patch */
+
+        if (numBandsInPatch >= lsb - sourceStartBand)
+        {
+            /* desired number bands are not available -> patch whole source range */
+            patchDistance   = targetStopBand - sourceStartBand;        /* get the targetOffset */
+            patchDistance   = patchDistance & ~1;                      /* rounding off odd numbers and make all even */
+            numBandsInPatch = lsb - (targetStopBand - patchDistance);
+
+            if (targetStopBand + numBandsInPatch > v_k_master[0])
+            {
+                i = numMaster;
+                if (targetStopBand + numBandsInPatch < v_k_master[numMaster])
+                {
+                    while (v_k_master[i] > targetStopBand + numBandsInPatch)
+                    {
+                        i--;
+                    }
+                }
+            }
+            else
+            {
+                i = 0;
+            }
+            numBandsInPatch =  v_k_master[i] - targetStopBand;
+        }
+
+        /* desired number bands are available -> get the minimal even patching distance */
+        patchDistance   = numBandsInPatch + targetStopBand - lsb;  /* get minimal distance */
+        patchDistance   = (patchDistance + 1) & ~1;                /* rounding up odd numbers and make all even */
+
+        /* All patches but first */
+        sourceStartBand = 1;
+
+        /* Check if we are close to goalSb */
+        if (goalSb - (targetStopBand + numBandsInPatch) < 3)
+        { /* MPEG doc */
+            goalSb = usb;
+        }
+
+
+        if ((numBandsInPatch < 3) && (patch > 0))
+        {
+            if (LC_flag == ON)
+            {
+
+                pv_memset((void *) &degreeAlias[targetStopBand], 0, numBandsInPatch*sizeof(*degreeAlias));
+            }
+            break;
+        }
+
+        if (numBandsInPatch <= 0)
+        {
+            continue;
+        }
+
+
+        /*
+         *  High Frequency generation
+         */
+
+        if (LC_flag == ON)
+        {
+
+            high_freq_generation_LC(sourceBufferReal,
+                                    (Int32 *)targetBufferReal,
+                                    alphar,
+                                    degreeAlias,
+                                    invFiltBandTable,
+                                    targetStopBand,
+                                    patchDistance,
+                                    numBandsInPatch,
+                                    startSample,
+                                    slopeLength,
+                                    stopSample,
+                                    BwVector,
+                                    sbrStartFreqOffset);
+
+        }
+#ifdef HQ_SBR
+        else
+        {
+
+            high_freq_generation(sourceBufferReal,
+                                 sourceBufferImag,
+                                 (Int32 *)targetBufferReal,
+                                 (Int32 *)targetBufferImag,
+                                 alphar,
+                                 alphai,
+                                 invFiltBandTable,
+                                 targetStopBand,
+                                 patchDistance,
+                                 numBandsInPatch,
+                                 startSample,
+                                 slopeLength,
+                                 stopSample,
+                                 BwVector,
+                                 sbrStartFreqOffset);
+
+        }
+#endif
+
+        targetStopBand += numBandsInPatch;
+
+        patch++;
+
+    }  /* targetStopBand */
+
+    Patch->noOfPatches = patch;
+
+    pv_memmove(BwVectorOld, BwVector, noInvFiltBands*sizeof(BwVector[0]));
+
+    *highBandStopSb = goalSb;
+
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void high_freq_coeff_LC(Int32 sourceBufferReal[][32],
+                        Int32 *alphar[2],
+                        Int32 *degreeAlias,
+                        Int32 *v_k_master,
+                        Int32 *scratch_mem)
+{
+
+    Int32  fac;
+    Int32 *k1;
+    struct ACORR_COEFS ac;
+    struct intg_div  quotient;
+
+    Int32 temp1;
+    Int32 temp2;
+    Int32 temp3;
+    Int32 autoCorrLength;
+    Int32 loBand;
+
+    k1 = scratch_mem;
+
+
+    autoCorrLength = 38;
+
+    for (loBand = 1; loBand < v_k_master[0]; loBand++)
+    {
+
+        calc_auto_corr_LC(&ac,
+                          sourceBufferReal,
+                          loBand,
+                          autoCorrLength);
+
+        if (ac.r11r && ac.det)
+        {
+
+            pv_div(ac.r01r, ac.r11r, &quotient);
+
+            fac = -(quotient.quotient >> 2);   /*  Q28 */
+
+            if (quotient.shift_factor > 0)
+            {
+                fac >>= quotient.shift_factor;    /* Q28 */
+            }
+            else if (quotient.shift_factor < 0)
+            {
+                if (quotient.shift_factor > -4)     /* |fac| < 8 */
+                {
+                    fac <<= (-quotient.shift_factor); /* Q28 */
+                }
+                else
+                {
+                    fac = 0x80000000;     /* overshoot possible fac = -8 */
+                }
+            }
+
+            /*
+             *  prevent for overflow of reflection coefficients
+             */
+            if (quotient.shift_factor > 0)
+            {
+                k1[loBand] = - quotient.quotient >> quotient.shift_factor;
+            }
+            else if (quotient.shift_factor == 0)
+            {
+                if (quotient.quotient >= 0x40000000)
+                {
+                    k1[loBand] = (Int32)0xC0000000;   /* -1.0 in Q30  */
+                }
+                else if (quotient.quotient <= (Int32)0xC0000000)
+                {
+                    k1[loBand] = 0x40000000;   /*  1.0 in Q30  */
+                }
+                else
+                {
+                    k1[loBand] = -quotient.quotient;
+                }
+            }
+            else
+            {
+                if (quotient.quotient > 0)
+                {
+                    k1[loBand] = (Int32)0xC0000000;   /* -1.0 in Q30  */
+                }
+                else
+                {
+                    k1[loBand] = 0x40000000;   /*  1.0 in Q30  */
+                }
+            }
+            /*
+             *   alphar[1][loBand] = ( ac.r01r * ac.r12r - ac.r02r * ac.r11r ) / ac.det;
+             */
+
+            temp1  = -fxp_mul32_Q30(ac.r02r, ac.r11r);
+            temp1  =  fxp_mac32_Q30(ac.r01r, ac.r12r, temp1);
+
+            temp2 = ac.det;
+            temp3 = temp1 > 0 ? temp1 : -temp1;
+            temp2 = temp2 > 0 ? temp2 : -temp2;
+
+            /* prevent for shootovers */
+            if ((temp3 >> 2) >= temp2 || fac == (Int32)0x80000000)
+            {
+                alphar[0][loBand] = 0;
+                alphar[1][loBand] = 0;
+            }
+            else
+            {
+                pv_div(temp1, ac.det, &quotient);
+                /*
+                 *  alphar[1][loBand] is lesser than 4.0
+                 */
+                alphar[1][loBand] = quotient.quotient;
+                quotient.shift_factor += 2;             /* Q28 */
+
+                if (quotient.shift_factor > 0)
+                {
+                    alphar[1][loBand] >>= quotient.shift_factor;    /* Q28 */
+                }
+                else if (quotient.shift_factor < 0)     /* at this point can only be -1 */
+                {
+                    alphar[1][loBand] <<= (-quotient.shift_factor); /* Q28 */
+                }
+
+                /*
+                 *  alphar[0][loBand] = - ( ac.r01r + alphar[1][loBand] * ac.r12r ) / ac.r11r;
+                 */
+
+                pv_div(ac.r12r, ac.r11r, &quotient);
+
+                temp3 = (quotient.quotient >> 2);       /*  Q28 */
+
+                if (quotient.shift_factor > 0)
+                {
+                    temp3 >>= quotient.shift_factor;    /* Q28 */
+                }
+                else if (quotient.shift_factor < 0)
+                {
+                    temp3 <<= (-quotient.shift_factor); /* Q28 */
+                }
+
+                alphar[0][loBand] = fac - fxp_mul32_Q28(alphar[1][loBand], temp3) ;    /* Q28 */
+
+                if ((alphar[0][loBand] >= 0x40000000) || (alphar[0][loBand] <= (Int32)0xC0000000))
+                {
+                    alphar[0][loBand] = 0;
+                    alphar[1][loBand] = 0;
+                }
+
+            }
+
+        }
+        else
+        {
+            alphar[0][loBand] = 0;
+            alphar[1][loBand] = 0;
+
+            k1[loBand] = 0;
+        }
+
+    }
+
+    k1[0] = 0;
+    degreeAlias[1] = 0;
+    for (loBand = 2; loBand < v_k_master[0]; loBand++)
+    {
+        degreeAlias[loBand] = 0;
+        if ((!(loBand & 1)) && (k1[loBand] < 0))
+        {
+            if (k1[loBand-1] < 0)
+            { // 2-CH Aliasing Detection
+                degreeAlias[loBand]   = 0x40000000;
+                if (k1[loBand-2] > 0)
+                { // 3-CH Aliasing Detection
+                    degreeAlias[loBand-1] = 0x40000000 - fxp_mul32_Q30(k1[loBand-1], k1[loBand-1]);
+
+                }
+            }
+            else if (k1[loBand-2] > 0)
+            { // 3-CH Aliasing Detection
+                degreeAlias[loBand] = 0x40000000 - fxp_mul32_Q30(k1[loBand-1], k1[loBand-1]);
+            }
+        }
+        if ((loBand & 1) && (k1[loBand] > 0))
+        {
+            if (k1[loBand-1] > 0)
+            { // 2-CH Aliasing Detection
+                degreeAlias[loBand]   = 0x40000000;
+                if (k1[loBand-2] < 0)
+                { // 3-CH Aliasing Detection
+                    degreeAlias[loBand-1] = 0x40000000 - fxp_mul32_Q30(k1[loBand-1], k1[loBand-1]);
+                }
+            }
+            else if (k1[loBand-2] < 0)
+            { // 3-CH Aliasing Detection
+                degreeAlias[loBand] = 0x40000000 - fxp_mul32_Q30(k1[loBand-1], k1[loBand-1]);
+            }
+        }
+    }
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void high_freq_generation_LC(Int32 sourceBufferReal[][32],
+                             Int32 *targetBufferReal,
+                             Int32 *alphar[2],
+                             Int32 *degreeAlias,
+                             Int32 *invFiltBandTable,
+                             Int32 targetStopBand,
+                             Int32 patchDistance,
+                             Int32 numBandsInPatch,
+                             Int32 startSample,
+                             Int32 slopeLength,
+                             Int32 stopSample,
+                             Int32 *BwVector,
+                             Int32 sbrStartFreqOffset)
+{
+
+    Int32  temp1;
+    Int32  temp2;
+    Int32  temp3;
+
+
+    Int32  a0r;
+    Int32  a1r;
+    Int32  i;
+    Int32  bw;
+    Int32  hiBand;
+    Int32  bwIndex;
+    Int32  loBand;
+    Int32  j;
+
+    bwIndex = 0;
+
+    for (hiBand = targetStopBand; hiBand < targetStopBand + numBandsInPatch; hiBand++)
+    {
+        loBand = hiBand - patchDistance;
+
+        if (hiBand != targetStopBand)
+        {
+            degreeAlias[hiBand] = degreeAlias[loBand];
+        }
+        else
+        {
+            degreeAlias[hiBand] = 0;
+        }
+
+        while (hiBand >= invFiltBandTable[bwIndex])
+        {
+            bwIndex++;
+        }
+
+        bw = BwVector[bwIndex];
+
+        /*
+         *  Inverse Filtering
+         */
+
+
+        j = hiBand - sbrStartFreqOffset;
+
+        if (bw > 0 && (alphar[0][loBand] | alphar[1][loBand]))
+        {
+            /* Apply current bandwidth expansion factor */
+            a0r = fxp_mul32_Q29(bw, alphar[0][loBand]);
+
+            bw  = fxp_mul32_Q31(bw, bw) << 2;
+
+            a1r = fxp_mul32_Q28(bw, alphar[1][loBand]);
+
+            i = startSample + slopeLength;
+
+            temp1 = sourceBufferReal[i    ][loBand];
+            temp2 = sourceBufferReal[i - 1][loBand];
+            temp3 = sourceBufferReal[i - 2][loBand];
+
+            for (; i < stopSample + slopeLength - 1; i++)
+            {
+
+
+                targetBufferReal[i*SBR_NUM_BANDS + j] = temp1 + fxp_mul32_Q28(a0r, temp2)  +
+                                                        fxp_mul32_Q28(a1r, temp3);
+
+
+                temp3 = temp2;
+                temp2 = temp1;
+                temp1 = sourceBufferReal[i + 1][loBand];
+            }
+            targetBufferReal[i*SBR_NUM_BANDS + j] = temp1 + fxp_mul32_Q28(a0r, temp2)  +
+                                                    fxp_mul32_Q28(a1r, temp3);
+
+        }
+        else
+        {
+
+            for (i = startSample + slopeLength; i < stopSample + slopeLength; i++)
+            {
+                targetBufferReal[i*SBR_NUM_BANDS + j] = sourceBufferReal[i][loBand];
+            }
+        }
+
+
+    }  /* hiBand */
+
+}
+
+
+#ifdef HQ_SBR
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void high_freq_coeff(Int32 sourceBufferReal[][32],
+                     Int32 sourceBufferImag[][32],
+                     Int32 *alphar[2],
+                     Int32 *alphai[2],
+                     Int32 *v_k_master)
+{
+
+    Int32  overflow_flag;
+
+    Int32  temp1r;
+    Int32  temp1i;
+    Int32  temp0r;
+    Int32  temp0i;
+    Int32  loBand;
+
+    struct ACORR_COEFS ac;
+    struct intg_div  quotient;
+
+    Int32 autoCorrLength;
+
+    autoCorrLength = 38;
+
+    for (loBand = 1; loBand < v_k_master[0]; loBand++)
+    {
+
+        calc_auto_corr(&ac,
+                       sourceBufferReal,
+                       sourceBufferImag,
+                       loBand,
+                       autoCorrLength);
+
+
+        overflow_flag = 0;
+
+        if (ac.det < 1)
+        {
+            /* ---  */
+            temp1r = 0;
+            temp1i = 0;
+            alphar[1][loBand] = 0;
+            alphai[1][loBand] = 0;
+
+        }
+        else
+        {
+
+            temp1r =  fxp_mul32_Q29(ac.r01r, ac.r12r);
+            temp1r =  fxp_msu32_Q29(ac.r01i, ac.r12i, temp1r);
+            temp1r =  fxp_msu32_Q29(ac.r02r, ac.r11r, temp1r);
+
+            temp1i =  fxp_mul32_Q29(ac.r01r, ac.r12i);
+            temp1i =  fxp_msu32_Q29(ac.r02i, ac.r11r, temp1i);
+            temp1i =  fxp_mac32_Q29(ac.r01i, ac.r12r, temp1i);
+
+            pv_div(temp1r, ac.det, &quotient);
+            overflow_flag = (quotient.shift_factor < -2) ? 1 : 0;
+            temp1r = quotient.quotient >> (2 + quotient.shift_factor);   /*  Q28 */
+            pv_div(temp1i, ac.det, &quotient);
+            overflow_flag = (quotient.shift_factor < -2) ? 1 : 0;
+            temp1i = quotient.quotient >> (2 + quotient.shift_factor);   /*  Q28 */
+
+            alphar[1][loBand] = temp1r;
+            alphai[1][loBand] = temp1i;
+
+        }
+
+        if (ac.r11r == 0)
+        {
+            temp0r = 0;
+            temp0i = 0;
+            alphar[0][loBand] = 0;
+            alphai[0][loBand] = 0;
+
+        }
+        else
+        {
+            temp0r = - (ac.r01r + fxp_mul32_Q28(temp1r, ac.r12r) + fxp_mul32_Q28(temp1i, ac.r12i));
+            temp0i = - (ac.r01i + fxp_mul32_Q28(temp1i, ac.r12r) - fxp_mul32_Q28(temp1r, ac.r12i));
+
+            pv_div(temp0r, ac.r11r, &quotient);
+            overflow_flag = (quotient.shift_factor < -2) ? 1 : 0;
+            temp0r = quotient.quotient >> (2 + quotient.shift_factor);   /*  Q28 */
+            pv_div(temp0i, ac.r11r, &quotient);
+            overflow_flag = (quotient.shift_factor < -2) ? 1 : 0;
+            temp0i = quotient.quotient >> (2 + quotient.shift_factor);   /*  Q28 */
+
+            alphar[0][loBand] = temp0r;
+            alphai[0][loBand] = temp0i;
+
+        }
+
+        /* prevent for shootovers */
+
+        if (fxp_mul32_Q28((temp0r >> 2), (temp0r >> 2)) + fxp_mul32_Q28((temp0i >> 2), (temp0i >> 2)) >= 0x10000000 ||
+                fxp_mul32_Q28((temp1r >> 2), (temp1r >> 2)) + fxp_mul32_Q28((temp1i >> 2), (temp1i >> 2)) >= 0x10000000 ||
+                overflow_flag)     /*  0x10000000 == 1 in Q28 */
+
+        {
+            alphar[0][loBand] = 0;
+            alphar[1][loBand] = 0;
+            alphai[0][loBand] = 0;
+            alphai[1][loBand] = 0;
+
+        }
+    }
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+
+void high_freq_generation(Int32 sourceBufferReal[][32],
+                          Int32 sourceBufferImag[][32],
+                          Int32 *targetBufferReal,
+                          Int32 *targetBufferImag,
+                          Int32 *alphar[2],
+                          Int32 *alphai[2],
+                          Int32 *invFiltBandTable,
+                          Int32 targetStopBand,
+                          Int32 patchDistance,
+                          Int32 numBandsInPatch,
+                          Int32 startSample,
+                          Int32 slopeLength,
+                          Int32 stopSample,
+                          Int32 *BwVector,
+                          Int32 sbrStartFreqOffset)
+{
+    Int32  temp1_r;
+    Int32  temp2_r;
+    Int32  temp3_r;
+    Int32  temp1_i;
+    Int32  temp2_i;
+    Int32  temp3_i;
+
+
+    Int32  a0i;
+    Int32  a1i;
+    Int32  a0r;
+    Int32  a1r;
+    Int32  i;
+    Int32  bw;
+    Int32  hiBand;
+    Int32  bwIndex;
+    Int32  loBand;
+    Int32  j;
+
+
+
+    int64_t tmp;
+
+    bwIndex = 0;
+
+    for (hiBand = targetStopBand; hiBand < targetStopBand + numBandsInPatch; hiBand++)
+    {
+
+        loBand = hiBand - patchDistance;
+
+        while (hiBand >= invFiltBandTable[bwIndex])
+        {
+            bwIndex++;
+        }
+
+        bw = BwVector[bwIndex];
+
+        /*
+         *  Inverse Filtering
+         */
+
+
+        j = hiBand - sbrStartFreqOffset;
+
+        if (bw >= 0 && (alphar[0][loBand] | alphar[1][loBand] |
+                        alphai[0][loBand] | alphai[1][loBand]))
+        {
+            /* Apply current bandwidth expansion factor */
+            a0r = fxp_mul32_Q29(bw, alphar[0][loBand]);
+            a0i = fxp_mul32_Q29(bw, alphai[0][loBand]);
+
+
+            bw  = fxp_mul32_Q30(bw, bw);
+
+
+            a1r = fxp_mul32_Q28(bw, alphar[1][loBand]);
+            a1i = fxp_mul32_Q28(bw, alphai[1][loBand]);
+
+
+            i  = startSample + slopeLength;
+            j += i * SBR_NUM_BANDS;
+
+            temp1_r = sourceBufferReal[i    ][loBand];
+            temp2_r = sourceBufferReal[i - 1][loBand];
+            temp3_r = sourceBufferReal[i - 2][loBand];
+
+            temp1_i = sourceBufferImag[i    ][loBand];
+            temp2_i = sourceBufferImag[i - 1][loBand];
+            temp3_i = sourceBufferImag[i - 2][loBand];
+
+            while (i < stopSample + slopeLength)
+            {
+                tmp =  fxp_mac64_Q31(((int64_t)temp1_r << 28),  a0r, temp2_r);
+                tmp =  fxp_mac64_Q31(tmp, -a0i, temp2_i);
+                tmp =  fxp_mac64_Q31(tmp,  a1r, temp3_r);
+                targetBufferReal[j] = (Int32)(fxp_mac64_Q31(tmp, -a1i, temp3_i) >> 28);
+
+                tmp =  fxp_mac64_Q31(((int64_t)temp1_i << 28),  a0i, temp2_r);
+                tmp =  fxp_mac64_Q31(tmp,  a0r, temp2_i);
+                tmp =  fxp_mac64_Q31(tmp,  a1i, temp3_r);
+                targetBufferImag[j] = (Int32)(fxp_mac64_Q31(tmp,  a1r, temp3_i) >> 28);
+
+                i++;
+                j += SBR_NUM_BANDS;
+
+                temp3_r  = temp2_r;
+                temp2_r  = temp1_r;
+                temp1_r  = sourceBufferReal[i ][loBand];
+
+                temp3_i  = temp2_i;
+                temp2_i  = temp1_i;
+                temp1_i  = sourceBufferImag[i ][loBand];
+
+            }
+
+        }
+
+
+
+        else
+        {
+            i = startSample + slopeLength;
+            j += i * SBR_NUM_BANDS;
+
+            for (; i < stopSample + slopeLength; i++)
+            {
+                targetBufferReal[j] = sourceBufferReal[i][loBand];
+                targetBufferImag[j] = sourceBufferImag[i][loBand];
+                j += SBR_NUM_BANDS;
+            }
+        }
+    }
+}
+
+#endif
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.h b/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.h
new file mode 100644
index 0000000..0e9c928
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_generate_high_freq.h
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_generate_high_freq.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GENERATE_HIGH_FREQ_H
+#define SBR_GENERATE_HIGH_FREQ_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "e_invf_mode.h"
+#include    "s_patch.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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 sbr_generate_high_freq(
+        Int32 sourceBufferReal[][32],
+        Int32 sourceBufferImag[][32],
+        Int32 *targetBufferReal,
+        Int32 *targetBufferImag,
+        INVF_MODE *invFiltMode,
+        INVF_MODE *prevInvFiltMode,
+        Int32 *invFiltBandTable,
+        Int32 noInvFiltBands,
+        Int32 highBandStartSb,
+        Int32 *v_k_master,
+        Int32 numMaster,
+        Int32 fs,
+        Int32 *frameInfo,
+        Int32 *degreeAlias,
+        Int32 scratch_mem[][64],
+        Int32 BwVector[MAX_NUM_PATCHES],
+        Int32 BwVectorOld[MAX_NUM_PATCHES],
+        struct PATCH * Patch,
+        Int32 LC_flag,
+        Int32 *highBandStopSb);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_additional_data.cpp b/media/libstagefright/codecs/aacdec/sbr_get_additional_data.cpp
new file mode 100644
index 0000000..60072dd
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_additional_data.cpp
@@ -0,0 +1,145 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_additional_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_additional_data.h"
+#include    "buf_getbits.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 sbr_get_additional_data(SBR_FRAME_DATA * hFrameData,
+                             BIT_BUFFER     * hBitBuf)
+{
+    Int32 i;
+
+    Int32 flag = buf_getbits(hBitBuf, 1);
+
+    if (flag)
+    {
+        for (i = 0; i < hFrameData->nSfb[HI]; i++)
+        {
+            hFrameData->addHarmonics[i] = buf_getbits(hBitBuf, 1);
+        }
+    }
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_additional_data.h b/media/libstagefright/codecs/aacdec/sbr_get_additional_data.h
new file mode 100644
index 0000000..51285c5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_additional_data.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_additional_data.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_ADDITIONAL_DATA_H
+#define SBR_GET_ADDITIONAL_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_header_data.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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 sbr_get_additional_data(SBR_FRAME_DATA * hFrameData,
+                             BIT_BUFFER     * hBitBuf);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_cpe.cpp b/media/libstagefright/codecs/aacdec/sbr_get_cpe.cpp
new file mode 100644
index 0000000..657d032
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_cpe.cpp
@@ -0,0 +1,266 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_cpe.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     hFrameDataLeft  - handle to struct SBR_FRAME_DATA for first channel
+                hFrameDataRight - handle to struct SBR_FRAME_DATA for first channel
+                hBitBuf         - handle to struct BIT_BUF
+
+ Return:        SbrFrameOK
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_cpe.h"
+#include    "buf_getbits.h"
+#include    "extractframeinfo.h"
+#include    "sbr_get_dir_control_data.h"
+#include    "sbr_get_envelope.h"
+#include    "sbr_get_noise_floor_data.h"
+#include    "sbr_get_additional_data.h"
+#include    "sbr_extract_extended_data.h"
+#include    "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+
+SBR_ERROR sbr_get_cpe(SBR_FRAME_DATA * hFrameDataLeft,
+                      SBR_FRAME_DATA * hFrameDataRight,
+                      BIT_BUFFER  * hBitBuf)
+{
+    Int32 i;
+    Int32 bits;
+    SBR_ERROR err =  SBRDEC_OK;
+
+    /* reserved bits */
+    bits = buf_getbits(hBitBuf, SI_SBR_RESERVED_PRESENT);
+
+    if (bits)
+    {
+        buf_getbits(hBitBuf, SI_SBR_RESERVED_BITS_DATA);
+        buf_getbits(hBitBuf, SI_SBR_RESERVED_BITS_DATA);
+    }
+
+    /* Read coupling flag */
+    bits = buf_getbits(hBitBuf, SI_SBR_COUPLING_BITS);
+
+    if (bits)
+    {
+        hFrameDataLeft->coupling = COUPLING_LEVEL;
+        hFrameDataRight->coupling = COUPLING_BAL;
+    }
+    else
+    {
+        hFrameDataLeft->coupling = COUPLING_OFF;
+        hFrameDataRight->coupling = COUPLING_OFF;
+    }
+
+
+    err = extractFrameInfo(hBitBuf, hFrameDataLeft);
+
+    if (err != SBRDEC_OK)
+    {
+        return err;
+    }
+
+    if (hFrameDataLeft->coupling)
+    {
+
+        pv_memcpy(hFrameDataRight->frameInfo,
+                  hFrameDataLeft->frameInfo,
+                  LENGTH_FRAME_INFO * sizeof(Int32));
+
+        hFrameDataRight->nNoiseFloorEnvelopes = hFrameDataLeft->nNoiseFloorEnvelopes;
+        hFrameDataRight->frameClass = hFrameDataLeft->frameClass;
+
+
+        sbr_get_dir_control_data(hFrameDataLeft, hBitBuf);
+        sbr_get_dir_control_data(hFrameDataRight, hBitBuf);
+
+        for (i = 0; i < hFrameDataLeft->nNfb; i++)
+        {
+            hFrameDataLeft->sbr_invf_mode_prev[i]  = hFrameDataLeft->sbr_invf_mode[i];
+            hFrameDataRight->sbr_invf_mode_prev[i] = hFrameDataRight->sbr_invf_mode[i];
+
+            hFrameDataLeft->sbr_invf_mode[i]  = (INVF_MODE) buf_getbits(hBitBuf, SI_SBR_INVF_MODE_BITS);
+            hFrameDataRight->sbr_invf_mode[i] = hFrameDataLeft->sbr_invf_mode[i];
+        }
+
+        sbr_get_envelope(hFrameDataLeft, hBitBuf);
+        sbr_get_noise_floor_data(hFrameDataLeft, hBitBuf);
+        sbr_get_envelope(hFrameDataRight, hBitBuf);
+
+    }
+    else
+    {
+        err = extractFrameInfo(hBitBuf, hFrameDataRight);
+
+        if (err != SBRDEC_OK)
+        {
+            return err;
+        }
+
+
+        sbr_get_dir_control_data(hFrameDataLeft,  hBitBuf);
+        sbr_get_dir_control_data(hFrameDataRight, hBitBuf);
+
+        for (i = 0; i <  hFrameDataLeft->nNfb; i++)
+        {
+            hFrameDataLeft->sbr_invf_mode_prev[i]  = hFrameDataLeft->sbr_invf_mode[i];
+            hFrameDataLeft->sbr_invf_mode[i]  =
+                (INVF_MODE) buf_getbits(hBitBuf, SI_SBR_INVF_MODE_BITS);
+        }
+
+        for (i = 0; i <  hFrameDataRight->nNfb; i++)
+        {
+            hFrameDataRight->sbr_invf_mode_prev[i] = hFrameDataRight->sbr_invf_mode[i];
+
+            hFrameDataRight->sbr_invf_mode[i] =
+                (INVF_MODE) buf_getbits(hBitBuf, SI_SBR_INVF_MODE_BITS);
+        }
+        sbr_get_envelope(hFrameDataLeft,  hBitBuf);
+        sbr_get_envelope(hFrameDataRight, hBitBuf);
+
+        sbr_get_noise_floor_data(hFrameDataLeft,  hBitBuf);
+
+    }
+
+    sbr_get_noise_floor_data(hFrameDataRight, hBitBuf);
+
+    pv_memset((void *)hFrameDataLeft->addHarmonics,
+              0,
+              hFrameDataLeft->nSfb[HI]*sizeof(Int32));
+
+    pv_memset((void *)hFrameDataRight->addHarmonics,
+              0,
+              hFrameDataRight->nSfb[HI]*sizeof(Int32));
+
+    sbr_get_additional_data(hFrameDataLeft, hBitBuf);
+    sbr_get_additional_data(hFrameDataRight, hBitBuf);
+
+    sbr_extract_extended_data(hBitBuf
+#ifdef PARAMETRICSTEREO
+                              , NULL
+#endif
+                             );
+
+    return SBRDEC_OK;
+
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_cpe.h b/media/libstagefright/codecs/aacdec/sbr_get_cpe.h
new file mode 100644
index 0000000..b6f99f8
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_cpe.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_cpe.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_CPE_H
+#define SBR_GET_CPE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+#include    "e_sbr_error.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_get_cpe(SBR_FRAME_DATA * hFrameDataLeft,
+                      SBR_FRAME_DATA * hFrameDataRight,
+                      BIT_BUFFER * hBitBuf);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.cpp b/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.cpp
new file mode 100644
index 0000000..3d7ad8c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.cpp
@@ -0,0 +1,153 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_dir_control_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     h_frame_data - handle to struct SBR_FRAME_DATA
+                hBitBuf      - handle to struct BIT_BUF
+
+ Return:        void
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Reads direction control data from bitstream
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_dir_control_data.h"
+#include    "buf_getbits.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 sbr_get_dir_control_data(SBR_FRAME_DATA * h_frame_data,
+                              BIT_BUFFER     * hBitBuf)
+{
+    Int32 i;
+
+    h_frame_data->nNoiseFloorEnvelopes = h_frame_data->frameInfo[0] > 1 ? 2 : 1;
+
+
+    for (i = 0; i < h_frame_data->frameInfo[0]; i++)
+    {
+        h_frame_data->domain_vec1[i] = buf_getbits(hBitBuf, SI_SBR_DOMAIN_BITS);
+    }
+
+    for (i = 0; i < h_frame_data->nNoiseFloorEnvelopes; i++)
+    {
+        h_frame_data->domain_vec2[i] = buf_getbits(hBitBuf, SI_SBR_DOMAIN_BITS);
+    }
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.h b/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.h
new file mode 100644
index 0000000..3b587dc
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_dir_control_data.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_dir_control_data.h
+ Funtions:
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_DIR_CONTROL_DATA_H
+#define SBR_GET_DIR_CONTROL_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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 sbr_get_dir_control_data(SBR_FRAME_DATA * h_frame_data,
+                              BIT_BUFFER * hBitBuf);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_envelope.cpp b/media/libstagefright/codecs/aacdec/sbr_get_envelope.cpp
new file mode 100644
index 0000000..e92abb1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_envelope.cpp
@@ -0,0 +1,265 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_envelope.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     h_frame_data - handle to struct SBR_FRAME_DATA
+                hBitBuf      - handle to struct BIT_BUF
+                channel      - channel number
+
+ Return:        void
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+          Reads envelope data from bitstream
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_envelope.h"
+#include    "s_huffman.h"
+#include    "e_coupling_mode.h"
+#include    "sbr_code_book_envlevel.h"
+#include    "buf_getbits.h"
+#include    "sbr_decode_huff_cw.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 sbr_get_envelope(SBR_FRAME_DATA * h_frame_data,
+                      BIT_BUFFER * hBitBuf)
+{
+    Int32   i;
+    Int32   j;
+    Int32   tmp;
+    Int32   no_band[MAX_ENVELOPES];
+    Int32   delta = 0;
+    Int32   offset = 0;
+    Int32   ampRes;
+    Int32   envDataTableCompFactor;
+    Int32   start_bits;
+    Int32   start_bits_balance;
+    SbrHuffman    hcb_t;
+    SbrHuffman    hcb_f;
+    COUPLING_MODE coupling = h_frame_data->coupling;
+
+    h_frame_data->nScaleFactors = 0;
+
+    if ((h_frame_data->frameClass   == FIXFIX) &&
+            (h_frame_data->frameInfo[0] == 1))
+    {
+        h_frame_data->ampRes = SBR_AMP_RES_1_5;
+    }
+    else
+    {
+        h_frame_data->ampRes = h_frame_data->sbr_header.ampResolution;
+    }
+
+    ampRes = h_frame_data->ampRes;
+
+    /*
+     *    Set number of bits for first value depending on amplitude resolution
+     */
+    if (ampRes == SBR_AMP_RES_3_0)
+    {
+        start_bits         = SI_SBR_START_ENV_BITS_AMP_RES_3_0;
+        start_bits_balance = SI_SBR_START_ENV_BITS_BALANCE_AMP_RES_3_0;
+    }
+    else
+    {
+        start_bits         = SI_SBR_START_ENV_BITS_AMP_RES_1_5;
+        start_bits_balance = SI_SBR_START_ENV_BITS_BALANCE_AMP_RES_1_5;
+    }
+
+    /*
+     *    Calculate number of values for each envelope and alltogether
+     */
+    for (i = 0; i < h_frame_data->frameInfo[0]; i++)
+    {
+        no_band[i] =
+            h_frame_data->nSfb[h_frame_data->frameInfo[h_frame_data->frameInfo[0] + 2 + i]];
+        h_frame_data->nScaleFactors += no_band[i];
+    }
+
+
+    /*
+     *    Select huffman codebook depending on coupling mode and amplitude resolution
+     */
+    if (coupling == COUPLING_BAL)
+    {
+        envDataTableCompFactor = 1;
+        if (ampRes == SBR_AMP_RES_1_5)
+        {
+            hcb_t = bookSbrEnvBalance10T;
+            hcb_f = bookSbrEnvBalance10F;
+        }
+        else
+        {
+            hcb_t = bookSbrEnvBalance11T;
+            hcb_f = bookSbrEnvBalance11F;
+        }
+    }
+    else
+    {
+        envDataTableCompFactor = 0;
+        if (ampRes == SBR_AMP_RES_1_5)
+        {
+            hcb_t = bookSbrEnvLevel10T;
+            hcb_f = bookSbrEnvLevel10F;
+        }
+        else
+        {
+            hcb_t = bookSbrEnvLevel11T;
+            hcb_f = bookSbrEnvLevel11F;
+        }
+    }
+
+    /*
+     *    Now read raw envelope data
+     */
+    for (j = 0; j < h_frame_data->frameInfo[0]; j++)
+    {
+        if (h_frame_data->domain_vec1[j] == FREQ)
+        {
+            if (coupling == COUPLING_BAL)
+            {
+                tmp = buf_getbits(hBitBuf, start_bits_balance);
+                h_frame_data->iEnvelope_man[offset] = tmp << envDataTableCompFactor;
+            }
+            else
+            {
+                tmp = buf_getbits(hBitBuf, start_bits);
+                h_frame_data->iEnvelope_man[offset] = tmp;
+            }
+        }
+
+        for (i = (1 - h_frame_data->domain_vec1[j]); i < no_band[j]; i++)
+        {
+
+            if (h_frame_data->domain_vec1[j] == FREQ)
+            {
+                delta = sbr_decode_huff_cw(hcb_f, hBitBuf);
+            }
+            else
+            {
+                delta = sbr_decode_huff_cw(hcb_t, hBitBuf);
+            }
+
+            h_frame_data->iEnvelope_man[offset + i] = delta << envDataTableCompFactor;
+        }
+        offset += no_band[j];
+    }
+
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_envelope.h b/media/libstagefright/codecs/aacdec/sbr_get_envelope.h
new file mode 100644
index 0000000..b7a266a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_envelope.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_envelope.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_ENVELOPE_H
+#define SBR_GET_ENVELOPE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void sbr_get_envelope(SBR_FRAME_DATA * h_frame_data,
+    BIT_BUFFER  * hBitBuf);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_header_data.cpp b/media/libstagefright/codecs/aacdec/sbr_get_header_data.cpp
new file mode 100644
index 0000000..42789ae
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_header_data.cpp
@@ -0,0 +1,221 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_header_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     h_sbr_header - handle to struct SBR_HEADER_DATA
+                hBitBuf      - handle to struct BIT_BUFFER
+                id_sbr       - SBR_ELEMENT_ID
+
+ Return:        error status - 0 if ok
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Reads header data from bitstream
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_header_data.h"
+#include    "sbr_constants.h"
+#include    "buf_getbits.h"
+#include    "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+SBR_HEADER_STATUS sbr_get_header_data(SBR_HEADER_DATA   * h_sbr_header,
+                                      BIT_BUFFER          * hBitBuf,
+                                      SBR_SYNC_STATE     syncState)
+{
+    SBR_HEADER_DATA lastHeader;
+    Int32 headerExtra1, headerExtra2;
+
+
+    /* Copy header to temporary header */
+    if (syncState == SBR_ACTIVE)
+    {
+        pv_memcpy(&lastHeader, h_sbr_header, sizeof(SBR_HEADER_DATA));
+    }
+    else
+    {
+        pv_memset((void *)&lastHeader, 0, sizeof(SBR_HEADER_DATA));
+    }
+
+
+    /* Read new header from bitstream */
+    h_sbr_header->ampResolution   = buf_getbits(hBitBuf, SI_SBR_AMP_RES_BITS);
+    h_sbr_header->startFreq       = buf_getbits(hBitBuf, SI_SBR_START_FREQ_BITS);
+    h_sbr_header->stopFreq        = buf_getbits(hBitBuf, SI_SBR_STOP_FREQ_BITS);
+    h_sbr_header->xover_band      = buf_getbits(hBitBuf, SI_SBR_XOVER_BAND_BITS);
+
+    buf_getbits(hBitBuf, SI_SBR_RESERVED_BITS_HDR);
+
+    headerExtra1    = buf_getbits(hBitBuf, SI_SBR_HEADER_EXTRA_1_BITS);
+    headerExtra2    = buf_getbits(hBitBuf, SI_SBR_HEADER_EXTRA_2_BITS);
+
+    /* handle extra header information */
+    if (headerExtra1)
+    {
+        h_sbr_header->freqScale   = buf_getbits(hBitBuf, SI_SBR_FREQ_SCALE_BITS);
+        h_sbr_header->alterScale  = buf_getbits(hBitBuf, SI_SBR_ALTER_SCALE_BITS);
+        h_sbr_header->noise_bands = buf_getbits(hBitBuf, SI_SBR_NOISE_BANDS_BITS);
+    }
+    else
+    { /* Set default values.*/
+        h_sbr_header->freqScale   = SBR_FREQ_SCALE_DEFAULT;
+        h_sbr_header->alterScale  = SBR_ALTER_SCALE_DEFAULT;
+        h_sbr_header->noise_bands = SBR_NOISE_BANDS_DEFAULT;
+    }
+
+
+    if (headerExtra2)
+    {
+        h_sbr_header->limiterBands    = buf_getbits(hBitBuf, SI_SBR_LIMITER_BANDS_BITS);
+        h_sbr_header->limiterGains    = buf_getbits(hBitBuf, SI_SBR_LIMITER_GAINS_BITS);
+        h_sbr_header->interpolFreq    = buf_getbits(hBitBuf, SI_SBR_INTERPOL_FREQ_BITS);
+        h_sbr_header->smoothingLength = buf_getbits(hBitBuf, SI_SBR_SMOOTHING_LENGTH_BITS);
+    }
+    else
+    { /* Set default values.*/
+        h_sbr_header->limiterBands    = SBR_LIMITER_BANDS_DEFAULT;
+        h_sbr_header->limiterGains    = SBR_LIMITER_GAINS_DEFAULT;
+        h_sbr_header->interpolFreq    = SBR_INTERPOL_FREQ_DEFAULT;
+        h_sbr_header->smoothingLength = SBR_SMOOTHING_LENGTH_DEFAULT;
+    }
+
+    if (syncState == SBR_ACTIVE)
+    {
+        h_sbr_header->status = HEADER_OK;
+
+        /* look for new settings */
+        if (lastHeader.startFreq   != h_sbr_header->startFreq   ||
+                lastHeader.stopFreq    != h_sbr_header->stopFreq    ||
+                lastHeader.xover_band  != h_sbr_header->xover_band  ||
+                lastHeader.freqScale   != h_sbr_header->freqScale   ||
+                lastHeader.alterScale  != h_sbr_header->alterScale  ||
+                lastHeader.noise_bands != h_sbr_header->noise_bands)
+        {
+            h_sbr_header->status = HEADER_RESET;
+        }
+    }
+    else
+    {
+        h_sbr_header->status = HEADER_RESET;
+    }
+
+    return h_sbr_header->status;
+}
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_header_data.h b/media/libstagefright/codecs/aacdec/sbr_get_header_data.h
new file mode 100644
index 0000000..7bfb272
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_header_data.h
@@ -0,0 +1,89 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_header_data.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_HEADER_DATA_H
+#define SBR_GET_HEADER_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_header_data.h"
+#include    "e_sbr_element_id.h"
+#include    "e_sbr_sync_state.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+SBR_HEADER_STATUS sbr_get_header_data(SBR_HEADER_DATA   *h_sbr_header,
+                                      BIT_BUFFER  * hBitBuf,
+                                      SBR_SYNC_STATE     syncState);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.cpp b/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.cpp
new file mode 100644
index 0000000..8d86158
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.cpp
@@ -0,0 +1,218 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_noise_floor_data.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     h_frame_data - handle to struct SBR_FRAME_DATA
+                hBitBuf      - handle to struct BIT_BUF
+
+ Return:        void
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Reads noise-floor-level data from bitstream
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_get_noise_floor_data.h"
+#include    "e_coupling_mode.h"
+#include    "buf_getbits.h"
+#include    "sbr_code_book_envlevel.h"
+#include    "s_huffman.h"
+#include    "sbr_decode_huff_cw.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 sbr_get_noise_floor_data(SBR_FRAME_DATA * h_frame_data,
+                              BIT_BUFFER * hBitBuf)
+{
+    Int32 i;
+    Int32 j;
+    Int32 k;
+    Int32 tmp;
+    Int32 delta;
+    Int32 noNoiseBands = h_frame_data->nNfb;
+    Int32 envDataTableCompFactor;
+
+    COUPLING_MODE coupling = h_frame_data->coupling;
+
+    SbrHuffman hcb_noiseF;
+    SbrHuffman hcb_noise;
+
+
+    if (coupling == COUPLING_BAL)
+    {
+        hcb_noise  = bookSbrNoiseBalance11T;
+        hcb_noiseF = bookSbrEnvBalance11F;  /* "bookSbrNoiseBalance11F" */
+        envDataTableCompFactor = 1;
+    }
+    else
+    {
+        hcb_noise  = bookSbrNoiseLevel11T;
+        hcb_noiseF = bookSbrEnvLevel11F;  /* "bookSbrNoiseLevel11F" */
+        envDataTableCompFactor = 0;
+    }
+
+    /*
+     *  Calculate number of values alltogether
+     */
+    h_frame_data->nNoiseFactors = h_frame_data->frameInfo[((h_frame_data->frameInfo[0]) << 1) + 3] * noNoiseBands;
+
+
+    for (i = 0; i < h_frame_data->nNoiseFloorEnvelopes; i++)
+    {
+        k = i * noNoiseBands;
+        if (h_frame_data->domain_vec2[i] == FREQ)
+        {
+            if (coupling == COUPLING_BAL)
+            {
+                tmp = buf_getbits(hBitBuf, SI_SBR_START_NOISE_BITS_BALANCE_AMP_RES_3_0) << 1;  /*  max. 62  */
+                h_frame_data->sbrNoiseFloorLevel_man[k] = tmp;
+                h_frame_data->sbrNoiseFloorLevel_exp[k] =   0;
+            }
+            else
+            {
+                tmp = buf_getbits(hBitBuf, SI_SBR_START_NOISE_BITS_AMP_RES_3_0);  /*  max. 31  */
+                h_frame_data->sbrNoiseFloorLevel_man[k] = tmp;
+                h_frame_data->sbrNoiseFloorLevel_exp[k] =   0;
+            }
+
+            for (j = 1; j < noNoiseBands; j++)
+            {
+                delta = sbr_decode_huff_cw(hcb_noiseF, hBitBuf); /*
+                                                                  *  -31 < delta < 31
+                                                                  *  -24 < delta < 24   COUPLING_BAL (incl. <<1)
+                                                                  */
+                h_frame_data->sbrNoiseFloorLevel_man[k+j] = delta << envDataTableCompFactor;
+                h_frame_data->sbrNoiseFloorLevel_exp[k+j] =   0;
+            }
+        }
+        else
+        {
+            for (j = 0; j < noNoiseBands; j++)
+            {
+                delta = sbr_decode_huff_cw(hcb_noise, hBitBuf);  /*
+                                                                  *  -31 < delta < 31
+                                                                  *  -24 < delta < 24   COUPLING_BAL (incl. <<1)
+                                                                  */
+                h_frame_data->sbrNoiseFloorLevel_man[k+j] = delta << envDataTableCompFactor;
+                h_frame_data->sbrNoiseFloorLevel_exp[k+j] =   0;
+            }
+        }
+    }
+}
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.h b/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.h
new file mode 100644
index 0000000..e61abda
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_noise_floor_data.h
@@ -0,0 +1,94 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_noise_floor_data.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_NOISE_FLOOR_DATA_H
+#define SBR_GET_NOISE_FLOOR_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void sbr_get_noise_floor_data(SBR_FRAME_DATA * h_frame_data,
+    BIT_BUFFER * hBitBuf);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_sce.cpp b/media/libstagefright/codecs/aacdec/sbr_get_sce.cpp
new file mode 100644
index 0000000..ba514f4
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_sce.cpp
@@ -0,0 +1,202 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_sce.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Arguments:     hFrameData - handle to struct SBR_FRAME_DATA
+                hBitBuf    - handle to struct BIT_BUF
+
+ Return:        SbrFrameOK
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+
+#include    "sbr_get_sce.h"
+#include    "sbr_get_additional_data.h"
+#include    "sbr_extract_extended_data.h"
+#include    "buf_getbits.h"
+#include    "sbr_get_envelope.h"
+#include    "sbr_get_noise_floor_data.h"
+#include    "extractframeinfo.h"
+#include    "sbr_get_dir_control_data.h"
+#include    "e_invf_mode.h"
+#include    "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_get_sce(SBR_FRAME_DATA * hFrameData,
+                      BIT_BUFFER * hBitBuf
+#ifdef PARAMETRICSTEREO
+                      , HANDLE_PS_DEC hParametricStereoDec
+#endif
+                     )
+{
+    Int32 i;
+    Int32 bits;
+    SBR_ERROR err =  SBRDEC_OK;
+
+    /* reserved bits */
+    bits = buf_getbits(hBitBuf, SI_SBR_RESERVED_PRESENT);
+
+    if (bits)
+    {
+        buf_getbits(hBitBuf, SI_SBR_RESERVED_BITS_DATA);
+    }
+
+    /* side info */
+    err = extractFrameInfo(hBitBuf, hFrameData);
+
+    if (err != SBRDEC_OK)
+    {
+        return err;
+    }
+
+
+    sbr_get_dir_control_data(hFrameData, hBitBuf);
+
+    for (i = 0; i < hFrameData->nNfb; i++)
+    {
+        hFrameData->sbr_invf_mode_prev[i] = hFrameData->sbr_invf_mode[i];
+        hFrameData->sbr_invf_mode[i] =
+            (INVF_MODE) buf_getbits(hBitBuf, SI_SBR_INVF_MODE_BITS);
+    }
+
+
+    /* raw data */
+    sbr_get_envelope(hFrameData, hBitBuf);
+
+    sbr_get_noise_floor_data(hFrameData, hBitBuf);
+
+    pv_memset((void *)hFrameData->addHarmonics,
+              0,
+              hFrameData->nSfb[HI]*sizeof(Int32));
+
+    sbr_get_additional_data(hFrameData, hBitBuf);
+
+    sbr_extract_extended_data(hBitBuf
+#ifdef PARAMETRICSTEREO
+                              , hParametricStereoDec
+#endif
+                             );
+
+    hFrameData->coupling = COUPLING_OFF;
+
+    return SBRDEC_OK;
+
+}
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/sbr_get_sce.h b/media/libstagefright/codecs/aacdec/sbr_get_sce.h
new file mode 100644
index 0000000..36adb04
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_get_sce.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_get_sce.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_GET_SCE_H
+#define SBR_GET_SCE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_bit_buffer.h"
+#include    "s_sbr_frame_data.h"
+#include    "e_sbr_error.h"
+
+#ifdef PARAMETRICSTEREO
+#include    "s_ps_dec.h"
+#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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    SBR_ERROR sbr_get_sce(SBR_FRAME_DATA * hFrameData,
+    BIT_BUFFER * hBitBuf
+#ifdef PARAMETRICSTEREO
+    , HANDLE_PS_DEC hParametricStereoDec
+#endif
+                         );
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.cpp b/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.cpp
new file mode 100644
index 0000000..833ace3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.cpp
@@ -0,0 +1,214 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_inv_filt_levelemphasis.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_inv_filt_levelemphasis.h"
+#include    "sbr_generate_high_freq.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
+----------------------------------------------------------------------------*/
+
+
+#include "pv_audio_type_defs.h"
+#include "fxp_mul32.h"
+
+#define R_SHIFT     29
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+
+const Int32 InvFiltFactors[5] = {Qfmt(0.00f),    /* OFF_LEVEL */
+                                 Qfmt(0.60f),     /* TRANSITION_LEVEL */
+                                 Qfmt(0.75f),     /* LOW_LEVEL */
+                                 Qfmt(0.90f),     /* MID_LEVEL */
+                                 Qfmt(0.98f)
+                                };    /* HIGH_LEVEL */
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void sbr_inv_filt_levelemphasis(INVF_MODE *invFiltMode,
+                                INVF_MODE *prevInvFiltMode,
+                                Int32 nNfb,
+                                Int32  BwVector[MAX_NUM_PATCHES],
+                                Int32  BwVectorOld[MAX_NUM_PATCHES])
+{
+    Int32 i;
+    Int32 j;
+    Int32 tmp;
+
+    for (i = 0; i < nNfb; i++)
+    {
+        switch (invFiltMode[i])
+        {
+            case INVF_LOW_LEVEL:
+                if (prevInvFiltMode[i] == INVF_OFF)
+                {
+                    j = 1;
+                }
+                else
+                {
+                    j = 2;
+                }
+                break;
+
+            case INVF_MID_LEVEL:
+                j = 3;
+                break;
+
+            case INVF_HIGH_LEVEL:
+                j = 4;
+                break;
+
+            default:
+                if (prevInvFiltMode[i] == INVF_LOW_LEVEL)
+                {
+                    j = 1;
+                }
+                else
+                {
+                    j = 0;
+                }
+        }
+
+        tmp  =  InvFiltFactors[j];
+
+        if (tmp < BwVectorOld[i])
+        {
+            tmp = ((tmp << 1) + tmp + BwVectorOld[i]) >> 2;
+        }
+        else
+        {
+            tmp =  fxp_mul32_Q29(Qfmt(0.90625f), tmp);
+            tmp =  fxp_mac32_Q29(Qfmt(0.09375f), BwVectorOld[i], tmp);
+        }
+
+        if (tmp < Qfmt(0.015625F))
+        {
+            tmp = 0;
+        }
+
+        if (tmp >= Qfmt(0.99609375f))
+        {
+            tmp = Qfmt(0.99609375f);
+        }
+
+        BwVector[i] = tmp;
+    }
+}
+
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.h b/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.h
new file mode 100644
index 0000000..586214c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_inv_filt_levelemphasis.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_inv_filt_levelemphasis.h
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_INV_FILT_LEVELEMPHASIS_H
+#define SBR_INV_FILT_LEVELEMPHASIS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "e_invf_mode.h"
+#include    "sbr_generate_high_freq.h"
+
+
+/*----------------------------------------------------------------------------
+; 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 sbr_inv_filt_levelemphasis(INVF_MODE *invFiltMode,
+                                INVF_MODE *prevInvFiltMode,
+                                Int32  nNfb,
+                                Int32  BwVector[MAX_NUM_PATCHES],
+                                Int32  BwVectorOld[MAX_NUM_PATCHES]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_open.cpp b/media/libstagefright/codecs/aacdec/sbr_open.cpp
new file mode 100644
index 0000000..868819a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_open.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_open.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_open.h"
+#include    "s_sbr_header_data.h"
+#include    "init_sbr_dec.h"
+#include    "e_sbr_error.h"
+#include    "aac_mem_funcs.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
+----------------------------------------------------------------------------*/
+const SBR_HEADER_DATA defaultHeader =
+{
+    HEADER_NOT_INITIALIZED,   /* status */
+    MASTER_RESET,             /* masterStatus */
+    0,                        /* crcEnable */
+    UP_BY_2,                  /* sampleRateMode */
+    SBR_AMP_RES_3_0,          /* ampResolution */
+    5,                        /* startFreq */
+    0,                        /* stopFreq */
+    0,                        /* xover_band */
+    SBR_FREQ_SCALE_DEFAULT,   /* freqScale */
+    SBR_ALTER_SCALE_DEFAULT,  /* alterScale */
+    SBR_NOISE_BANDS_DEFAULT,  /* noise_bands */
+    0,                        /* noNoiseBands */
+    SBR_LIMITER_BANDS_DEFAULT,
+    SBR_LIMITER_GAINS_DEFAULT,
+    SBR_INTERPOL_FREQ_DEFAULT,
+    SBR_SMOOTHING_LENGTH_DEFAULT
+};
+
+/*----------------------------------------------------------------------------
+; 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 sbr_open(Int32 sampleRate,
+              SBR_DEC *sbrDec,
+              SBRDECODER_DATA * self,
+              bool bDownSampledSbr)
+
+{
+    Int16 i ;
+
+    SBR_CHANNEL *SbrChannel;
+
+
+    SbrChannel = self->SbrChannel;
+
+    for (i = 0; i < MAX_NUM_CHANNELS; i++)
+    {
+        pv_memset((void *)&(SbrChannel[i]),
+                  0,
+                  sizeof(SBR_CHANNEL));
+
+        /* init a default header such that we can at least do upsampling later */
+
+        pv_memcpy(&(SbrChannel[i].frameData.sbr_header),
+                  &defaultHeader,
+                  sizeof(SBR_HEADER_DATA));
+
+        /* should be handled by sample rate mode bit */
+        if (sampleRate > 24000 || bDownSampledSbr)
+        {
+            SbrChannel[i].frameData.sbr_header.sampleRateMode = SINGLE_RATE;
+        }
+
+
+        SbrChannel[i].outFrameSize =
+            init_sbr_dec(sampleRate,
+                         self->SbrChannel[0].frameData.sbr_header.sampleRateMode,
+                         sbrDec,
+                         &(SbrChannel[i].frameData));
+
+        SbrChannel[i].syncState     = UPSAMPLING;
+
+        SbrChannel[i].frameData.sUp = 1;        /* reset mode */
+    }
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_open.h b/media/libstagefright/codecs/aacdec/sbr_open.h
new file mode 100644
index 0000000..8d17ffa
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_open.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_open.h
+ Funtions:
+    get_dse
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_OPEN_H
+#define SBR_OPEN_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_sbr_channel.h"
+#include "sbr_dec.h"
+/*----------------------------------------------------------------------------
+; 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 sbr_open(Int32 sampleRate,
+              SBR_DEC *sbrDec,
+              SBRDECODER_DATA * self,
+              bool bDownSampledSbr);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_read_data.cpp b/media/libstagefright/codecs/aacdec/sbr_read_data.cpp
new file mode 100644
index 0000000..2220fce
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_read_data.cpp
@@ -0,0 +1,324 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_read_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    INPUT
+
+    SBRDECODER self,
+    SBRBITSTREAM * stream,
+    float *timeData,
+    int numChannels
+
+    OUTPUT
+
+    errorCode, noError if successful
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        sbr decoder processing, set up SBR decoder phase 2 in case of
+        different cotrol data
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_read_data.h"
+#include    "s_bit_buffer.h"
+#include    "buf_getbits.h"
+#include    "sbr_get_sce.h"
+#include    "sbr_get_cpe.h"
+#include    "sbr_reset_dec.h"
+#include    "sbr_get_header_data.h"
+#include    "sbr_crc_check.h"
+#include    "aac_mem_funcs.h"
+
+
+#include    "init_sbr_dec.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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_read_data(SBRDECODER_DATA * self,
+                        SBR_DEC * sbrDec,
+                        SBRBITSTREAM *stream)
+{
+    SBR_ERROR sbr_err =  SBRDEC_OK;
+    int32_t SbrFrameOK = 1;
+    int32_t sbrCRCAlwaysOn = 0;
+
+    UInt32 bs_header_flag = 0;
+
+    SBR_HEADER_STATUS headerStatus = HEADER_OK;
+
+    SBR_CHANNEL *SbrChannel = self->SbrChannel;
+
+    int32_t zeropadding_bits;
+
+    BIT_BUFFER bitBuf ;
+
+    /*
+     *  evaluate Bitstream
+     */
+
+    bitBuf.buffer_word    = 0;
+    bitBuf.buffered_bits  = 0;
+    bitBuf.nrBitsRead     = 0;
+
+    bitBuf.char_ptr  =  stream->sbrElement[0].Data;
+    bitBuf.bufferLen = (stream->sbrElement[0].Payload) << 3;
+
+
+    /*
+     *  we have to skip a nibble because the first element of Data only
+     *  contains a nibble of data !
+     */
+    buf_getbits(&bitBuf, LEN_NIBBLE);
+
+    if ((stream->sbrElement[0].ExtensionType == SBR_EXTENSION_CRC) ||
+            sbrCRCAlwaysOn)
+    {
+        int32_t CRCLen = ((stream->sbrElement[0].Payload - 1) << 3) + 4 - SI_SBR_CRC_BITS;
+        SbrFrameOK = sbr_crc_check(&bitBuf, CRCLen);
+    }
+
+
+    if (SbrFrameOK)
+    {
+        /*
+         *  The sbr data seems ok, if the header flag is set we read the header
+         *  and check if vital parameters have changed since the previous frame.
+         *  If the syncState equals UPSAMPLING, the SBR Tool has not been
+         *  initialised by SBR header data, and can only do upsampling
+         */
+
+        bs_header_flag = buf_getbits(&bitBuf, 1);  /* read Header flag */
+
+        if (bs_header_flag)
+        {
+            /*
+             *  If syncState == SBR_ACTIVE, it means that we've had a SBR header
+             *  before, and we will compare with the previous header to see if a
+             *  reset is required. If the syncState equals UPSAMPLING this means
+             *  that the SBR-Tool so far is only initialised to do upsampling
+             *  and hence we need to do a reset, and initialise the system
+             *  according to the present header.
+             */
+
+            headerStatus = sbr_get_header_data(&(SbrChannel[0].frameData.sbr_header),
+                                               &bitBuf,
+                                               SbrChannel[0].syncState);
+        }     /* if (bs_header_flag) */
+
+
+        switch (stream->sbrElement[0].ElementID)
+        {
+            case SBR_ID_SCE :
+
+                /* change of control data, reset decoder */
+                if (headerStatus == HEADER_RESET)
+                {
+                    sbr_err = sbr_reset_dec(&(SbrChannel[0].frameData),
+                                            sbrDec,
+                                            self->SbrChannel[0].frameData.sbr_header.sampleRateMode);
+
+                    if (sbr_err != SBRDEC_OK)
+                    {
+                        break;
+                    }
+                    /*
+                     * At this point we have a header and the system has been reset,
+                     * hence syncState from now on will be SBR_ACTIVE.
+                     */
+                    SbrChannel[0].syncState     = SBR_ACTIVE;
+                }
+
+                if ((SbrChannel[0].syncState == SBR_ACTIVE))
+                {
+                    sbr_err = sbr_get_sce(&(SbrChannel[0].frameData),
+                                          &bitBuf
+#ifdef PARAMETRICSTEREO
+                                          , self->hParametricStereoDec
+#endif
+                                         );
+
+                    if (sbr_err != SBRDEC_OK)
+                    {
+                        break;
+                    }
+                }
+
+                break;
+
+            case SBR_ID_CPE :
+
+                if (bs_header_flag)
+                {
+                    pv_memcpy(&(SbrChannel[1].frameData.sbr_header),
+                              &(SbrChannel[0].frameData.sbr_header),
+                              sizeof(SBR_HEADER_DATA));
+                }
+
+                /* change of control data, reset decoder */
+                if (headerStatus == HEADER_RESET)
+                {
+                    for (int32_t lr = 0 ; lr < 2 ; lr++)
+                    {
+                        sbr_err = sbr_reset_dec(&(SbrChannel[lr].frameData),
+                                                sbrDec,
+                                                self->SbrChannel[0].frameData.sbr_header.sampleRateMode);
+
+                        if (sbr_err != SBRDEC_OK)
+                        {
+                            break;
+                        }
+
+                        SbrChannel[lr].syncState = SBR_ACTIVE;
+                    }
+                }
+
+                if (SbrChannel[0].syncState == SBR_ACTIVE)
+                {
+                    sbr_err = sbr_get_cpe(&(SbrChannel[0].frameData),
+                                          &(SbrChannel[1].frameData),
+                                          &bitBuf);
+
+                    if (sbr_err != SBRDEC_OK)
+                    {
+                        break;
+                    }
+
+                }
+                break;
+
+            default:
+                sbr_err = SBRDEC_ILLEGAL_PLUS_ELE_ID;
+                break;
+        }
+
+    }           /* if (SbrFrameOK) */
+
+    /*
+     *  Check that the bits read did not go beyond SBR frame boundaries
+     */
+
+    zeropadding_bits = (8 - (bitBuf.nrBitsRead & 0x7)) & 0x7;
+
+    if ((bitBuf.nrBitsRead + zeropadding_bits)  > bitBuf.bufferLen)
+    {
+        sbr_err = SBRDEC_INVALID_BITSTREAM;
+    }
+
+    return sbr_err;
+}
+
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_read_data.h b/media/libstagefright/codecs/aacdec/sbr_read_data.h
new file mode 100644
index 0000000..74cf5b9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_read_data.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_read_data.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_READ_DATA
+#define SBR_READ_DATA
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "e_sbr_error.h"
+#include "s_sbr_channel.h"
+#include "s_sbrbitstream.h"
+#include "sbr_dec.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    SBR_ERROR sbr_read_data(SBRDECODER_DATA * self,
+    SBR_DEC * sbrDec,
+    SBRBITSTREAM *stream);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.cpp b/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.cpp
new file mode 100644
index 0000000..487496f
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.cpp
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_requantize_envelope_data.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_constants.h"
+#include    "sbr_requantize_envelope_data.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define R_SHIFT     30
+#define Qfmt(x)   (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+/*----------------------------------------------------------------------------
+; 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 sbr_requantize_envelope_data(SBR_FRAME_DATA * hFrameData)
+
+{
+    Int32 i;
+
+
+    Int32  nScaleFactors      =  hFrameData->nScaleFactors;
+    Int32  nNoiseFactors      =  hFrameData->nNoiseFactors;
+    Int32  ampRes             =  hFrameData->ampRes;
+    Int32 *iEnvelope_man      =  hFrameData->iEnvelope_man;
+    Int32 *iEnvelope_exp      =  hFrameData->iEnvelope_exp;
+    Int32 *sbrNoiseFloorLevel_man = hFrameData->sbrNoiseFloorLevel_man;
+    Int32 *sbrNoiseFloorLevel_exp = hFrameData->sbrNoiseFloorLevel_exp;
+
+    /*
+     *  ampRes could be 0 (resolution step = 1.5 dB) or
+     *                  1 (resolution step = 3 dB)
+     */
+    if (ampRes)
+    {
+        /*  iEnvelope[i] always positive  6 bits max */
+        for (i = 0; i < nScaleFactors; i++)
+        {
+
+            iEnvelope_exp[i] = iEnvelope_man[i] + 6;
+            iEnvelope_man[i] = Qfmt(1.000F);
+        }
+    }
+    else
+    {
+        /*  iEnvelope[i] always positive  7 bits max */
+        for (i = 0; i < nScaleFactors; i++)
+        {
+            iEnvelope_exp[i] = (iEnvelope_man[i] >> 1) + 6;
+            if (iEnvelope_man[i] & 0x1)   /*  odd */
+            {
+                iEnvelope_man[i] = Qfmt(1.41421356237310F);
+            }
+            else
+            {
+                iEnvelope_man[i] = Qfmt(1.000F);
+            }
+        }
+
+    }
+    for (i = 0; i < nNoiseFactors; i++)
+    {
+        /*  sbrNoiseFloorLevel[i] varies from -31 to 31 if no coupling is used */
+
+        sbrNoiseFloorLevel_exp[i] = NOISE_FLOOR_OFFSET - sbrNoiseFloorLevel_man[i];
+        sbrNoiseFloorLevel_man[i] = 0x40000000;
+    }
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.h b/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.h
new file mode 100644
index 0000000..2113586
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_requantize_envelope_data.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_requantize_envelope_data.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_REQUANTIZE_ENVELOPE_DATA_H
+#define SBR_REQUANTIZE_ENVELOPE_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sbr_frame_data.h"
+
+/*----------------------------------------------------------------------------
+; 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 sbr_requantize_envelope_data(SBR_FRAME_DATA * hFrameData);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_reset_dec.cpp b/media/libstagefright/codecs/aacdec/sbr_reset_dec.cpp
new file mode 100644
index 0000000..810a34a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_reset_dec.cpp
@@ -0,0 +1,269 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_reset_dec.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    resets sbr decoder structure
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef AAC_PLUS
+
+#include    "sbr_dec.h"
+
+#include    "pv_log2.h"
+#include    "fxp_mul32.h"
+
+
+#include    "sbr_reset_dec.h"
+#include    "sbr_find_start_andstop_band.h"
+#include    "sbr_update_freq_scale.h"
+#include    "sbr_downsample_lo_res.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
+----------------------------------------------------------------------------*/
+
+SBR_ERROR sbr_reset_dec(SBR_FRAME_DATA * hFrameData,
+                        SBR_DEC * sbrDec,
+                        Int32 upsampleFac)
+{
+
+    SBR_ERROR err = SBRDEC_OK;
+    Int lsbM;
+    Int lsb;
+    Int usb;
+    Int32 i;
+    Int32 tmp_q1;
+
+    SBR_HEADER_DATA *headerData  = &(hFrameData->sbr_header);
+    Int32           samplingFreq = sbrDec->outSampleRate;
+
+    hFrameData->reset_flag = 1;
+
+    /*Calculate master frequency function */
+    err = sbr_find_start_andstop_band(samplingFreq,
+                                      headerData->startFreq,
+                                      headerData->stopFreq,
+                                      &lsbM,
+                                      &usb);
+
+    if (err != SBRDEC_OK)
+    {
+        return err;
+    }
+
+    /* Calculate new v_k_master if needed */
+    if (headerData->masterStatus == MASTER_RESET)
+    {
+        sbr_update_freq_scale(sbrDec->V_k_master,
+                              &(sbrDec->Num_Master),
+                              lsbM,
+                              usb,
+                              headerData->freqScale,
+                              headerData->alterScale,
+                              0);
+
+    }
+
+    /*Derive Hiresolution from master frequency function*/
+
+    sbrDec->NSfb[HI] = sbrDec->Num_Master - headerData->xover_band;
+
+    for (i = headerData->xover_band; i <= sbrDec->Num_Master; i++)
+    {
+        sbrDec->FreqBandTable[HI][i-headerData->xover_band] = (Int)sbrDec->V_k_master[i];
+    }
+
+
+    if ((sbrDec->NSfb[HI] & 0x01) == 0) /* if even number of hires bands */
+    {
+
+        sbrDec->NSfb[LO] = sbrDec->NSfb[HI] >> 1;
+        /* Use every second lo-res=hi-res[0,2,4...] */
+        for (i = 0; i <= sbrDec->NSfb[LO]; i++)
+        {
+            sbrDec->FreqBandTable[LO][i] = sbrDec->FreqBandTable[HI][(i<<1)];
+        }
+    }
+    else
+    {            /* odd number of hi-res which means xover is odd */
+
+        sbrDec->NSfb[LO] = (sbrDec->NSfb[HI] + 1) >> 1;
+        /* Use lo-res=hi-res[0,1,3,5 ...] */
+        sbrDec->FreqBandTable[LO][0] = sbrDec->FreqBandTable[HI][0];
+        for (i = 1; i <= sbrDec->NSfb[LO]; i++)
+        {
+            sbrDec->FreqBandTable[LO][i] = sbrDec->FreqBandTable[HI][(i<<1)-1];
+        }
+
+    }
+
+    lsb = sbrDec->FreqBandTable[LOW_RES][0];
+    usb = sbrDec->FreqBandTable[LOW_RES][sbrDec->NSfb[LOW_RES]];
+
+    sbrDec->lowSubband  = lsb;
+    sbrDec->highSubband = usb;
+    sbrDec->noSubbands  = usb - lsb;
+
+    if ((lsb > 32) || (sbrDec->noSubbands <= 0))
+    {
+        return SBRDEC_ILLEGAL_SCFACTORS;   /* invalid bands */
+    }
+
+    /* Calculate number of noise bands */
+    if (headerData->noise_bands == 0)
+    {
+        sbrDec->NoNoiseBands = 1;
+    }
+    else /* Calculate number of noise bands 1,2 or 3 bands/octave */
+    {
+
+        if (! lsb)
+        {
+            return SBRDEC_ILLEGAL_SCFACTORS;   /* avoid div by 0 */
+        }
+
+        tmp_q1 = pv_log2((usb << 20) / lsb);
+
+        tmp_q1 = fxp_mul32_Q15(headerData->noise_bands, tmp_q1);
+
+        sbrDec->NoNoiseBands = (tmp_q1 + 16) >> 5;
+
+        if (sbrDec->NoNoiseBands == 0)
+        {
+            sbrDec->NoNoiseBands = 1;
+        }
+    }
+
+    headerData->noNoiseBands = sbrDec->NoNoiseBands;
+
+    /* Get noise bands */
+    sbr_downsample_lo_res(sbrDec->FreqBandTableNoise,
+                          sbrDec->NoNoiseBands,
+                          sbrDec->FreqBandTable[LO],
+                          sbrDec->NSfb[LO]);
+
+    sbrDec->sbStopCodec = sbrDec->lowSubband;
+
+    if (sbrDec->sbStopCodec > (upsampleFac << 5))
+    {
+        sbrDec->sbStopCodec = (upsampleFac << 5);
+    }
+
+    hFrameData->nSfb[LO] = sbrDec->NSfb[LO];
+    hFrameData->nSfb[HI] = sbrDec->NSfb[HI];
+    hFrameData->nNfb     = hFrameData->sbr_header.noNoiseBands;
+    hFrameData->offset   = ((hFrameData->nSfb[LO]) << 1) - hFrameData->nSfb[HI];
+
+    return (SBRDEC_OK);
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_reset_dec.h b/media/libstagefright/codecs/aacdec/sbr_reset_dec.h
new file mode 100644
index 0000000..0ff94a5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_reset_dec.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_reset_dec.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+ $Id: ct_envcalc.h,v 1.3 2002/11/29 16:11:49 kaehleof Exp $
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_RESET_DEC_H
+#define SBR_RESET_DEC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "s_sbr_frame_data.h"
+#include    "sbr_dec.h"
+#include    "e_sbr_error.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+SBR_ERROR sbr_reset_dec(SBR_FRAME_DATA * hFrameData,
+                        SBR_DEC * sbrDec,
+                        Int32 upsampleFac);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.cpp b/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.cpp
new file mode 100644
index 0000000..18bd5d9
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.cpp
@@ -0,0 +1,364 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_update_freq_scale.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+SC 29 Software Copyright Licencing Disclaimer:
+
+This software module was originally developed by
+  Coding Technologies
+
+and edited by
+  -
+
+in the course of development of the ISO/IEC 13818-7 and ISO/IEC 14496-3
+standards for reference purposes and its performance may not have been
+optimized. This software module is an implementation of one or more tools as
+specified by the ISO/IEC 13818-7 and ISO/IEC 14496-3 standards.
+ISO/IEC gives users free license to this software module or modifications
+thereof for use in products claiming conformance to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International
+Standards. ISO/IEC gives users the same free license to this software module or
+modifications thereof for research purposes and further ISO/IEC standardisation.
+Those intending to use this software module in products are advised that its
+use may infringe existing patents. ISO/IEC have no liability for use of this
+software module or modifications thereof. Copyright is not released for
+products that do not conform to audiovisual and image-coding related ITU
+Recommendations and/or ISO/IEC International Standards.
+The original developer retains full right to modify and use the code for its
+own purpose, assign or donate the code to a third party and to inhibit third
+parties from using the code for products that do not conform to audiovisual and
+image-coding related ITU Recommendations and/or ISO/IEC International Standards.
+This copyright notice must be included in all copies or derivative works.
+Copyright (c) ISO/IEC 2002.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include    "sbr_update_freq_scale.h"
+#include    "shellsort.h"
+
+#include    "pv_pow2.h"
+#include    "pv_log2.h"
+
+#include "fxp_mul32.h"
+#define R_SHIFT     30
+#define Q_fmt(x)    (Int32)(x*((Int32)1<<R_SHIFT) + (x>=0?0.5F:-0.5F))
+#define Q28fmt(x)   (Int32)(x*((Int32)1<<28) + (x>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; 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 sbr_update_freq_scale(Int32 * v_k_master,
+                           Int32 *h_num_bands,
+                           const Int32 lsbM,
+                           const Int32 usb,
+                           const Int32 freqScale,
+                           const Int32 alterScale,
+                           const Int32 channelOffset)
+{
+    Int32 i;
+    Int32 numBands = 0;
+    Int32 numBands2;
+    Int32 tmp_q1;
+
+    if (freqScale > 0) /*Bark mode*/
+    {
+        Int32 reg;
+        Int32 regions;
+        Int32 b_p_o;
+        Int32 k[3];
+        Int32 d[MAX_SECOND_REGION];
+        Int32 d2[MAX_SECOND_REGION];
+        Int32 w[2] = {Q_fmt(1.0F), Q_fmt(1.0F)};
+
+
+        k[0] = lsbM;
+        k[1] = usb;
+        k[2] = usb;
+
+        b_p_o = (freqScale == 1)  ? 12 : 8;
+        b_p_o = (freqScale == 2)  ? 10 : b_p_o;
+
+        w[1]  = (alterScale == 0) ? Q_fmt(0.5f) : Q_fmt(0.384615384615386f);
+
+        if (usb > fxp_mul32_Q28(lsbM, Q28fmt(2.2449)))
+        {
+            regions = 2;
+            k[1] = (lsbM << 1);
+        }
+        else
+        {
+            regions = 1;
+        }
+
+        *h_num_bands = 0;
+        for (reg = 0; reg < regions; reg++)
+        {
+            if (reg == 0)
+            {
+
+                tmp_q1 = pv_log2((k[1] << 20) / k[0]);
+
+                tmp_q1 = fxp_mul32_Q15(tmp_q1, b_p_o);
+                tmp_q1 = (tmp_q1 + 32) >> 6;
+
+                numBands = tmp_q1 << 1;
+
+
+                CalcBands(d, k[0], k[1], numBands);                                    /* CalcBands => d   */
+                shellsort(d, numBands);                                              /* SortBands sort d */
+                cumSum(k[0] - channelOffset,
+                       d,
+                       numBands,
+                       (v_k_master + *h_num_bands));   /* cumsum */
+
+                *h_num_bands += numBands;                                            /* Output nr of bands */
+            }
+            else
+            {
+                tmp_q1 = pv_log2((k[reg + 1] << 20) / k[reg]);
+
+                tmp_q1 = fxp_mul32_Q30(tmp_q1, w[reg]);
+                tmp_q1 = fxp_mul32_Q15(tmp_q1, b_p_o);
+                tmp_q1 = (tmp_q1 + 16) >> 5;
+
+                numBands2 = tmp_q1 << 1;
+
+                CalcBands(d2, k[reg], k[reg+1], numBands2);                            /* CalcBands => d   */
+                shellsort(d2, numBands2);                                              /* SortBands sort d */
+                if (d[numBands-1] > d2[0])
+                {
+
+                    Int32   change = d[numBands-1] - d2[0];
+                    /* Limit the change so that the last band cannot get narrower than the first one */
+                    if (change > (d2[numBands2-1] - d2[0]) >> 1)
+                    {
+                        change = (d2[numBands2-1] - d2[0]) >> 1;
+                    }
+
+                    d2[0] += change;
+                    d2[numBands2-1] -= change;
+                    shellsort(d2, numBands2);
+
+                }
+                cumSum(k[reg] - channelOffset,
+                       d2,
+                       numBands2,
+                       v_k_master + *h_num_bands);   /* cumsum */
+
+                *h_num_bands += numBands2;                                           /* Output nr of bands */
+            }
+        }
+    }
+    else
+    {                         /* Linear mode */
+        Int32     k2_achived;
+        Int32     k2_diff;
+        Int32     diff_tot[MAX_OCTAVE + MAX_SECOND_REGION];
+        Int32     dk;
+        Int32     incr = 0;
+
+
+        if (alterScale)
+        {
+            numBands = (usb - lsbM) >> 1;
+            dk = 1;
+            k2_achived = lsbM + numBands;
+        }
+        else
+        {
+            numBands = usb - lsbM;
+            if (numBands & 0x1) /* equivalent rounding */
+            {
+                numBands--;
+            }
+            dk = 2;
+            k2_achived = lsbM + (numBands << 1);
+        }
+
+        k2_diff = usb - k2_achived;
+
+        for (i = 0; i < numBands; i++)
+        {
+            diff_tot[i] = dk;
+        }
+
+        if (k2_diff < 0)        /* If linear scale wasn't achived */
+        {
+            incr = 1;           /* and we got too large SBR area */
+            i = 0;
+        }
+
+        if (k2_diff > 0)        /* If linear scale wasn't achived */
+        {
+            incr = -1;            /* and we got too small SBR area */
+            i = numBands - 1;
+        }
+
+        /* Adjust diff vector to get spec. SBR range */
+        while (k2_diff != 0)
+        {
+            diff_tot[i] -=  incr;
+            i += incr;
+            k2_diff += incr;
+        }
+
+        cumSum(lsbM,
+               diff_tot,
+               numBands,
+               v_k_master); /* cumsum */
+
+        *h_num_bands = numBands;                      /* Output nr of bands */
+    }
+}
+
+
+void CalcBands(Int32 * diff,
+               Int32 start,
+               Int32 stop,
+               Int32 num_bands)
+{
+    Int32 i;
+    Int32 previous;
+    Int32 current;
+    Int32 tmp_q1;
+
+
+    previous = start;
+
+    for (i = 1; i <= num_bands; i++)
+    {
+        /*              float temp=(start * pow( (float)stop/start, (float)i/num_bands)); */
+
+        tmp_q1 = pv_log2((stop << 20) / start);
+
+        tmp_q1 = fxp_mul32_Q20(tmp_q1, (i << 27) / num_bands);
+        tmp_q1 = pv_pow2(tmp_q1);
+
+        tmp_q1 = fxp_mul32_Q20(tmp_q1, start);
+
+        current = (tmp_q1 + 16) >> 5;
+
+        diff[i-1] = current - previous;
+        previous  = current;
+    }
+
+}  /* End CalcBands */
+
+
+void cumSum(Int32 start_value,
+            Int32 * diff,
+            Int32 length,
+            Int32 * start_adress)
+{
+    Int32 i;
+    Int32 *pt_start_adress   = start_adress;
+    Int32 *pt_start_adress_1 = start_adress;
+    Int32 *pt_diff           = diff;
+
+    if (length > 0)  /*  avoid possible error on loop */
+    {
+        *(pt_start_adress_1++) = start_value;
+
+        for (i = (length >> 1); i != 0; i--)
+        {
+            *(pt_start_adress_1++) = *(pt_start_adress++) + *(pt_diff++);
+            *(pt_start_adress_1++) = *(pt_start_adress++) + *(pt_diff++);
+        }
+
+        if (length&1)
+        {
+            *(pt_start_adress_1) = *(pt_start_adress) + *(pt_diff);
+        }
+    }
+
+}   /* End cumSum */
+
+
+#endif
diff --git a/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.h b/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.h
new file mode 100644
index 0000000..4acf3aa
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sbr_update_freq_scale.h
@@ -0,0 +1,104 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: sbr_update_freq_scale.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SBR_UPDATE_FREQ_SCALE_H
+#define SBR_UPDATE_FREQ_SCALE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define MAX_OCTAVE        29
+#define MAX_SECOND_REGION 50
+
+/*----------------------------------------------------------------------------
+; 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 sbr_update_freq_scale(Int32 * v_k_master,
+                           Int32 *h_num_bands,
+                           const Int32 lsbM,
+                           const Int32 usb,
+                           const Int32 freqScale,
+                           const Int32 alterScale,
+                           const Int32 channelOffset);
+
+
+void CalcBands(Int32 * diff,
+               Int32 start,
+               Int32 stop,
+               Int32 num_bands);
+
+void cumSum(Int32 start_value,
+            Int32 * diff,
+            Int32 length,
+            Int32 * start_adress);
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/set_mc_info.cpp b/media/libstagefright/codecs/aacdec/set_mc_info.cpp
new file mode 100644
index 0000000..5a11941
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/set_mc_info.cpp
@@ -0,0 +1,309 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/set_mc_info.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified per review comments
+
+ Description: Change audioObjectType from Int to enum types
+
+ Who:                               Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pMC_Info    = pointer to structure MC_Info that holds information of
+                  multiple channels' configurations
+                  Data type pointer to MC_Info
+
+    objectType  = variable that holds the Audio Object Type of current
+                  file/bitstream.
+                  Data type Int
+
+    sampling_rate_idx = variable that indicates the sampling rate of the
+                        source file being encoded
+                        Data Type Int
+
+    tag         = variable that stores the element instance tag of the
+                  first (front) channel element.
+                  Data type Int
+
+    is_cpe      = variable that indicates if a Channel Pair Element (CPE)
+                  or a Single Channel Element (SCE) is used.
+                  Data type Int (maybe Boolean)
+
+    pWinSeqInfo = array of pointers that points to structures holding
+                  frame information of long and short window sequences.
+                  Data type FrameInfo
+
+    pSfbwidth128 = array that will store the scalefactor bandwidth of
+                   short window sequence frame.
+                   Data type Int array
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    return SUCCESS
+
+ Pointers and Buffers Modified:
+    pMC_Info->nch           contains the number of channels depending
+                            upon if CPE or SCE is used
+    pMC_Info->objectType    contents updated with the decoded Audio
+                            Object Type
+
+    pMC_Info->ch_info.tag   contents updated with the value of decoded
+                            channel element tag
+
+    PMC_Info->ch_info.cpe   contents updated depending upon if CPE or
+                            SCE is used
+
+    pWinSeqInfo             contents updated by calling infoinit if
+                            sampling_rate_idx is different from
+                            previous value
+
+    pSfbWidth128            contents updated by calling infoinit if
+                            sampling_rate_idx is different from
+                            previous value
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the channel configuration information. The
+ structure MC_Info stores the number of channels, channel element tag.
+ If sampling rate index is different from the previous value,
+ The frame information will be updated by calling infoinit.c
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall update the relevant information on channel configs
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+  (2) ISO/IEC 14496-3: 1999(E)
+    Subpart 1   p20 Table 1.6.3
+    Subpart 4   p30 5.1.2.1
+    Subpart 4   p31 4.5.2.1.1
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    pMC_Info->nch   = 0;
+
+    pMC_Info->profile = objectType;
+
+    IF (pMC_Info->sampling_rate_idx != sampling_rate_idx)
+    THEN
+        pMC_Info->sampling_rate_idx = sampling_rate_idx;
+
+        CALL infoinit(
+                samp_rate_idx = sampling_rate_idx
+                ppWin_seq_info= pWinSeqInfo
+                pSfbwidth128  = pSfbwidth128)
+        MODIFYING(pWinSeqInfo, pSfbwidth128)
+        RETURNING(None)
+    ENDIF
+
+    pCh_Info = &pMC_Info->ch_info[0];
+    pCh_Info->tag = tag;
+
+    IF (is_cpe == FALSE)
+    THEN
+        pCh_Info->cpe = FALSE;
+
+        pMC_Info->nch = 1;
+
+    ELSE
+        pCh_Info->cpe = TRUE;
+        pCh_Info = &pMC_Info->ch_info[1];
+        pCh_Info->tag = tag;
+        pCh_Info->cpe = TRUE;
+
+        pMC_Info->nch = 2;
+
+    ENDIF
+
+    RETURN(SUCCESS)
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "set_mc_info.h"
+#include    "huffman.h"
+#include    "s_ch_info.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
+----------------------------------------------------------------------------*/
+Int set_mc_info(
+    MC_Info     *pMC_Info,
+    const tMP4AudioObjectType audioObjectType, /* used to be profile */
+    const Int    sampling_rate_idx,
+    const Int    tag,   /* always pass-in last element's value */
+    const Int    is_cpe,
+    FrameInfo   *pWinSeqInfo[],
+    Int          sfbwidth128[]
+)
+{
+    Ch_Info *pCh_Info; /*optional task: eliminate this structure */
+
+    /*
+     *   audioObjectType and sampling rate
+     *   re-configure if new sampling rate
+     *
+     */
+    pMC_Info->audioObjectType = audioObjectType;
+
+    if (pMC_Info->sampling_rate_idx != sampling_rate_idx)
+    {
+        pMC_Info->sampling_rate_idx = sampling_rate_idx;
+
+        Int status;
+        status = infoinit(sampling_rate_idx,
+                          pWinSeqInfo,
+                          sfbwidth128);
+        if (SUCCESS != status)
+        {
+            return 1;
+        }
+    }
+
+    /*
+     * first setup values for mono config, Single Channel Element (SCE)
+     * then if stereo, go inside if(is_cpe != FALSE) branch to setup
+     * values for stereo.
+     * set the channel counts
+     * save tag for left channel
+     */
+    pMC_Info->nch   = 1 + is_cpe;
+
+    pCh_Info = &pMC_Info->ch_info[0];
+    pCh_Info->tag = tag;
+    pCh_Info->cpe = is_cpe;
+
+    /* This if branch maybe deleted in the future */
+    if (is_cpe != FALSE)
+    {
+        /* Channel Pair Element (CPE) */
+        /* right channel*/
+        pCh_Info = &pMC_Info->ch_info[1];
+        pCh_Info->cpe = TRUE;
+
+    }
+
+    return(SUCCESS); /* possible future error checkings */
+}
diff --git a/media/libstagefright/codecs/aacdec/set_mc_info.h b/media/libstagefright/codecs/aacdec/set_mc_info.h
new file mode 100644
index 0000000..8043b3b
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/set_mc_info.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/set_mc_info.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: (1) use enum type for audioObjectType (2) update revision history
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes function declaration for set_mc_info.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SET_MC_INFO_H
+#define SET_MC_INFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_mc_info.h"
+#include    "s_frameinfo.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+Int set_mc_info(
+    MC_Info     *pMC_Info,
+    const tMP4AudioObjectType objectType, /* used to be profile */
+    const Int    sampling_rate_idx,
+    const Int    tag,   /* always pass-in last element's value */
+    const Int    is_cpe,
+    FrameInfo   *pWinSeqInfo[],
+    Int          pSfbwidth128[]
+);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/sfb.cpp b/media/libstagefright/codecs/aacdec/sfb.cpp
new file mode 100644
index 0000000..f2d3a3e
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sfb.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/sfb.c
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: created to define the scalefactor bands for all sampling rates
+
+ Description: Change short to Int16
+
+ Description: Modified structure to avoid assigning addresses to constant
+              tables. This solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers
+              - Eliminated redundant vector sfb_96_128.
+              - Eliminated references to contant vector addresses in
+                samp_rate_info
+
+ Who:                              Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+ Local Stores/Buffers/Pointers Needed:
+
+ Global Stores/Buffers/Pointers Needed:
+
+ Outputs:
+
+ Pointers and Buffers Modified:
+
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function defines the scalefactor bands for all sampling rates
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3: 1999(E)
+    Subpart 4       p66     (sfb tables)
+                    p111    (4.6.10)
+                    p200    (Annex 4.B.5)
+
+------------------------------------------------------------------------------
+ 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    "pv_audio_type_defs.h"
+#include    "sfb.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
+----------------------------------------------------------------------------*/
+const Int16 sfb_96_1024[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    32, 36, 40, 44, 48, 52, 56,
+    64, 72, 80, 88, 96, 108, 120,
+    132, 144, 156, 172, 188, 212, 240,
+    276, 320, 384, 448, 512, 576, 640,
+    704, 768, 832, 896, 960, 1024
+};         /* 41 scfbands */
+
+const Int16 sfb_64_1024[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    32, 36, 40, 44, 48, 52, 56,
+    64, 72, 80, 88, 100, 112, 124,
+    140, 156, 172, 192, 216, 240, 268,
+    304, 344, 384, 424, 464, 504, 544,
+    584, 624, 664, 704, 744, 784, 824,
+    864, 904, 944, 984, 1024
+};               /* 41 scfbands 47 */
+
+const Int16 sfb_64_128[] =
+{
+    4, 8, 12, 16, 20, 24, 32,
+    40, 48, 64, 92, 128
+};                   /* 12 scfbands */
+
+
+const Int16 sfb_48_1024[] =
+{
+    4,  8,  12, 16, 20, 24, 28,
+    32, 36, 40, 48, 56, 64, 72,
+    80, 88, 96, 108,    120,    132,    144,
+    160,    176,    196,    216,    240,    264,    292,
+    320,    352,    384,    416,    448,    480,    512,
+    544,    576,    608,    640,    672,    704,    736,
+    768,    800,    832,    864,    896,    928,    1024
+};
+/* 49  scfbands*/
+
+const Int16 sfb_48_128[] =
+{
+    4,  8,  12, 16, 20, 28, 36,
+    44, 56, 68, 80, 96, 112, 128
+};         /* 14 scfbands */
+
+const Int16 sfb_32_1024[] =
+{
+    4,  8,  12, 16, 20, 24, 28,
+    32, 36, 40, 48, 56, 64, 72,
+    80, 88, 96, 108,    120,    132,    144,
+    160,    176,    196,    216,    240,    264,    292,
+    320,    352,    384,    416,    448,    480,    512,
+    544,    576,    608,    640,    672,    704,    736,
+    768,    800,    832,    864,    896,    928,    960,
+    992,    1024
+};                         /* 51 scfbands */
+
+const Int16 sfb_24_1024[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    32, 36, 40, 44, 52, 60, 68,
+    76, 84, 92, 100, 108, 116, 124,
+    136, 148, 160, 172, 188, 204, 220,
+    240, 260, 284, 308, 336, 364, 396,
+    432, 468, 508, 552, 600, 652, 704,
+    768, 832, 896, 960, 1024
+};              /* 47 scfbands */
+
+const Int16 sfb_24_128[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    36, 44, 52, 64, 76, 92, 108,
+    128
+};                                   /* 15 scfbands */
+
+const Int16 sfb_16_1024[] =
+{
+    8, 16, 24, 32, 40, 48, 56,
+    64, 72, 80, 88, 100, 112, 124,
+    136, 148, 160, 172, 184, 196, 212,
+    228, 244, 260, 280, 300, 320, 344,
+    368, 396, 424, 456, 492, 532, 572,
+    616, 664, 716, 772, 832, 896, 960,
+    1024
+};                                  /* 43 scfbands */
+
+const Int16 sfb_16_128[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    32, 40, 48, 60, 72, 88, 108,
+    128
+};                                   /* 15 scfbands */
+
+const Int16 sfb_8_1024[] =
+{
+    12, 24, 36, 48, 60, 72, 84,
+    96, 108, 120, 132, 144, 156, 172,
+    188, 204, 220, 236, 252, 268, 288,
+    308, 328, 348, 372, 396, 420, 448,
+    476, 508, 544, 580, 620, 664, 712,
+    764, 820, 880, 944, 1024
+};               /* 40 scfbands */
+
+const Int16 sfb_8_128[] =
+{
+    4, 8, 12, 16, 20, 24, 28,
+    36, 44, 52, 60, 72, 88, 108,
+    128
+};                                   /* 15 scfbands */
+
+const SR_Info samp_rate_info[12] =
+{
+    /* sampling_frequency, #long sfb, #short sfb */
+    /* samp_rate, nsfb1024, nsfb128 */
+    {96000, 41, 12},       /* 96000 */
+    {88200, 41, 12},       /* 88200 */
+    {64000, 47, 12},       /* 64000 */
+    {48000, 49, 14},       /* 48000 */
+    {44100, 49, 14},       /* 44100 */
+    {32000, 51, 14},       /* 32000 */
+    {24000, 47, 15},       /* 24000 */
+    {22050, 47, 15},       /* 22050 */
+    {16000, 43, 15},       /* 16000 */
+    {12000, 43, 15},       /* 12000 */
+    {11025, 43, 15},       /* 11025 */
+    { 8000, 40, 15},       /* 8000  */
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
diff --git a/media/libstagefright/codecs/aacdec/sfb.h b/media/libstagefright/codecs/aacdec/sfb.h
new file mode 100644
index 0000000..0cc1707
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/sfb.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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: sfb.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: created to declare scalefactor bands for all sampling rates
+
+ Description: Change short to Int16
+
+ Description: Eliminated declaration of sfb_96_128 array, values are equal
+              to array sfb_64_128
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ this file declares the scalefactor bands for all sampling rates
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SFB_H
+#define SFB_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_sr_info.h"
+#include    "e_progconfigconst.h"
+
+/*----------------------------------------------------------------------------
+; 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 Int16 sfb_96_1024[];  /* 41 scfbands */
+
+extern const Int16 sfb_64_1024[];  /* 41 scfbands 47 */
+
+extern const Int16 sfb_64_128[];  /* 12 scfbands */
+
+
+extern const Int16 sfb_48_1024[]; /* 49 scfbands */
+
+extern const Int16 sfb_48_128[];  /* 14 scfbands */
+
+extern const Int16 sfb_32_1024[];  /* 51 scfbands */
+
+extern const Int16 sfb_24_1024[];  /* 47 scfbands */
+
+extern const Int16 sfb_24_128[];  /* 15 scfbands */
+
+extern const Int16 sfb_16_1024[];  /* 43 scfbands */
+
+extern const Int16 sfb_16_128[];  /* 15 scfbands */
+
+extern const Int16 sfb_8_1024[];  /* 40 scfbands */
+
+extern const Int16 sfb_8_128[];  /* 15 scfbands */
+
+extern const SR_Info samp_rate_info[12];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/shellsort.cpp b/media/libstagefright/codecs/aacdec/shellsort.cpp
new file mode 100644
index 0000000..5feb803
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/shellsort.cpp
@@ -0,0 +1,138 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: shellsort.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        Sorting routine
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "shellsort.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 shellsort(Int32 in[], Int32 n)
+{
+
+    Int32     i;
+    Int32     j;
+    Int32     v;
+    Int32     inc = 1;
+
+    do
+    {
+        inc = 3 * inc + 1;
+    }
+    while (inc <= n);
+
+    do
+    {
+        inc = inc / 3;
+        for (i = inc + 1; i <= n; i++)
+        {
+            v = in[i-1];
+            j = i;
+            while (in[j-inc-1] > v)
+            {
+                in[j-1] = in[j-inc-1];
+                j -= inc;
+                if (j <= inc)
+                {
+                    break;
+                }
+            }
+            in[j-1] = v;
+        }
+    }
+    while (inc > 1);
+
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/aacdec/shellsort.h b/media/libstagefright/codecs/aacdec/shellsort.h
new file mode 100644
index 0000000..a4658e3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/shellsort.h
@@ -0,0 +1,84 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: shellsort.h
+ Funtions:
+    get_dse
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+------------------------------------------------------------------------------
+
+
+ ----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SHELLSORT_H
+#define SHELLSORT_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 shellsort(Int32 in[], Int32 n);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/stereo_2_mono.h b/media/libstagefright/codecs/aacdec/stereo_2_mono.h
new file mode 100644
index 0000000..3e27c70
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/stereo_2_mono.h
@@ -0,0 +1,97 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: stereo_2_mono.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for the declaration of the function stereo_2_mono()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef STEREO_2_MONO_H
+#define STEREO_2_MONO_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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 stereo_2_mono(
+        const Int16   sourceLeft[],
+        const Int16   sourceRight[],
+        Int16   outputBuffer[],
+        const Int     sourcePointsPerChannel);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* STEREO_2_MONO_H */
+
diff --git a/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp b/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp
new file mode 100644
index 0000000..c1418e3
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp
@@ -0,0 +1,483 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Filename: synthesis_sub_band.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                   Date: MM/DD/YYYY
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    Int32 vec[],            Input vector, 32-bit
+    const Int32 *cosTerms,  Cosine Terms
+    Int32 *scratch_mem      Scratch memory
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Implement root squared of a number
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+#include "pv_audio_type_defs.h"
+#include "fxp_mul32.h"
+#include "dct64.h"
+#include "synthesis_sub_band.h"
+#include "mdst.h"
+#include "dct16.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Qfmt_30(x)   (Int32)(x*((Int32)(1<<30)) + (x>=0?0.5F:-0.5F))
+#define Qfmt_25(x)   (Int32)(x*((Int32)(1<<25))*(1.5625F) + (x>=0?0.5F:-0.5F))
+
+#define SCALE_DOWN_LP   Qfmt_30(0.075000F)  /* 3/40 */
+#define SCALE_DOWN_HQ     Qfmt_30(0.009375F*0.64F)  /* 3/40 * 1/8 */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+const Int32 CosTable_64[64] =
+{
+    Qfmt_25(0.50003765191555F),   Qfmt_25(40.74468810335183F),   Qfmt_25(0.50033903744282F),   Qfmt_25(13.58429025728446F),
+    Qfmt_25(0.50094271763809F),   Qfmt_25(8.15384860246681F),   Qfmt_25(0.50185051748424F),   Qfmt_25(5.82768837784465F),
+    Qfmt_25(0.50306519130137F),   Qfmt_25(4.53629093696936F),   Qfmt_25(0.50459044322165F),   Qfmt_25(3.71524273832697F),
+    Qfmt_25(0.50643095492855F),   Qfmt_25(3.14746219178191F),   Qfmt_25(0.50859242104981F),   Qfmt_25(2.73164502877394F),
+    Qfmt_25(0.51108159270668F),   Qfmt_25(2.41416000025008F),   Qfmt_25(0.51390632984754F),   Qfmt_25(2.16395781875198F),
+    Qfmt_25(0.51707566313349F),   Qfmt_25(1.96181784857117F),   Qfmt_25(0.52059986630189F),   Qfmt_25(1.79520521907789F),
+    Qfmt_25(0.52449054011472F),   Qfmt_25(1.65559652426412F),   Qfmt_25(0.52876070920749F),   Qfmt_25(1.53699410085250F),
+    Qfmt_25(0.53342493339713F),   Qfmt_25(1.43505508844143F),   Qfmt_25(0.53849943529198F),   Qfmt_25(1.34655762820629F),
+    Qfmt_25(0.54400224638178F),   Qfmt_25(1.26906117169912F),   Qfmt_25(0.54995337418324F),   Qfmt_25(1.20068325572942F),
+    Qfmt_25(0.55637499348989F),   Qfmt_25(1.13994867510150F),   Qfmt_25(0.56329166534170F),   Qfmt_25(1.08568506425801F),
+    Qfmt_25(0.57073058801215F),   Qfmt_25(1.03694904091039F),   Qfmt_25(0.57872188513482F),   Qfmt_25(0.99297296126755F),
+    Qfmt_25(0.58729893709379F),   Qfmt_25(0.95312587439212F),   Qfmt_25(0.59649876302446F),   Qfmt_25(0.91688444618465F),
+    Qfmt_25(0.60636246227215F),   Qfmt_25(0.88381100455962F),   Qfmt_25(0.61693572600507F),   Qfmt_25(0.85353675100661F),
+    Qfmt_25(0.62826943197077F),   Qfmt_25(0.82574877386279F),   Qfmt_25(0.64042033824166F),   Qfmt_25(0.80017989562169F),
+    Qfmt_25(0.65345189537513F),   Qfmt_25(0.77660065823396F),   Qfmt_25(0.66743520092634F),   Qfmt_25(0.75481293911653F),
+    Qfmt_25(0.68245012597642F),   Qfmt_25(0.73464482364786F),   Qfmt_25(0.69858665064723F),   Qfmt_25(0.71594645497057F),
+};
+
+
+/*----------------------------------------------------------------------------
+; 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 synthesis_sub_band_LC(Int32 Sr[], Int16 data[])
+{
+
+    Int32 *temp_o1 = (Int32 *) & data[0];
+
+    Int   i;
+    Int32 *pt_temp_e;
+    Int32 *pt_temp_o = temp_o1;
+    Int32 *pt_temp_x = &Sr[63];
+    Int32 temp1;
+    Int32 temp2;
+    Int32 temp3;
+    Int32 temp11;
+
+    Int16 *pt_data_1;
+    Int16 *pt_data_2;
+
+    Int32 *pt_Sr_1 = Sr;
+    Int16 tmp1;
+    Int16 tmp2;
+    Int16 tmp11;
+    Int16 tmp22;
+    const Int32 *pt_cosTerms = CosTable_48;
+
+
+    temp2 = *(pt_temp_x--);
+    for (i = 20; i != 0; i--)
+    {
+        temp1 = *(pt_Sr_1);
+        temp3 = *(pt_cosTerms++);
+        *(pt_Sr_1++) =   temp1  + temp2;
+        *(pt_temp_o++) = fxp_mul32_Q31((temp1 - temp2), temp3) << 1;
+        temp2 = *(pt_temp_x--);
+    }
+
+    for (i = 12; i != 0; i--)
+    {
+        temp1 = *(pt_Sr_1);
+        temp3 = *(pt_cosTerms++);
+        *(pt_Sr_1++) =   temp1  + temp2;
+        *(pt_temp_o++) = fxp_mul32_Q26((temp1 - temp2), temp3);
+        temp2 = *(pt_temp_x--);
+    }
+
+
+    pv_split_LC(temp_o1, &Sr[32]);
+
+    dct_16(temp_o1, 1);     // Even terms
+    dct_16(&Sr[32], 1);     // Odd  terms
+
+    /* merge */
+
+
+    pt_Sr_1 = &temp_o1[31];
+    pt_temp_e   =  &temp_o1[15];
+    pt_temp_o   =  &Sr[47];
+
+    temp1 = *(pt_temp_o--);
+    *(pt_Sr_1--) = temp1;
+    for (i = 5; i != 0; i--)
+    {
+        temp2 = *(pt_temp_o--);
+        *(pt_Sr_1--) = *(pt_temp_e--);
+        *(pt_Sr_1--) = temp1 + temp2;
+        temp3 = *(pt_temp_o--);
+        *(pt_Sr_1--) = *(pt_temp_e--);
+        *(pt_Sr_1--) = temp2 + temp3;
+        temp1 = *(pt_temp_o--);
+        *(pt_Sr_1--) = *(pt_temp_e--);
+        *(pt_Sr_1--) = temp1 + temp3;
+    }
+
+
+    pv_split_LC(Sr, &Sr[32]);
+
+    dct_16(Sr, 1);     // Even terms
+    dct_16(&Sr[32], 1);     // Odd  terms
+
+
+    pt_temp_x   =  &temp_o1[31];
+    pt_temp_e   =  &Sr[15];
+    pt_temp_o   =  &Sr[47];
+
+    pt_data_1 = &data[95];
+
+    temp2  = *(pt_temp_x--);
+    temp11 = *(pt_temp_x--);
+    temp1  = *(pt_temp_o--);
+
+    *(pt_data_1--) = (Int16) fxp_mul32_Q31(temp2, SCALE_DOWN_LP);
+    *(pt_data_1--) = (Int16) fxp_mul32_Q31(temp1, SCALE_DOWN_LP);
+
+    for (i = 5; i != 0; i--)
+    {
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP);
+        temp3         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP);
+        temp2          = *(pt_temp_o--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp3), SCALE_DOWN_LP);
+        temp11         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp1 + temp2), SCALE_DOWN_LP);
+
+
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp3), SCALE_DOWN_LP);
+        temp1         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP);
+        temp3          = *(pt_temp_o--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp1), SCALE_DOWN_LP);
+        temp11         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp2 + temp3), SCALE_DOWN_LP);
+
+
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp1), SCALE_DOWN_LP);
+        temp2         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP);
+        temp1          = *(pt_temp_o--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP);
+        temp11         = *(pt_temp_x--);
+        *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp1 + temp3), SCALE_DOWN_LP);
+    }
+
+    *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP);
+    *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e), SCALE_DOWN_LP);
+
+    /* ---- merge ends---- */
+
+
+    pt_data_1 = &data[95];
+    pt_data_2 = &data[96];
+
+    *(pt_data_2++) =   0;
+    tmp1  =  *(pt_data_1--);
+    tmp2  =  *(pt_data_1--);
+    tmp11 =  *(pt_data_1--);
+    tmp22 =  *(pt_data_1--);
+
+    for (i = 7; i != 0; i--)
+    {
+        *(pt_data_2++) = (-tmp1);
+        *(pt_data_2++) = (-tmp2);
+        *(pt_data_2++) = (-tmp11);
+        *(pt_data_2++) = (-tmp22);
+        tmp1  =  *(pt_data_1--);
+        tmp2  =  *(pt_data_1--);
+        tmp11 =  *(pt_data_1--);
+        tmp22 =  *(pt_data_1--);
+    }
+
+
+    *(pt_data_2++) = (-tmp1);
+    *(pt_data_2++) = (-tmp2);
+    *(pt_data_2++) = (-tmp11);
+
+    pt_data_2 = &data[0];
+
+    *(pt_data_2++) =  tmp22;
+    tmp1  =  *(pt_data_1--);
+    tmp2  =  *(pt_data_1--);
+    tmp11 =  *(pt_data_1--);
+    tmp22 =  *(pt_data_1--);
+
+    for (i = 7; i != 0; i--)
+    {
+        *(pt_data_2++) =  tmp1;
+        *(pt_data_2++) =  tmp2;
+        *(pt_data_2++) =  tmp11;
+        *(pt_data_2++) =  tmp22;
+        tmp1  =  *(pt_data_1--);
+        tmp2  =  *(pt_data_1--);
+        tmp11 =  *(pt_data_1--);
+        tmp22 =  *(pt_data_1--);
+    }
+
+    *(pt_data_2++) =  tmp1;
+    *(pt_data_2++) =  tmp2;
+    *(pt_data_2++) =  tmp11;
+    *(pt_data_2)   =  tmp22;
+
+}
+
+
+void synthesis_sub_band_LC_down_sampled(Int32 Sr[], Int16 data[])
+{
+
+    Int i ;
+    Int16 *pt_data_1;
+
+    pt_data_1 = &data[0];
+
+    dct_32(Sr);
+
+    for (i = 0; i < 16; i++)
+    {
+        pt_data_1[   i] = (Int16)(Sr[16-i] >> 5);
+        pt_data_1[16+i] = (Int16)(Sr[i] >> 5);
+        pt_data_1[32+i] = (Int16)(Sr[16+i] >> 5);
+    }
+    for (i = 0; i < 15; i++)
+    {
+        pt_data_1[49+i] = (Int16)(-Sr[31-i] >> 5);
+    }
+    pt_data_1[48] = 0;
+}
+
+
+#ifdef HQ_SBR
+
+void synthesis_sub_band(Int32 Sr[], Int32 Si[], Int16 data[])
+{
+
+
+    Int32 i ;
+    Int16 *pt_data_1;
+    Int16 *pt_data_2;
+    Int32 *pt_Sr_1;
+    Int32 *pt_Sr_2;
+    Int32 *pt_Si_1;
+    Int32 *pt_Si_2;
+
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 tmp3;
+    Int32 tmp4;
+
+    Int32 cosx;
+    const Int32 *pt_CosTable = CosTable_64;
+
+
+    pt_Sr_1 = &Sr[0];
+    pt_Sr_2 = &Sr[63];
+
+    pt_Si_1 = &Si[0];
+    pt_Si_2 = &Si[63];
+
+
+    tmp3 = *pt_Sr_1;
+
+    for (i = 32; i != 0; i--)
+    {
+        tmp4 = *pt_Si_2;
+        cosx = *(pt_CosTable++);
+        *(pt_Sr_1++) = fxp_mul32_Q31(tmp3, cosx);
+        tmp3 = *pt_Si_1;
+        *(pt_Si_1++) = fxp_mul32_Q31(tmp4, cosx);
+        tmp4 = *pt_Sr_2;
+        cosx = *(pt_CosTable++);
+        *(pt_Si_2--) = fxp_mul32_Q31(tmp3, cosx);
+        *(pt_Sr_2--) = fxp_mul32_Q31(tmp4, cosx);
+        tmp3 = *pt_Sr_1;
+    }
+
+
+    dct_64(Sr, (Int32 *)data);
+    dct_64(Si, (Int32 *)data);
+
+
+    pt_data_1 = &data[0];
+    pt_data_2 = &data[127];
+
+    pt_Sr_1 = &Sr[0];
+    pt_Si_1 = &Si[0];
+
+    tmp1 = *(pt_Sr_1++);
+    tmp3 = *(pt_Sr_1++);
+    tmp2 = *(pt_Si_1++);
+    tmp4 = *(pt_Si_1++);
+
+    for (i = 32; i != 0; i--)
+    {
+        *(pt_data_1++) = (Int16) fxp_mul32_Q31((tmp2 - tmp1), SCALE_DOWN_HQ);
+        *(pt_data_1++) = (Int16) fxp_mul32_Q31(-(tmp3 + tmp4), SCALE_DOWN_HQ);
+        *(pt_data_2--) = (Int16) fxp_mul32_Q31((tmp1 + tmp2), SCALE_DOWN_HQ);
+        *(pt_data_2--) = (Int16) fxp_mul32_Q31((tmp3 - tmp4), SCALE_DOWN_HQ);
+
+        tmp1 = *(pt_Sr_1++);
+        tmp3 = *(pt_Sr_1++);
+        tmp2 = *(pt_Si_1++);
+        tmp4 = *(pt_Si_1++);
+    }
+
+}
+
+
+const Int32 exp_m0_25_phi[32] =
+{
+
+    0x7FFEFE6E,  0x7FEAFB4A, 0x7FC2F827, 0x7F87F505,
+    0x7F38F1E4,  0x7ED6EEC6, 0x7E60EBAB, 0x7DD6E892,
+    0x7D3AE57D,  0x7C89E26D, 0x7BC6DF61, 0x7AEFDC59,
+    0x7A06D958,  0x790AD65C, 0x77FBD367, 0x76D9D079,
+    0x75A6CD92,  0x7460CAB2, 0x7308C7DB, 0x719EC50D,
+    0x7023C248,  0x6E97BF8C, 0x6CF9BCDA, 0x6B4BBA33,
+    0x698CB796,  0x67BDB505, 0x65DEB27F, 0x63EFB005,
+    0x61F1AD97,  0x5FE4AB36, 0x5DC8A8E2, 0x5B9DA69C
+};
+
+void synthesis_sub_band_down_sampled(Int32 Sr[], Int32 Si[], Int16 data[])
+{
+
+    Int16 k;
+    Int16 *pt_data_1;
+    Int32 exp_m0_25;
+    const Int32 *pt_exp = exp_m0_25_phi;
+
+    Int32 *XX = Sr;
+    Int32 *YY = (Int32 *)data;
+    Int32 tmp1;
+    Int32 tmp2;
+
+    for (k = 0; k < 32; k++)
+    {
+        exp_m0_25 = *(pt_exp++);
+        tmp1 = Sr[k];
+        tmp2 = Si[k];
+        XX[k]    = cmplx_mul32_by_16(-tmp1,  tmp2, exp_m0_25);
+        YY[31-k] = cmplx_mul32_by_16(tmp2,  tmp1, exp_m0_25);
+    }
+
+    mdct_32(XX);
+    mdct_32(YY);
+
+    for (k = 0; k < 32; k++)
+    {
+        Si[k] = YY[k];
+    }
+
+    pt_data_1 = data;
+
+    for (k = 0; k < 16; k++)
+    {
+        *(pt_data_1++)  = (Int16)((XX[2*k  ] + Si[2*k  ]) >> 14);
+        *(pt_data_1++)  = (Int16)((XX[2*k+1] - Si[2*k+1]) >> 14);
+    }
+
+    for (k = 15; k > -1; k--)
+    {
+        *(pt_data_1++)  = (Int16)(-(XX[2*k+1] + Si[2*k+1]) >> 14);
+        *(pt_data_1++)  = (Int16)(-(XX[2*k  ] - Si[2*k  ]) >> 14);
+    }
+
+}
+
+
+#endif      /* HQ_SBR */
+
+#endif      /*  AAC_PLUS */
+
+
diff --git a/media/libstagefright/codecs/aacdec/synthesis_sub_band.h b/media/libstagefright/codecs/aacdec/synthesis_sub_band.h
new file mode 100644
index 0000000..042c488
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/synthesis_sub_band.h
@@ -0,0 +1,78 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: synthesis_sub_band.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef SYNTHESIS_SUB_BAND_H
+#define SYNTHESIS_SUB_BAND_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    void synthesis_sub_band_LC(Int32 Sr[], Int16 data[]);
+    void synthesis_sub_band_LC_down_sampled(Int32 Sr[], Int16 data[]);
+
+
+#ifdef HQ_SBR
+
+    void synthesis_sub_band(Int32 Sr[], Int32 Si[], Int16 data[]);
+    void synthesis_sub_band_down_sampled(Int32 Sr[], Int32 Si[], Int16 data[]);
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* SYNTHESIS_SUB_BAND_H */
+
diff --git a/media/libstagefright/codecs/aacdec/tns_ar_filter.cpp b/media/libstagefright/codecs/aacdec/tns_ar_filter.cpp
new file mode 100644
index 0000000..db31a63
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_ar_filter.cpp
@@ -0,0 +1,474 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_ar_filter.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Implemented 24-bit fixed point version
+               Optimized C code
+
+ Description:
+            - Added OVERFLOW_SHIFT_DOWN to avoid overflow.
+            - Increased precision by using the Q format of the LPC coefficient.
+            - Modified interface to add LPC Q format and scratch memory
+              for the state variables.
+            - Added pv_memset to clear state filter
+            - Updated format for comments (to PV standard)
+            - Updated copyright notice
+
+ Description:
+            - Changed multiplication scheme to increase precision. This
+              works better than older version.
+
+ Description:
+            - Include log2(order) as a scaling down parameter.
+
+ Description:
+            Modified to reflect code review comments
+                - misspelled words, extra comments and explicit requirements
+
+ Description:
+            deleted comment about fix Q format (L 107)
+
+ Description:  Implemented a more efficient version, which eliminated the use
+ of "scratch memory" via introducing a pointer that references the actual
+ output.
+
+ Description: Removed the parameter "scratch_Int32_buffer" as this space
+ in memory is no longer needed by this function.
+
+ Description: Removed references to "scratch_Int32_buffer" in the Inputs
+ section.
+
+ Description:
+    Modified casting to ensure proper operations for different platforms
+
+ Description:
+    Per code review comment:
+    Eliminated casting to UInt and Int in b_low and b_high, they are
+    redundant and may add unncessary extra cycles in some platforms
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Description: Changed the order of the unsigned * signed multiply so the
+ casting to Int32 is performed on the unsigned operand.
+
+ Description:
+    Modified 32 by 16 bit multiplications to avoid unnecessary moves to
+    registers. Also split the code (based on flag direction) to simplify
+    pointer's updates
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    spec  = spectral input to be shaped by the filter.
+            Fixed point format
+            Int32[]
+            length = spec_length
+
+    spec_length  = length of spec array.
+            const Int
+
+    direction = direction for application of tns filter.
+                +1  filters spectrum from low to high frequencies
+                    (first input to filter is spec[0])
+                -1  filters spectrum from high to low frequencies
+                    (first input to filter is spec[spec_length-1])
+                const Int
+
+    lpc   = array of lpc coefficients, minus lpc[0] which is assumed to be "1"
+            Fixed point format
+            const Int[]
+            length = TNS_MAX_ORDER
+
+    Q_lpc = Q format for the lpc coeffcients (for max. precision, it assumes
+            that all 16 bits are used)
+            const Int
+
+    order = order of the TNS filter (Range of 1 - TNS_MAX_ORDER)
+            Int
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    spec = contains spectral data after application of TNS filter
+           Int32 array
+           length = spec_length
+
+
+ Local Stores Modified:
+
+ Global Stores Modified:
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    A block of spectral data (Int32 spec[]) of length (const Int spec_length)
+    is processed by a simple all-pole filter defined by
+    LPC coefficients passed via (const Int lpc[])
+
+    TNS filter equation
+        y(n) =  x(n) - lpc(2)*y(n-1) - ... - lpc(order+1)*y(n-order)
+
+    The filter calculation is performed in place, i.e. the output is passed
+    back to the calling function via (Int32 spec[])
+
+    The filter's order is defined by the variable (const Int order)
+    The direction of the filter's application is defined by (const Int inc)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This function should match the functionality of the ISO code.
+    The implementation does support filter orders bigger or equal to 1.
+    The size of the spectral coeffcients has to be bigger or equal than 1.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.8 (Temporal Noise Shaping)
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+    FOR (i=0; i<order; i++)
+        state[i] = 0;
+    ENDFOR
+
+    IF (inc == -1)
+    THEN
+        spec = spec + spec_length - 1;
+    ENDIF
+
+    FOR (i=0; i<spec_length; i++)
+
+        y = *spec;
+
+        FOR (j=0; j<order; j++)
+
+            y -= lpc[j] * state[j];
+
+        ENDFOR
+
+        FOR (j=order-1; j>0; j--)
+
+            state[j] = state[j-1];
+
+        ENDFOR
+
+        state[0] = y;
+
+        *spec = y;
+
+        spec = spec + inc;
+
+    ENDFOR
+
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+
+   When the code is written for a specific target processor
+     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 "pv_audio_type_defs.h"
+#include "e_tns_const.h"
+#include "tns_ar_filter.h"
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define MASK_LOW16               0xFFFF
+#define UPPER16                      16
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+Int tns_ar_filter(
+    Int32 spec[],
+    const Int spec_length,
+    const Int direction,
+    const Int32 lpc[],
+    const Int Q_lpc,
+    const Int order)
+{
+
+    Int i;
+    Int j;
+
+    /*
+     * Multiplication related variables
+     */
+
+    Int32 temp;
+
+    /*
+     *  Filter related variables
+     */
+    Int32 y0;
+
+    /*
+     *  Circular buffer to hold the filter's state
+     *  (y[n-1],y[n-2],y[n-3],etc.)
+     *
+     *  p_state and p_lpc should take advantage
+     *  of any special circular buffer instructions
+     *  if this code is hand-optimized in assembly.
+     */
+
+    Int32 *p_state = NULL;
+
+    const Int32 *p_lpc;
+
+
+    Int shift_up;
+    Int shift_down_amount;
+
+    /*
+     *  Pointer to the I/O memory space
+     */
+    Int32 *p_spec = spec;
+
+
+    i = 0;
+    j = order;
+
+    /*
+     *  get the power of 2 that is bigger than the order
+     *  i is the bit counter and j is modified until exceed
+     *  the power of 2 corresponding to TNS_MAX_ORDER
+     */
+
+    while (j < 0x010)
+    {
+        j <<= 1;
+        i++;
+    }
+
+    /*
+     *  5 is the number of bits needed to represent 0x010
+     *  TNS_MAX_ORDER = 20, power of 2 that include 20 is 5
+     */
+    shift_down_amount = 4 - i;
+
+    shift_up = UPPER16 - Q_lpc;
+
+    /*
+     *  shift_down_amount == power of 2 that is bigger than the order - 1
+     */
+
+    shift_down_amount += shift_up;
+
+    if (direction == -1)
+    {
+        p_spec += spec_length - 1;
+
+        for (i = order; i != 0; i--)
+        {
+
+            y0 = *p_spec >> shift_down_amount;
+
+            p_lpc = lpc;
+
+            /* 32 by 32 bit multiplication */
+            for (j = order; j > i; j--)
+            {
+                temp = *p_state++;
+                y0 -= fxp_mul32_Q31(temp, *(p_lpc++)) << shift_up;
+            }
+
+            /*
+            * Record the output in-place
+            */
+            p_state     = p_spec;
+            *(p_spec--) = y0;
+
+        }
+
+        if (spec_length > order)
+        {
+            for (i = (spec_length - order); i != 0; i--)
+            {
+                y0 = *p_spec >> shift_down_amount;
+
+                p_lpc = &(lpc[0]);
+
+                /* 32 by 32 bit multiplication */
+                for (j = order; j != 0; j--)
+                {
+                    temp = *p_state++;
+                    y0 -= fxp_mul32_Q31(temp, *(p_lpc++)) << shift_up;
+                }
+
+                /*
+                 * Record the output in-place
+                 */
+                p_state     = p_spec;
+                *(p_spec--) = y0;
+
+            } /* END for (i = (spec_length - order); i>0; i--) */
+        }
+
+    }
+    else
+    {
+        for (i = order; i != 0; i--)
+        {
+
+            p_lpc =  lpc;
+
+            y0 = 0;
+
+            /* 32 by 32 bit multiplication */
+            for (j = order; j > i; j--)
+            {
+                y0 -= fxp_mul32_Q31(*p_state--, *(p_lpc++));
+            }
+
+            p_state     = p_spec;
+            /*
+            * Record the output in-place
+            */
+            *(p_spec) = (*p_spec >> shift_down_amount) + (y0 << shift_up);
+            p_spec++;
+        }
+
+        if (spec_length > order)
+        {
+            for (i = (spec_length - order); i != 0; i--)
+            {
+                p_lpc =  lpc;
+
+                y0 = 0;
+
+                /* 32 by 32 bit multiplication */
+                for (j = order; j != 0; j--)
+                {
+                    y0 -= fxp_mul32_Q31(*p_state--, *(p_lpc++));
+                }
+
+                p_state     = p_spec;
+                /*
+                 * Record the output in-place
+                 */
+                *(p_spec) = (*p_spec >> shift_down_amount) + (y0 << shift_up);
+                p_spec++;
+
+            } /* END for (i = (spec_length - order); i>0; i--) */
+        }
+    }
+
+    return(shift_down_amount);
+
+
+} /* tns_ar_filter */
diff --git a/media/libstagefright/codecs/aacdec/tns_ar_filter.h b/media/libstagefright/codecs/aacdec/tns_ar_filter.h
new file mode 100644
index 0000000..2538b4d
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_ar_filter.h
@@ -0,0 +1,104 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_ar_filter.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Per request of JT, the lpc coefficients q-format will now
+ be transmitted to the function.
+
+ Description: Removed the parameter "scratch_Int32_buffer" as this space
+ in memory is no longer needed by this function.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This function includes the function declaration for tns_ar_filter()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef TNS_AR_FILTER_H
+#define TNS_AR_FILTER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "e_tns_const.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    Int tns_ar_filter(
+        Int32 spec[],
+        const Int spec_length,
+        const Int inc,
+        const Int32 lpc[],
+        const Int lpc_qformat,
+        const Int order);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/aacdec/tns_decode_coef.cpp b/media/libstagefright/codecs/aacdec/tns_decode_coef.cpp
new file mode 100644
index 0000000..366cce5
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_decode_coef.cpp
@@ -0,0 +1,500 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_decode_coef.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Implemented in 16-bit Fixed Point
+
+ Description:  Implemented in 24-bit Fixed Point
+
+ Description:  Modified to return the calculated LPC coefficients "in place"
+ This saves memory, cycles, etc. because it saves a large temporary
+ array being declared on the stack in another function (tns_setup_filter)
+
+ Description:  Modified to return the q-format of the lpc coefficients.
+
+ Description:  Modified for more reliable overflow protection.  tns_decode_coef
+ no longer relies on "reasonable" outputs.  This code should handle all
+ possible inputs.
+
+ Description:  Modified per review comments.
+
+ Description:  Added check condition to avoid numbers with a Q bigger than
+        15 from being passed, otherwise in a 16-bit number the sign is lost.
+
+ Description:  Modified to utilize scratch memory techniques, thereby
+ eliminating two arrays of size TNS_MAX_ORDER, which were previously declared
+ on the stack.
+
+ Description: Updated the SW template to include the full pathname to the
+ source file and a slightly modified copyright header.
+
+ Description:
+ (1) Changed the order of the unsigned * signed multiply so the
+     casting to Int32 is performed on the unsigned operand.
+
+ (2) Removed some unnecessary casting.
+ (3) Fixed a problem where a 16-bit value was casted to 32-bits AFTER
+     a shift.  It should have been cast to 32-bits BEFORE the shifting.
+
+
+ Description:  modified precision of coefficients
+
+ Who:                                   Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ The inputs and their range are defined in ISO/IEC 14496-3:1999(E)
+                                            Part 3 MPEG-4 Audio
+                                            Subpart 4
+
+ Inputs:       order    = RANGE = 1-20
+               const Int
+
+               coef_res = RANGE = 0-1
+               const Int
+
+               lpc_coef = RANGE = -8 to 7 if coef_res = 1   compression OFF
+                                  -4 to 3 if coef_res = 1   compression ON
+                                  -4 to 3 if coef_res = 0   compression OFF
+                                  -2 to 1 if coef_res = 0   compression ON
+
+               [Int *, length TNS_MAX_ORDER]
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    q_lpc     = q_format for the calculated LPC coefs.
+    Int
+
+ Pointers and Buffers Modified:
+    lpc_coef  = used to return the calculated LPC coefs in-place.
+    Int *
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+This function calculates the LPC coefs from the encoded coefs...
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+This function should match the functionality of the ISO source code within
+a reasonable tolerance for fixed point errors.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.8 (Temporal Noise Shaping)
+ (2) Markel & Gray Page 95
+     As referenced in the ISO source code
+
+ (3) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+ PSEUDOCODE:  (ISO Reference Code)
+
+    int i, m;
+    Real iqfac, iqfac_m;
+    Real lpc_fp[TNS_MAX_ORDER+1];
+    Real sin_result_fp[TNS_MAX_ORDER+1], b[TNS_MAX_ORDER+1];
+
+    Inverse quantization
+    iqfac   = (Real)(((1 << (coef_res-1)) - 0.5) / (PI/2.0));
+    iqfac_m = (Real)(((1 << (coef_res-1)) + 0.5) / (PI/2.0));
+
+    for (i=0; i<order; i++)
+    {
+        sin_result[i+1] =
+        (Real)sin( coef[i] / ((coef[i] >= 0) ? iqfac : iqfac_m) );
+    }
+
+    lpc[0] = 1;
+    for (m=1; m<=order; m++)
+    {
+
+        b[0] = lpc[0];
+        for (i=1; i<m; i++)
+        {
+            b[i] = sin_result[m] * lpc[m-i];
+            b[i] += lpc[i];
+        }
+
+        b[m] = sin_result[m];
+
+
+        for (i=0; i<=m; i++)
+        {
+            lpc[i] = b[i];
+        }
+
+    }
+
+    return;
+
+}
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_tns_const.h"
+#include "tns_decode_coef.h"
+#include "fxp_mul32.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define MASK_LOW16  0xffff
+#define UPPER16     16
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/*
+ * Derivation of tns_tables and q_tns_tables
+ *
+ * As defined in the ISO source code
+ * (with the modification that our coef_res has a range[0,1]
+ * The ISO code has a range of [3,4])
+ *
+ *               pi / 2                              pi / 2
+ * iqfac =  --------------------      iqfac_m =  --------------------
+ *          (coef_res + 2) - 1/                  (coef_res + 2) + 1/
+ *         2                 /2                 2                 /2
+ *
+ *
+ * ... Move 1/2 into denominator
+ *
+ *              pi                                   pi
+ * iqfac =  --------------------      iqfac_m =  --------------------
+ *          (coef_res + 3)                        (coef_res + 3)
+ *         2               - 1                   2              + 1
+ *
+ *
+ * if a coef is negative, it is multiplied by iqfac_m
+ *           if positive, "   "     "         iqfac
+ *
+ * The range of coefs is limited to  -4:3 if coef_res = 0
+ *                                   -8:7 if coef_res = 1
+ *
+ *
+ *
+ */
+
+
+const Int32 tns_table[2][16] =
+{
+    {
+        -2114858546,  -1859775393,  -1380375881,  -734482665,
+        0,    931758235,   1678970324,  2093641749
+    },
+    {
+        -2138322861,  -2065504841,  -1922348530,  -1713728946,
+        -1446750378,  -1130504462,   -775760571,   -394599085,
+        0,    446486956,    873460290,   1262259218,
+        1595891361,   1859775393,   2042378317,   2135719508
+    }
+};
+
+
+const Int neg_offset[2] = {4, 8};
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+ FUNCTION NAME: tns_decode_coef
+    Decoder transmitted coefficients for one TNS filter
+----------------------------------------------------------------------------*/
+
+Int tns_decode_coef(
+    const Int   order,
+    const Int   coef_res,
+    Int32 lpc_coef[TNS_MAX_ORDER],
+    Int32 scratchTnsDecCoefMem[2*TNS_MAX_ORDER])
+{
+
+    /* Simple loop counters */
+    Int i;
+    Int m;
+
+    /* Arrays for calculation of the LPC */
+    Int32 *pB = &(scratchTnsDecCoefMem[TNS_MAX_ORDER]);
+
+    Int32 *pA = scratchTnsDecCoefMem;
+
+    Int32 *temp_ptr = NULL;
+
+    /* Pointer for reading/storing the lpc_coef in place */
+    Int32 *pLPC;
+    Int q_lpc = Q_LPC;
+
+    /* TNS table related variables */
+    const Int32 *pTnsTable;
+    Int coef_offset;
+    Int32 table_index;
+    Int shift_amount;
+    Int32 sin_result;
+
+    Int32 tempInt32;
+
+    Int32 max;
+    Int32 mask;
+
+    Int32 mult_high;
+
+    /* Conversion to LPC coefficients Ref. (2) */
+    coef_offset = neg_offset[coef_res];
+    pTnsTable   = tns_table[coef_res];
+
+    m = 0;
+    pLPC = lpc_coef;
+
+
+    /*
+     *  Conversion to LPC coefficients
+     */
+
+    do
+    {
+        table_index = coef_offset + *(pLPC++);
+
+        /* Equiv. to sin_result  = tns_table[coef_res][table_index]; */
+        sin_result = *(pTnsTable + table_index);
+
+        /* sin_result has a range of -0.999 to +0.999 in Q-31 */
+
+        /*
+         * It is important that this for loop is not entered on the first
+         * iteration of the do-while( m < order ) loop.
+         */
+        for (i = m; i > 0; i--)
+        {
+
+            /*
+             * temp_ptr used to optimize index into pA
+             * mult = (Int32)( pA[m-i] * sin_result);
+             */
+
+            mult_high = fxp_mul32_Q31(*(temp_ptr--), sin_result);
+
+            /*
+             *  pB[i] = pA[i] + sin_result * pA[m-i]
+             *
+             *  (mult_high <<1)  eliminates extra sign bit
+             */
+
+            *(pB++) =  *(pA++) + (mult_high << 1);
+
+        } /* END for (i=m; i > 0; i--) */
+
+
+        /* Shift to place pB[m] in q_lpc format */
+
+        *pB =  sin_result >> 12;
+
+        /*
+         * Swapping the pointers here has the same effect
+         * as specifically copying the data from b to a
+         */
+
+        temp_ptr = pA;
+        pA       = pB;
+        pB       = temp_ptr;
+
+        /*
+         *  At this point, pA = pA[m]
+         *             and pB = pB[m]
+         */
+        temp_ptr = pA;
+
+        tempInt32 = *(pA);
+
+        mask = tempInt32 >> 31;
+        tempInt32 ^= mask;
+
+        max = tempInt32;
+
+        /*
+         * It is important that this for loop is not entered on the first
+         * iteration of the do-while( m < order ) loop.
+         */
+        for (i = m; i > 0; i--)
+        {
+            tempInt32 = *(--pA);
+
+            mask = tempInt32 >> 31;
+            tempInt32 ^= mask;
+
+            max |= tempInt32;
+        }
+
+        pB -= m;
+
+        /*
+         * Here, pA = &(pA[0])
+         * and   pB = &(pB[0])
+         */
+
+        if (max >= 0x40000000L)
+        {
+            max >>= 1;
+
+            for (i = m; i > 0; i--)
+            {
+                *(pA++) >>= 1;
+                *(pB++) >>= 1;
+            }
+
+            /* Shift the most recent entry down also */
+            *(pA) >>= 1;
+
+            q_lpc--;
+
+            pA -= m;
+            pB -= m;
+        }
+
+        m++;
+
+    }
+    while (m < order);
+
+
+    /*
+     * The following code compacts
+     * 32-bit LPC coefficients into 16-bit numbers,
+     * shifting by the minimum amount necessary.
+     */
+
+    shift_amount = 0;
+
+    while (max > 32767)
+    {
+        max >>= 1;
+        shift_amount++;
+    }
+
+    /*
+     * This while loop is for protective purposes only.
+     * I have not found data that causes it to be entered.
+     *
+     */
+    if (max != 0)
+    {
+        while (max < 16384)
+        {
+            max <<= 1;
+            shift_amount--;
+        }
+    }
+
+
+    pLPC = lpc_coef;
+
+    if (shift_amount >= 0)
+    {
+
+        for (m = order; m > 0; m--)
+        {
+            *(pLPC++) = *(pA++) << (16 - shift_amount);
+        }
+    }
+
+
+    q_lpc -= shift_amount;
+
+    /*
+     *  make sure that the numbers have some meaning, q_lpc can not be
+     *  bigger than 15 (15 bits + sign)
+     */
+
+    if (q_lpc > 15)
+    {
+        shift_amount = q_lpc - 15;
+        pLPC = lpc_coef;
+
+        for (m = order; m > 0; m--)
+        {
+            *(pLPC++) >>= shift_amount;
+        }
+
+        q_lpc -= shift_amount;
+    }
+
+    return (q_lpc);
+
+} /* tns_decode_coef */
diff --git a/media/libstagefright/codecs/aacdec/tns_decode_coef.h b/media/libstagefright/codecs/aacdec/tns_decode_coef.h
new file mode 100644
index 0000000..a6bac6c
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_decode_coef.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_decode_coef.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to return the LPC coefficients in-place, so the
+ interface to tns_decode_coef is changed.
+
+ Description: Modified to return the q-format of the LPC coefficients.
+
+ Description: Modified so that only the function is declared here.  extern
+ references to constant tables removed.  Also, new copyright header included.
+
+ Description: Modified to include extra parameter, so tns_decode_coef can use
+ scratch memory techniques.
+
+ Description:
+ (1) Modified to include the lines...
+
+    #ifdef __cplusplus
+    extern "C" {
+    #endif
+
+    #ifdef __cplusplus
+    }
+    #endif
+
+ (2) Updated the copyright header.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This function includes the function declaration for tns_decode_coef()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef TNS_DECODE_COEF_H
+#define TNS_DECODE_COEF_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    Int tns_decode_coef(
+        const Int   order,
+        const Int   coef_res,
+        Int32 lpc_coef[],
+        Int32 scratchTnsDecCoefMem[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* TNS_DECODE_COEF */
diff --git a/media/libstagefright/codecs/aacdec/tns_inv_filter.cpp b/media/libstagefright/codecs/aacdec/tns_inv_filter.cpp
new file mode 100644
index 0000000..631f887
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_inv_filter.cpp
@@ -0,0 +1,421 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_inv_filter.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changes made per review comments.
+
+ Description: As requested by JT, the q-format for the LPC coefficients is
+ now passed via the parameter lpc_qformat.
+
+ Description: For speed, the calculation of the shift amount was pulled
+ outside of the loop.
+
+ Description:
+    Modified casting to ensure proper operations for different platforms
+
+ Description:
+    Simplified MAC operations for filter by eliminating extra variables
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    coef           = spectral input to be shaped by the filter.
+                     Fixed point format
+                     [Int32[], length = num_coef]
+
+    num_coef       = length of spec array.
+                     [const Int]
+
+    direction      = direction for application of tns filter.
+                     +1 applies forward filter
+                     (first input to filter is coef[0])
+                     -1 applies reversed filter
+                     (first input to filter is coef[num_coef-1])
+                     [const Int]
+
+    lpc            = array of lpc coefficients.
+                     Fixed point format Q-11
+                     [const Int[], length = TNS_MAX_ORDER]
+
+    lpc_qformat    = The q-format of the lpc coefficients.
+                     [const Int]
+
+    order          = order of the TNS filter (Range of 1 : TNS_MAX_ORDER)
+                     [const Int]
+
+    scratch_memory = scratch_memory needed for filter operation
+                     [Int[], length = TNS_MAX_ORDER]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    coef = contains spectral data after application of TNS filter
+           q-format is not modified.
+           Int32 array
+           length = num_coef
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    A block of spectral data (Int32 coef[]) of length (const Int num_coef)
+    is processed by a simple all-zero filter defined by
+    LPC coefficients passed via (const Int lpc[])
+
+    TNS filter equation
+        y(n) =  x(n) + lpc(2)*x(n-1) + ... + lpc(order+1)*x(n-order)
+
+    The filter calculation is performed in place, i.e. the output is passed
+    back to the calling function via (Int32 coef[])
+
+    In order to avoid overflow, the filter input (Int32 coef[]) must utilize
+    only the lower 16-bits.  The upper 16-bits must be available.
+
+    The filter's order is defined by the variable (const Int order)
+
+    The direction of the filter's application is defined by
+    (const Int direction)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    [Int32 coef] must store no more than 16 bits of data.
+
+    This is required to utilize methods that do not change the q-format of
+    the input data [Int32 coef], and to make use of a fast
+    16 x 16 bit multiply.
+
+    This function should not be called for order <= 0.
+
+    This function must not be called with lpc_qformat < 5
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.6.4.1 (LTP with TNS)
+        Subpart 4.6.8 (Temporal Noise Shaping)
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF (direction == -1)
+    THEN
+        pCoef = pCoef + (num_coef - 1);
+    END IF
+
+    FOR (i = order; i > 0; i--)
+
+        *(pFilterInput) = 0;
+        pFilterInput = pFilterInput + 1;
+
+    END FOR
+
+    wrap_point = 0;
+
+    shift_amt  = (lpc_qformat - 5);
+
+    FOR (i = num_coef; i > 0; i--)
+
+        pLPC = lpc;
+
+        mult = 0;
+
+        FOR (j = wrap_point; j>0; j--)
+
+           tempInt32 = (Int32)(*(pLPC) * *(pFilterInput));
+           tempInt32 = tempInt32 >> 5;
+
+           mult = mult + tempInt32;
+
+           pFilterInput = pFilterInput + 1;
+           pLPC = pLPC + 1;
+
+        ENDFOR
+
+        pFilterInput = scratch_memory;
+
+        FOR (j = (order - wrap_point); j>0; j--)
+
+           tempInt32 = (Int32)(*(pLPC) * *(pFilterInput));
+           tempInt32 = tempInt32 >> 5;
+
+           mult = mult + tempInt32;
+
+           pFilterInput = pFilterInput + 1;
+           pLPC = pLPC + 1;
+
+        ENDFOR
+
+        pFilterInput = pFilterInput - 1;
+        *(pFilterInput) = (Int)(*pCoef);
+
+        mult = mult >> shift_amt;
+
+        *(pCoef) = *(pCoef) + mult;
+
+        pCoef = pCoef + direction;
+
+        wrap_point = wrap_point + 1;
+
+        IF (wrap_point == order)
+        THEN
+            wrap_point = 0;
+        END IF
+
+    END FOR
+
+------------------------------------------------------------------------------
+ RESOURCES USED
+
+   When the code is written for a specific target processor
+     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 "pv_audio_type_defs.h"
+#include "tns_inv_filter.h"
+#include "fxp_mul32.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 tns_inv_filter(
+    Int32 coef[],
+    const Int num_coef,
+    const Int direction,
+    const Int32 lpc[],
+    const Int lpc_qformat,
+    const Int order,
+    Int32 scratch_memory[])
+{
+
+    Int i;
+    Int j;
+    Int shift_amt;
+    Int wrap_point;
+
+    Int32 mult;
+
+    /*
+     * Circular buffer to hold the filter's input
+     *
+     * (x[n-1],x[n-2],x[n-3],etc.)
+     *
+     * This scratch space is necessary, because
+     * the filter's output is returned in-place.
+     *
+     * pFilterInput and pLPC should take advantage
+     * of any special circular buffer instructions
+     * if this code is hand-optimized in assembly.
+     *
+     */
+    Int32 *pFilterInput = scratch_memory;
+
+    const Int32 *pLPC;
+
+    /*
+     * Pointer to the I/O memory space
+     */
+    Int32 *pCoef = coef;
+
+    if (direction == -1)
+    {
+        pCoef += (num_coef - 1);
+    }
+
+    /* Make sure the scratch memory is "clean" */
+    for (i = order; i != 0; i--)
+    {
+        *(pFilterInput++) = 0;
+    }
+
+    wrap_point = 0;
+
+    shift_amt  = (lpc_qformat - 5);
+
+    for (i = num_coef; i > 0; i--)
+    {
+        /*
+         * Copy spectral input into special
+         * filter input buffer.
+         */
+        pLPC = lpc;
+
+        mult = 0;
+
+        /*
+         * wrap_point = 0 when this code is
+         * entered for the first iteration of
+         * for(i=num_coef; i>0; i--)
+         *
+         * So, this first for-loop will be
+         * skipped when i == num_coef.
+         */
+
+        for (j = wrap_point; j > 0; j--)
+        {
+            mult += fxp_mul32_Q31(*(pLPC++), *(pFilterInput++)) >> 5;
+
+        } /* for (j = wrap_point; j>0; j--) */
+
+        /*
+         * pFilterInput has reached &scratch_memory[order-1]
+         * Reset pointer to beginning of filter's state memory
+         */
+        pFilterInput = scratch_memory;
+
+        for (j = (order - wrap_point); j > 0; j--)
+        {
+            mult += fxp_mul32_Q31(*(pLPC++), *(pFilterInput++)) >> 5;
+
+        } /* for (j = wrap_point; j>0; j--) */
+
+
+        /*
+         * Fill the filter's state buffer
+         * avoid obvious casting
+         */
+        *(--pFilterInput) = (*pCoef);
+
+
+        /* Scale the data down so the output q-format is not adjusted.
+         *
+         * Here is an equation, which shows how the spectral coefficients
+         * and lpc coefficients are multiplied and the spectral
+         * coefficient's q-format does not change.
+         *
+         * Q-(coef) * Q-(lpc_qformat) >> 5 = Q-(coef + lpc_q_format - 5)
+         *
+         * Q-(coef + lpc_q_format - 5) >> (lpc_qformat - 5) = Q-(coef)
+         */
+
+        /* Store output in place */
+        *(pCoef) += (mult >> shift_amt);
+
+        /* Adjust pointers and placeholders */
+        pCoef += direction;
+
+        wrap_point++;
+
+        if (wrap_point == order)
+        {
+            wrap_point = 0;
+        }
+
+    } /* for (i = num_coef; i > 0; i--) */
+
+} /* tns_inv_filter */
diff --git a/media/libstagefright/codecs/aacdec/tns_inv_filter.h b/media/libstagefright/codecs/aacdec/tns_inv_filter.h
new file mode 100644
index 0000000..1b57fc1
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/tns_inv_filter.h
@@ -0,0 +1,99 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: tns_inv_filter.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Per request of JT, the lpc coefficients q-format will now
+ be transmitted to the function.
+
+ Description: The scratch memory was mistakenly declared here as type "Int32"
+ It should have been "Int"
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file contains the function declaration for
+ tns_inv_filter.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef TNS_INV_FILTER_H
+#define TNS_INV_FILTER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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 tns_inv_filter(
+    Int32 coef[],
+    const Int   num_coef,
+    const Int   inc,
+    const Int32 lpc[],
+    const Int   lpc_qformat,
+    const Int   order,
+    Int32 scratch_memory[]);
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/trans4m_freq_2_time_fxp.cpp b/media/libstagefright/codecs/aacdec/trans4m_freq_2_time_fxp.cpp
new file mode 100644
index 0000000..6ccc023
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/trans4m_freq_2_time_fxp.cpp
@@ -0,0 +1,2604 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Pathname: trans4m_freq_2_time_fxp.c
+  Function: trans4m_freq_2_time_fxp
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+    changed to decrement loop
+    change wnd_shape from structure to passing parameters
+    modified window tables from UInt to UInt16 to assure proper operation
+    without dubious typecast
+    changed logic to hit most common states first.
+    modified Time_data from Int to Int32 to hold
+    possible overflow before saturation process.
+
+ Description:
+    Increase processing on some loop by using more pointers
+    changed interface to avoid passing a pointer for wnd_shape_prev_bk, this
+    element is not change in this function because of this function use
+    in the LTP module
+
+ Description:
+    Added rounding to multiplication
+
+ Description:
+    Update input description and eliminate unneeded comments
+
+ Description:
+    LONG_START_WINDOW was using SHORT_WINDOW instead of
+    HALF_SHORT_WINDOW, causing a for loop to exceed its count
+
+ Description:
+    Modified structure of code so exp is not tested before it
+    is initialized.  Also, new structure avoids double-testing
+    of exp_freq = ALL_ZEROS_BUFFER.
+
+ Description:
+    The result of a shift is undefined if the right operand is greater than
+    or equal to the number of bits in the left expression's type
+    To avoid undefined shift by 32, a check of the shift has been
+    added, so the function proceeds only when the exponent is less
+    than 32. By design the shift up is related to the global gain,
+    and controlled by the encoder, so saturation is not allowed.
+    In both short and long window, processing is skip if an all zero
+    input buffer or excessive down shift is detected.
+
+ Description:
+    Changes according to code review comments. Also, modified if-else
+    structure so the imdct_fxp is not called with an all zero input buffer
+
+ Description:
+    Replaced function buffer_normalization by buffer_adaptation, to ease
+    use of 16 bits. Function buffer_normalization becomes  obsolete.
+
+ Description:
+    Modified call to imdct_fxp to reflect extended precision use. Added
+    routine buffer_adaptation to extract 16 MSB and keep highest.
+    precision. Modify casting to ensure proper operations for different
+    platforms
+
+ Description:
+    Eliminate double access to memory by loading data directly to the
+    time array. Also reduced cycle count and added precision by combining
+    downshifting in only one operation. Added adaptive rounding factor.
+    Change exponent threshold when operations are waived. It is use to be 32
+    but by combining downshifting, this new threshold is now 16. This may
+    avoid unneeded calculations for extremely small numbers.
+
+ Description:
+    Per review comments:
+        - Added comments to clarify buffer_adaptation function
+        - Deleted  reference to include file "buffer_normalization.h"
+        - Modified IF-ELSE so long_windows case is considered first
+        - Eliminated extra IF when computing the rounding, so when exp ==0
+          less cycles are used shifting than in an extra if-else
+        - Corrected negative shift when computing rounding factor
+        - Added condition when exp > 16 (for long windows)
+
+ Description:
+    Modified IF-ELSE structure so now ALL_ZEROS_BUFFER condition is share
+    with exp > 16 condition. This avoid code duplication for both cases.
+
+ Description:
+        - Modified function interface to add output_buffer
+        - Eliminated the 32 bit version of the current output, calculations
+          are placed directly in output_buffer. In this way the buffer
+          Time_data needs only to be 1024 Int32, instead of 2048 (per channel).
+          Also, added the limit macro inside the function (this reduces access
+          to memory).
+        - Updated Pseudo - Code
+
+ Description:
+    Per review comments:
+          Corrected line sizes and mispelling,  added comments and swap
+          order or switch statement for ONLY_LONG_SEQUENCE.
+
+ Description:
+    Eliminated adaptive rounding due to potential saturation.
+
+ Description:
+    Eliminated use of buffer adaptation by shifting this functionality inside
+    the imdct_fxp() routine. Also modified the call to imdct_fxp to accomodate
+    new function interface.
+    Modified macro limit() to save cycles when testing the most common case:
+    no saturation.
+
+ Description:
+    Changed new function interface for imdct_fxp().
+
+ Description:
+    Replaced for-loop with memset and memcopy.
+
+ Who:                         Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Frequency_data    =  vector with spectral information, size 2048
+                         type Int32
+
+    Time_data         =  buffer with data from previous Frequency to Time
+                         conversion, used for overlap and add, size 1024
+                         type Int32
+
+    Output_buffer     =  place holder for current output,  size 1024
+                         type Int16
+
+    wnd_seq           =  window sequence
+                         type WINDOW_SEQUENCE
+
+    wnd_shape_prev_bk =  previous window shape type
+                         type Int
+
+    wnd_shape_this_bk =  current window shape type
+                         type Int
+
+    Q_format          =  Q format for the input frequency data
+                         type Int
+
+    freq_2_time_buffer[] =  scratch memory for computing FFT
+                         type Int32
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    Output_buffer
+    Time_data
+    Frequency_data
+    pWnd_shape_prev_bk
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+The time/frequency representation of the signal is mapped onto the time
+domain by feeding it into the filterbank module. This module consists of
+an inverse modified discrete cosine transform (IMDCT), and a window and an
+overlap-add function. In order to adapt the time/frequency resolution of the
+filterbank to the characteristics of the input signal, a block switching tool
+is also adopted. N represents the window length, where N is a function of the
+window_sequence. For each channel, the N/2 time-frequency values are
+transformed into the N time domain values via the IMDCT. After applying the
+window function, for each channel, the first half of the sequence is added to
+the second half of the previous block windowed sequence to reconstruct the
+output samples for each channel outi,n.
+
+The adaptation of the time-frequency resolution of the filterbank to the
+characteristics of the input signal is done by shifting between transforms
+whose input lengths are either 2048 or 256 samples. By enabling the block
+switching tool, the following transitions are meaningful:
+
+from ONLY_LONG_SEQUENCE to   { LONG_START_SEQUENCE
+                               ONLY_LONG_SEQUENCE
+
+from LONG_START_SEQUENCE to  { LONG_STOP_SEQUENCE
+                               EIGHT_SHORT_SEQUENCE
+
+from LONG_STOP_SEQUENCE to   { LONG_START_SEQUENCE
+                               ONLY_LONG_SEQUENCE
+
+from EIGHT_SHORT_SEQUENCE to { LONG_STOP_SEQUENCE
+                               EIGHT_SHORT_SEQUENCE
+
+Window shape decisions are made by the encoder on a frame-by-frame-basis.
+The window selected is applicable to the second half of the window function
+only, since the first half is constrained to use the appropriate window
+shape from the preceding frame.
+The 2048 time-domain values x'(i)(n), (i window, n sample) to be windowed are
+the last 1024 values of the previous window_sequence concatenated with 1024
+values of the current block. The formula below shows this fact:
+
+                     |  x(i-1)(n+1024)      for    0 < n < 1024
+            x'(i)(n) {
+                     |  x(i)(n)             for 1024 < n < 2048
+
+
+Buffer Time_data data from previous Frequency to Time conversion, used
+for overlap and add
+
+Once the window shape is selected, the window_shape syntax element is
+initialized. Together with the chosen window_sequence all information needed
+for windowing exist.
+With the window halves described below all window_sequences can be assembled.
+For window_shape == 1, the window coefficients are given by the Kaiser -
+Bessel derived (KBD) window.
+Otherwise, for window_shape == 0, a sine window is employed.
+
+The window length N can be 2048 or 256 for the KBD and the sine window.
+All four window_sequences explained below have a total length of 2048
+samples.
+For all kinds of window_sequences the window_shape of the left half of
+the first transform window is determined by the window shape of the previous
+block.
+
+In the case of EIGHT_SHORT_SEQUENCE the processing is done in-place and
+in descendent order to avoid using extra memory.
+The ordering is as follows:
+
+                                            Pn: Previous data for window n
+                                            Cn:  Current data for window n
+
+
+                                                128 freq.
+                                                 samples
+                  FREQ                          ++++++
+IN                         ===========================
+                                                    \
+                                                      \
+                                                        ->  256 time
+                                                             samples
+
+                                                           P8    C8
+           8                                            #######++++++
+                                                    P7     C7
+           7                                     #######++++++
+           :                                :
+           :                                :
+                            P2    C2
+           2             #######++++++
+                     P1    C1
+           1      #######++++++
+                                                                          TIME
+OUT          ==============================================================
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This module shall implement a scheme to switch between window types
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] ISO 14496-3:1999, pag 111
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+
+    IF ( wnd_seq == EIGHT_SHORT_SEQUENCE)
+    THEN
+
+        FOR ( i=0; i<LONG_WINDOW; i++)
+            Time_data[LONG_WINDOW + i] = 0;
+        ENDFOR
+
+        FOR ( wnd=NUM_SHORT_WINDOWS-1; wnd>=0; wnd--)
+
+            pFreqInfo = &Frequency_data[ wnd*SHORT_WINDOW];
+
+            CALL IMDCT( pFreqInfo, SHORT_BLOCK1);
+            MODIFYING(pFreqInfo)
+
+
+            IF (wnd == 0)
+            THEN
+                pShort_Window_1 = &Short_Window[wnd_shape_prev_bk][0];
+            ELSE
+                pShort_Window_1 = &Short_Window[wnd_shape_this_bk][0];
+            ENDIF
+
+            pShort_Window_2   =
+                    &Short_Window[wnd_shape->this_bk][SHORT_WINDOW_m_1];
+
+            FOR( i=0, j=SHORT_WINDOW; i<SHORT_WINDOW; i++, j--)
+                pFreqInfo[             i]  *= pShort_Window_1[i];
+                pFreqInfo[SHORT_WINDOW+i]  *= pShort_Window_2[j];
+            ENDFOR
+
+
+            FOR( i=0; i<SHORT_BLOCK1; i++)
+                Time_data[W_L_STOP_1 + SHORT_WINDOW*wnd + i] += pFreqInfo[i];
+            ENDFOR
+
+        ENDFOR
+
+        FOR ( i=0; i<LONG_WINDOW; i++)
+            temp              = Time_data[i];
+            Output_buffer[i]  = Time_data[i];
+            Time_data[i]      = temp;
+        ENDFOR
+    ELSE
+
+        CALL IMDCT( Frequency_data, LONG_BLOCK1)
+            MODIFYING(Frequency_data)
+
+        SWITCH ( wnd_seq)
+
+            CASE ( ONLY_LONG_SEQUENCE)
+
+                pLong_Window_1 = &Long_Window[wnd_shape_prev_bk][0];
+                pLong_Window_2 =
+                        &Long_Window[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+                FOR (i=0; i<LONG_WINDOW; i++)
+                    Frequency_data[            i] *= *pLong_Window_1++;
+                    Frequency_data[LONG_WINDOW+i] *= *pLong_Window_2--;
+                ENDFOR
+
+                BREAK
+
+            CASE ( LONG_START_SEQUENCE)
+
+                pLong_Window_1 = &Long_Window[wnd_shape_prev_bk][0];
+
+                FOR ( i=0; i<LONG_WINDOW; i++)
+                    Frequency_data[ i] *= *pLong_Window_1++;
+                ENDFOR
+
+                pShort_Window_1   =
+                        &Short_Window[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+                FOR ( i=0; i<SHORT_WINDOW; i++)
+                    Frequency_data[W_L_START_1 + i] *= *pShort_Window_1--;
+                ENDFOR
+
+                FOR ( i=W_L_START_2; i<LONG_BLOCK1; i++)
+                    Frequency_data[W_L_START_2 + i] = 0;
+                ENDFOR
+
+                BREAK
+
+
+            CASE ( LONG_STOP_SEQUENCE )
+
+                FOR ( i=0; i<W_L_STOP_1; i++)
+                    Frequency_data[ i] = 0;
+                ENDFOR
+
+                pShort_Window_1   = &Short_Window[wnd_shape_prev_bk][0];
+
+                FOR ( i=0; i<SHORT_WINDOW; i++)
+                    Frequency_data[W_L_STOP_1+ i] *= *pShort_Window_1++;
+                ENDFOR
+
+                pLong_Window_1 =
+                        &Long_Window[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+                FOR ( i=0; i<LONG_WINDOW; i++)
+                    Frequency_data[LONG_WINDOW + i]  *=  *pLong_Window_1--;
+                ENDFOR
+
+                BREAK
+
+        }
+
+
+        FOR ( i=0; i<LONG_WINDOW; i++)
+            Output_buffer[i]  = Frequency_data[i]  + Time_data[i];
+            Time_data[i] = Frequency_data[LONG_WINDOW+i];
+        ENDFOR
+
+    }
+
+    ENDIF
+
+
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "aac_mem_funcs.h"
+#include "window_block_fxp.h"
+#include "imdct_fxp.h"
+
+#include "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; limit(x) saturates any number that exceeds a 16-bit representation into a
+; 16 bit number.
+----------------------------------------------------------------------------*/
+
+#define  ROUNDING_SCALED     (ROUNDING<<(16 - SCALING))
+
+
+#if defined(PV_ARM_V5)
+
+
+__inline Int16 sat(Int32 y)
+{
+    Int32 x;
+    Int32 z;
+    __asm
+    {
+        mov x, ROUNDING_SCALED
+        mov y, y, lsl #(15-SCALING)
+        qdadd z, x, y
+        mov y, z, lsr #16
+    }
+    return((Int16)y);
+}
+
+#define  limiter( y, x)   y = sat(x);
+
+
+
+#elif defined(PV_ARM_GCC_V5)
+
+
+__inline Int16 sat(Int32 y)
+{
+    register Int32 x;
+    register Int32 ra = (Int32)y;
+    register Int32 z = ROUNDING_SCALED;
+
+
+    asm volatile(
+        "mov %0, %1, lsl #5\n\t"    // (15-SCALING) assembler does not take symbols
+        "qdadd %0, %2, %0\n\t"
+        "mov %0, %0, lsr #16"
+    : "=&r*i"(x)
+                : "r"(ra),
+                "r"(z));
+
+    return ((Int16)x);
+}
+
+#define  limiter( y, x)   y = sat(x);
+
+
+#elif defined(PV_ARM_MSC_EVC_V5)
+
+
+#define  limiter( y, x)       z = x<< (15-SCALING); \
+                              y = _DAddSatInt( ROUNDING_SCALED, z)>>16;
+
+
+#else
+
+#define  limiter( y, x)   z = ((x + ROUNDING )>>SCALING); \
+                          if ((z>>15) != (z>>31))         \
+                          {                                    \
+                              z = (z >> 31) ^ INT16_MAX;       \
+                          } \
+                          y = (Int16)(z);
+
+#endif
+
+
+/*----------------------------------------------------------------------------
+; 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 FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+#ifdef AAC_PLUS
+
+
+void trans4m_freq_2_time_fxp_1(
+    Int32               Frequency_data[],
+    Int32               Time_data[],
+    Int16               Output_buffer[],
+    WINDOW_SEQUENCE     wnd_seq,
+    Int                 wnd_shape_prev_bk,
+    Int                 wnd_shape_this_bk,
+    Int                 Q_format,
+    Int32               abs_max_per_window[],
+    Int32               freq_2_time_buffer[])
+
+{
+    Int exp;
+    Int shift;
+
+    Int  i;
+    Int  wnd;
+#if !(defined( PV_ARM_GCC_V5)||(PV_ARM_V5))
+    Int32 z;
+#endif
+
+    Int16 *pFreqInfo;
+    Int32 temp;
+    Int32 test;
+
+    Int16 *pFreq_2_Time_data_1;
+    Int16 *pFreq_2_Time_data_2;
+
+    const Int16 *pLong_Window_1;
+    const Int16 *pLong_Window_2;
+    const Int16 *pShort_Window_1;
+    const Int16 *pShort_Window_2;
+
+    Int32 *pOverlap_and_Add_Buffer_1;
+    Int32 *pOverlap_and_Add_Buffer_2;
+
+    Int16  *pOutput_buffer;
+    Int16  *pOutput_buffer_2;
+
+    const Int16 * Long_Window_fxp[NUM_WINDOW_SHAPES];
+    const Int16 * Short_Window_fxp[NUM_WINDOW_SHAPES];
+
+    Long_Window_fxp[0] = Long_Window_sine_fxp;
+    Long_Window_fxp[1] = Long_Window_KBD_fxp;
+    Short_Window_fxp[0] = Short_Window_sine_fxp;
+    Short_Window_fxp[1] = Short_Window_KBD_fxp;
+
+
+    if (wnd_seq != EIGHT_SHORT_SEQUENCE)
+    {
+
+        pFreqInfo = (Int16 *)Frequency_data;
+
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  LONG_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[0]);
+
+
+
+        /*
+         *  The C Programming Language, Second Edition, Kernighan & Ritchie,
+         *  page 206.
+         *  "The result [of a shift] is undefined if the right operand is
+         *  negative, or greater than or equal to the number of bits in the
+         *  left expression's type"
+         *   => avoid shift by 32 or 16
+         */
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = pFreqInfo;
+
+            switch (wnd_seq)
+            {
+
+                case ONLY_LONG_SEQUENCE:
+                default:
+
+                    pOutput_buffer = Output_buffer;
+
+                    pOverlap_and_Add_Buffer_1 = Time_data;
+
+                    {
+                        const Int16 *pLong_Window_2 = &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+                        Int32 * pFreq2T = (Int32 *)pFreqInfo;
+                        Int32 * win = (Int32 *) & Long_Window_fxp[wnd_shape_prev_bk][0];
+                        Int shift = exp + 15 - SCALING;
+
+
+                        Int32 * pFreq2T_2 = &pFreq2T[HALF_LONG_WINDOW];
+
+
+                        for (i = HALF_LONG_WINDOW; i != 0; i--)
+                        {
+                            Int16 win1, win2;
+                            Int32  temp2, test2;
+
+                            Int32  winx;
+
+                            temp2 = *(pFreq2T++);
+                            winx = *(win++);
+
+                            test  = *(pOverlap_and_Add_Buffer_1++);
+                            test2 = *(pOverlap_and_Add_Buffer_1--);
+                            temp  =   fxp_mul_16_by_16bb(temp2, winx) >> shift;
+                            temp2 =   fxp_mul_16_by_16tt(temp2, winx) >> shift;
+                            limiter(*(pOutput_buffer++), (temp + test));
+                            limiter(*(pOutput_buffer++), (temp2 + test2));
+
+                            temp2 = *(pFreq2T_2++);
+
+                            win1  = *(pLong_Window_2--);
+                            win2  = *(pLong_Window_2--);
+                            temp  = fxp_mul_16_by_16bb(temp2, win1) >> shift;
+                            test2 = fxp_mul_16_by_16tb(temp2, win2) >> shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp;
+                            *(pOverlap_and_Add_Buffer_1++) = test2;
+
+                        }
+                    }
+
+                    break;
+
+                case LONG_START_SEQUENCE:
+
+
+                    pFreq_2_Time_data_2 =
+                        &pFreq_2_Time_data_1[ HALF_LONG_WINDOW];
+
+                    pLong_Window_1 = &Long_Window_fxp[wnd_shape_prev_bk][0];
+                    pLong_Window_2 = &pLong_Window_1[ HALF_LONG_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[0];
+                    pOverlap_and_Add_Buffer_2 = &Time_data[HALF_LONG_WINDOW];
+
+                    pOutput_buffer   = Output_buffer;
+                    pOutput_buffer_2 = pOutput_buffer + HALF_LONG_WINDOW;
+
+
+                    shift = exp + 15 - SCALING;
+
+                    for (i = HALF_LONG_WINDOW; i != 0; i--)
+                    {
+
+                        Int16 win1, win2;
+                        Int16  dat1, dat2;
+                        Int32  test1, test2;
+
+                        dat1   = *(pFreq_2_Time_data_1++);
+                        win1   = *(pLong_Window_1++);
+                        test1  = *(pOverlap_and_Add_Buffer_1++);
+
+                        dat2  =  *(pFreq_2_Time_data_2++);
+                        win2  = *(pLong_Window_2++);
+                        test2 = *(pOverlap_and_Add_Buffer_2++);
+
+                        limiter(*(pOutput_buffer++), (test1 + (fxp_mul_16_by_16(dat1, win1) >> shift)));
+
+                        limiter(*(pOutput_buffer_2++), (test2 + (fxp_mul_16_by_16(dat2, win2) >> shift)));
+
+                    }
+
+                    /*
+                     *  data unchanged from  LONG_WINDOW to W_L_START_1
+                     *  only scaled accordingly
+                     */
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[0];
+                    pFreq_2_Time_data_1       = &pFreqInfo[LONG_WINDOW];
+
+                    exp -= SCALING;
+
+                    if (exp >= 0)
+                    {
+
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0; i--)
+                        {
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++) >> exp;
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++) >> exp;
+
+                        }
+
+                    }
+                    else if (exp < 0)
+                    {
+
+                        Int shift = -exp;
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0 ; i--)
+                        {
+                            Int32 temp2 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp2;
+                            temp2 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp2;
+                        }
+
+                    }
+                    else
+                    {
+
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0; i--)
+                        {
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++);
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++);
+
+                        }
+
+                    }
+
+
+                    pFreq_2_Time_data_1  = &pFreqInfo[W_L_START_1];
+                    pFreq_2_Time_data_2  =
+                        &pFreq_2_Time_data_1[HALF_SHORT_WINDOW];
+
+                    pShort_Window_1   =
+                        &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+                    pShort_Window_2   = pShort_Window_1 - HALF_SHORT_WINDOW;
+
+                    pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1 +
+                                                HALF_SHORT_WINDOW;
+
+
+                    for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                    {
+                        Int16 win1, win2;
+                        Int16  dat1, dat2;
+                        Int32  temp2;
+                        dat1  = (*pFreq_2_Time_data_1++);
+                        dat2  = (*pFreq_2_Time_data_2++);
+                        win1  = *(pShort_Window_1--);
+                        win2  = *(pShort_Window_2--);
+
+                        temp   =   fxp_mul_16_by_16(dat1, win1) >> shift;
+                        *(pOverlap_and_Add_Buffer_1++) = temp;
+
+                        temp2 =   fxp_mul_16_by_16(dat2, win2) >> shift;
+                        *(pOverlap_and_Add_Buffer_2++) = temp2;
+
+
+                    }
+
+
+                    pOverlap_and_Add_Buffer_1 += HALF_SHORT_WINDOW;
+
+                    pv_memset(
+                        pOverlap_and_Add_Buffer_1,
+                        0,
+                        (LONG_BLOCK1 - W_L_START_2)
+                        *sizeof(*pOverlap_and_Add_Buffer_1));
+
+
+                    break;
+
+
+                case LONG_STOP_SEQUENCE:
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[ W_L_STOP_2];
+
+                    pOutput_buffer         = &Output_buffer[W_L_STOP_2];
+
+                    pFreq_2_Time_data_1      = &pFreqInfo[W_L_STOP_2];
+
+                    exp -= SCALING; /*  !!!! */
+
+                    if (exp > 0)
+                    {
+                        Int16 tmp1 = (*(pFreq_2_Time_data_1++) >> exp);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pOutput_buffer++), (temp + tmp1));
+
+                            tmp1 = *(pFreq_2_Time_data_1++) >> exp;
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        }
+                    }
+                    else if (exp < 0)
+                    {
+                        shift = -exp;
+                        Int32 temp1 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pOutput_buffer++), (temp + temp1));
+
+                            temp1 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        }
+                    }
+                    else
+                    {
+                        Int16 tmp1 = *(pFreq_2_Time_data_1++);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pOutput_buffer++), (temp + tmp1));
+
+                            tmp1 = *(pFreq_2_Time_data_1++);
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        }
+                    }
+
+
+                    pShort_Window_1 = &Short_Window_fxp[wnd_shape_prev_bk][0];
+                    pShort_Window_2 = &pShort_Window_1[HALF_SHORT_WINDOW];
+
+                    pFreq_2_Time_data_1 = &pFreqInfo[W_L_STOP_1];
+                    pFreq_2_Time_data_2 =
+                        &pFreq_2_Time_data_1[HALF_SHORT_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[ W_L_STOP_1];
+                    pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1
+                                                + HALF_SHORT_WINDOW;
+
+                    pOutput_buffer   = &Output_buffer[W_L_STOP_1];
+                    pOutput_buffer_2 = pOutput_buffer + HALF_SHORT_WINDOW;
+
+                    exp += SCALING;  /* +8 back to what it was */
+
+                    shift = exp + 15 - SCALING;
+
+
+                    for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                    {
+                        Int16 win1;
+                        Int16  dat1;
+
+                        dat1 = *(pFreq_2_Time_data_1++);
+                        win1 = *(pShort_Window_1++);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        test  = fxp_mul_16_by_16(dat1, win1);
+
+                        limiter(*(pOutput_buffer++), (temp + (test >> shift)));
+
+                        dat1 = *(pFreq_2_Time_data_2++);
+                        win1 = *(pShort_Window_2++);
+                        temp = *(pOverlap_and_Add_Buffer_2++);
+                        test =  fxp_mul_16_by_16(dat1, win1);
+                        limiter(*(pOutput_buffer_2++), (temp + (test >> shift)));
+
+                    }
+
+
+                    pFreq_2_Time_data_2 = &pFreqInfo[LONG_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = Time_data;
+
+                    pOutput_buffer = Output_buffer;
+
+                    pLong_Window_2   =
+                        &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+
+                    /*
+                     *  Copy previous time in current buffer, also copy overlap
+                     *  and add buffer
+                     */
+
+                    for (i = W_L_STOP_1; i != 0; i--)
+                    {
+                        Int16 win1;
+                        Int16 dat1;
+
+                        win1 = *(pLong_Window_2--);
+                        dat1 = *pFreq_2_Time_data_2++;
+
+                        limiter(*(pOutput_buffer++), *(pOverlap_and_Add_Buffer_1));
+
+
+                        temp = fxp_mul_16_by_16(dat1, win1) >> shift;
+                        *(pOverlap_and_Add_Buffer_1++) = temp ;
+
+                    }
+
+                    for (i = (LONG_WINDOW - W_L_STOP_1); i != 0; i--)
+                    {
+                        temp = fxp_mul_16_by_16(*pFreq_2_Time_data_2++, *(pLong_Window_2--)) >> shift;
+                        *(pOverlap_and_Add_Buffer_1++) = temp ;
+                    }
+
+
+                    break;
+
+
+
+            } /* switch (wnd_seq) */
+
+        }   /*  if (exp < 16)  */
+
+        else
+        {
+            /* all zeros buffer or excessive down shift */
+
+            /* Overlap and add, setup buffer for next iteration */
+            pOverlap_and_Add_Buffer_1 = &Time_data[0];
+
+            pOutput_buffer = Output_buffer;
+
+            temp  = (*pOverlap_and_Add_Buffer_1++);
+
+            for (i = LONG_WINDOW; i != 0; i--)
+            {
+
+                limiter(*(pOutput_buffer++), temp);
+
+                temp = (*pOverlap_and_Add_Buffer_1++);
+
+            }
+
+            pv_memset(Time_data, 0, LONG_WINDOW*sizeof(Time_data[0]));
+
+
+        }
+
+    }
+    else
+    {
+
+        Int32 *pScrath_mem;
+        Int32 *pScrath_mem_entry;
+        Int32  *pFrequency_data = Frequency_data;
+
+        Int32 * pOverlap_and_Add_Buffer_1;
+        Int32 * pOverlap_and_Add_Buffer_2;
+        Int32 * pOverlap_and_Add_Buffer_1x;
+        Int32 * pOverlap_and_Add_Buffer_2x;
+
+        /*
+         *  Frequency_data is 2*LONG_WINDOW length but only
+         *  the first LONG_WINDOW elements are filled in,
+         *  then the second part can be used as scratch mem,
+         *  then grab data from one window at a time in
+         *  reverse order.
+         *  The upper LONG_WINDOW Int32 are used to hold the
+         *  computed overlap and add, used in the next call to
+         *  this function, and also as sctrach memory
+         */
+
+        /*
+         *  Frequency_data usage for the case EIGHT_SHORT_SEQUENCE
+
+          |<----- Input Freq. data ----->|< Overlap & Add ->| Unused |-Scratch-|
+          |                              |  Store for next  |        |  memory |
+          |                              |  call            |        |         |
+          |                              |                  |        |         |
+          |//////////////////////////////|\\\\\\\\\\\\\\\\\\|--------|+++++++++|
+          |                              |                  |        |         |
+          0                         LONG_WINDOW        LONG_WINDOW   |   2*LONG_WINDOW
+                                                            +        |         |
+                                                       W_L_STOP_2    |         |
+                                                                     |<--   -->|
+                                                                      SHORT_WINDOW +
+                                                                    HALF_SHORT_WINDOW
+          *
+          */
+
+        pOverlap_and_Add_Buffer_1  = &pFrequency_data[
+                                         LONG_WINDOW + 3*SHORT_WINDOW + HALF_SHORT_WINDOW];
+
+        /*
+         *  Initialize to zero, only the firt short window used in overlap
+         *  and add
+         */
+        pv_memset(
+            pOverlap_and_Add_Buffer_1,
+            0,
+            SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+
+        /*
+         *  Showt windows are evaluated in decresing order. Windows from 7
+         *  to 0 are break down in four cases: window numbers 7 to 5, 4, 3,
+         *  and 2 to 0.
+         *  The data from short windows 3 and 4 is situated at the boundary
+         *  between the 'overlap and add' buffer and the output buffer.
+         */
+        for (wnd = NUM_SHORT_WINDOWS - 1; wnd >= NUM_SHORT_WINDOWS / 2 + 1; wnd--)
+        {
+
+            pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+            exp = imdct_fxp(
+                      (Int32 *)pFreqInfo,
+                      freq_2_time_buffer,
+                      SHORT_BLOCK1,
+                      Q_format,
+                      abs_max_per_window[wnd]);
+
+            pOverlap_and_Add_Buffer_1 =
+                &pFrequency_data[ W_L_STOP_1 + SHORT_WINDOW*wnd];
+
+
+            pOverlap_and_Add_Buffer_2 =
+                pOverlap_and_Add_Buffer_1 + SHORT_WINDOW;
+
+            /*
+             *  If all element are zero or if the exponent is bigger than
+             *  16 ( it becomes an undefined shift) ->  skip
+             */
+
+            if (exp < 16)
+            {
+
+
+                pFreq_2_Time_data_1 = &pFreqInfo[0];
+                pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+                /*
+                 *  Each of the eight short blocks is windowed separately.
+                 *  Window shape decisions are made on a frame-by-frame
+                 *  basis.
+                 */
+
+                pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+                pShort_Window_2   =
+                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+
+
+                /*
+                 * For short windows from 7 to 5
+                 *                                      |   =========================
+                 *                                      |   |     5     6     7
+                 *               _--_  _--_  _--_  _--_ | _-|-_  _--_  _--_  _--_
+                 *              /    \/    \/    \/    \|/  |  \/    \/    \/    \
+                 *             /     /\    /\    /\    /|\  |  /\    /\    /\     \
+                 *            /     /  \  /  \  /  \  / | \ | /  \  /  \  /  \     \
+                 *           /     /    \/    \/    \/  |  \|/    \/    \     \     \
+                 *      --------------------------------|---[///////////////////////]--------
+                 *
+                 */
+
+
+                shift = exp + 15 - SCALING;
+
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    Int16 win1, win2;
+                    Int16  dat1, dat2;
+
+                    dat2 = *(pFreq_2_Time_data_2++);
+                    win2 = *(pShort_Window_2--);
+                    temp = *pOverlap_and_Add_Buffer_2;
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+
+                    *(pOverlap_and_Add_Buffer_2++) =  temp + (fxp_mul_16_by_16(dat2, win2) >> shift);
+
+                    *(pOverlap_and_Add_Buffer_1++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                }
+
+            }   /* if (exp < 16) */
+            else
+            {
+                pv_memset(
+                    pOverlap_and_Add_Buffer_1,
+                    0,
+                    SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+            }
+
+
+        }/* for ( wnd=NUM_SHORT_WINDOWS-1; wnd>=NUM_SHORT_WINDOWS/2; wnd--) */
+
+
+        wnd = NUM_SHORT_WINDOWS / 2;
+
+        pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+        /*
+         *  scratch memory is allocated in an unused part of memory
+         */
+
+
+        pScrath_mem = &pFrequency_data[ 2*LONG_WINDOW - HALF_SHORT_WINDOW];
+
+        pOverlap_and_Add_Buffer_1 = &pFrequency_data[ LONG_WINDOW];
+
+        pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1
+                                    + HALF_SHORT_WINDOW;
+
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  SHORT_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[wnd]);
+
+        /*
+         *  If all element are zero or if the exponent is bigger than
+         *  16 ( it becomes an undefined shift) ->  skip
+         */
+
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = &pFreqInfo[0];
+            pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+            pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+            pShort_Window_2 =
+                &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+            /*
+             * For short window 4
+             *                                    ====|===========
+             *                                        |   4
+             *                                    |   |   |      |
+             *                _--_  _--_  _--_  _-|-_ | _-|-_  _-|-_  _--_  _--_
+             *               /    \/    \/    \/  |  \|/  |  \/  |  \/    \/    \
+             *              /     /\    /\    /\  |  /|\  |  /\  |  /\    /\     \
+             *             /     /  \  /  \  /  \ | / | \ | /  \ | /  \  /  \     \
+             *            /     /    \/    \/    \|/  |  \|/    \|/    \/    \     \
+             *      ------------------------------[\\\|\\\|//////]-------------------
+             *           |                        | A | B |   C  |
+             *           |
+             *        W_L_STOP_1
+             */
+
+            shift = exp + 15 - SCALING;
+            {
+                Int16 win1;
+                Int16  dat1;
+                /* -------- segment A ---------------*/
+                dat1 = *(pFreq_2_Time_data_1++);
+                win1 = *(pShort_Window_1++);
+                for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pScrath_mem++)  =  fxp_mul_16_by_16(dat1, win1) >> (shift);
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+                }
+
+                /* -------- segment B ---------------*/
+                for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pOverlap_and_Add_Buffer_1++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+                }
+
+                /* -------- segment C ---------------*/
+                temp = *pOverlap_and_Add_Buffer_2;
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pOverlap_and_Add_Buffer_2++)  =  temp + (fxp_mul_16_by_16(dat1, win1) >> shift);
+
+                    temp = *pOverlap_and_Add_Buffer_2;
+                    dat1 = *(pFreq_2_Time_data_2++);
+                    win1 = *(pShort_Window_2--);
+                }
+            }
+
+        }   /* if (exp < 16) */
+        else
+        {
+            pv_memset(
+                pScrath_mem,
+                0,
+                HALF_SHORT_WINDOW*sizeof(*pScrath_mem));
+
+            pv_memset(
+                pOverlap_and_Add_Buffer_1,
+                0,
+                HALF_SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+        }
+
+
+        wnd = NUM_SHORT_WINDOWS / 2 - 1;
+
+        pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+        pScrath_mem_entry =
+            &pFrequency_data[2*LONG_WINDOW - HALF_SHORT_WINDOW - SHORT_WINDOW];
+        pScrath_mem = pScrath_mem_entry;
+
+        pOverlap_and_Add_Buffer_1 = &pFrequency_data[ LONG_WINDOW];
+
+        /* point to end of buffer less HALF_SHORT_WINDOW */
+
+        pOutput_buffer_2 = &Output_buffer[LONG_WINDOW - HALF_SHORT_WINDOW];
+        pOutput_buffer   = pOutput_buffer_2;
+
+        pOverlap_and_Add_Buffer_1x = &Time_data[W_L_STOP_1 + SHORT_WINDOW*(wnd+1)];  /* !!!! */
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  SHORT_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[wnd]);
+
+        /*
+         *  If all element are zero or if the exponent is bigger than
+         *  16 ( it becomes an undefined shift) ->  skip
+         */
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = &pFreqInfo[0];
+            pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+            /*
+             * For short window 3
+             *                             ===========|====
+             *                                    3   |
+             *                             |      |   |   |
+             *               _--_  _--_  _-|-_  _-|-_ | _-|-_  _--_  _--_  _--_
+             *              /    \/    \/  |  \/  |  \|/  |  \/    \/    \/    \
+             *             /     /\    /\  |  /\  |  /|\  |  /\    /\    /\     \
+             *            /     /  \  /  \ | /  \ | / | \ | /  \  /  \  /  \     \
+             *           /     /    \/    \|/    \|/  |  \|/    \/    \     \     \
+             *     -----|------------------[\\\\\\|///|///]--------------------------
+             *          |                  |   A  | B | C |
+             *
+             *      W_L_STOP_1
+             */
+
+
+            pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+            pShort_Window_2 =
+                &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+            shift = exp + 15 - SCALING;
+
+
+            Int16 win1;
+            Int16  dat1;
+            /* -------- segment A ---------------*/
+            dat1 = *(pFreq_2_Time_data_1++);
+            win1 = *(pShort_Window_1++);
+            for (i = SHORT_WINDOW; i != 0; i--)
+            {
+                *(pScrath_mem++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+                dat1 = *(pFreq_2_Time_data_1++);
+                win1 = *(pShort_Window_1++);
+            }
+
+            dat1 = *(pFreq_2_Time_data_2++);
+            win1 = *(pShort_Window_2--);
+
+            /* -------- segment B ---------------*/
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+                test = fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                temp =  *(pScrath_mem++) + test;
+
+
+                test = *(pOverlap_and_Add_Buffer_1x++);  /* !!!! */
+
+                limiter(*(pOutput_buffer++), (temp + test));
+
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+
+            }
+
+            /* -------- segment C ---------------*/
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+                temp = fxp_mul_16_by_16(dat1, win1) >> (shift);
+
+                *(pOverlap_and_Add_Buffer_1++) += temp;
+
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+            }
+
+        }   /* if (exp < 16) */
+        else
+        {
+
+            pv_memset(
+                pScrath_mem,
+                0,
+                SHORT_WINDOW*sizeof(*pScrath_mem));
+
+            pScrath_mem += SHORT_WINDOW;
+
+            temp = *(pScrath_mem++);
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+                limiter(*(pOutput_buffer++), temp);
+                temp = *(pScrath_mem++);
+
+
+            }
+        }
+
+
+        for (wnd = NUM_SHORT_WINDOWS / 2 - 2; wnd >= 0; wnd--)
+        {
+
+
+            pOutput_buffer_2 -= SHORT_WINDOW;
+            pOutput_buffer = pOutput_buffer_2;
+
+            /*
+             * The same memory is used as scratch in every iteration
+             */
+            pScrath_mem = pScrath_mem_entry;
+
+            pOverlap_and_Add_Buffer_2x =
+                &Time_data[W_L_STOP_1 + SHORT_WINDOW*(wnd+1)];
+
+            pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+
+
+            exp = imdct_fxp(
+                      (Int32 *)pFreqInfo,
+                      freq_2_time_buffer,
+                      SHORT_BLOCK1,
+                      Q_format,
+                      abs_max_per_window[wnd]);
+
+            /*
+             *  If all element are zero or if the exponent is bigger than
+             *  16 ( it becomes an undefined shift) ->  skip
+             */
+
+            if (exp < 16)
+            {
+
+                pFreq_2_Time_data_1 = &pFreqInfo[0];
+                pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+                /*
+                 *  Each of the eight short blocks is windowed separately.
+                 *  Window shape decisions are made on a frame-by-frame
+                 *  basis.
+                 */
+
+                pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+                if (wnd == 0)
+                {
+                    pShort_Window_1 =
+                        &Short_Window_fxp[wnd_shape_prev_bk][0];
+                }
+
+                pShort_Window_2   =
+                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+                /*
+                 * For short windows from 2 to 0
+                 *
+                 *          =========================
+                 *                                       |
+                 *                0     1     2      |   |
+                 *               _--_  _--_  _--_  _-|-_ | _--_  _--_  _--_  _--_
+                 *              /    \/    \/    \/  |  \|/    \/    \/    \/    \
+                 *             /     /\    /\    /\  |  /|\    /\    /\    /\     \
+                 *            /     /  \  /  \  /  \ | / | \  /  \  /  \  /  \     \
+                 *           /     /    \/    \/    \|/  |  \/    \/    \     \     \
+                 *      ----[\\\\\\\\\\\\\\\\\\\\\\\\]---|-----------------------------
+                 *          |
+                 *
+                 *      W_L_STOP_1
+                 */
+
+                shift = exp + 15 - SCALING;
+
+                Int16 dat1 = *(pFreq_2_Time_data_2++);
+                Int16 win1 = *(pShort_Window_2--);
+
+                temp  =  *(pScrath_mem);
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    test  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                    temp += test;
+
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+
+                    limiter(*(pOutput_buffer++), (temp + *(pOverlap_and_Add_Buffer_2x++)));
+
+
+                    *(pScrath_mem++) = fxp_mul_16_by_16(dat1, win1) >> shift;
+                    dat1 = *(pFreq_2_Time_data_2++);
+                    win1 = *(pShort_Window_2--);
+                    temp  =  *(pScrath_mem);
+
+                }
+
+            }   /* if (exp < 16) */
+            else
+            {
+                test  = *(pScrath_mem);
+                temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    limiter(*(pOutput_buffer++), (temp + test));
+
+                    *(pScrath_mem++) = 0;
+                    test  =  *(pScrath_mem);
+                    temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+                }
+            }
+
+        }   /* for ( wnd=NUM_SHORT_WINDOWS/2-1; wnd>=0; wnd--) */
+
+        pOverlap_and_Add_Buffer_2x =  &Time_data[W_L_STOP_1];
+
+        pScrath_mem = pScrath_mem_entry;
+
+        pOutput_buffer_2 -= SHORT_WINDOW;
+        pOutput_buffer = pOutput_buffer_2;
+
+        test  = *(pScrath_mem++);
+        temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+        for (i = SHORT_WINDOW; i != 0; i--)
+        {
+            limiter(*(pOutput_buffer++), (temp + test));
+
+            test  = *(pScrath_mem++);
+            temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+        }
+
+        pOverlap_and_Add_Buffer_1x = Time_data;
+
+        pOutput_buffer = Output_buffer;
+
+
+        temp = *(pOverlap_and_Add_Buffer_1x++);
+
+        for (i = W_L_STOP_1; i != 0; i--)
+        {
+            limiter(*(pOutput_buffer++), temp);
+
+            temp = *(pOverlap_and_Add_Buffer_1x++);
+        }
+
+        pOverlap_and_Add_Buffer_1x = &Time_data[0];
+
+        pOverlap_and_Add_Buffer_2 = &pFrequency_data[LONG_WINDOW];
+
+        /*
+         *  update overlap and add buffer,
+         *  so is ready for next iteration
+         */
+
+        for (int i = 0; i < W_L_STOP_2; i++)
+        {
+            temp = *(pOverlap_and_Add_Buffer_2++);
+            *(pOverlap_and_Add_Buffer_1x++) = temp;
+        }
+
+        pv_memset(
+            pOverlap_and_Add_Buffer_1x,
+            0,
+            W_L_STOP_1*sizeof(*pOverlap_and_Add_Buffer_1x));
+
+    } /* if ( wnd_seq != EIGHT_SHORT_SEQUENCE) */
+
+}
+
+#endif
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+
+void trans4m_freq_2_time_fxp_2(
+    Int32               Frequency_data[],
+    Int32               Time_data[],
+    WINDOW_SEQUENCE     wnd_seq,
+    Int                 wnd_shape_prev_bk,
+    Int                 wnd_shape_this_bk,
+    Int                 Q_format,
+    Int32               abs_max_per_window[],
+    Int32               freq_2_time_buffer[],
+    Int16               *Interleaved_output)
+
+{
+
+    Int exp;
+    Int shift;
+
+    Int  i;
+    Int  wnd;
+#if !(defined( PV_ARM_GCC_V5)||(PV_ARM_V5))
+    Int32 z;
+#endif
+    Int16 *pFreqInfo;
+    Int32 temp;
+    Int32 test;
+
+    Int16 *pFreq_2_Time_data_1;
+    Int16 *pFreq_2_Time_data_2;
+
+    const Int16 *pLong_Window_1;
+    const Int16 *pLong_Window_2;
+    const Int16 *pShort_Window_1;
+    const Int16 *pShort_Window_2;
+
+    Int32 *pOverlap_and_Add_Buffer_1;
+    Int32 *pOverlap_and_Add_Buffer_2;
+
+    Int16  *pInterleaved_output;
+    Int16  *pInterleaved_output_2;
+
+
+    const Int16 * Long_Window_fxp[NUM_WINDOW_SHAPES];
+    const Int16 * Short_Window_fxp[NUM_WINDOW_SHAPES];
+
+    Long_Window_fxp[0] = Long_Window_sine_fxp;
+    Long_Window_fxp[1] = Long_Window_KBD_fxp;
+    Short_Window_fxp[0] = Short_Window_sine_fxp;
+    Short_Window_fxp[1] = Short_Window_KBD_fxp;
+
+    if (wnd_seq != EIGHT_SHORT_SEQUENCE)
+    {
+
+        pFreqInfo = (Int16 *)Frequency_data;
+
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  LONG_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[0]);
+
+
+        /*
+         *  The C Programming Language, Second Edition, Kernighan & Ritchie,
+         *  page 206.
+         *  "The result [of a shift] is undefined if the right operand is
+         *  negative, or greater than or equal to the number of bits in the
+         *  left expression's type"
+         *   => avoid shift by 32 or 16
+         */
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = pFreqInfo;
+
+
+            switch (wnd_seq)
+            {
+
+                case ONLY_LONG_SEQUENCE:
+                default:
+
+                {
+                    pOverlap_and_Add_Buffer_1 = Time_data;
+
+                    pInterleaved_output = Interleaved_output;
+
+                    {
+
+                        const Int16 *pLong_Window_2 = &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+                        Int32 * pFreq2T   = (Int32 *)pFreqInfo;
+                        Int32 * pFreq2T_2 = &pFreq2T[HALF_LONG_WINDOW];
+                        Int32 * win = (Int32 *) & Long_Window_fxp[wnd_shape_prev_bk][0];
+
+                        Int shift = exp + 15 - SCALING;
+
+                        for (i = HALF_LONG_WINDOW; i != 0; i--)
+                        {
+                            Int16 win1, win2;
+                            Int32  temp2, test2;
+
+                            Int32  winx;
+
+                            temp2 = *(pFreq2T++);
+                            winx = *(win++);
+
+                            test  = *(pOverlap_and_Add_Buffer_1++);
+                            test2 = *(pOverlap_and_Add_Buffer_1--);
+                            temp  =   fxp_mul_16_by_16bb(temp2, winx) >> shift;
+                            temp2 =   fxp_mul_16_by_16tt(temp2, winx) >> shift;
+
+                            limiter(*(pInterleaved_output), (temp + test));
+
+                            limiter(*(pInterleaved_output + 2), (temp2 + test2));
+                            pInterleaved_output += 4;
+
+                            temp2 = *(pFreq2T_2++);
+
+                            win1  = *(pLong_Window_2--);
+                            win2  = *(pLong_Window_2--);
+                            temp  = fxp_mul_16_by_16bb(temp2, win1) >> shift;
+                            test2 = fxp_mul_16_by_16tb(temp2, win2) >> shift;
+
+                            *(pOverlap_and_Add_Buffer_1++) = temp;
+                            *(pOverlap_and_Add_Buffer_1++) = test2;
+                        }
+
+                    }
+
+                }
+
+                break;
+
+                case LONG_START_SEQUENCE:
+
+                    pFreq_2_Time_data_2 =
+                        &pFreq_2_Time_data_1[ HALF_LONG_WINDOW];
+
+                    pLong_Window_1 = &Long_Window_fxp[wnd_shape_prev_bk][0];
+                    pLong_Window_2 = &pLong_Window_1[ HALF_LONG_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[0];
+                    pOverlap_and_Add_Buffer_2 = &Time_data[HALF_LONG_WINDOW];
+
+
+                    pInterleaved_output   = Interleaved_output;
+                    pInterleaved_output_2 = pInterleaved_output + (2 * HALF_LONG_WINDOW);
+
+
+                    /*
+                     *  process first  LONG_WINDOW elements
+                     */
+
+                    shift = exp + 15 - SCALING;
+
+                    for (i = HALF_LONG_WINDOW; i != 0; i--)
+                    {
+                        Int16 win1, win2;
+                        Int16  dat1, dat2;
+                        Int32  test1, test2;
+
+                        dat1   = *(pFreq_2_Time_data_1++);
+                        win1   = *(pLong_Window_1++);
+                        test1  = *(pOverlap_and_Add_Buffer_1++);
+
+                        dat2  =  *(pFreq_2_Time_data_2++);
+                        win2  = *(pLong_Window_2++);
+                        test2 = *(pOverlap_and_Add_Buffer_2++);
+
+                        limiter(*(pInterleaved_output), (test1 + (fxp_mul_16_by_16(dat1, win1) >> shift)));
+
+                        pInterleaved_output   += 2;
+
+                        limiter(*(pInterleaved_output_2), (test2 + (fxp_mul_16_by_16(dat2, win2) >> shift)));
+
+                        pInterleaved_output_2    += 2;
+                    }
+
+
+                    /*
+                     *  data unchanged from  LONG_WINDOW to W_L_START_1
+                     *  only scaled accordingly
+                     */
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[0];
+                    pFreq_2_Time_data_1       = &pFreqInfo[LONG_WINDOW];
+
+                    exp -= SCALING;
+
+                    if (exp >= 0)
+                    {
+
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0; i--)
+                        {
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++) >> exp;
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++) >> exp;
+
+                        }
+
+                    }
+                    else if (exp < 0)
+                    {
+
+                        Int shift = -exp;
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0 ; i--)
+                        {
+                            Int32 temp2 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp2;
+                            temp2 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp2;
+                        }
+
+                    }
+                    else
+                    {
+
+                        for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0; i--)
+                        {
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++);
+                            *(pOverlap_and_Add_Buffer_1++) =
+                                *(pFreq_2_Time_data_1++);
+
+                        }
+
+                    }
+
+
+                    pFreq_2_Time_data_1  = &pFreqInfo[W_L_START_1];
+                    pFreq_2_Time_data_2  =
+                        &pFreq_2_Time_data_1[HALF_SHORT_WINDOW];
+
+                    pShort_Window_1   =
+                        &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+                    pShort_Window_2   = pShort_Window_1 - HALF_SHORT_WINDOW;
+
+                    pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1 +
+                                                HALF_SHORT_WINDOW;
+
+                    {
+                        Int16 win1, win2;
+                        Int16  dat1, dat2;
+                        Int32  temp2;
+
+                        for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                        {
+
+                            dat1  = (*pFreq_2_Time_data_1++);
+                            dat2  = (*pFreq_2_Time_data_2++);
+                            win1  = *(pShort_Window_1--);
+                            win2  = *(pShort_Window_2--);
+
+                            temp   =   fxp_mul_16_by_16(dat1, win1) >> shift;
+                            *(pOverlap_and_Add_Buffer_1++) = temp;
+
+                            temp2 =   fxp_mul_16_by_16(dat2, win2) >> shift;
+                            *(pOverlap_and_Add_Buffer_2++) = temp2;
+
+                        }
+                    }
+
+                    pOverlap_and_Add_Buffer_1 += HALF_SHORT_WINDOW;
+
+
+                    pv_memset(
+                        pOverlap_and_Add_Buffer_1,
+                        0,
+                        (LONG_BLOCK1 - W_L_START_2)
+                        *sizeof(*pOverlap_and_Add_Buffer_1));
+
+
+                    break;
+
+
+                case LONG_STOP_SEQUENCE:
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[ W_L_STOP_2];
+
+                    pInterleaved_output    = &Interleaved_output[2*W_L_STOP_2];
+
+                    pFreq_2_Time_data_1      = &pFreqInfo[W_L_STOP_2];
+
+                    exp -= SCALING;
+
+
+                    if (exp > 0)
+                    {
+                        Int16 tmp1 = (*(pFreq_2_Time_data_1++) >> exp);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pInterleaved_output), (temp + tmp1));
+
+                            pInterleaved_output += 2;
+                            tmp1 = *(pFreq_2_Time_data_1++) >> exp;
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+                        }
+                    }
+                    else if (exp < 0)
+                    {
+                        shift = -exp;
+
+                        Int32 temp1 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pInterleaved_output), (temp + temp1));
+
+                            pInterleaved_output += 2;
+                            temp1 = ((Int32) * (pFreq_2_Time_data_1++)) << shift;
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+                        }
+                    }
+                    else
+                    {
+                        Int16 tmp1 = *(pFreq_2_Time_data_1++);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+                        for (i = (LONG_WINDOW - W_L_STOP_2); i != 0; i--)
+                        {
+                            limiter(*(pInterleaved_output), (temp + tmp1));
+
+                            pInterleaved_output += 2;
+                            tmp1 = *(pFreq_2_Time_data_1++);
+                            temp = *(pOverlap_and_Add_Buffer_1++);
+                        }
+                    }
+
+
+
+                    pShort_Window_1 = &Short_Window_fxp[wnd_shape_prev_bk][0];
+                    pShort_Window_2 = &pShort_Window_1[HALF_SHORT_WINDOW];
+
+                    pFreq_2_Time_data_1 = &pFreqInfo[W_L_STOP_1];
+                    pFreq_2_Time_data_2 =
+                        &pFreq_2_Time_data_1[HALF_SHORT_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = &Time_data[ W_L_STOP_1];
+                    pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1
+                                                + HALF_SHORT_WINDOW;
+
+
+                    pInterleaved_output   = &Interleaved_output[2*W_L_STOP_1];
+                    pInterleaved_output_2 = pInterleaved_output + (2 * HALF_SHORT_WINDOW);
+
+                    exp += SCALING;  /* +8 back to what it was */
+                    shift = exp + 15 - SCALING;
+
+
+                    for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                    {
+
+                        Int16 win1;
+                        Int16 dat1;
+
+                        dat1 = *(pFreq_2_Time_data_1++);
+                        win1 = *(pShort_Window_1++);
+                        temp = *(pOverlap_and_Add_Buffer_1++);
+
+                        test  = fxp_mul_16_by_16(dat1, win1);
+
+                        limiter(*(pInterleaved_output), (temp + (test >> shift)));
+
+                        pInterleaved_output += 2;
+
+                        dat1 = *(pFreq_2_Time_data_2++);
+                        win1 = *(pShort_Window_2++);
+                        temp = *(pOverlap_and_Add_Buffer_2++);
+                        test =  fxp_mul_16_by_16(dat1, win1);
+
+                        limiter(*(pInterleaved_output_2), (temp + (test >> shift)));
+
+                        pInterleaved_output_2 += 2;
+
+                    }
+
+
+
+                    pFreq_2_Time_data_2 = &pFreqInfo[LONG_WINDOW];
+
+                    pOverlap_and_Add_Buffer_1 = Time_data;
+
+
+                    pInterleaved_output = Interleaved_output;
+
+                    pLong_Window_2   =
+                        &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+
+                    /*
+                     *  Copy previous time in current buffer, also copy overlap
+                     *  and add buffer
+                     */
+
+                    for (i = W_L_STOP_1; i != 0; i--)
+                    {
+
+                        Int16 win1;
+                        Int16 dat1;
+
+                        win1 = *(pLong_Window_2--);
+                        dat1 = *pFreq_2_Time_data_2++;
+
+                        limiter(*(pInterleaved_output), *(pOverlap_and_Add_Buffer_1));
+
+                        pInterleaved_output += 2;
+
+                        temp = fxp_mul_16_by_16(dat1, win1) >> shift;
+                        *(pOverlap_and_Add_Buffer_1++) = temp ;
+
+                    }
+
+                    for (i = (LONG_WINDOW - W_L_STOP_1); i != 0; i--)
+                    {
+
+                        temp = fxp_mul_16_by_16(*pFreq_2_Time_data_2++, *(pLong_Window_2--)) >> shift;
+                        *(pOverlap_and_Add_Buffer_1++) = temp ;
+
+                    }
+
+                    break;
+
+
+
+            } /* switch (wnd_seq) */
+
+        }   /*  if (exp < 16)  */
+
+        else
+        {
+            /* all zeros buffer or excessive down shift */
+
+            /* Overlap and add, setup buffer for next iteration */
+            pOverlap_and_Add_Buffer_1 = &Time_data[0];
+
+            pInterleaved_output = Interleaved_output;
+
+
+            temp  = (*pOverlap_and_Add_Buffer_1++);
+            for (i = LONG_WINDOW; i != 0; i--)
+            {
+
+                limiter(*(pInterleaved_output), temp);
+
+                pInterleaved_output += 2;
+                temp  = (*pOverlap_and_Add_Buffer_1++);
+            }
+            pv_memset(Time_data, 0, LONG_WINDOW*sizeof(Time_data[0]));
+        }
+
+    }
+    else
+    {
+
+        Int32 *pScrath_mem;
+        Int32 *pScrath_mem_entry;
+        Int32  *pFrequency_data = Frequency_data;
+
+        Int32 * pOverlap_and_Add_Buffer_1;
+        Int32 * pOverlap_and_Add_Buffer_2;
+        Int32 * pOverlap_and_Add_Buffer_1x;
+        Int32 * pOverlap_and_Add_Buffer_2x;
+
+
+        /*
+         *  Frequency_data is 2*LONG_WINDOW length but only
+         *  the first LONG_WINDOW elements are filled in,
+         *  then the second part can be used as scratch mem,
+         *  then grab data from one window at a time in
+         *  reverse order.
+         *  The upper LONG_WINDOW Int32 are used to hold the
+         *  computed overlap and add, used in the next call to
+         *  this function, and also as sctrach memory
+         */
+
+        /*
+         *  Frequency_data usage for the case EIGHT_SHORT_SEQUENCE
+
+          |<----- Input Freq. data ----->|< Overlap & Add ->| Unused |-Scratch-|
+          |                              |  Store for next  |        |  memory |
+          |                              |  call            |        |         |
+          |                              |                  |        |         |
+          |//////////////////////////////|\\\\\\\\\\\\\\\\\\|--------|+++++++++|
+          |                              |                  |        |         |
+          0                         LONG_WINDOW        LONG_WINDOW   |   2*LONG_WINDOW
+                                                            +        |         |
+                                                       W_L_STOP_2    |         |
+                                                                     |<--   -->|
+                                                                      SHORT_WINDOW +
+                                                                    HALF_SHORT_WINDOW
+          *
+          */
+
+        pOverlap_and_Add_Buffer_1  = &pFrequency_data[
+                                         LONG_WINDOW + 3*SHORT_WINDOW + HALF_SHORT_WINDOW];
+
+        /*
+         *  Initialize to zero, only the firt short window used in overlap
+         *  and add
+         */
+        pv_memset(
+            pOverlap_and_Add_Buffer_1,
+            0,
+            SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+
+        /*
+         *  Showt windows are evaluated in decresing order. Windows from 7
+         *  to 0 are break down in four cases: window numbers 7 to 5, 4, 3,
+         *  and 2 to 0.
+         *  The data from short windows 3 and 4 is situated at the boundary
+         *  between the 'overlap and add' buffer and the output buffer.
+         */
+        for (wnd = NUM_SHORT_WINDOWS - 1; wnd >= NUM_SHORT_WINDOWS / 2 + 1; wnd--)
+        {
+
+            pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+            exp = imdct_fxp(
+                      (Int32 *)pFreqInfo,
+                      freq_2_time_buffer,
+                      SHORT_BLOCK1,
+                      Q_format,
+                      abs_max_per_window[wnd]);
+
+            /*  W_L_STOP_1 == (LONG_WINDOW - SHORT_WINDOW)>>1 */
+            pOverlap_and_Add_Buffer_1 =
+                &pFrequency_data[ W_L_STOP_1 + SHORT_WINDOW*wnd];
+
+
+            pOverlap_and_Add_Buffer_2 =
+                pOverlap_and_Add_Buffer_1 + SHORT_WINDOW;
+
+            /*
+             *  If all element are zero or if the exponent is bigger than
+             *  16 ( it becomes an undefined shift) ->  skip
+             */
+
+            if (exp < 16)
+            {
+
+
+                pFreq_2_Time_data_1 = &pFreqInfo[0];
+                pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+                /*
+                 *  Each of the eight short blocks is windowed separately.
+                 *  Window shape decisions are made on a frame-by-frame
+                 *  basis.
+                 */
+
+                pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+                pShort_Window_2   =
+                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+
+
+                /*
+                 * For short windows from 7 to 5
+                 *                                      |   =========================
+                 *                                      |   |     5     6     7
+                 *               _--_  _--_  _--_  _--_ | _-|-_  _--_  _--_  _--_
+                 *              /    \/    \/    \/    \|/  |  \/    \/    \/    \
+                 *             /     /\    /\    /\    /|\  |  /\    /\    /\     \
+                 *            /     /  \  /  \  /  \  / | \ | /  \  /  \  /  \     \
+                 *           /     /    \/    \/    \/  |  \|/    \/    \     \     \
+                 *      --------------------------------|---[///////////////////////]--------
+                 *
+                 */
+
+
+                shift = exp + 15 - SCALING;
+
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    Int16 win1, win2;
+                    Int16  dat1, dat2;
+
+                    dat2 = *(pFreq_2_Time_data_2++);
+                    win2 = *(pShort_Window_2--);
+                    temp = *pOverlap_and_Add_Buffer_2;
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+
+                    *(pOverlap_and_Add_Buffer_2++) =  temp + (fxp_mul_16_by_16(dat2, win2) >> shift);
+
+                    *(pOverlap_and_Add_Buffer_1++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                }
+
+            }   /* if (exp < 16) */
+            else
+            {
+                pv_memset(
+                    pOverlap_and_Add_Buffer_1,
+                    0,
+                    SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+            }
+
+
+        }/* for ( wnd=NUM_SHORT_WINDOWS-1; wnd>=NUM_SHORT_WINDOWS/2; wnd--) */
+
+
+        wnd = NUM_SHORT_WINDOWS / 2;
+
+        pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+        /*
+         *  scratch memory is allocated in an unused part of memory
+         */
+
+
+        pScrath_mem = &pFrequency_data[ 2*LONG_WINDOW - HALF_SHORT_WINDOW];
+
+        pOverlap_and_Add_Buffer_1 = &pFrequency_data[ LONG_WINDOW];
+
+        pOverlap_and_Add_Buffer_2 = pOverlap_and_Add_Buffer_1
+                                    + HALF_SHORT_WINDOW;
+
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  SHORT_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[wnd]);
+
+        /*
+         *  If all element are zero or if the exponent is bigger than
+         *  16 ( it becomes an undefined shift) ->  skip
+         */
+
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = &pFreqInfo[0];
+            pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+            pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+            pShort_Window_2 =
+                &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+            /*
+             * For short window 4
+             *                                    ====|===========
+             *                                        |   4
+             *                                    |   |   |      |
+             *                _--_  _--_  _--_  _-|-_ | _-|-_  _-|-_  _--_  _--_
+             *               /    \/    \/    \/  |  \|/  |  \/  |  \/    \/    \
+             *              /     /\    /\    /\  |  /|\  |  /\  |  /\    /\     \
+             *             /     /  \  /  \  /  \ | / | \ | /  \ | /  \  /  \     \
+             *            /     /    \/    \/    \|/  |  \|/    \|/    \/    \     \
+             *      ------------------------------[\\\|\\\|//////]-------------------
+             *           |                        | A | B |   C  |
+             *           |
+             *        W_L_STOP_1
+             */
+
+            shift = exp + 15 - SCALING;
+            {
+                Int16 win1;
+                Int16  dat1;
+                /* -------- segment A ---------------*/
+                dat1 = *(pFreq_2_Time_data_1++);
+                win1 = *(pShort_Window_1++);
+                for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pScrath_mem++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+                }
+
+                /* -------- segment B ---------------*/
+                for (i = HALF_SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pOverlap_and_Add_Buffer_1++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+                }
+
+                /* -------- segment C ---------------*/
+                temp = *pOverlap_and_Add_Buffer_2;
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    *(pOverlap_and_Add_Buffer_2++)  =  temp + (fxp_mul_16_by_16(dat1, win1) >> shift);
+
+                    temp = *pOverlap_and_Add_Buffer_2;
+                    dat1 = *(pFreq_2_Time_data_2++);
+                    win1 = *(pShort_Window_2--);
+                }
+            }
+
+        }   /* if (exp < 16) */
+        else
+        {
+            pv_memset(
+                pScrath_mem,
+                0,
+                HALF_SHORT_WINDOW*sizeof(*pScrath_mem));
+
+            pv_memset(
+                pOverlap_and_Add_Buffer_1,
+                0,
+                HALF_SHORT_WINDOW*sizeof(*pOverlap_and_Add_Buffer_1));
+        }
+
+
+        wnd = NUM_SHORT_WINDOWS / 2 - 1;
+
+        pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+        pScrath_mem_entry =
+            &pFrequency_data[2*LONG_WINDOW - HALF_SHORT_WINDOW - SHORT_WINDOW];
+
+
+        pScrath_mem = pScrath_mem_entry;
+
+        pOverlap_and_Add_Buffer_1 = &pFrequency_data[ LONG_WINDOW];
+
+        /* point to end of buffer less HALF_SHORT_WINDOW */
+
+        pInterleaved_output_2 = &Interleaved_output[2*(LONG_WINDOW - HALF_SHORT_WINDOW)];
+        pInterleaved_output = pInterleaved_output_2;
+
+        pOverlap_and_Add_Buffer_1x = &Time_data[W_L_STOP_1 + SHORT_WINDOW*(wnd+1)];
+
+
+        exp = imdct_fxp(
+                  (Int32 *)pFreqInfo,
+                  freq_2_time_buffer,
+                  SHORT_BLOCK1,
+                  Q_format,
+                  abs_max_per_window[wnd]);
+
+        /*
+         *  If all element are zero or if the exponent is bigger than
+         *  16 ( it becomes an undefined shift) ->  skip
+         */
+
+        if (exp < 16)
+        {
+
+            pFreq_2_Time_data_1 = &pFreqInfo[0];
+            pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+            /*
+             * For short window 3
+             *                             ===========|====
+             *                                    3   |
+             *                             |      |   |   |
+             *               _--_  _--_  _-|-_  _-|-_ | _-|-_  _--_  _--_  _--_
+             *              /    \/    \/  |  \/  |  \|/  |  \/    \/    \/    \
+             *             /     /\    /\  |  /\  |  /|\  |  /\    /\    /\     \
+             *            /     /  \  /  \ | /  \ | / | \ | /  \  /  \  /  \     \
+             *           /     /    \/    \|/    \|/  |  \|/    \/    \     \     \
+             *     -----|------------------[\\\\\\|///|///]--------------------------
+             *          |                  |   A  | B | C |
+             *
+             *      W_L_STOP_1
+             */
+
+
+            pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+            pShort_Window_2 =
+                &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+            shift = exp + 15 - SCALING;
+
+            Int16 win1;
+            Int16  dat1;
+            /* -------- segment A ---------------*/
+            dat1 = *(pFreq_2_Time_data_1++);
+            win1 = *(pShort_Window_1++);
+            for (i = SHORT_WINDOW; i != 0; i--)
+            {
+                *(pScrath_mem++)  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+                dat1 = *(pFreq_2_Time_data_1++);
+                win1 = *(pShort_Window_1++);
+            }
+
+            dat1 = *(pFreq_2_Time_data_2++);
+            win1 = *(pShort_Window_2--);
+
+
+            /* -------- segment B ---------------*/
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+                test = fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                temp =  *(pScrath_mem++) + test;
+
+                test = *(pOverlap_and_Add_Buffer_1x++);
+                limiter(*(pInterleaved_output), (temp + test));
+
+
+                pInterleaved_output += 2;
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+
+            }
+
+            /* -------- segment C ---------------*/
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+
+                temp = fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                *(pOverlap_and_Add_Buffer_1++) += temp;
+
+                dat1 = *(pFreq_2_Time_data_2++);
+                win1 = *(pShort_Window_2--);
+            }
+
+
+        }   /* if (exp < 16) */
+        else
+        {
+
+            pv_memset(
+                pScrath_mem,
+                0,
+                SHORT_WINDOW*sizeof(*pScrath_mem));
+
+            pScrath_mem += SHORT_WINDOW;
+
+            temp = *(pScrath_mem++);
+            for (i = HALF_SHORT_WINDOW; i != 0; i--)
+            {
+                limiter(*(pInterleaved_output), (temp));
+
+                pInterleaved_output += 2;
+                temp = *(pScrath_mem++);
+
+            }
+        }
+
+
+        for (wnd = NUM_SHORT_WINDOWS / 2 - 2; wnd >= 0; wnd--)
+        {
+
+
+            pInterleaved_output_2 -= (SHORT_WINDOW * 2);
+            pInterleaved_output = pInterleaved_output_2;
+
+            /*
+             * The same memory is used as scratch in every iteration
+             */
+            pScrath_mem = pScrath_mem_entry;
+
+            pOverlap_and_Add_Buffer_2x =
+                &Time_data[W_L_STOP_1 + SHORT_WINDOW*(wnd+1)];
+
+            pFreqInfo = (Int16 *) & pFrequency_data[ wnd*SHORT_WINDOW];
+
+
+
+            exp = imdct_fxp(
+                      (Int32 *)pFreqInfo,
+                      freq_2_time_buffer,
+                      SHORT_BLOCK1,
+                      Q_format,
+                      abs_max_per_window[wnd]);
+
+            /*
+             *  If all element are zero or if the exponent is bigger than
+             *  16 ( it becomes an undefined shift) ->  skip
+             */
+
+            if (exp < 16)
+            {
+
+                pFreq_2_Time_data_1 = &pFreqInfo[0];
+                pFreq_2_Time_data_2 = &pFreqInfo[SHORT_WINDOW];
+
+
+                /*
+                 *  Each of the eight short blocks is windowed separately.
+                 *  Window shape decisions are made on a frame-by-frame
+                 *  basis.
+                 */
+
+                pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+
+                if (wnd == 0)
+                {
+                    pShort_Window_1 =
+                        &Short_Window_fxp[wnd_shape_prev_bk][0];
+                }
+
+                pShort_Window_2   =
+                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+
+                /*
+                 * For short windows from 2 to 0
+                 *
+                 *          =========================
+                 *                                       |
+                 *                0     1     2      |   |
+                 *               _--_  _--_  _--_  _-|-_ | _--_  _--_  _--_  _--_
+                 *              /    \/    \/    \/  |  \|/    \/    \/    \/    \
+                 *             /     /\    /\    /\  |  /|\    /\    /\    /\     \
+                 *            /     /  \  /  \  /  \ | / | \  /  \  /  \  /  \     \
+                 *           /     /    \/    \/    \|/  |  \/    \/    \     \     \
+                 *      ----[\\\\\\\\\\\\\\\\\\\\\\\\]---|-----------------------------
+                 *          |
+                 *
+                 *      W_L_STOP_1
+                 */
+
+                shift = exp + 15 - SCALING;
+
+                Int16 dat1 = *(pFreq_2_Time_data_2++);
+                Int16 win1 = *(pShort_Window_2--);
+
+                temp  =  *(pScrath_mem);
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    test  =  fxp_mul_16_by_16(dat1, win1) >> shift;
+
+                    temp += test;
+                    dat1 = *(pFreq_2_Time_data_1++);
+                    win1 = *(pShort_Window_1++);
+
+                    limiter(*(pInterleaved_output), (temp + *(pOverlap_and_Add_Buffer_2x++)));
+
+                    pInterleaved_output += 2;
+
+                    *(pScrath_mem++) = fxp_mul_16_by_16(dat1, win1) >> shift;
+                    dat1 = *(pFreq_2_Time_data_2++);
+                    win1 = *(pShort_Window_2--);
+                    temp  =  *(pScrath_mem);
+
+                }
+
+            }   /* if (exp < 16) */
+            else
+            {
+                test  = *(pScrath_mem);
+                temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+                for (i = SHORT_WINDOW; i != 0; i--)
+                {
+                    limiter(*(pInterleaved_output), (temp + test));
+
+                    pInterleaved_output += 2;
+
+                    *(pScrath_mem++) = 0;
+                    test  =  *(pScrath_mem);
+                    temp  = *(pOverlap_and_Add_Buffer_2x++);
+                }
+            }
+
+        }   /* for ( wnd=NUM_SHORT_WINDOWS/2-1; wnd>=0; wnd--) */
+
+        pOverlap_and_Add_Buffer_2x =  &Time_data[W_L_STOP_1];
+
+        pScrath_mem = pScrath_mem_entry;
+
+        pInterleaved_output_2 -= (SHORT_WINDOW * 2);
+        pInterleaved_output    = pInterleaved_output_2;
+
+        test  = *(pScrath_mem++);
+        temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+        for (i = SHORT_WINDOW; i != 0; i--)
+        {
+            limiter(*(pInterleaved_output), (temp + test));
+
+            pInterleaved_output += 2;
+            test  = *(pScrath_mem++);
+            temp  = *(pOverlap_and_Add_Buffer_2x++);
+
+        }
+
+        pOverlap_and_Add_Buffer_1x = Time_data;
+
+        pInterleaved_output = Interleaved_output;
+
+
+        temp = *(pOverlap_and_Add_Buffer_1x++);
+        for (i = W_L_STOP_1; i != 0; i--)
+        {
+            limiter(*(pInterleaved_output), temp);
+
+            pInterleaved_output += 2;
+            temp = *(pOverlap_and_Add_Buffer_1x++);
+
+        }
+
+        pOverlap_and_Add_Buffer_1x = &Time_data[0];
+
+        pOverlap_and_Add_Buffer_2 = &pFrequency_data[LONG_WINDOW];
+
+        /*
+         *  update overlap and add buffer,
+         *  so is ready for next iteration
+         */
+
+        for (int i = 0; i < W_L_STOP_2; i++)
+        {
+            temp = *(pOverlap_and_Add_Buffer_2++);
+            *(pOverlap_and_Add_Buffer_1x++) = temp;
+        }
+
+        pv_memset(
+            pOverlap_and_Add_Buffer_1x,
+            0,
+            W_L_STOP_1*sizeof(*pOverlap_and_Add_Buffer_1x));
+
+    } /* if ( wnd_seq != EIGHT_SHORT_SEQUENCE) */
+
+
+
+
+}   /* trans4m_freq_2_time_fxp */
+
+
+
+
diff --git a/media/libstagefright/codecs/aacdec/trans4m_time_2_freq_fxp.cpp b/media/libstagefright/codecs/aacdec/trans4m_time_2_freq_fxp.cpp
new file mode 100644
index 0000000..b1b44f0
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/trans4m_time_2_freq_fxp.cpp
@@ -0,0 +1,663 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+  Pathname: trans4m_time_2_freq_fxp.c
+  Function: trans4m_time_2_freq_fxp
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+        Modified normalization, so it now happen per window basis, eliminated
+        shifts left or rigth to accomodate TNS inverse filtering. The output
+        is 32 bits but only the lowest 16 are being used.
+        Modified fuction interface
+
+ Description: Modified variable names with leading "p" for pointers
+
+ Description:
+        Modified call to mdct_fxp to reflect extended precision use. Added routine
+        buffer_adaptation to extract 16 MSB and keep highest precision.
+        Modify casting to ensure proper operations for different platforms
+
+ Description:
+        Added comments according to code review
+
+ Description:
+        Removed include file "buffer_normalization.h"
+
+ Description:
+        Eliminated buffer_adaptation() and embedded its functionality in other
+        functions. Commented out the short window section given that this is
+        not supported by the standards
+
+ Description:
+        Added shift down operation for case when the window was equal to one.
+        This was not needed previuosly because buffer_adaptation() was doing
+        it.
+
+ Description: Created local version of vectors Long_Window_fxp and
+              Short_Window_fxp. This solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers.
+
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    Time2Freq_data    =  buffer with data in the time domain, it holds 2048
+                         points of input time data
+                         Output holds frequency (first 1024 points )
+                         type Int32
+
+    wnd_seq           =  window sequence
+                         type WINDOW_SEQUENCE
+
+    wnd_shape_prev_bk =  previous window shape type
+                         type Int
+
+    wnd_shape_this_bk =  current window shape type
+                         type Int
+
+    pQ_format          =  Holds the Q format of the data in, and data out
+                         type Int *
+
+    mem_4_in_place_FFT[] =  scratch memory for computing FFT, 1024 point
+                         type Int32
+
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    Frequency information (1024 pts.) is returned in Time2Freq_data
+    pQ_format content spectral coefficients Q format
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+The time/frequency representation of the signal is mapped onto the frequency
+domain by feeding it into the filterbank module. This module consists of
+a modified discrete cosine transform (MDCT), (windowing and DCT).
+In order to adapt the time/frequency resolution of the filterbank to the
+ characteristics of the input signal, a block switching tool is also
+adopted. N represents the window length, where N is a function of the
+window_sequence. For each channel, the N time values are transformed into the
+N/2 frequency domain values via the MDCT.
+
+The adaptation of the time-frequency resolution of the filterbank to the
+characteristics of the input signal is done by shifting between transforms
+whose input lengths are either 2048 or 256 samples. By enabling the block
+switching tool, the following transitions are meaningful:
+
+from ONLY_LONG_SEQUENCE to   { LONG_START_SEQUENCE
+                               ONLY_LONG_SEQUENCE
+
+from LONG_START_SEQUENCE to  { LONG_STOP_SEQUENCE
+                               EIGHT_SHORT_SEQUENCE
+
+from LONG_STOP_SEQUENCE to   { LONG_START_SEQUENCE
+                               ONLY_LONG_SEQUENCE
+
+from EIGHT_SHORT_SEQUENCE to { LONG_STOP_SEQUENCE
+                               EIGHT_SHORT_SEQUENCE
+
+Window shape decisions are made by the encoder on a frame-by-frame-basis.
+The window selected is applicable to the second half of the window function
+only, since the first half is constrained to use the appropriate window
+shape from the preceding frame.
+The 2048 time-domain values x'(i)(n), (i window, n sample) to be windowed are
+the last 1024 values of the previous window_sequence concatenated with 1024
+values of the current block. The formula below shows this fact:
+
+                     |  x(i-1)(n+1024)      for    0 < n < 1024
+            x'(i)(n) {
+                     |  x(i)(n)             for 1024 < n < 2048
+
+
+
+Once the window shape is selected, the window_shape syntax element is
+initialized. Together with the chosen window_sequence all information needed
+for windowing exist.
+With the window halves described below all window_sequences can be assembled.
+For window_shape == 1, the window coefficients are given by the Kaiser -
+Bessel derived (KBD) window.
+Otherwise, for window_shape == 0, a sine window is employed.
+
+The window length N can be 2048 or 256 for the KBD and the sine window.
+All four window_sequences explained below have a total length of 2048
+samples.
+For all kinds of window_sequences the window_shape of the left half of
+the first transform window is determined by the window shape of the previous
+block.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This module shall implement a scheme to switch between window types and
+    in turn perform time to frequency transformations
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] ISO 14496-3:1999, pag 111
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF ( wnd_seq == EIGHT_SHORT_SEQUENCE)
+    THEN
+
+
+        FOR ( wnd=0; wnd<NUM_SHORT_WINDOWS; wnd++)
+
+            time_info = &Time2Freq_data[ W_L_STOP_1 + wnd*SHORT_WINDOW]
+
+            FOR( i=0; i<SHORT_BLOCK1; i++)
+                aux_temp[i] = time_info[i]
+            ENDFOR
+
+
+            IF (wnd == 0)
+            THEN
+                pShort_Window_1 = &Short_Window[wnd_shape_prev_bk][0]
+            ELSE
+                pShort_Window_1 = &Short_Window[wnd_shape_this_bk][0]
+            ENDIF
+
+
+            pShort_Window_2   =
+                    &Short_Window[wnd_shape->this_bk][SHORT_WINDOW_m_1]
+
+            FOR( i=0, j=SHORT_WINDOW; i<SHORT_WINDOW; i++, j--)
+                aux_temp[             i]  *= pShort_Window_1[i]
+                aux_temp[SHORT_WINDOW+i]  *= pShort_Window_2[j]
+            ENDFOR
+
+
+            CALL MDCT( aux_temp, SHORT_BLOCK1)
+            MODIFYING( aux_temp)
+
+            FOR( i=0; i<SHORT_WINDOW; i++)
+                Time2Freq_data[wnd*SHORT_WINDOW + i] = aux_temp[i];
+            ENDFOR
+
+        ENDFOR
+
+    ELSE
+
+        SWITCH ( wnd_seq)
+
+            CASE ( ONLY_LONG_SEQUENCE)
+
+                pLong_Window_1 = &Long_Window[wnd_shape_prev_bk][0]
+                pLong_Window_2 =
+                        &Long_Window[wnd_shape_this_bk][LONG_WINDOW_m_1]
+
+                FOR (i=0; i<LONG_WINDOW; i++)
+                    Time2Freq_data[            i] *= *pLong_Window_1++
+                    Time2Freq_data[LONG_WINDOW+i] *= *pLong_Window_2--
+                ENDFOR
+
+                BREAK
+
+
+            CASE ( LONG_START_SEQUENCE)
+
+                pLong_Window_1 = &Long_Window[wnd_shape_prev_bk][0];
+
+                FOR ( i=0; i<LONG_WINDOW; i++)
+                    Time2Freq_data[ i] *= *pLong_Window_1++;
+                ENDFOR
+
+
+                pShort_Window_1   =
+                        &Short_Window[wnd_shape->this_bk][SHORT_WINDOW_m_1];
+
+                FOR ( i=0; i<SHORT_WINDOW; i++)
+                    Time2Freq_data[W_L_START_1 + i] *= *pShort_Window_1--;
+                ENDFOR
+
+
+                FOR ( i=W_L_START_2; i<LONG_BLOCK1; i++)
+                    Time2Freq_data[W_L_START_2 + i] = 0;
+                ENDFOR
+
+                BREAK
+
+
+            CASE ( LONG_STOP_SEQUENCE )
+
+                FOR ( i=0; i<W_L_STOP_1; i++)
+                    Time2Freq_data[ i] = 0;
+                ENDFOR
+
+
+                pShort_Window_1   = &Short_Window[wnd_shape->prev_bk][0];
+
+                FOR ( i=0; i<SHORT_WINDOW; i++)
+                    Time2Freq_data[W_L_STOP_1+ i] *= *pShort_Window_1++;
+                ENDFOR
+
+
+                pLong_Window_1 =
+                        &Long_Window[wnd_shape->this_bk][LONG_WINDOW_m_1];
+
+                FOR ( i=0; i<LONG_WINDOW; i++)
+                    Time2Freq_data[LONG_WINDOW + i]  *=  *pLong_Window_1--;
+                ENDFOR
+
+                BREAK
+
+
+        }
+
+        MDCT( Time2Freq_data, LONG_BLOCK1);
+        MODIFYING( Time2Freq_data)
+
+    ENDIF
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "aac_mem_funcs.h"
+#include "window_block_fxp.h"
+#include "mdct_fxp.h"
+#include "long_term_prediction.h"
+#include    "fxp_mul32.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void trans4m_time_2_freq_fxp(
+    Int32   Time2Freq_data[],       /* time data size 2048 */
+    WINDOW_SEQUENCE wnd_seq,        /* window sequence */
+    Int     wnd_shape_prev_bk,      /* window shape, current and previous  */
+    Int     wnd_shape_this_bk,
+    Int     *pQ_format,
+    Int32   mem_4_in_place_FFT[])   /* scratch memory for computing FFT */
+{
+
+    Int  i;
+
+    Int32   *pAux_temp_1;
+    Int32   *pAux_temp_2;
+    Int32   *pAux_temp;
+//    Int32   temp;
+    const   Int16 *pLong_Window_1;
+    const   Int16 *pLong_Window_2;
+    const   Int16 *pShort_Window_1;
+    const   Int16 *pShort_Window_2;
+    Int     shift = *pQ_format - 1;
+
+    const Int16 * Long_Window_fxp[NUM_WINDOW_SHAPES];
+    const Int16 * Short_Window_fxp[NUM_WINDOW_SHAPES];
+
+    Long_Window_fxp[0] = Long_Window_sine_fxp;
+    Long_Window_fxp[1] = Long_Window_KBD_fxp;
+    Short_Window_fxp[0] = Short_Window_sine_fxp;
+    Short_Window_fxp[1] = Short_Window_KBD_fxp;
+
+    if (wnd_seq != EIGHT_SHORT_SEQUENCE)
+    {
+
+        pAux_temp = Time2Freq_data;
+
+        *pQ_format = LTP_Q_FORMAT - *pQ_format;
+
+        pAux_temp_1 = pAux_temp;
+
+        switch (wnd_seq)
+        {
+
+            case LONG_START_SEQUENCE:
+
+                pAux_temp_2 = &pAux_temp_1[HALF_LONG_WINDOW];
+
+                pLong_Window_1 = &Long_Window_fxp[wnd_shape_prev_bk][0];
+                pLong_Window_2 = &pLong_Window_1[ HALF_LONG_WINDOW];
+
+
+
+
+                for (i = HALF_LONG_WINDOW; i > 0; i--)
+                {
+
+                    *pAux_temp_1 = fxp_mul32_by_16((*pAux_temp_1), *pLong_Window_1++) >> shift;
+                    pAux_temp_1++;
+                    *pAux_temp_2 = fxp_mul32_by_16((*pAux_temp_2), *pLong_Window_2++) >> shift;
+                    pAux_temp_2++;
+
+                }
+
+
+                /* data unchanged from  LONG_WINDOW to W_L_START_1 */
+                pAux_temp_1 = &pAux_temp[LONG_WINDOW];
+                if (shift)
+                {
+                    for (i = (W_L_START_1 - LONG_WINDOW) >> 1; i != 0; i--)
+                    {
+                        *(pAux_temp_1++) >>= shift;
+                        *(pAux_temp_1++) >>= shift;
+                    }
+                }
+
+
+                pAux_temp_1 = &pAux_temp[W_L_START_1];
+                pAux_temp_2 = &pAux_temp_1[HALF_SHORT_WINDOW];
+
+                pShort_Window_1   =
+                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+
+                pShort_Window_2   = pShort_Window_1 - HALF_SHORT_WINDOW;
+
+                for (i = HALF_SHORT_WINDOW; i > 0; i--)
+                {
+
+                    *pAux_temp_1 = fxp_mul32_by_16((*pAux_temp_1), *pShort_Window_1--) >> shift;
+                    pAux_temp_1++;
+                    *pAux_temp_2 = fxp_mul32_by_16((*pAux_temp_2), *pShort_Window_2--) >> shift;
+                    pAux_temp_2++;
+
+                }
+
+                pAux_temp_1 = &pAux_temp[W_L_START_2];
+
+                pv_memset(
+                    pAux_temp_1,
+                    0,
+                    (LONG_BLOCK1 - W_L_START_2)*sizeof(*pAux_temp_1));
+
+                break;
+
+
+            case LONG_STOP_SEQUENCE:
+
+                pv_memset(
+                    pAux_temp_1,
+                    0,
+                    (W_L_STOP_1)*sizeof(*pAux_temp_1));
+
+                pShort_Window_1   = &Short_Window_fxp[wnd_shape_prev_bk][0];
+                pShort_Window_2   = &pShort_Window_1[HALF_SHORT_WINDOW];
+
+                pAux_temp_1      = &pAux_temp_1[W_L_STOP_1];
+                pAux_temp_2      = pAux_temp_1 + HALF_SHORT_WINDOW;
+
+                for (i = HALF_SHORT_WINDOW; i > 0; i--)
+                {
+
+                    *pAux_temp_1 = fxp_mul32_by_16((*pAux_temp_1), *pShort_Window_1++) >> shift;
+                    pAux_temp_1++;
+                    *pAux_temp_2 = fxp_mul32_by_16((*pAux_temp_2), *pShort_Window_2++) >> shift;
+                    pAux_temp_2++;
+
+
+                }
+
+                /* data unchanged from  W_L_STOP_2 to LONG_WINDOW */
+                pAux_temp_1 = &pAux_temp[W_L_STOP_2];
+
+                if (shift)
+                {
+                    for (i = ((LONG_WINDOW - W_L_STOP_2) >> 1); i != 0; i--)
+                    {
+                        *(pAux_temp_1++) >>= shift;
+                        *(pAux_temp_1++) >>= shift;
+                    }
+                }
+
+
+
+                pAux_temp_1 = &pAux_temp[LONG_WINDOW];
+                pAux_temp_2 =  pAux_temp_1 + HALF_LONG_WINDOW;
+
+                pLong_Window_1 =
+                    &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+
+                pLong_Window_2   = &pLong_Window_1[-HALF_LONG_WINDOW];
+
+                for (i = HALF_LONG_WINDOW; i > 0; i--)
+                {
+                    *pAux_temp_1 = fxp_mul32_by_16((*pAux_temp_1), *pLong_Window_1--) >> shift;
+                    pAux_temp_1++;
+                    *pAux_temp_2 = fxp_mul32_by_16((*pAux_temp_2), *pLong_Window_2--) >> shift;
+                    pAux_temp_2++;
+
+                }
+
+                break;
+
+            case ONLY_LONG_SEQUENCE:
+            default:
+
+                pAux_temp_2 = &pAux_temp[LONG_WINDOW];
+
+                pLong_Window_1 = &Long_Window_fxp[wnd_shape_prev_bk][0];
+
+
+                pLong_Window_2 =
+                    &Long_Window_fxp[wnd_shape_this_bk][LONG_WINDOW_m_1];
+
+
+                for (i = LONG_WINDOW; i > 0; i--)
+                {
+
+                    *pAux_temp_1 = fxp_mul32_by_16((*pAux_temp_1), *pLong_Window_1++) >> shift;
+                    pAux_temp_1++;
+                    *pAux_temp_2 = fxp_mul32_by_16((*pAux_temp_2), *pLong_Window_2--) >> shift;
+                    pAux_temp_2++;
+                }
+
+                break;
+
+        }   /* end switch ( wnd_seq)  */
+
+
+
+        *pQ_format += mdct_fxp(
+                          pAux_temp,
+                          mem_4_in_place_FFT,
+                          LONG_BLOCK1);
+
+
+    }   /* end if( wnd_seq != EIGHT_SHORT_SEQUENCE) */
+
+
+
+    /*****************************************/
+    /* decoding process for short window */
+    /*****************************************/
+
+    /*
+     * For short window the following code will be applied
+     * in the future when short window is supported in the
+     * standards
+     */
+    /*-------------------------------------------------------------------------
+
+    *        pAux_temp = &mem_4_in_place_FFT[(2*SHORT_BLOCK1)];
+    *
+    *        for ( wnd=0; wnd<NUM_SHORT_WINDOWS; wnd++)
+    *        {
+    *
+    *            pShort_Window_1 = &Short_Window_fxp[wnd_shape_this_bk][0];
+    *
+    *            if (wnd == 0)
+    *            {
+    *                pShort_Window_1 = &Short_Window_fxp[wnd_shape_prev_bk][0];
+    *            }
+    *
+    *            pShort_Window_2   =
+    *                    &Short_Window_fxp[wnd_shape_this_bk][SHORT_WINDOW_m_1];
+    *
+    *            pAux_temp_1 =  pAux_temp;
+    *            pAux_temp_2 = pAux_temp_1 + SHORT_WINDOW;
+    *
+    *            Q_aux = 0;
+    *
+    *            buffer_adaptation (
+    *                &Q_aux,
+    *                &Time2Freq_data[ W_L_STOP_1 + wnd*SHORT_WINDOW],
+    *                (void *) pAux_temp,
+    *                SHORT_BLOCK1,
+    *                USING_INT,
+    *                16);
+    *
+    *
+    *            for ( i=SHORT_WINDOW; i>0; i--)
+    *            {
+    *                temp           = (*pAux_temp_1) * *pShort_Window_1++;
+    *                *pAux_temp_1++ = (temp + 0x08000L) >> 16;
+    *
+    *                temp           = (*pAux_temp_2) * *pShort_Window_2--;
+    *                *pAux_temp_2++ = (temp + 0x08000L) >> 16;
+    *
+    *            }
+    *
+    *
+    *            exp = mdct_fxp(
+    *                pAux_temp,
+    *                mem_4_in_place_FFT,
+    *                SHORT_BLOCK1);
+    *
+    *
+    *            exp += Q_aux;
+    *
+    *            pAux_temp_1  =  pAux_temp;
+    *            pAux_temp_2  =  pAux_temp_1  +  HALF_SHORT_WINDOW;
+    *            pTime_data_1 = &Time2Freq_data[wnd*SHORT_WINDOW];
+    *            pTime_data_2 =  pTime_data_1 + HALF_SHORT_WINDOW;
+    *
+    *
+    *            if (exp > 0)
+    *            {
+    *                for ( i=HALF_SHORT_WINDOW; i>0; i--)
+    *                {
+    *                    *pTime_data_1++ = (*pAux_temp_1++>>exp);
+    *                    *pTime_data_2++ = (*pAux_temp_2++>>exp);
+    *                }
+    *            }
+    *            else if (exp < 0)
+    *            {
+    *                exp = -exp;
+    *                for ( i=HALF_SHORT_WINDOW; i>0; i--)
+    *                {
+    *                    *pTime_data_1++ = (*pAux_temp_1++<<exp);
+    *                    *pTime_data_2++ = (*pAux_temp_2++<<exp);
+    *                }
+    *            }
+    *            else
+    *            {
+    *                for ( i=HALF_SHORT_WINDOW; i>0; i--)
+    *                {
+    *                    *pTime_data_1++ = (*pAux_temp_1++);
+    *                    *pTime_data_2++ = (*pAux_temp_2++);
+    *                }
+    *            }
+    *
+    *        }
+    *
+    *    }
+    *
+    *--------------------------------------------------------------------------*/
+
+}   /* trans4m_time_2_freq_fxp */
diff --git a/media/libstagefright/codecs/aacdec/unpack_idx.cpp b/media/libstagefright/codecs/aacdec/unpack_idx.cpp
new file mode 100644
index 0000000..9180994
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/unpack_idx.cpp
@@ -0,0 +1,660 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./src/unpack_idx.c
+ Function:  unpack_idx
+            unpack_idx_sgn
+            unpack_idx_esc
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Modified from original shareware code
+
+ Description:  Eliminated 3 divisions and 1 multiplication through a table
+ look-up method for calculating 1/mod and constant allocation of 1/mod^3
+ and 1/mod^2.
+ Eliminated 3 additions through simple optimizations in the code.
+ Changed if/else  statement to a switch/case utilizing fall-through.
+
+ Description:   Made changes per review comments.  Main improvements were
+ in change of switch/case to if statement, and use of temporary variable
+ to hold value of *pQuantSpec.
+
+ Description: (1) Typecast codeword_indx to Int32 before multiplication, this
+              assures the shift operation happens on a 32-bit product on
+              TI-C55x processor.
+              (2) define temp_spec as Int32 to avoid overflow
+
+ Description: Modified per review comments
+              (1) remove the two typecastings of codeword_indx when
+                  pHuffCodebook->dim == DIMENSION_4
+              (2) temp_spec is Int because the result never exceeds 16 bits
+
+ Description: Break up and combine unpack index with sign bit reading and for
+              special escape code. Parent function must know which one of the
+              3 functions should be called.
+
+ Description: Put back if-statement to get the max.
+
+ Description: When searching for the max, there was some instances where the
+              max was compared against a negative number, so the max was never
+              updated (defaulted to 0), leading to block processing in other
+              magnitude sensitive stages.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+          Int  quant_spec[]  = Array for storage of the quantized
+                               spectral coefficients.  Length is either 2 or 4.
+                               See Ref #1, Page 76 for a complete description.
+
+          Int  codeword_indx = The index into the Huffman table.
+                               Range is [1-288]
+
+    const Hcb *pHuffCodebook = Pointer to HuffmanCodebook information.
+
+          BITS  *pInputStream = Pointer to the bitstream buffer.
+          Int *max           = Pointer to maximum coefficient value.
+
+ Local Stores/Buffers/Pointers Needed:
+    const UInt div_mod[18]   = An array with the values for 1/mod
+                               stored in Q-formats 13.
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    Int quant_spec[] = Output (the quantized and signed spectral coefficients)
+                       returned via this pointer.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function decodes quantized spectral coefficients and decode their signs
+ from the input bitstream. Quantized spectral coefficients are transmitted as
+ four-tuples or 2-tuples, and this information is conveyed to the function via
+ the variable HuffCodebook->dim.
+
+ See Reference #1 for a complete description
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ This function shall correctly calculate pQuantSpec[], given the inputs
+
+ codeword_indx     = {1-288};
+ HuffCodebook->off = {0, 1, 4};
+ HuffCodebook->mod = {3, 8, 9, 13, 17};
+
+ mod =   LAV + 1 if unsigned codebook
+ mod = 2*LAV + 1 if   signed codebook
+
+ Range of values for LAV is {2,7,12,16} if unsigned
+                            {1,4}       if   signed
+
+ Additionally,
+     LAV <= 2 if dim == 4
+
+ This restricts mod ==  3                if dim == 4
+            and mod == {3, 8, 9, 13, 17} if dim == 2
+
+ This function will NOT function correctly if fed values that do not
+ meet the requirements as stated above.
+
+ This limitation on the range of values was determined by analysis
+ of Reference #1 (see below.)
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 14496-3:1999(E)
+     Part 3
+        Subpart 4.6.3.3   Decoding Process
+        Subpart 4.6.4     Tables
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC  gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her  own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    IF (pHuffCodebook->dim == 4)
+        *(pQuantSpec) = codeword_indx/(3^3);
+        codeword_indx = codeword_indx - *(pQuantSpec)*(3^3);
+        *(pQuantSpec) = *(pQuantSpec) - off;
+
+        pQuantSpec    = pQuantSpec + 1;
+
+        *(pQuantSpec) = codeword_indx/(3^2);
+        codeword_indx = codeword_indx - *(pQuantSpec)*(3^2);
+        *(pQuantSpec) = *(pQuantSpec) - off;
+
+        pQuantSpec    = pQuantSpec + 1;
+    ENDIF
+
+        *(pQuantSpec) = codeword_indx/mod;
+        codeword_indx = codeword_indx - (*pQuantSpec)*mod;
+        *(pQuantSpec) = *(pQuantSpec) - off;
+
+        pQuantSpec    = pQuantSpec + 1;
+
+        *(pQuantSpec) = codeword_indx - off;
+
+------------------------------------------------------------------------------
+ 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 "pv_audio_type_defs.h"
+#include "s_hcb.h"
+#include "ibstream.h"
+#include "unpack_idx.h"
+
+#include "fxp_mul32.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define DIV_3_CUBED    19  /* 19 = 1/27 in Q-9 format    */
+#define THREE_CUBED    27  /* 27 = 3^3                   */
+
+#define DIV_3_SQUARED  57  /* 57 = 1/9  in Q-9 format    */
+#define THREE_SQUARED   9  /*  9 = 3^2                   */
+
+#define Q_FORMAT_MOD   13  /* Q-format for 1/mod table   */
+#define Q_FORMAT_MOD2   9  /* Q-format for DIV_3_SQUARED */
+#define Q_FORMAT_MOD3   9  /* Q-format for DIV_3_CUBED   */
+
+#define LOWER_5_BITS_MASK 0x1F
+
+
+#if ( defined(PV_ARM_V5) || defined(PV_ARM_V4))
+
+__inline Int32 abs1(Int32 x)
+{
+    Int32 z;
+    /*
+        z = x - (x<0);
+        x = z ^ sign(z)
+     */
+    __asm
+    {
+        sub  z, x, x, lsr #31
+        eor  x, z, z, asr #31
+    }
+    return (x);
+}
+
+#define pv_abs(x)   abs1(x)
+
+
+#else
+
+#define pv_abs(x)   ((x) > 0)? (x) : (-x)
+
+#endif
+
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/*--------------------------------------------------------------------------
+    Possible values for mod = {3,8,9,13,17}
+
+    There exists "empty" spaces in the table.  These can potentially
+    be utilized by other const tables, if available memory becomes an issue.
+---------------------------------------------------------------------------*/
+
+const Int div_mod[18] =   /*   mod   index  Q-format */
+{
+    /* ----------------------- */
+    0xCC,                 /* |      |  0  |          */
+    0xCC,                 /* |      |  1  |          */
+    0xCC,                 /* |      |  2  |          */
+    2731,                 /* |  3   |  3  |   13     */
+    0xCC,                 /* |      |  4  |          */
+    0xCC,                 /* |      |  5  |          */
+    0xCC,                 /* |      |  6  |          */
+    0xCC,                 /* |      |  7  |          */
+    1025,                 /* |  8   |  8  |   13     */
+    911,                 /* |  9   |  9  |   13     */
+    0xCC,                 /* |      | 10  |          */
+    0xCC,                 /* |      | 11  |          */
+    0xCC,                 /* |      | 12  |          */
+    631,                 /* |  13  | 13  |   13     */
+    0xCC,                 /* |      | 14  |          */
+    0xCC,                 /* |      | 15  |          */
+    0xCC,                 /* |      | 16  |          */
+    482,                 /* |  17  | 17  |   13     */
+};
+
+/*----------------------------------------------------------------------------
+; 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 unpack_idx(
+    Int16   quant_spec[],
+    Int codeword_indx,
+    const Hcb   *pHuffCodebook,
+    BITS  *pInputStream,
+    Int *max)
+{
+    Int16 *pQuantSpec = &quant_spec[0];
+    Int  temp_spec;
+
+    const Int mod = pHuffCodebook->mod;
+    const Int off = pHuffCodebook->off;
+
+    OSCL_UNUSED_ARG(pInputStream);
+
+
+    if (pHuffCodebook->dim == DIMENSION_4)
+    {
+        /* Calculate pQuantSpec[0] */
+
+        temp_spec      = (codeword_indx * DIV_3_CUBED) >> Q_FORMAT_MOD3;
+
+        codeword_indx -= temp_spec * THREE_CUBED;
+
+        temp_spec -= off;
+        *pQuantSpec++  = (Int16)temp_spec;
+
+        temp_spec = pv_abs(temp_spec);
+
+        if (temp_spec > *max)
+        {
+            *max = temp_spec;
+        }
+
+        /* Calculate pQuantSpec[1] */
+        temp_spec      = (codeword_indx * DIV_3_SQUARED) >> Q_FORMAT_MOD2;
+
+        codeword_indx -= temp_spec * THREE_SQUARED;
+
+        temp_spec -= off;
+        *pQuantSpec++  = (Int16)temp_spec;
+
+        temp_spec = pv_abs(temp_spec);
+
+        if (temp_spec > *max)
+        {
+            *max = temp_spec;
+        }
+    }
+
+    /*
+     *  Calculate pQuantSpec[2] if dim == 4
+     *  Calculate pQuantSpec[0] if dim == 2
+     */
+
+    temp_spec      = ((Int32) codeword_indx * div_mod[mod]) >> Q_FORMAT_MOD;
+
+    codeword_indx -= temp_spec * mod;
+
+    temp_spec -= off;
+    *pQuantSpec++  = (Int16)temp_spec;
+
+    temp_spec = pv_abs(temp_spec);
+
+
+    if (temp_spec > *max)
+    {
+        *max = temp_spec;
+    }
+
+    /*
+    *  Calculate pQuantSpec[3] if dim == 4
+    *  Calculate pQuantSpec[1] if dim == 2
+    */
+    codeword_indx -= off;
+    *pQuantSpec    = (Int16)codeword_indx ;
+
+
+    codeword_indx = pv_abs(codeword_indx);
+
+    if (codeword_indx > *max)
+    {
+        *max = codeword_indx;
+    }
+
+
+    return ;
+} /* unpack_idx */
+
+
+void unpack_idx_sgn(
+    Int16   quant_spec[],
+    Int codeword_indx,
+    const Hcb   *pHuffCodebook,
+    BITS  *pInputStream,
+    Int *max)
+{
+    Int16 *pQuantSpec = &quant_spec[0];
+    Int  temp_spec;
+    Int  sgn;
+
+    const Int mod = pHuffCodebook->mod;
+    const Int off = pHuffCodebook->off;
+
+
+
+    if (pHuffCodebook->dim == DIMENSION_4)
+    {
+        /* Calculate pQuantSpec[0] */
+        preload_cache((Int32 *)pQuantSpec);
+        temp_spec      = (codeword_indx * DIV_3_CUBED) >> Q_FORMAT_MOD3;
+
+        codeword_indx -= temp_spec * THREE_CUBED;
+
+        temp_spec -= off;
+        if (temp_spec)
+        {
+            sgn = get1bits(pInputStream);
+
+
+            *pQuantSpec++ = (Int16)((sgn) ? -temp_spec : temp_spec);
+
+            temp_spec = pv_abs(temp_spec);
+
+            if (temp_spec > *max)
+            {
+                *max = temp_spec;
+            }
+
+        }
+        else
+        {
+            *pQuantSpec++ = 0;
+        }
+
+        /* Calculate pQuantSpec[1] */
+        temp_spec      = (codeword_indx * DIV_3_SQUARED) >> Q_FORMAT_MOD2;
+
+        codeword_indx -= temp_spec * THREE_SQUARED;
+
+        temp_spec -= off;
+        if (temp_spec)
+        {
+
+            sgn = get1bits(pInputStream);
+
+            *pQuantSpec++ = (Int16)((sgn) ? -temp_spec : temp_spec);
+
+            temp_spec = pv_abs(temp_spec);
+
+            if (temp_spec > *max)
+            {
+                *max = temp_spec;
+            }
+        }
+        else
+        {
+            *pQuantSpec++ = 0;
+        }
+    }
+
+    /*
+     *  Calculate pQuantSpec[2] if dim == 4
+     *  Calculate pQuantSpec[0] if dim == 2
+     */
+
+    temp_spec      = ((Int32) codeword_indx * div_mod[mod]) >> Q_FORMAT_MOD;
+
+    codeword_indx -= temp_spec * mod;
+
+    temp_spec -= off;
+    if (temp_spec)
+    {
+
+        sgn = get1bits(pInputStream);
+
+        *pQuantSpec++ = (Int16)((sgn) ? -temp_spec : temp_spec);
+
+        temp_spec = pv_abs(temp_spec);
+
+        if (temp_spec > *max)
+        {
+            *max = temp_spec;
+        }
+    }
+    else
+    {
+        *pQuantSpec++ = 0;
+    }
+
+    /*
+     *  Calculate pQuantSpec[3] if dim == 4
+     *  Calculate pQuantSpec[1] if dim == 2
+     */
+    codeword_indx -= off;
+    if (codeword_indx)
+    {
+
+        sgn = get1bits(pInputStream);
+
+        *pQuantSpec = (Int16)((sgn) ? -codeword_indx : codeword_indx);
+
+        codeword_indx = pv_abs(codeword_indx);
+
+        if (codeword_indx > *max)
+        {
+            *max = codeword_indx;
+        }
+    }
+    else
+    {
+        *pQuantSpec = 0;
+    }
+
+    return ;
+} /* unpack_idx_sgn */
+
+
+void unpack_idx_esc(
+    Int16   quant_spec[],
+    Int codeword_indx,
+    const Hcb   *pHuffCodebook,
+    BITS  *pInputStream,
+    Int *max)
+{
+    Int  temp_spec;
+    Int  sgn1 = 0, sgn2 = 0;
+    Int N;
+    Int32 esc_seq;
+
+    const Int mod = pHuffCodebook->mod;
+    const Int off = pHuffCodebook->off;
+
+
+    temp_spec      = ((Int32) codeword_indx * div_mod[mod]) >> Q_FORMAT_MOD;
+
+    codeword_indx -= temp_spec * mod;
+
+    temp_spec -= off;
+    if (temp_spec)
+    {
+        sgn1 = get1bits(pInputStream);
+    }
+
+    codeword_indx -= off;
+    if (codeword_indx)
+    {
+        sgn2 = get1bits(pInputStream);
+    }
+
+
+    if ((temp_spec & LOWER_5_BITS_MASK) == 16)
+    {
+        N = 3;
+        do
+        {
+            N++;
+
+            esc_seq = get1bits(pInputStream);
+
+        }
+        while (esc_seq != 0);
+
+        esc_seq  = getbits(N, pInputStream);
+
+        esc_seq += (1 << N);
+
+
+        temp_spec = (Int)((temp_spec * esc_seq) >> 4);
+
+    }
+
+
+    if (sgn1)
+    {
+        quant_spec[0]  = (Int16)(-temp_spec);
+    }
+    else
+    {
+        quant_spec[0]  = (Int16)temp_spec;
+    }
+
+    temp_spec = pv_abs(temp_spec);
+
+    if (temp_spec > *max)
+    {
+        *max = temp_spec;
+    }
+
+    if ((codeword_indx & LOWER_5_BITS_MASK) == 16)
+    {
+        N = 3;
+        do
+        {
+            N++;
+
+            esc_seq = get1bits(pInputStream);
+
+        }
+        while (esc_seq != 0);
+
+        esc_seq  = getbits(N, pInputStream);
+
+        esc_seq += (1 << N);
+
+        codeword_indx = (Int)((codeword_indx * esc_seq) >> 4);
+    }
+
+
+
+
+    if (sgn2)
+    {
+        quant_spec[1]    = (Int16)(-codeword_indx);
+    }
+    else
+    {
+        quant_spec[1]    = (Int16)codeword_indx;
+    }
+
+
+    codeword_indx = pv_abs(codeword_indx);
+
+    if (codeword_indx > *max)
+    {
+        *max = codeword_indx;
+    }
+
+
+    return ;
+} /* unpack_idx_esc */
diff --git a/media/libstagefright/codecs/aacdec/unpack_idx.h b/media/libstagefright/codecs/aacdec/unpack_idx.h
new file mode 100644
index 0000000..a308c4a
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/unpack_idx.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: ./include/unpack_idx.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This header file includes the function definition for unpack_idx()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef UNPACK_IDX_H
+#define UNPACK_IDX_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pv_audio_type_defs.h"
+#include    "s_hcb.h"
+#include    "s_bits.h"
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define DIMENSION_4     4
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void unpack_idx(
+        Int16  QuantSpec[],
+        Int  codeword_indx,
+        const Hcb *pHuffCodebook,
+        BITS  *pInputStream,
+        Int *max);
+    void unpack_idx_sgn(
+        Int16  quant_spec[],
+        Int  codeword_indx,
+        const Hcb *pHuffCodebook,
+        BITS  *pInputStream,
+        Int *max);
+    void unpack_idx_esc(
+        Int16  quant_spec[],
+        Int  codeword_indx,
+        const Hcb *pHuffCodebook,
+        BITS  *pInputStream,
+        Int *max);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/aacdec/window_block_fxp.h b/media/libstagefright/codecs/aacdec/window_block_fxp.h
new file mode 100644
index 0000000..f936199
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/window_block_fxp.h
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: window_block_fxp.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+    modified function definition: Time_data from Int to Int32
+    change wnd_shape from structure to passing parameters
+    delete definition of wnd_shape1, not needed.
+
+ Description: Modified based on unit test comments
+
+ Description: Change copyright, add () around constants.
+
+ Description:
+    changed Long_Window_fxp and Short _Window_fxp tables definition, from
+    "const UInt16 *"  to "const UInt16 * const" to avoid global variable
+    definition.
+
+ Description: Updated function trans4m_freq_2_time_fxp definition
+
+ Description:  Modified function interface to add output_buffer
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for window and block switch
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ (1) ISO/IEC 13818-7 Part 7: Advanced Audo Coding (AAC)
+
+
+ (2) MPEG-2 NBC Audio Decoder
+   "This software module was originally developed by AT&T, Dolby
+   Laboratories, Fraunhofer Gesellschaft IIS in the course of development
+   of the MPEG-2 NBC/MPEG-4 Audio standard ISO/IEC 13818-7, 14496-1,2 and
+   3. This software module is an implementation of a part of one or more
+   MPEG-2 NBC/MPEG-4 Audio tools as specified by the MPEG-2 NBC/MPEG-4
+   Audio standard. ISO/IEC gives users of the MPEG-2 NBC/MPEG-4 Audio
+   standards free license to this software module or modifications thereof
+   for use in hardware or software products claiming conformance to the
+   MPEG-2 NBC/MPEG-4 Audio  standards. Those intending to use this software
+   module in hardware or software products are advised that this use may
+   infringe existing patents. The original developer of this software
+   module and his/her company, the subsequent editors and their companies,
+   and ISO/IEC have no liability for use of this software module or
+   modifications thereof in an implementation. Copyright is not released
+   for non MPEG-2 NBC/MPEG-4 Audio conforming products.The original
+   developer retains full right to use the code for his/her own purpose,
+   assign or donate the code to a third party and to inhibit third party
+   from using the code for non MPEG-2 NBC/MPEG-4 Audio conforming products.
+   This copyright notice must be included in all copies or derivative
+   works."
+   Copyright(c)1996.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef WINDOW_BLOCK_FXP_H
+#define WINDOW_BLOCK_FXP_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "e_window_shape.h"
+#include "e_window_sequence.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define LONG_WINDOW         (1024)
+#define SHORT_WINDOW        (128)
+
+#define HALF_LONG_WINDOW    (LONG_WINDOW>>1)
+#define HALF_SHORT_WINDOW   (SHORT_WINDOW>>1)
+
+#define NUM_SHORT_WINDOWS   (8)
+#define LONG_WINDOW_m_1     (LONG_WINDOW-1)
+#define SHORT_WINDOW_m_1    (SHORT_WINDOW-1)
+
+    /*
+     *  Limits for window sequences, they are used to build
+     *  each long window, they are defined in the standards
+     */
+#define W_L_START_1         ((3*LONG_WINDOW - SHORT_WINDOW)>>1)
+#define W_L_START_2         ((3*LONG_WINDOW + SHORT_WINDOW)>>1)
+#define W_L_STOP_1          ((LONG_WINDOW - SHORT_WINDOW)>>1)
+#define W_L_STOP_2          ((LONG_WINDOW + SHORT_WINDOW)>>1)
+
+
+#define LONG_BLOCK1          (2*LONG_WINDOW)
+#define SHORT_BLOCK1         (2*SHORT_WINDOW)
+
+
+#define  SCALING    10
+#define  ROUNDING     (1<<(SCALING-1))
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Int16 Short_Window_KBD_fxp[ SHORT_WINDOW];
+    extern const Int16 Long_Window_KBD_fxp[ LONG_WINDOW];
+    extern const Int16 Short_Window_sine_fxp[ SHORT_WINDOW];
+    extern const Int16 Long_Window_sine_fxp[ LONG_WINDOW];
+
+    extern const Int16 * const Long_Window_fxp[];
+    extern const Int16 * const Short_Window_fxp[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void trans4m_freq_2_time_fxp(
+        Int32   Frequency_data[],
+        Int32   Time_data[],
+#ifdef AAC_PLUS
+        Int32   Output_buffer[],
+#else
+        Int16   Output_buffer[],
+#endif
+        WINDOW_SEQUENCE wnd_seq,
+        Int     wnd_shape_prev_bk,
+        Int     wnd_shape_this_bk,
+        Int     Q_format,
+        Int32   abs_max_per_window[],
+        Int32   freq_2_time_buffer[] ,
+        Int16   *Interleave_output
+    );
+
+
+
+    void trans4m_freq_2_time_fxp_1(
+        Int32   Frequency_data[],
+        Int32   Time_data[],
+        Int16   Output_buffer[],
+        WINDOW_SEQUENCE wnd_seq,
+        Int     wnd_shape_prev_bk,
+        Int     wnd_shape_this_bk,
+        Int     Q_format,
+        Int32   abs_max_per_window[],
+        Int32   freq_2_time_buffer[]
+    );
+
+
+    void trans4m_freq_2_time_fxp_2(
+        Int32   Frequency_data[],
+        Int32   Time_data[],
+        WINDOW_SEQUENCE wnd_seq,
+        Int     wnd_shape_prev_bk,
+        Int     wnd_shape_this_bk,
+        Int     Q_format,
+        Int32   abs_max_per_window[],
+        Int32   freq_2_time_buffer[] ,
+        Int16   *Interleave_output
+    );
+
+    void trans4m_time_2_freq_fxp(
+        Int32   Time2Freq_data[],
+        WINDOW_SEQUENCE wnd_seq,
+        Int     wnd_shape_prev_bk,
+        Int     wnd_shape_this_bk,
+        Int     *pQ_format,
+        Int32   mem_4_in_place_FFT[]);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /*  WINDOW_BLOCK_FXP_H */
+
diff --git a/media/libstagefright/codecs/aacdec/window_tables_fxp.cpp b/media/libstagefright/codecs/aacdec/window_tables_fxp.cpp
new file mode 100644
index 0000000..aa04225
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/window_tables_fxp.cpp
@@ -0,0 +1,730 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: window_tables_fxp.c
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+    changed table content definition from UInt to UInt16.
+
+ Description:
+    changed Long_Window_fxp and Short _Window_fxp tables definition, from
+    "const UInt16 *"  to "const UInt16 * const" to avoid global variable
+    definition.
+
+ Description:
+    Improved rounding on table elements.
+
+ Description: Eliminated structure to avoid assigning addresses to constant
+              tables. This solve linking problem when using the
+              /ropi option (Read-only position independent) for some
+              compilers
+              - Eliminated Long_Window_fxp and Short_Window_fxp as global
+                contants vectors
+
+ Who:                       Date:
+ Description:
+
+  ------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+    Window tables
+
+        For a sine table with N  points:
+
+            w_left  = sin(pi/N (n + 1/2))     for 0   =< n < N/2
+
+            w_rigth = sin(pi/N (n + 1/2))     for N/2 =< n < N
+
+
+        For Kaiser-Bessel derived (KBD)
+
+                               n             N/2
+            w_left  =  sqrt(( SUM W(p,a) )/( SUM W(p,a) )   for   0   =< n < N/2
+                              p=0            p=0
+
+
+                             N-n-1           N/2
+            w_rigth =  sqrt(( SUM W(p,a) )/( SUM W(p,a) )   for   N/2 =< n < N
+                              p=0            p=0
+
+
+            W(p,a) see ISO 14496-3, pag 113
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+    This module shall implement the fix point verwion of the windowing tables
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+    [1] ISO 14496-3, pag 113
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_audio_type_defs.h"
+#include "window_block_fxp.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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+
+const Int16 Long_Window_sine_fxp[LONG_WINDOW] =
+{
+
+
+    0x0019,  0x004B,  0x007E,  0x00B0,
+    0x00E2,  0x0114,  0x0147,  0x0179,
+    0x01AB,  0x01DD,  0x0210,  0x0242,
+    0x0274,  0x02A7,  0x02D9,  0x030B,
+    0x033D,  0x0370,  0x03A2,  0x03D4,
+    0x0406,  0x0438,  0x046B,  0x049D,
+    0x04CF,  0x0501,  0x0534,  0x0566,
+    0x0598,  0x05CA,  0x05FC,  0x062F,
+    0x0661,  0x0693,  0x06C5,  0x06F7,
+    0x072A,  0x075C,  0x078E,  0x07C0,
+    0x07F2,  0x0825,  0x0857,  0x0889,
+    0x08BB,  0x08ED,  0x091F,  0x0951,
+    0x0984,  0x09B6,  0x09E8,  0x0A1A,
+    0x0A4C,  0x0A7E,  0x0AB0,  0x0AE2,
+    0x0B14,  0x0B46,  0x0B78,  0x0BAB,
+    0x0BDD,  0x0C0F,  0x0C41,  0x0C73,
+    0x0CA5,  0x0CD7,  0x0D09,  0x0D3B,
+    0x0D6D,  0x0D9F,  0x0DD1,  0x0E03,
+    0x0E35,  0x0E67,  0x0E99,  0x0ECA,
+    0x0EFC,  0x0F2E,  0x0F60,  0x0F92,
+    0x0FC4,  0x0FF6,  0x1028,  0x105A,
+    0x108B,  0x10BD,  0x10EF,  0x1121,
+    0x1153,  0x1185,  0x11B6,  0x11E8,
+    0x121A,  0x124C,  0x127D,  0x12AF,
+    0x12E1,  0x1312,  0x1344,  0x1376,
+    0x13A8,  0x13D9,  0x140B,  0x143C,
+    0x146E,  0x14A0,  0x14D1,  0x1503,
+    0x1534,  0x1566,  0x1598,  0x15C9,
+    0x15FB,  0x162C,  0x165E,  0x168F,
+    0x16C1,  0x16F2,  0x1724,  0x1755,
+    0x1786,  0x17B8,  0x17E9,  0x181B,
+    0x184C,  0x187D,  0x18AF,  0x18E0,
+    0x1911,  0x1942,  0x1974,  0x19A5,
+    0x19D6,  0x1A07,  0x1A39,  0x1A6A,
+    0x1A9B,  0x1ACC,  0x1AFD,  0x1B2E,
+    0x1B60,  0x1B91,  0x1BC2,  0x1BF3,
+    0x1C24,  0x1C55,  0x1C86,  0x1CB7,
+    0x1CE8,  0x1D19,  0x1D4A,  0x1D7B,
+    0x1DAC,  0x1DDC,  0x1E0D,  0x1E3E,
+    0x1E6F,  0x1EA0,  0x1ED1,  0x1F01,
+    0x1F32,  0x1F63,  0x1F94,  0x1FC4,
+    0x1FF5,  0x2026,  0x2056,  0x2087,
+    0x20B7,  0x20E8,  0x2119,  0x2149,
+    0x217A,  0x21AA,  0x21DB,  0x220B,
+    0x223C,  0x226C,  0x229C,  0x22CD,
+    0x22FD,  0x232E,  0x235E,  0x238E,
+    0x23BE,  0x23EF,  0x241F,  0x244F,
+    0x247F,  0x24AF,  0x24E0,  0x2510,
+    0x2540,  0x2570,  0x25A0,  0x25D0,
+    0x2600,  0x2630,  0x2660,  0x2690,
+    0x26C0,  0x26F0,  0x2720,  0x274F,
+    0x277F,  0x27AF,  0x27DF,  0x280F,
+    0x283E,  0x286E,  0x289E,  0x28CD,
+    0x28FD,  0x292D,  0x295C,  0x298C,
+    0x29BB,  0x29EB,  0x2A1A,  0x2A4A,
+    0x2A79,  0x2AA8,  0x2AD8,  0x2B07,
+    0x2B37,  0x2B66,  0x2B95,  0x2BC4,
+    0x2BF4,  0x2C23,  0x2C52,  0x2C81,
+    0x2CB0,  0x2CDF,  0x2D0E,  0x2D3D,
+    0x2D6C,  0x2D9B,  0x2DCA,  0x2DF9,
+    0x2E28,  0x2E57,  0x2E86,  0x2EB5,
+    0x2EE3,  0x2F12,  0x2F41,  0x2F70,
+    0x2F9E,  0x2FCD,  0x2FFC,  0x302A,
+    0x3059,  0x3087,  0x30B6,  0x30E4,
+    0x3113,  0x3141,  0x316F,  0x319E,
+    0x31CC,  0x31FA,  0x3229,  0x3257,
+    0x3285,  0x32B3,  0x32E1,  0x330F,
+    0x333E,  0x336C,  0x339A,  0x33C8,
+    0x33F6,  0x3423,  0x3451,  0x347F,
+    0x34AD,  0x34DB,  0x3509,  0x3536,
+    0x3564,  0x3592,  0x35BF,  0x35ED,
+    0x361A,  0x3648,  0x3676,  0x36A3,
+    0x36D0,  0x36FE,  0x372B,  0x3759,
+    0x3786,  0x37B3,  0x37E0,  0x380E,
+    0x383B,  0x3868,  0x3895,  0x38C2,
+    0x38EF,  0x391C,  0x3949,  0x3976,
+    0x39A3,  0x39D0,  0x39FD,  0x3A29,
+    0x3A56,  0x3A83,  0x3AB0,  0x3ADC,
+    0x3B09,  0x3B35,  0x3B62,  0x3B8E,
+    0x3BBB,  0x3BE7,  0x3C14,  0x3C40,
+    0x3C6C,  0x3C99,  0x3CC5,  0x3CF1,
+    0x3D1D,  0x3D4A,  0x3D76,  0x3DA2,
+    0x3DCE,  0x3DFA,  0x3E26,  0x3E52,
+    0x3E7D,  0x3EA9,  0x3ED5,  0x3F01,
+    0x3F2D,  0x3F58,  0x3F84,  0x3FB0,
+    0x3FDB,  0x4007,  0x4032,  0x405E,
+    0x4089,  0x40B5,  0x40E0,  0x410B,
+    0x4136,  0x4162,  0x418D,  0x41B8,
+    0x41E3,  0x420E,  0x4239,  0x4264,
+    0x428F,  0x42BA,  0x42E5,  0x4310,
+    0x433B,  0x4365,  0x4390,  0x43BB,
+    0x43E5,  0x4410,  0x443B,  0x4465,
+    0x448F,  0x44BA,  0x44E4,  0x450F,
+    0x4539,  0x4563,  0x458D,  0x45B8,
+    0x45E2,  0x460C,  0x4636,  0x4660,
+    0x468A,  0x46B4,  0x46DE,  0x4707,
+    0x4731,  0x475B,  0x4785,  0x47AE,
+    0x47D8,  0x4802,  0x482B,  0x4855,
+    0x487E,  0x48A7,  0x48D1,  0x48FA,
+    0x4923,  0x494D,  0x4976,  0x499F,
+    0x49C8,  0x49F1,  0x4A1A,  0x4A43,
+    0x4A6C,  0x4A95,  0x4ABE,  0x4AE6,
+    0x4B0F,  0x4B38,  0x4B61,  0x4B89,
+    0x4BB2,  0x4BDA,  0x4C03,  0x4C2B,
+    0x4C53,  0x4C7C,  0x4CA4,  0x4CCC,
+    0x4CF4,  0x4D1D,  0x4D45,  0x4D6D,
+    0x4D95,  0x4DBD,  0x4DE5,  0x4E0D,
+    0x4E34,  0x4E5C,  0x4E84,  0x4EAB,
+    0x4ED3,  0x4EFB,  0x4F22,  0x4F4A,
+    0x4F71,  0x4F99,  0x4FC0,  0x4FE7,
+    0x500E,  0x5036,  0x505D,  0x5084,
+    0x50AB,  0x50D2,  0x50F9,  0x5120,
+    0x5147,  0x516D,  0x5194,  0x51BB,
+    0x51E2,  0x5208,  0x522F,  0x5255,
+    0x527C,  0x52A2,  0x52C8,  0x52EF,
+    0x5315,  0x533B,  0x5361,  0x5387,
+    0x53AE,  0x53D4,  0x53FA,  0x541F,
+    0x5445,  0x546B,  0x5491,  0x54B7,
+    0x54DC,  0x5502,  0x5527,  0x554D,
+    0x5572,  0x5598,  0x55BD,  0x55E2,
+    0x5608,  0x562D,  0x5652,  0x5677,
+    0x569C,  0x56C1,  0x56E6,  0x570B,
+    0x5730,  0x5754,  0x5779,  0x579E,
+    0x57C2,  0x57E7,  0x580C,  0x5830,
+    0x5854,  0x5879,  0x589D,  0x58C1,
+    0x58E5,  0x590A,  0x592E,  0x5952,
+    0x5976,  0x599A,  0x59BD,  0x59E1,
+    0x5A05,  0x5A29,  0x5A4C,  0x5A70,
+    0x5A94,  0x5AB7,  0x5ADA,  0x5AFE,
+    0x5B21,  0x5B44,  0x5B68,  0x5B8B,
+    0x5BAE,  0x5BD1,  0x5BF4,  0x5C17,
+    0x5C3A,  0x5C5D,  0x5C7F,  0x5CA2,
+    0x5CC5,  0x5CE7,  0x5D0A,  0x5D2C,
+    0x5D4F,  0x5D71,  0x5D94,  0x5DB6,
+    0x5DD8,  0x5DFA,  0x5E1C,  0x5E3E,
+    0x5E60,  0x5E82,  0x5EA4,  0x5EC6,
+    0x5EE8,  0x5F09,  0x5F2B,  0x5F4D,
+    0x5F6E,  0x5F90,  0x5FB1,  0x5FD2,
+    0x5FF4,  0x6015,  0x6036,  0x6057,
+    0x6078,  0x6099,  0x60BA,  0x60DB,
+    0x60FC,  0x611D,  0x613D,  0x615E,
+    0x617F,  0x619F,  0x61C0,  0x61E0,
+    0x6200,  0x6221,  0x6241,  0x6261,
+    0x6281,  0x62A1,  0x62C1,  0x62E1,
+    0x6301,  0x6321,  0x6341,  0x6360,
+    0x6380,  0x63A0,  0x63BF,  0x63DF,
+    0x63FE,  0x641D,  0x643D,  0x645C,
+    0x647B,  0x649A,  0x64B9,  0x64D8,
+    0x64F7,  0x6516,  0x6535,  0x6554,
+    0x6572,  0x6591,  0x65AF,  0x65CE,
+    0x65EC,  0x660B,  0x6629,  0x6647,
+    0x6666,  0x6684,  0x66A2,  0x66C0,
+    0x66DE,  0x66FC,  0x6719,  0x6737,
+    0x6755,  0x6772,  0x6790,  0x67AE,
+    0x67CB,  0x67E8,  0x6806,  0x6823,
+    0x6840,  0x685D,  0x687A,  0x6897,
+    0x68B4,  0x68D1,  0x68EE,  0x690B,
+    0x6927,  0x6944,  0x6961,  0x697D,
+    0x699A,  0x69B6,  0x69D2,  0x69EE,
+    0x6A0B,  0x6A27,  0x6A43,  0x6A5F,
+    0x6A7B,  0x6A97,  0x6AB2,  0x6ACE,
+    0x6AEA,  0x6B05,  0x6B21,  0x6B3C,
+    0x6B58,  0x6B73,  0x6B8E,  0x6BAA,
+    0x6BC5,  0x6BE0,  0x6BFB,  0x6C16,
+    0x6C31,  0x6C4C,  0x6C66,  0x6C81,
+    0x6C9C,  0x6CB6,  0x6CD1,  0x6CEB,
+    0x6D06,  0x6D20,  0x6D3A,  0x6D54,
+    0x6D6E,  0x6D88,  0x6DA2,  0x6DBC,
+    0x6DD6,  0x6DF0,  0x6E0A,  0x6E23,
+    0x6E3D,  0x6E56,  0x6E70,  0x6E89,
+    0x6EA2,  0x6EBC,  0x6ED5,  0x6EEE,
+    0x6F07,  0x6F20,  0x6F39,  0x6F52,
+    0x6F6B,  0x6F83,  0x6F9C,  0x6FB4,
+    0x6FCD,  0x6FE5,  0x6FFE,  0x7016,
+    0x702E,  0x7046,  0x705F,  0x7077,
+    0x708F,  0x70A6,  0x70BE,  0x70D6,
+    0x70EE,  0x7105,  0x711D,  0x7134,
+    0x714C,  0x7163,  0x717A,  0x7192,
+    0x71A9,  0x71C0,  0x71D7,  0x71EE,
+    0x7205,  0x721C,  0x7232,  0x7249,
+    0x7260,  0x7276,  0x728D,  0x72A3,
+    0x72B9,  0x72D0,  0x72E6,  0x72FC,
+    0x7312,  0x7328,  0x733E,  0x7354,
+    0x7369,  0x737F,  0x7395,  0x73AA,
+    0x73C0,  0x73D5,  0x73EB,  0x7400,
+    0x7415,  0x742A,  0x743F,  0x7454,
+    0x7469,  0x747E,  0x7493,  0x74A8,
+    0x74BC,  0x74D1,  0x74E5,  0x74FA,
+    0x750E,  0x7522,  0x7537,  0x754B,
+    0x755F,  0x7573,  0x7587,  0x759B,
+    0x75AE,  0x75C2,  0x75D6,  0x75E9,
+    0x75FD,  0x7610,  0x7624,  0x7637,
+    0x764A,  0x765E,  0x7671,  0x7684,
+    0x7697,  0x76A9,  0x76BC,  0x76CF,
+    0x76E2,  0x76F4,  0x7707,  0x7719,
+    0x772C,  0x773E,  0x7750,  0x7762,
+    0x7774,  0x7786,  0x7798,  0x77AA,
+    0x77BC,  0x77CE,  0x77DF,  0x77F1,
+    0x7803,  0x7814,  0x7825,  0x7837,
+    0x7848,  0x7859,  0x786A,  0x787B,
+    0x788C,  0x789D,  0x78AE,  0x78BE,
+    0x78CF,  0x78E0,  0x78F0,  0x7901,
+    0x7911,  0x7921,  0x7931,  0x7941,
+    0x7952,  0x7962,  0x7971,  0x7981,
+    0x7991,  0x79A1,  0x79B0,  0x79C0,
+    0x79CF,  0x79DF,  0x79EE,  0x79FD,
+    0x7A0D,  0x7A1C,  0x7A2B,  0x7A3A,
+    0x7A49,  0x7A57,  0x7A66,  0x7A75,
+    0x7A83,  0x7A92,  0x7AA0,  0x7AAF,
+    0x7ABD,  0x7ACB,  0x7AD9,  0x7AE7,
+    0x7AF5,  0x7B03,  0x7B11,  0x7B1F,
+    0x7B2D,  0x7B3A,  0x7B48,  0x7B55,
+    0x7B63,  0x7B70,  0x7B7D,  0x7B8B,
+    0x7B98,  0x7BA5,  0x7BB2,  0x7BBF,
+    0x7BCB,  0x7BD8,  0x7BE5,  0x7BF1,
+    0x7BFE,  0x7C0A,  0x7C17,  0x7C23,
+    0x7C2F,  0x7C3B,  0x7C47,  0x7C53,
+    0x7C5F,  0x7C6B,  0x7C77,  0x7C83,
+    0x7C8E,  0x7C9A,  0x7CA5,  0x7CB1,
+    0x7CBC,  0x7CC7,  0x7CD2,  0x7CDD,
+    0x7CE8,  0x7CF3,  0x7CFE,  0x7D09,
+    0x7D14,  0x7D1E,  0x7D29,  0x7D33,
+    0x7D3E,  0x7D48,  0x7D52,  0x7D5C,
+    0x7D67,  0x7D71,  0x7D7B,  0x7D84,
+    0x7D8E,  0x7D98,  0x7DA2,  0x7DAB,
+    0x7DB5,  0x7DBE,  0x7DC8,  0x7DD1,
+    0x7DDA,  0x7DE3,  0x7DEC,  0x7DF5,
+    0x7DFE,  0x7E07,  0x7E10,  0x7E18,
+    0x7E21,  0x7E29,  0x7E32,  0x7E3A,
+    0x7E42,  0x7E4B,  0x7E53,  0x7E5B,
+    0x7E63,  0x7E6B,  0x7E73,  0x7E7A,
+    0x7E82,  0x7E8A,  0x7E91,  0x7E99,
+    0x7EA0,  0x7EA7,  0x7EAF,  0x7EB6,
+    0x7EBD,  0x7EC4,  0x7ECB,  0x7ED2,
+    0x7ED8,  0x7EDF,  0x7EE6,  0x7EEC,
+    0x7EF3,  0x7EF9,  0x7EFF,  0x7F05,
+    0x7F0C,  0x7F12,  0x7F18,  0x7F1E,
+    0x7F23,  0x7F29,  0x7F2F,  0x7F35,
+    0x7F3A,  0x7F40,  0x7F45,  0x7F4A,
+    0x7F50,  0x7F55,  0x7F5A,  0x7F5F,
+    0x7F64,  0x7F69,  0x7F6D,  0x7F72,
+    0x7F77,  0x7F7B,  0x7F80,  0x7F84,
+    0x7F88,  0x7F8D,  0x7F91,  0x7F95,
+    0x7F99,  0x7F9D,  0x7FA1,  0x7FA4,
+    0x7FA8,  0x7FAC,  0x7FAF,  0x7FB3,
+    0x7FB6,  0x7FB9,  0x7FBD,  0x7FC0,
+    0x7FC3,  0x7FC6,  0x7FC9,  0x7FCC,
+    0x7FCE,  0x7FD1,  0x7FD4,  0x7FD6,
+    0x7FD9,  0x7FDB,  0x7FDD,  0x7FE0,
+    0x7FE2,  0x7FE4,  0x7FE6,  0x7FE8,
+    0x7FEA,  0x7FEB,  0x7FED,  0x7FEF,
+    0x7FF0,  0x7FF2,  0x7FF3,  0x7FF5,
+    0x7FF6,  0x7FF7,  0x7FF8,  0x7FF9,
+    0x7FFA,  0x7FFB,  0x7FFC,  0x7FFC,
+    0x7FFD,  0x7FFD,  0x7FFE,  0x7FFE,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF
+
+};
+
+
+const Int16 Short_Window_sine_fxp[SHORT_WINDOW] =
+{
+
+    0x00C9,  0x025B,  0x03ED,  0x057F,
+    0x0711,  0x08A2,  0x0A33,  0x0BC4,
+    0x0D54,  0x0EE3,  0x1072,  0x1201,
+    0x138F,  0x151C,  0x16A8,  0x1833,
+    0x19BE,  0x1B47,  0x1CCF,  0x1E57,
+    0x1FDD,  0x2161,  0x22E5,  0x2467,
+    0x25E8,  0x2767,  0x28E5,  0x2A61,
+    0x2BDC,  0x2D55,  0x2ECC,  0x3041,
+    0x31B5,  0x3326,  0x3496,  0x3604,
+    0x376F,  0x38D9,  0x3A40,  0x3BA5,
+    0x3D07,  0x3E68,  0x3FC5,  0x4121,
+    0x427A,  0x43D0,  0x4524,  0x4675,
+    0x47C3,  0x490F,  0x4A58,  0x4B9D,
+    0x4CE0,  0x4E20,  0x4F5D,  0x5097,
+    0x51CE,  0x5302,  0x5432,  0x5560,
+    0x568A,  0x57B0,  0x58D3,  0x59F3,
+    0x5B0F,  0x5C28,  0x5D3E,  0x5E4F,
+    0x5F5D,  0x6068,  0x616E,  0x6271,
+    0x6370,  0x646C,  0x6563,  0x6656,
+    0x6746,  0x6832,  0x6919,  0x69FD,
+    0x6ADC,  0x6BB7,  0x6C8E,  0x6D61,
+    0x6E30,  0x6EFB,  0x6FC1,  0x7083,
+    0x7140,  0x71F9,  0x72AE,  0x735E,
+    0x740A,  0x74B2,  0x7555,  0x75F3,
+    0x768D,  0x7722,  0x77B3,  0x783F,
+    0x78C7,  0x794A,  0x79C8,  0x7A41,
+    0x7AB6,  0x7B26,  0x7B91,  0x7BF8,
+    0x7C59,  0x7CB6,  0x7D0E,  0x7D62,
+    0x7DB0,  0x7DFA,  0x7E3E,  0x7E7E,
+    0x7EB9,  0x7EEF,  0x7F21,  0x7F4D,
+    0x7F74,  0x7F97,  0x7FB4,  0x7FCD,
+    0x7FE1,  0x7FF0,  0x7FF9,  0x7FFE
+};
+
+
+
+const Int16 Long_Window_KBD_fxp[LONG_WINDOW] =
+{
+
+    0x000A,  0x000E,  0x0012,  0x0015,
+    0x0019,  0x001C,  0x0020,  0x0023,
+    0x0026,  0x002A,  0x002D,  0x0030,
+    0x0034,  0x0038,  0x003B,  0x003F,
+    0x0043,  0x0047,  0x004B,  0x004F,
+    0x0053,  0x0057,  0x005B,  0x0060,
+    0x0064,  0x0069,  0x006D,  0x0072,
+    0x0077,  0x007C,  0x0081,  0x0086,
+    0x008B,  0x0091,  0x0096,  0x009C,
+    0x00A1,  0x00A7,  0x00AD,  0x00B3,
+    0x00B9,  0x00BF,  0x00C6,  0x00CC,
+    0x00D3,  0x00DA,  0x00E0,  0x00E7,
+    0x00EE,  0x00F5,  0x00FD,  0x0104,
+    0x010C,  0x0113,  0x011B,  0x0123,
+    0x012B,  0x0133,  0x013C,  0x0144,
+    0x014D,  0x0156,  0x015F,  0x0168,
+    0x0171,  0x017A,  0x0183,  0x018D,
+    0x0197,  0x01A1,  0x01AB,  0x01B5,
+    0x01BF,  0x01CA,  0x01D4,  0x01DF,
+    0x01EA,  0x01F5,  0x0200,  0x020C,
+    0x0217,  0x0223,  0x022F,  0x023B,
+    0x0247,  0x0253,  0x0260,  0x026D,
+    0x027A,  0x0287,  0x0294,  0x02A1,
+    0x02AF,  0x02BC,  0x02CA,  0x02D8,
+    0x02E7,  0x02F5,  0x0304,  0x0312,
+    0x0321,  0x0331,  0x0340,  0x034F,
+    0x035F,  0x036F,  0x037F,  0x038F,
+    0x03A0,  0x03B0,  0x03C1,  0x03D2,
+    0x03E3,  0x03F5,  0x0406,  0x0418,
+    0x042A,  0x043C,  0x044F,  0x0461,
+    0x0474,  0x0487,  0x049A,  0x04AE,
+    0x04C1,  0x04D5,  0x04E9,  0x04FD,
+    0x0512,  0x0526,  0x053B,  0x0550,
+    0x0566,  0x057B,  0x0591,  0x05A7,
+    0x05BD,  0x05D3,  0x05EA,  0x0601,
+    0x0618,  0x062F,  0x0646,  0x065E,
+    0x0676,  0x068E,  0x06A6,  0x06BF,
+    0x06D8,  0x06F1,  0x070A,  0x0723,
+    0x073D,  0x0757,  0x0771,  0x078C,
+    0x07A6,  0x07C1,  0x07DC,  0x07F7,
+    0x0813,  0x082F,  0x084B,  0x0867,
+    0x0884,  0x08A0,  0x08BD,  0x08DA,
+    0x08F8,  0x0916,  0x0933,  0x0952,
+    0x0970,  0x098F,  0x09AE,  0x09CD,
+    0x09EC,  0x0A0C,  0x0A2C,  0x0A4C,
+    0x0A6C,  0x0A8D,  0x0AAD,  0x0ACF,
+    0x0AF0,  0x0B11,  0x0B33,  0x0B55,
+    0x0B78,  0x0B9A,  0x0BBD,  0x0BE0,
+    0x0C03,  0x0C27,  0x0C4B,  0x0C6F,
+    0x0C93,  0x0CB8,  0x0CDD,  0x0D02,
+    0x0D27,  0x0D4D,  0x0D73,  0x0D99,
+    0x0DBF,  0x0DE6,  0x0E0C,  0x0E33,
+    0x0E5B,  0x0E82,  0x0EAA,  0x0ED2,
+    0x0EFB,  0x0F23,  0x0F4C,  0x0F75,
+    0x0F9F,  0x0FC8,  0x0FF2,  0x101C,
+    0x1047,  0x1071,  0x109C,  0x10C7,
+    0x10F3,  0x111E,  0x114A,  0x1176,
+    0x11A3,  0x11D0,  0x11FC,  0x122A,
+    0x1257,  0x1285,  0x12B3,  0x12E1,
+    0x130F,  0x133E,  0x136D,  0x139C,
+    0x13CB,  0x13FB,  0x142B,  0x145B,
+    0x148B,  0x14BC,  0x14ED,  0x151E,
+    0x1550,  0x1581,  0x15B3,  0x15E5,
+    0x1618,  0x164A,  0x167D,  0x16B0,
+    0x16E3,  0x1717,  0x174B,  0x177F,
+    0x17B3,  0x17E8,  0x181D,  0x1852,
+    0x1887,  0x18BC,  0x18F2,  0x1928,
+    0x195E,  0x1995,  0x19CB,  0x1A02,
+    0x1A39,  0x1A71,  0x1AA8,  0x1AE0,
+    0x1B18,  0x1B50,  0x1B89,  0x1BC1,
+    0x1BFA,  0x1C34,  0x1C6D,  0x1CA7,
+    0x1CE0,  0x1D1A,  0x1D55,  0x1D8F,
+    0x1DCA,  0x1E05,  0x1E40,  0x1E7B,
+    0x1EB7,  0x1EF2,  0x1F2E,  0x1F6B,
+    0x1FA7,  0x1FE4,  0x2020,  0x205D,
+    0x209B,  0x20D8,  0x2116,  0x2153,
+    0x2191,  0x21D0,  0x220E,  0x224D,
+    0x228B,  0x22CA,  0x2309,  0x2349,
+    0x2388,  0x23C8,  0x2408,  0x2448,
+    0x2488,  0x24C9,  0x2509,  0x254A,
+    0x258B,  0x25CC,  0x260E,  0x264F,
+    0x2691,  0x26D3,  0x2715,  0x2757,
+    0x2799,  0x27DC,  0x281F,  0x2861,
+    0x28A4,  0x28E8,  0x292B,  0x296E,
+    0x29B2,  0x29F6,  0x2A3A,  0x2A7E,
+    0x2AC2,  0x2B06,  0x2B4B,  0x2B8F,
+    0x2BD4,  0x2C19,  0x2C5E,  0x2CA3,
+    0x2CE9,  0x2D2E,  0x2D74,  0x2DB9,
+    0x2DFF,  0x2E45,  0x2E8B,  0x2ED1,
+    0x2F18,  0x2F5E,  0x2FA5,  0x2FEB,
+    0x3032,  0x3079,  0x30C0,  0x3107,
+    0x314E,  0x3195,  0x31DD,  0x3224,
+    0x326C,  0x32B4,  0x32FB,  0x3343,
+    0x338B,  0x33D3,  0x341B,  0x3463,
+    0x34AC,  0x34F4,  0x353D,  0x3585,
+    0x35CE,  0x3616,  0x365F,  0x36A8,
+    0x36F1,  0x373A,  0x3783,  0x37CC,
+    0x3815,  0x385E,  0x38A7,  0x38F0,
+    0x393A,  0x3983,  0x39CC,  0x3A16,
+    0x3A5F,  0x3AA9,  0x3AF2,  0x3B3C,
+    0x3B86,  0x3BCF,  0x3C19,  0x3C63,
+    0x3CAC,  0x3CF6,  0x3D40,  0x3D8A,
+    0x3DD3,  0x3E1D,  0x3E67,  0x3EB1,
+    0x3EFB,  0x3F45,  0x3F8E,  0x3FD8,
+    0x4022,  0x406C,  0x40B6,  0x4100,
+    0x414A,  0x4193,  0x41DD,  0x4227,
+    0x4271,  0x42BB,  0x4304,  0x434E,
+    0x4398,  0x43E1,  0x442B,  0x4475,
+    0x44BE,  0x4508,  0x4551,  0x459B,
+    0x45E4,  0x462E,  0x4677,  0x46C0,
+    0x4709,  0x4753,  0x479C,  0x47E5,
+    0x482E,  0x4877,  0x48C0,  0x4909,
+    0x4951,  0x499A,  0x49E3,  0x4A2B,
+    0x4A74,  0x4ABC,  0x4B04,  0x4B4D,
+    0x4B95,  0x4BDD,  0x4C25,  0x4C6D,
+    0x4CB5,  0x4CFC,  0x4D44,  0x4D8C,
+    0x4DD3,  0x4E1A,  0x4E62,  0x4EA9,
+    0x4EF0,  0x4F37,  0x4F7E,  0x4FC4,
+    0x500B,  0x5051,  0x5098,  0x50DE,
+    0x5124,  0x516A,  0x51B0,  0x51F6,
+    0x523B,  0x5281,  0x52C6,  0x530B,
+    0x5351,  0x5396,  0x53DA,  0x541F,
+    0x5464,  0x54A8,  0x54EC,  0x5530,
+    0x5574,  0x55B8,  0x55FC,  0x563F,
+    0x5683,  0x56C6,  0x5709,  0x574C,
+    0x578F,  0x57D1,  0x5814,  0x5856,
+    0x5898,  0x58DA,  0x591B,  0x595D,
+    0x599E,  0x59E0,  0x5A21,  0x5A61,
+    0x5AA2,  0x5AE3,  0x5B23,  0x5B63,
+    0x5BA3,  0x5BE3,  0x5C22,  0x5C62,
+    0x5CA1,  0x5CE0,  0x5D1F,  0x5D5D,
+    0x5D9C,  0x5DDA,  0x5E18,  0x5E56,
+    0x5E93,  0x5ED1,  0x5F0E,  0x5F4B,
+    0x5F87,  0x5FC4,  0x6000,  0x603D,
+    0x6079,  0x60B4,  0x60F0,  0x612B,
+    0x6166,  0x61A1,  0x61DC,  0x6216,
+    0x6250,  0x628A,  0x62C4,  0x62FE,
+    0x6337,  0x6370,  0x63A9,  0x63E2,
+    0x641A,  0x6452,  0x648A,  0x64C2,
+    0x64F9,  0x6531,  0x6568,  0x659E,
+    0x65D5,  0x660B,  0x6641,  0x6677,
+    0x66AD,  0x66E2,  0x6717,  0x674C,
+    0x6781,  0x67B5,  0x67E9,  0x681D,
+    0x6851,  0x6885,  0x68B8,  0x68EB,
+    0x691D,  0x6950,  0x6982,  0x69B4,
+    0x69E6,  0x6A17,  0x6A48,  0x6A79,
+    0x6AAA,  0x6ADB,  0x6B0B,  0x6B3B,
+    0x6B6A,  0x6B9A,  0x6BC9,  0x6BF8,
+    0x6C27,  0x6C55,  0x6C83,  0x6CB1,
+    0x6CDF,  0x6D0D,  0x6D3A,  0x6D67,
+    0x6D93,  0x6DC0,  0x6DEC,  0x6E18,
+    0x6E44,  0x6E6F,  0x6E9A,  0x6EC5,
+    0x6EF0,  0x6F1A,  0x6F44,  0x6F6E,
+    0x6F98,  0x6FC1,  0x6FEA,  0x7013,
+    0x703C,  0x7064,  0x708C,  0x70B4,
+    0x70DB,  0x7103,  0x712A,  0x7151,
+    0x7177,  0x719D,  0x71C3,  0x71E9,
+    0x720F,  0x7234,  0x7259,  0x727E,
+    0x72A2,  0x72C7,  0x72EB,  0x730E,
+    0x7332,  0x7355,  0x7378,  0x739B,
+    0x73BD,  0x73E0,  0x7402,  0x7424,
+    0x7445,  0x7466,  0x7487,  0x74A8,
+    0x74C9,  0x74E9,  0x7509,  0x7529,
+    0x7548,  0x7568,  0x7587,  0x75A5,
+    0x75C4,  0x75E2,  0x7601,  0x761E,
+    0x763C,  0x7659,  0x7676,  0x7693,
+    0x76B0,  0x76CC,  0x76E9,  0x7705,
+    0x7720,  0x773C,  0x7757,  0x7772,
+    0x778D,  0x77A8,  0x77C2,  0x77DC,
+    0x77F6,  0x780F,  0x7829,  0x7842,
+    0x785B,  0x7874,  0x788C,  0x78A5,
+    0x78BD,  0x78D5,  0x78EC,  0x7904,
+    0x791B,  0x7932,  0x7949,  0x795F,
+    0x7976,  0x798C,  0x79A2,  0x79B7,
+    0x79CD,  0x79E2,  0x79F7,  0x7A0C,
+    0x7A21,  0x7A35,  0x7A4A,  0x7A5E,
+    0x7A72,  0x7A85,  0x7A99,  0x7AAC,
+    0x7ABF,  0x7AD2,  0x7AE5,  0x7AF7,
+    0x7B09,  0x7B1B,  0x7B2D,  0x7B3F,
+    0x7B51,  0x7B62,  0x7B73,  0x7B84,
+    0x7B95,  0x7BA5,  0x7BB6,  0x7BC6,
+    0x7BD6,  0x7BE6,  0x7BF6,  0x7C05,
+    0x7C15,  0x7C24,  0x7C33,  0x7C42,
+    0x7C50,  0x7C5F,  0x7C6D,  0x7C7B,
+    0x7C89,  0x7C97,  0x7CA5,  0x7CB2,
+    0x7CC0,  0x7CCD,  0x7CDA,  0x7CE7,
+    0x7CF3,  0x7D00,  0x7D0C,  0x7D18,
+    0x7D25,  0x7D31,  0x7D3C,  0x7D48,
+    0x7D53,  0x7D5F,  0x7D6A,  0x7D75,
+    0x7D80,  0x7D8B,  0x7D95,  0x7DA0,
+    0x7DAA,  0x7DB4,  0x7DBE,  0x7DC8,
+    0x7DD2,  0x7DDC,  0x7DE5,  0x7DEF,
+    0x7DF8,  0x7E01,  0x7E0A,  0x7E13,
+    0x7E1C,  0x7E25,  0x7E2D,  0x7E36,
+    0x7E3E,  0x7E46,  0x7E4E,  0x7E56,
+    0x7E5E,  0x7E66,  0x7E6D,  0x7E75,
+    0x7E7C,  0x7E83,  0x7E8B,  0x7E92,
+    0x7E99,  0x7EA0,  0x7EA6,  0x7EAD,
+    0x7EB3,  0x7EBA,  0x7EC0,  0x7EC6,
+    0x7ECD,  0x7ED3,  0x7ED9,  0x7EDE,
+    0x7EE4,  0x7EEA,  0x7EF0,  0x7EF5,
+    0x7EFA,  0x7F00,  0x7F05,  0x7F0A,
+    0x7F0F,  0x7F14,  0x7F19,  0x7F1E,
+    0x7F23,  0x7F27,  0x7F2C,  0x7F30,
+    0x7F35,  0x7F39,  0x7F3D,  0x7F41,
+    0x7F46,  0x7F4A,  0x7F4E,  0x7F52,
+    0x7F55,  0x7F59,  0x7F5D,  0x7F60,
+    0x7F64,  0x7F68,  0x7F6B,  0x7F6E,
+    0x7F72,  0x7F75,  0x7F78,  0x7F7B,
+    0x7F7E,  0x7F81,  0x7F84,  0x7F87,
+    0x7F8A,  0x7F8D,  0x7F90,  0x7F92,
+    0x7F95,  0x7F97,  0x7F9A,  0x7F9C,
+    0x7F9F,  0x7FA1,  0x7FA4,  0x7FA6,
+    0x7FA8,  0x7FAA,  0x7FAC,  0x7FAE,
+    0x7FB1,  0x7FB3,  0x7FB5,  0x7FB6,
+    0x7FB8,  0x7FBA,  0x7FBC,  0x7FBE,
+    0x7FBF,  0x7FC1,  0x7FC3,  0x7FC4,
+    0x7FC6,  0x7FC8,  0x7FC9,  0x7FCB,
+    0x7FCC,  0x7FCD,  0x7FCF,  0x7FD0,
+    0x7FD1,  0x7FD3,  0x7FD4,  0x7FD5,
+    0x7FD6,  0x7FD8,  0x7FD9,  0x7FDA,
+    0x7FDB,  0x7FDC,  0x7FDD,  0x7FDE,
+    0x7FDF,  0x7FE0,  0x7FE1,  0x7FE2,
+    0x7FE3,  0x7FE4,  0x7FE4,  0x7FE5,
+    0x7FE6,  0x7FE7,  0x7FE8,  0x7FE8,
+    0x7FE9,  0x7FEA,  0x7FEA,  0x7FEB,
+    0x7FEC,  0x7FEC,  0x7FED,  0x7FEE,
+    0x7FEE,  0x7FEF,  0x7FEF,  0x7FF0,
+    0x7FF0,  0x7FF1,  0x7FF1,  0x7FF2,
+    0x7FF2,  0x7FF3,  0x7FF3,  0x7FF4,
+    0x7FF4,  0x7FF4,  0x7FF5,  0x7FF5,
+    0x7FF6,  0x7FF6,  0x7FF6,  0x7FF7,
+    0x7FF7,  0x7FF7,  0x7FF8,  0x7FF8,
+    0x7FF8,  0x7FF8,  0x7FF9,  0x7FF9,
+    0x7FF9,  0x7FF9,  0x7FFA,  0x7FFA,
+    0x7FFA,  0x7FFA,  0x7FFA,  0x7FFB,
+    0x7FFB,  0x7FFB,  0x7FFB,  0x7FFB,
+    0x7FFC,  0x7FFC,  0x7FFC,  0x7FFC,
+    0x7FFC,  0x7FFC,  0x7FFC,  0x7FFC,
+    0x7FFD,  0x7FFD,  0x7FFD,  0x7FFD,
+    0x7FFD,  0x7FFD,  0x7FFD,  0x7FFD,
+    0x7FFD,  0x7FFD,  0x7FFE,  0x7FFE,
+    0x7FFE,  0x7FFE,  0x7FFE,  0x7FFE,
+    0x7FFE,  0x7FFE,  0x7FFE,  0x7FFE,
+    0x7FFE,  0x7FFE,  0x7FFE,  0x7FFE,
+    0x7FFE,  0x7FFE,  0x7FFE,  0x7FFE,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF
+
+};
+
+
+
+
+const Int16 Short_Window_KBD_fxp[SHORT_WINDOW] =
+{
+
+    0x0001,  0x0004,  0x0008,  0x000D,
+    0x0014,  0x001D,  0x0029,  0x0039,
+    0x004C,  0x0063,  0x0080,  0x00A2,
+    0x00CB,  0x00FB,  0x0133,  0x0174,
+    0x01BE,  0x0214,  0x0275,  0x02E3,
+    0x035E,  0x03E8,  0x0481,  0x052B,
+    0x05E7,  0x06B4,  0x0795,  0x088A,
+    0x0993,  0x0AB2,  0x0BE7,  0x0D32,
+    0x0E94,  0x100E,  0x119F,  0x1347,
+    0x1507,  0x16DE,  0x18CC,  0x1AD0,
+    0x1CEB,  0x1F1A,  0x215F,  0x23B6,
+    0x2620,  0x289C,  0x2B27,  0x2DC0,
+    0x3066,  0x3317,  0x35D2,  0x3894,
+    0x3B5C,  0x3E28,  0x40F6,  0x43C4,
+    0x468F,  0x4956,  0x4C18,  0x4ED1,
+    0x5181,  0x5425,  0x56BC,  0x5944,
+    0x5BBB,  0x5E21,  0x6073,  0x62B1,
+    0x64DA,  0x66EC,  0x68E7,  0x6ACB,
+    0x6C96,  0x6E49,  0x6FE4,  0x7166,
+    0x72D0,  0x7421,  0x755B,  0x767E,
+    0x778A,  0x7881,  0x7962,  0x7A30,
+    0x7AEA,  0x7B92,  0x7C29,  0x7CB0,
+    0x7D28,  0x7D92,  0x7DF0,  0x7E42,
+    0x7E89,  0x7EC7,  0x7EFC,  0x7F2A,
+    0x7F50,  0x7F71,  0x7F8C,  0x7FA3,
+    0x7FB6,  0x7FC5,  0x7FD2,  0x7FDC,
+    0x7FE4,  0x7FEB,  0x7FF0,  0x7FF4,
+    0x7FF7,  0x7FF9,  0x7FFB,  0x7FFC,
+    0x7FFD,  0x7FFE,  0x7FFE,  0x7FFE,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF,
+    0x7FFF,  0x7FFF,  0x7FFF,  0x7FFF
+};
+
diff --git a/media/libstagefright/codecs/aacdec/write_output.h b/media/libstagefright/codecs/aacdec/write_output.h
new file mode 100644
index 0000000..0085a63
--- /dev/null
+++ b/media/libstagefright/codecs/aacdec/write_output.h
@@ -0,0 +1,138 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Pathname: write_output.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Change function prototype.
+
+ Description: Remove CR/LF from unknown editor
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Header file for the declaration of the function write_output()
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef WRITE_OUTPUT_H
+#define WRITE_OUTPUT_H
+
+#include "pv_audio_type_defs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; INCLUDES
+    ----------------------------------------------------------------------------*/
+#include "pvmp4audiodecoder_api.h"
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+#ifndef AAC_PLUS
+
+    Int write_output(
+        const Int16   sourceLeft[],
+        const Int16   sourceRight[],
+        Int16   outputBuffer[],
+        const Int     sourcePointsPerChannel,
+        const Int     sourceChannels,
+        const Int     requestedChannels,
+        const tPVMP4AudioDecoderOutputFormat  outputFormat);
+
+#else
+
+    Int write_output(
+        const Int16   sourceLeft[],
+        const Int16   sourceRight[],
+        Int16   outputBuffer[],
+        const Int     sourcePointsPerChannel,
+        const Int     sourceChannels,
+        const Int     requestedChannels,
+#ifdef PARAMETRICSTEREO
+        Int32 sbrEnablePS,
+#endif
+        const tPVMP4AudioDecoderOutputFormat  outputFormat);
+
+#ifdef AAC_32_BIT_INTERFACE
+
+    Int write_output_1(
+        const Int32   sourceLeft[],
+        const Int32   sourceRight[],
+        Int16   outputBuffer[],
+        const Int     sourcePointsPerChannel,
+        const Int     sourceChannels,
+        const Int     requestedChannels,
+        const tPVMP4AudioDecoderOutputFormat  outputFormat);
+#endif
+
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* WRITE_OUTPUT_H */
+
+
diff --git a/media/libstagefright/codecs/amrnb/Android.mk b/media/libstagefright/codecs/amrnb/Android.mk
new file mode 100644
index 0000000..2e43120
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/Android.mk
@@ -0,0 +1,4 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codecs/amrnb/common/Android.mk b/media/libstagefright/codecs/amrnb/common/Android.mk
new file mode 100644
index 0000000..2657a52
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/Android.mk
@@ -0,0 +1,76 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	src/add.cpp \
+ 	src/az_lsp.cpp \
+ 	src/bitno_tab.cpp \
+ 	src/bitreorder_tab.cpp \
+ 	src/bits2prm.cpp \
+ 	src/bytesused.cpp \
+ 	src/c2_9pf_tab.cpp \
+ 	src/copy.cpp \
+ 	src/div_32.cpp \
+ 	src/div_s.cpp \
+ 	src/extract_h.cpp \
+ 	src/extract_l.cpp \
+ 	src/gains_tbl.cpp \
+ 	src/gc_pred.cpp \
+ 	src/gmed_n.cpp \
+ 	src/grid_tbl.cpp \
+ 	src/gray_tbl.cpp \
+ 	src/int_lpc.cpp \
+ 	src/inv_sqrt.cpp \
+ 	src/inv_sqrt_tbl.cpp \
+ 	src/l_abs.cpp \
+ 	src/l_deposit_h.cpp \
+ 	src/l_deposit_l.cpp \
+ 	src/l_shr_r.cpp \
+ 	src/log2.cpp \
+ 	src/log2_norm.cpp \
+ 	src/log2_tbl.cpp \
+ 	src/lsfwt.cpp \
+ 	src/lsp.cpp \
+ 	src/lsp_az.cpp \
+ 	src/lsp_lsf.cpp \
+ 	src/lsp_lsf_tbl.cpp \
+ 	src/lsp_tab.cpp \
+ 	src/mult_r.cpp \
+ 	src/norm_l.cpp \
+ 	src/norm_s.cpp \
+ 	src/overflow_tbl.cpp \
+ 	src/ph_disp_tab.cpp \
+ 	src/pow2.cpp \
+ 	src/pow2_tbl.cpp \
+ 	src/pred_lt.cpp \
+ 	src/q_plsf.cpp \
+ 	src/q_plsf_3.cpp \
+ 	src/q_plsf_3_tbl.cpp \
+ 	src/q_plsf_5.cpp \
+ 	src/q_plsf_5_tbl.cpp \
+ 	src/qua_gain_tbl.cpp \
+ 	src/reorder.cpp \
+ 	src/residu.cpp \
+ 	src/round.cpp \
+ 	src/set_zero.cpp \
+ 	src/shr.cpp \
+ 	src/shr_r.cpp \
+ 	src/sqrt_l.cpp \
+ 	src/sqrt_l_tbl.cpp \
+ 	src/sub.cpp \
+ 	src/syn_filt.cpp \
+ 	src/vad1.cpp \
+ 	src/weight_a.cpp \
+ 	src/window_tab.cpp
+
+LOCAL_C_INCLUDES := \
+        $(LOCAL_PATH)/include
+
+LOCAL_CFLAGS := \
+        -DOSCL_UNUSED_ARG= -DOSCL_IMPORT_REF= -DOSCL_EXPORT_REF=
+
+LOCAL_PRELINK_MODULE:= false
+
+LOCAL_MODULE := libstagefright_amrnb_common
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/amrnb/common/include/abs_s.h b/media/libstagefright/codecs/amrnb/common/include/abs_s.h
new file mode 100644
index 0000000..e92eaf4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/abs_s.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: ./gsm-amr/c/include/abs_s.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for abs_s function.
+
+ Description: Updated template to make it build for Symbian.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the abs_s function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ABS_S_H
+#define ABS_S_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 abs_s(Word16 var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* ABS_S_H */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/add.h b/media/libstagefright/codecs/amrnb/common/include/add.h
new file mode 100644
index 0000000..43daeca
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/add.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/add.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Created separate header file for add function.
+
+ Description: Changed function prototype; pointer to  overflow flag is passed
+              in as a parameter.
+
+ Description: Updated copyright section.
+              Changed "overflow" to "pOverflow" in the function prototype.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                           Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the add function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef ADD_H
+#define ADD_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 add(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ADD_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/az_lsp.h b/media/libstagefright/codecs/amrnb/common/include/az_lsp.h
new file mode 100644
index 0000000..3e15ba3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/az_lsp.h
@@ -0,0 +1,120 @@
+/* ------------------------------------------------------------------
+ * 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/az_lsp.h.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Changed function prototype; pointer to  overflow flag is passed
+              in as a parameter. Added extern declaration for grid_tbl[],
+              defined in grid_tbl.c
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                           Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the function Az_lsp()
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef AZ_LSP_H
+#define AZ_LSP_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define grid_points 60
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern Word16 grid[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void Az_lsp(
+        Word16 a[],         /* (i)  : predictor coefficients (MP1)               */
+        Word16 lsp[],       /* (o)  : line spectral pairs (M)                    */
+        Word16 old_lsp[],   /* (i)  : old lsp[] (in case not found 10 roots) (M) */
+        Flag   *pOverflow   /* (i/o): overflow flag                              */
+    );
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _AZ_LSP_H */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op.h b/media/libstagefright/codecs/amrnb/common/include/basic_op.h
new file mode 100644
index 0000000..f6c80e2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/basic_op.h
@@ -0,0 +1,448 @@
+/* ------------------------------------------------------------------
+ * 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: ./include/basic_op.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Revised basic_op.h since the basicop2.c functions were split
+          up into separate source and header files. This function was
+          retained because there are legacy GSM AMR C functions that still
+          include this file. This file now includes the various basicop2
+          functions' header files instead of defining the function
+          prototypes.
+
+ Description: Including header files with platform specific inline assembly
+              instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes all the basicop2.c functions' header files.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BASIC_OP_H
+#define BASIC_OP_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basicop_malloc.h"
+
+#if defined(PV_ARM_V5)
+#include "basic_op_arm_v5.h"
+
+#elif defined(PV_ARM_GCC_V5)
+#include "basic_op_arm_gcc_v5.h"
+
+#else
+#include "basic_op_c_equivalent.h"
+
+#endif
+
+
+
+#include    "add.h"
+#include    "div_s.h"
+#include    "div_32.h"
+#include    "extract_h.h"
+#include    "extract_l.h"
+#include    "l_deposit_h.h"
+#include    "l_deposit_l.h"
+#include    "l_shr_r.h"
+#include    "mult_r.h"
+#include    "norm_l.h"
+#include    "norm_s.h"
+#include    "round.h"
+#include    "shr_r.h"
+#include    "sub.h"
+#include    "shr.h"
+#include    "l_abs.h"
+#include    "l_negate.h"
+#include    "l_extract.h"
+#include    "l_abs.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 NAME: mac_32
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+        L_var1_hi = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        L_var1_lo = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+        L_var2_hi = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        L_var2_lo = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit mac operation resulted in overflow
+
+     Returns:
+        L_var3 = 32-bit result of L_var3 + (L_var1 * L_var2)(Word32)
+
+    */
+    static inline Word32 Mac_32(Word32 L_var3,
+    Word16 L_var1_hi,
+    Word16 L_var1_lo,
+    Word16 L_var2_hi,
+    Word16 L_var2_lo,
+    Flag *pOverflow)
+    {
+        Word16  product;
+
+        L_var3 = L_mac(L_var3, L_var1_hi, L_var2_hi, pOverflow);
+
+        product = mult(L_var1_hi, L_var2_lo, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        product = mult(L_var1_lo, L_var2_hi, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        return (L_var3);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: mac_32_16
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+        L_var1_hi = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        L_var1_lo = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+        var2= 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit mac operation resulted in overflow
+
+     Returns:
+        L_var3 = 32-bit result of L_var3 + (L_var1 * var2)(Word32)
+    */
+
+    static inline Word32 Mac_32_16(Word32 L_var3,
+                                   Word16 L_var1_hi,
+                                   Word16 L_var1_lo,
+                                   Word16 var2,
+                                   Flag  *pOverflow)
+    {
+        Word16  product;
+
+        L_var3 = L_mac(L_var3, L_var1_hi, var2, pOverflow);
+
+        product = mult(L_var1_lo, var2, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        return (L_var3);
+    }
+
+
+    /*----------------------------------------------------------------------------
+         Function Name : negate
+
+         Negate var1 with saturation, saturate in the case where input is -32768:
+                      negate(var1) = sub(0,var1).
+
+         Inputs :
+          var1
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var1 <= 0x7fff.
+
+         Outputs :
+          none
+
+         Return Value :
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var_out <= 0x7fff.
+     ----------------------------------------------------------------------------*/
+
+    static inline Word16 negate(Word16 var1)
+    {
+        return (((var1 == MIN_16) ? MAX_16 : -var1));
+    }
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : shl
+
+         Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill
+         the var2 LSB of the result. If var2 is negative, arithmetically shift
+         var1 right by -var2 with sign extension. Saturate the result in case of
+         underflows or overflows.
+
+         Inputs :
+          var1
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var1 <= 0x7fff.
+
+          var2
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var1 <= 0x7fff.
+
+          pOverflow : pointer to overflow (Flag)
+
+         Return Value :
+          var_out
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var_out <= 0x7fff.
+     ----------------------------------------------------------------------------*/
+
+    static inline Word16 shl(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word16 var_out = 0;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        if (var2 < 0)
+        {
+            var2 = -var2;
+            if (var2 < 15)
+            {
+                var_out = var1 >> var2;
+            }
+
+        }
+        else
+        {
+            var_out = var1 << var2;
+            if (var_out >> var2 != var1)
+            {
+                var_out = (var1 >> 15) ^ MAX_16;
+            }
+        }
+        return (var_out);
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : L_shl
+
+         Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero
+         fill the var2 LSB of the result. If var2 is negative, arithmetically
+         shift L_var1 right by -var2 with sign extension. Saturate the result in
+         case of underflows or overflows.
+
+         Inputs :
+          L_var1   32 bit long signed integer (Word32) whose value falls in the
+                   range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+          var2
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range :  8000 <= var2 <= 7fff.
+
+          pOverflow : pointer to overflow (Flag)
+
+         Return Value :
+                   32 bit long signed integer (Word32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+    static inline Word32 L_shl(Word32 L_var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 L_var_out = 0;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        if (var2 > 0)
+        {
+            L_var_out = L_var1 << var2;
+            if (L_var_out >> var2 != L_var1)
+            {
+                L_var_out = (L_var1 >> 31) ^ MAX_32;
+            }
+        }
+        else
+        {
+            var2 = -var2;
+            if (var2 < 31)
+            {
+                L_var_out = L_var1 >> var2;
+            }
+
+        }
+
+        return (L_var_out);
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : L_shr
+
+         Arithmetically shift the 32 bit input L_var1 right var2 positions with
+         sign extension. If var2 is negative, arithmetically shift L_var1 left
+         by -var2 and zero fill the -var2 LSB of the result. Saturate the result
+         in case of underflows or overflows.
+
+         Inputs :
+          L_var1   32 bit long signed integer (Word32) whose value falls in the
+                   range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+          var2
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range :  8000 <= var2 <= 7fff.
+
+          pOverflow : pointer to overflow (Flag)
+
+         Return Value :
+                   32 bit long signed integer (Word32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+    static inline Word32 L_shr(Word32 L_var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 L_var_out = 0;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        if (var2 > 0)
+        {
+            if (var2 < 31)
+            {
+                L_var_out = L_var1 >> var2;
+            }
+        }
+        else
+        {
+            var2 = -var2;
+
+            L_var_out = L_var1 << (var2) ;
+            if ((L_var_out >> (var2)) != L_var1)
+            {
+                L_var_out = (L_var1 >> 31) ^ MAX_32;
+            }
+
+        }
+
+        return (L_var_out);
+    }
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : abs_s
+
+          Absolute value of var1; abs_s(-32768) = 32767.
+
+         Inputs :
+          var1
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x8000 <= var1 <= 0x7fff.
+
+          pOverflow : pointer to overflow (Flag)
+
+         Outputs :
+          none
+
+         Return Value :
+                   16 bit short signed integer (Word16) whose value falls in the
+                   range : 0x0000 <= var_out <= 0x7fff.
+
+     ----------------------------------------------------------------------------*/
+
+    static inline Word16 abs_s(Word16 var1)
+    {
+
+        Word16 y = var1 - (var1 < 0);
+        y = y ^(y >> 15);
+        return (y);
+
+    }
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* BASIC_OP_H */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h b/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h
new file mode 100644
index 0000000..48f0bcb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_gcc_v5.h
@@ -0,0 +1,543 @@
+/* ------------------------------------------------------------------
+ * 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: ./include/basic_op_arm_gcc_v5.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes all the GCC-ARM V5 basicop.c functions.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BASIC_OP_ARM_GCC_V5_H
+#define BASIC_OP_ARM_GCC_V5_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
+    ----------------------------------------------------------------------------*/
+
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_add
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_sum = 32-bit sum of L_var1 and L_var2 (Word32)
+    */
+
+    __inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("qadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb)
+                            );
+        return (result);
+
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_sub
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_diff = 32-bit difference of L_var1 and L_var2 (Word32)
+    */
+    __inline Word32 L_sub(Word32 L_var1, Word32 L_var2, Flag *pOverflow)
+{
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("qsub %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb)
+                            );
+
+        return (result);
+    }
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mac
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 + (var1 * var2)(Word32)
+    */
+    static inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+{
+        register Word32 ra = L_var3;
+        register Word32 rb = var1;
+        register Word32 rc = var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(result)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(rc)
+                             : "r"(ra), "r"(result)
+                            );
+
+        return (rc);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        L_var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+
+    __inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+{
+        register Word32 ra = var1;
+        register Word32 rb = var2;
+        Word32 result;
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product)
+                             : "r"(ra), "r"(rb)
+                            );
+
+        asm volatile("qadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(product), "r"(product)
+                            );
+
+        return(result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_msu
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 - (var1 * var2)
+    */
+    __inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+{
+        register Word32 ra = L_var3;
+        register Word32 rb = var1;
+        register Word32 rc = var2;
+        Word32 product;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("qdsub %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(product)
+                            );
+
+        return (result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant word of first input (Word16).
+        L_var1_lo = least significant word of first input (Word16).
+        L_var2_hi = most significant word of second input (Word16).
+        L_var2_lo = least significant word of second input (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit multiply operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+    static inline Word32 Mpy_32(Word16 L_var1_hi,
+                                Word16 L_var1_lo,
+                                Word16 L_var2_hi,
+                                Word16 L_var2_lo,
+                                Flag   *pOverflow)
+{
+        register Word32 product32;
+        register Word32 L_sum;
+        register Word32 L_product, result;
+        register Word32 ra = L_var1_hi;
+        register Word32 rb = L_var1_lo;
+        register Word32 rc = L_var2_hi;
+        register Word32 rd = L_var2_lo;
+
+
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(ra), "r"(rc)
+                            );
+        asm volatile("mov %0, #0"
+             : "=r"(result)
+                    );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_sum)
+                             : "r"(result), "r"(L_product)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product32)
+                             : "r"(ra), "r"(rd)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(ra)
+                             : "r"(product32)
+                            );
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(L_sum), "r"(ra)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product32)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(rb)
+                             : "r"(product32)
+                            );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_sum)
+                             : "r"(L_product), "r"(rb)
+                            );
+
+        return (L_sum);
+    }
+
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32_16
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant 16 bits of 32-bit input (Word16).
+        L_var1_lo = least significant 16 bits of 32-bit input (Word16).
+        var2  = 16-bit signed integer (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit product operation resulted in overflow
+
+     Returns:
+        product = 32-bit product of the 32-bit L_var1 and 16-bit var1 (Word32)
+    */
+    static inline Word32 Mpy_32_16(Word16 L_var1_hi,
+                                   Word16 L_var1_lo,
+                                   Word16 var2,
+                                   Flag *pOverflow)
+{
+
+        register Word32 ra = L_var1_hi;
+        register Word32 rb = L_var1_lo;
+        register Word32 rc = var2;
+        Word32 result, L_product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(ra), "r"(rc)
+                            );
+        asm volatile("mov %0, #0"
+             : "=r"(result)
+                    );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(result), "r"(L_product)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(result)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(ra)
+                             : "r"(result)
+                            );
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(L_product), "r"(ra)
+                            );
+
+        return (result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the add operation resulted in overflow
+
+     Returns:
+        product = 16-bit limited product of var1 and var2 (Word16)
+    */
+    __inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+{
+        register Word32 ra = var1;
+        register Word32 rb = var2;
+        Word32 product;
+        Word32 temp;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile(
+            "smulbb %0, %1, %2"
+    : "=r"(temp)
+                    : "r"(ra), "r"(rb)
+                );
+        asm volatile(
+            "qadd %0, %1, %2\n\t"
+            "mov %0, %0, asr #16"
+    : "=&r*i"(product)
+                    : "r"(temp), "r"(temp)
+                );
+
+        return ((Word16) product);
+    }
+
+    __inline Word32 amrnb_fxp_mac_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+{
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        register Word32 rc = L_var3;
+        Word32 result;
+
+        asm volatile("smlabb %0, %1, %2, %3"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb), "r"(rc)
+                            );
+        return (result);
+    }
+
+    __inline Word32 amrnb_fxp_msu_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+{
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        register Word32 rc = L_var3;
+        Word32 result;
+
+        asm volatile("rsb %0, %1, #0"
+             : "=r"(ra)
+                             : "r"(ra)
+                            );
+
+        asm volatile("smlabb %0, %1, %2, %3"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb), "r"(rc)
+                            );
+        return (result);
+    }
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BASIC_OP_ARM_GCC_V5_H */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_v5.h b/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_v5.h
new file mode 100644
index 0000000..c939356
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/basic_op_arm_v5.h
@@ -0,0 +1,440 @@
+/* ------------------------------------------------------------------
+ * 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: ./include/basic_op_arm_v5.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes all the ARM-V5 based basicop.c functions.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BASIC_OP_ARM_V5_H
+#define BASIC_OP_ARM_V5_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
+    ----------------------------------------------------------------------------*/
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_add
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_sum = 32-bit sum of L_var1 and L_var2 (Word32)
+    */
+
+    __inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+        __asm
+        {
+            QADD result, L_var1, L_var2
+        }
+        return(result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_sub
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_diff = 32-bit difference of L_var1 and L_var2 (Word32)
+    */
+    __inline Word32 L_sub(Word32 L_var1, Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            QSUB result, L_var1, L_var2
+        }
+
+        return(result);
+
+    }
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mac
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 + (var1 * var2)(Word32)
+    */
+    __inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 L_sum;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm {SMULBB result, var1, var2}
+        __asm {QDADD L_sum, L_var3, result}
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        L_var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+    __inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            QADD   result, product, product
+        }
+
+        return (result);
+    }
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_msu
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 - (var1 * var2)
+    */
+    __inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 product;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            QDSUB  result, L_var3, product
+        }
+
+        return (result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant word of first input (Word16).
+        L_var1_lo = least significant word of first input (Word16).
+        L_var2_hi = most significant word of second input (Word16).
+        L_var2_lo = least significant word of second input (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit multiply operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+    __inline Word32 Mpy_32(Word16 L_var1_hi, Word16 L_var1_lo, Word16 L_var2_hi,
+                           Word16 L_var2_lo, Flag   *pOverflow)
+
+    {
+
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 product32;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB L_product, L_var1_hi, L_var2_hi
+            QDADD L_product, 0, L_product
+            SMULBB product32, L_var1_hi, L_var2_lo
+        }
+        product32 >>= 15;
+        __asm
+        {
+            QDADD L_sum, L_product, product32
+        }
+        L_product = L_sum;
+        __asm
+        {
+            SMULBB product32, L_var1_lo, L_var2_hi
+        }
+        product32 >>= 15;
+        __asm
+        {
+            QDADD L_sum, L_product, product32
+        }
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32_16
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant 16 bits of 32-bit input (Word16).
+        L_var1_lo = least significant 16 bits of 32-bit input (Word16).
+        var2  = 16-bit signed integer (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit product operation resulted in overflow
+
+     Returns:
+        product = 32-bit product of the 32-bit L_var1 and 16-bit var1 (Word32)
+    */
+    __inline Word32 Mpy_32_16(Word16 L_var1_hi,
+                              Word16 L_var1_lo,
+                              Word16 var2,
+                              Flag *pOverflow)
+    {
+
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm {SMULBB L_product, L_var1_hi, var2}
+        __asm {QDADD L_product, 0, L_product}
+        __asm {SMULBB result, L_var1_lo, var2}
+        result >>= 15;
+        __asm {QDADD L_sum, L_product, result}
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the add operation resulted in overflow
+
+     Returns:
+        product = 16-bit limited product of var1 and var2 (Word16)
+    */
+    __inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            MOV    product, product, ASR #15
+            CMP    product, 0x7FFF
+            MOVGE  product, 0x7FFF
+        }
+
+        return ((Word16) product);
+    }
+
+    __inline Word32 amrnb_fxp_mac_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+    {
+        Word32 result;
+        __asm
+        {
+            smlabb result, L_var1, L_var2, L_var3
+        }
+        return result;
+    }
+
+    __inline Word32 amrnb_fxp_msu_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+    {
+        Word32 result;
+        __asm
+        {
+            rsb L_var1, L_var1, #0
+            smlabb result, L_var1, L_var2, L_var3
+        }
+        return result;
+    }
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BASIC_OP_ARM_V5_H */
diff --git a/media/libstagefright/codecs/amrnb/common/include/basic_op_c_equivalent.h b/media/libstagefright/codecs/amrnb/common/include/basic_op_c_equivalent.h
new file mode 100644
index 0000000..35638e3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/basic_op_c_equivalent.h
@@ -0,0 +1,505 @@
+/* ------------------------------------------------------------------
+ * 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: ./include/basic_op_c_equivalent.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes all the C-Equivalent basicop.c functions.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BASIC_OP_C_EQUIVALENT_H
+#define BASIC_OP_C_EQUIVALENT_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
+    ----------------------------------------------------------------------------*/
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_add
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_sum = 32-bit sum of L_var1 and L_var2 (Word32)
+    */
+    static inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 L_sum;
+
+        L_sum = L_var1 + L_var2;
+
+        if ((L_var1 ^ L_var2) >= 0)
+        {
+            if ((L_sum ^ L_var1) < 0)
+            {
+                L_sum = (L_var1 < 0) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_sub
+    ------------------------------------------------------------------------------
+     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.
+
+        L_var2 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_diff = 32-bit difference of L_var1 and L_var2 (Word32)
+    */
+    static inline Word32 L_sub(register Word32 L_var1, register Word32 L_var2,
+                               register Flag *pOverflow)
+    {
+        Word32 L_diff;
+
+        L_diff = L_var1 - L_var2;
+
+        if ((L_var1 ^ L_var2) < 0)
+        {
+            if ((L_diff ^ L_var1) & MIN_32)
+            {
+                L_diff = (L_var1 < 0L) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+
+        return (L_diff);
+    }
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mac
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 + (var1 * var2)(Word32)
+    */
+    __inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 L_sum;
+        result = (Word32) var1 * var2;
+        if (result != (Word32) 0x40000000L)
+        {
+            L_sum = (result << 1) + L_var3;
+
+            /* Check if L_sum and L_var_3 share the same sign */
+            if ((L_var3 ^ result) > 0)
+            {
+                if ((L_sum ^ L_var3) < 0)
+                {
+                    L_sum = (L_var3 < 0) ? MIN_32 : MAX_32;
+                    *pOverflow = 1;
+                }
+            }
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_sum = MAX_32;
+        }
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        L_var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit add operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+    static inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 L_product;
+
+        L_product = (Word32) var1 * var2;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;          /* Multiply by 2 */
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_product = MAX_32;
+        }
+
+        return (L_product);
+    }
+
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: L_msu
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var3 = 32 bit long signed integer (Word32) whose value falls
+                 in the range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit operation resulted in overflow
+
+     Returns:
+        result = 32-bit result of L_var3 - (var1 * var2)
+    */
+
+    static inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        result = L_mult(var1, var2, pOverflow);
+        result = L_sub(L_var3, result, pOverflow);
+
+        return (result);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant word of first input (Word16).
+        L_var1_lo = least significant word of first input (Word16).
+        L_var2_hi = most significant word of second input (Word16).
+        L_var2_lo = least significant word of second input (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit multiply operation resulted in overflow
+
+     Returns:
+        L_product = 32-bit product of L_var1 and L_var2 (Word32)
+    */
+    __inline Word32 Mpy_32(Word16 L_var1_hi,
+                           Word16 L_var1_lo,
+                           Word16 L_var2_hi,
+                           Word16 L_var2_lo,
+                           Flag   *pOverflow)
+    {
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 product32;
+
+        OSCL_UNUSED_ARG(pOverflow);
+        L_product = (Word32) L_var1_hi * L_var2_hi;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;
+        }
+        else
+        {
+            L_product = MAX_32;
+        }
+
+        /* result = mult (L_var1_hi, L_var2_lo, pOverflow); */
+        product32 = ((Word32) L_var1_hi * L_var2_lo) >> 15;
+
+        /* L_product = L_mac (L_product, result, 1, pOverflow); */
+        L_sum = L_product + (product32 << 1);
+
+        if ((L_product ^ product32) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+            }
+        }
+
+        L_product = L_sum;
+
+        /* result = mult (L_var1_lo, L_var2_hi, pOverflow); */
+        product32 = ((Word32) L_var1_lo * L_var2_hi) >> 15;
+
+        /* L_product = L_mac (L_product, result, 1, pOverflow); */
+        L_sum = L_product + (product32 << 1);
+
+        if ((L_product ^ product32) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+            }
+        }
+        return (L_sum);
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: Mpy_32_16
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        L_var1_hi = most significant 16 bits of 32-bit input (Word16).
+        L_var1_lo = least significant 16 bits of 32-bit input (Word16).
+        var2  = 16-bit signed integer (Word16).
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the 32 bit product operation resulted in overflow
+
+     Returns:
+        product = 32-bit product of the 32-bit L_var1 and 16-bit var1 (Word32)
+    */
+
+    __inline Word32 Mpy_32_16(Word16 L_var1_hi,
+                              Word16 L_var1_lo,
+                              Word16 var2,
+                              Flag *pOverflow)
+    {
+
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 result;
+        L_product = (Word32) L_var1_hi * var2;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_product = MAX_32;
+        }
+
+        result = ((Word32)L_var1_lo * var2) >> 15;
+
+        L_sum  =  L_product + (result << 1);
+
+        if ((L_product ^ result) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+        return (L_sum);
+
+    }
+
+    /*
+    ------------------------------------------------------------------------------
+     FUNCTION NAME: mult
+    ------------------------------------------------------------------------------
+     INPUT AND OUTPUT DEFINITIONS
+
+     Inputs:
+        var1 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+        var2 = 16 bit short signed integer (Word16) whose value falls in
+               the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+        pOverflow = pointer to overflow (Flag)
+
+     Outputs:
+        pOverflow -> 1 if the add operation resulted in overflow
+
+     Returns:
+        product = 16-bit limited product of var1 and var2 (Word16)
+    */
+    static inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 product;
+
+        product = ((Word32) var1 * var2) >> 15;
+
+        /* Saturate result (if necessary). */
+        /* var1 * var2 >0x00007fff is the only case */
+        /* that saturation occurs. */
+
+        if (product > 0x00007fffL)
+        {
+            *pOverflow = 1;
+            product = (Word32) MAX_16;
+        }
+
+
+        /* Return the product as a 16 bit value by type casting Word32 to Word16 */
+
+        return ((Word16) product);
+    }
+
+
+    static inline Word32 amrnb_fxp_mac_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+    {
+        Word32 result;
+
+        result = L_var3 + L_var1 * L_var2;
+
+        return result;
+    }
+
+    static inline Word32 amrnb_fxp_msu_16_by_16bb(Word32 L_var1, Word32 L_var2, Word32 L_var3)
+    {
+        Word32 result;
+
+        result = L_var3 - L_var1 * L_var2;
+
+        return result;
+    }
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* BASIC_OP_C_EQUIVALENT_H */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/basicop_malloc.h b/media/libstagefright/codecs/amrnb/common/include/basicop_malloc.h
new file mode 100644
index 0000000..363d148
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/basicop_malloc.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/basicop_malloc.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains constant definitions and external references to the stores
+ used by any arithmetic function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BASICOP_MALLOC_H
+#define BASICOP_MALLOC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define MAX_32 (Word32)0x7fffffffL
+#define MIN_32 (Word32)0x80000000L
+
+#define MAX_16 (Word16)0x7fff
+#define MIN_16 (Word16)0x8000
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern  Flag Overflow;
+    extern  Flag Carry;
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/bitno_tab.h b/media/libstagefright/codecs/amrnb/common/include/bitno_tab.h
new file mode 100644
index 0000000..a170750
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/bitno_tab.h
@@ -0,0 +1,146 @@
+/* ------------------------------------------------------------------
+ * 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/bitno_tab.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Define "const Word16 *bitno[N_MODES]" as "const Word16 *const
+                      bitno[N_MODES]"
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a tables in bitno_tab.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BITNO_TAB_H
+#define BITNO_TAB_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define BIT_0      0
+#define BIT_1      1
+
+#define PRMNO_MR475 17
+#define PRMNO_MR515 19
+#define PRMNO_MR59  19
+#define PRMNO_MR67  19
+#define PRMNO_MR74  19
+#define PRMNO_MR795 23
+#define PRMNO_MR102 39
+#define PRMNO_MR122 57
+#define PRMNO_MRDTX 5
+
+    /* number of parameters to first subframe */
+#define PRMNOFSF_MR475 7
+#define PRMNOFSF_MR515 7
+#define PRMNOFSF_MR59  7
+#define PRMNOFSF_MR67  7
+#define PRMNOFSF_MR74  7
+#define PRMNOFSF_MR795 8
+#define PRMNOFSF_MR102 12
+#define PRMNOFSF_MR122 18
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 prmno[];
+    extern const Word16 prmnofsf[];
+    extern const Word16 bitno_MR475[];
+    extern const Word16 bitno_MR515[];
+    extern const Word16 bitno_MR59[];
+    extern const Word16 bitno_MR67[];
+    extern const Word16 bitno_MR74[];
+    extern const Word16 bitno_MR95[];
+    extern const Word16 bitno_MR102[];
+    extern const Word16 bitno_MR122[];
+    extern const Word16 bitno_MRDTX[];
+    extern const Word16 *const bitno[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/bitreorder_tab.h b/media/libstagefright/codecs/amrnb/common/include/bitreorder_tab.h
new file mode 100644
index 0000000..bfcb4cf
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/bitreorder_tab.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.
+****************************************************************************************/
+/*
+
+ Pathname: .audio/gsm-amr/c/include/bitreorder.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Define "const Word16 *reorderBits[NUM_MODES-1]" as
+              "const Word16 *const reorderBits[NUM_MODES-1]".
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a tables in bitreorder.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BITREORDER_H
+#define BITREORDER_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 numOfBits[];
+    extern const Word16 reorderBits_MR475[];
+    extern const Word16 reorderBits_MR515[];
+    extern const Word16 reorderBits_MR59[];
+    extern const Word16 reorderBits_MR67[];
+    extern const Word16 reorderBits_MR74[];
+    extern const Word16 reorderBits_MR795[];
+    extern const Word16 reorderBits_MR102[];
+    extern const Word16 reorderBits_MR122[];
+
+    extern const Word16 *const reorderBits[];
+    extern const Word16 numCompressedBytes[];
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/bits2prm.h b/media/libstagefright/codecs/amrnb/common/include/bits2prm.h
new file mode 100644
index 0000000..6a11bb4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/bits2prm.h
@@ -0,0 +1,91 @@
+/* ------------------------------------------------------------------
+ * 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             : bits2prm.h
+*      Purpose          : Retrieves the vector of encoder parameters from
+*                       : the received serial bits in a frame.
+*
+*****************************************************************************
+*/
+#ifndef bits2prm_h
+#define bits2prm_h "$Id $"
+
+/*
+*****************************************************************************
+*                         INCLUDE FILES
+*****************************************************************************
+*/
+#include "typedef.h"
+#include "mode.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    *****************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    *****************************************************************************
+    */
+
+    /*
+    *****************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    *****************************************************************************
+    */
+    /*
+    **************************************************************************
+    *
+    *  Function    : Bits2prm
+    *  Purpose     : Retrieves the vector of encoder parameters from
+    *                the received serial bits in a frame.
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    OSCL_IMPORT_REF void Bits2prm(
+        enum Mode mode,
+        Word16 bits[],   /* input : serial bits, (244 + bfi)               */
+        Word16 prm[]     /* output: analysis parameters, (57+1 parameters) */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/bytesused.h b/media/libstagefright/codecs/amrnb/common/include/bytesused.h
new file mode 100644
index 0000000..934efbe
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/bytesused.h
@@ -0,0 +1,109 @@
+/* ------------------------------------------------------------------
+ * 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/BytesUsed.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a table BytesUsed.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef BYTESUSED_H
+#define BYTESUSED_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*--------------------------------------------------------------------------*/
+#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 short BytesUsed[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/cnst.h b/media/libstagefright/codecs/amrnb/common/include/cnst.h
new file mode 100644
index 0000000..b648eb7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/cnst.h
@@ -0,0 +1,129 @@
+/* ------------------------------------------------------------------
+ * 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 the Speech code (encoder, decoder, and postfilter)
+ constant parameters.
+
+ NOTE: This file must be synchronized with /gsm-amr/asm/include/cnst.inc file.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef _CNST_H_
+#define _CNST_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define L_TOTAL      320       /* Total size of speech buffer.             */
+#define L_WINDOW     240       /* Window size in LP analysis               */
+#define L_FRAME      160       /* Frame size                               */
+#define L_FRAME_BY2  80        /* Frame size divided by 2                  */
+#define L_SUBFR      40        /* Subframe size                            */
+#define L_CODE       40        /* codevector length                        */
+#define NB_TRACK     5         /* number of tracks                         */
+#define STEP         5         /* codebook step size                       */
+#define NB_TRACK_MR102  4      /* number of tracks mode mr102              */
+#define STEP_MR102      4      /* codebook step size mode mr102            */
+#define M            10        /* Order of LP filter                       */
+#define MP1          (M+1)     /* Order of LP filter + 1                   */
+#define LSF_GAP      205       /* Minimum distance between LSF after quan- */
+    /* tization; 50 Hz = 205                    */
+#define LSP_PRED_FAC_MR122 21299 /* MR122 LSP prediction factor (0.65 Q15) */
+#define AZ_SIZE       (4*M+4)  /* Size of array of LP filters in 4 subfr.s */
+#define PIT_MIN_MR122 18       /* Minimum pitch lag (MR122 mode)           */
+#define PIT_MIN       20       /* Minimum pitch lag (all other modes)      */
+#define PIT_MAX       143      /* Maximum pitch lag                        */
+#define L_INTERPOL    (10+1)   /* Length of filter for interpolation       */
+#define L_INTER_SRCH  4        /* Length of filter for CL LTP search       */
+    /* interpolation                            */
+
+#define MU       26214         /* Factor for tilt compensation filter 0.8  */
+#define AGC_FAC  29491         /* Factor for automatic gain control 0.9    */
+
+#define L_NEXT       40        /* Overhead in LP analysis                  */
+#define SHARPMAX  13017        /* Maximum value of pitch sharpening        */
+#define SHARPMIN  0            /* Minimum value of pitch sharpening        */
+
+
+#define MAX_PRM_SIZE    57     /* max. num. of params                      */
+#define MAX_SERIAL_SIZE 244    /* max. num. of serial bits                 */
+
+#define GP_CLIP   15565        /* Pitch gain clipping = 0.95               */
+#define N_FRAME   7            /* old pitch gains in average calculation   */
+
+#define EHF_MASK 0x0008        /* encoder homing frame pattern             */
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _CNST_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/cnst_vad.h b/media/libstagefright/codecs/amrnb/common/include/cnst_vad.h
new file mode 100644
index 0000000..6877a1b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/cnst_vad.h
@@ -0,0 +1,133 @@
+/* ------------------------------------------------------------------
+ * 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             : cnst_vad.h
+*      Purpose          : Constants and definitions for VAD
+*
+********************************************************************************
+*/
+#ifndef cnst_vad_h
+#define cnst_vad_h "$Id $"
+
+#define FRAME_LEN 160    /* Length (samples) of the input frame          */
+#define COMPLEN 9        /* Number of sub-bands used by VAD              */
+#define INV_COMPLEN 3641 /* 1.0/COMPLEN*2^15                             */
+#define LOOKAHEAD 40     /* length of the lookahead used by speech coder */
+
+#define UNITY 512        /* Scaling used with SNR calculation            */
+#define UNIRSHFT 6       /* = log2(MAX_16/UNITY)                         */
+
+#define TONE_THR (Word16)(0.65*MAX_16) /* Threshold for tone detection   */
+
+/* Constants for background spectrum update */
+#define ALPHA_UP1   (Word16)((1.0 - 0.95)*MAX_16)  /* Normal update, upwards:   */
+#define ALPHA_DOWN1 (Word16)((1.0 - 0.936)*MAX_16) /* Normal update, downwards  */
+#define ALPHA_UP2   (Word16)((1.0 - 0.985)*MAX_16) /* Forced update, upwards    */
+#define ALPHA_DOWN2 (Word16)((1.0 - 0.943)*MAX_16) /* Forced update, downwards  */
+#define ALPHA3      (Word16)((1.0 - 0.95)*MAX_16)  /* Update downwards          */
+#define ALPHA4      (Word16)((1.0 - 0.9)*MAX_16)   /* For stationary estimation */
+#define ALPHA5      (Word16)((1.0 - 0.5)*MAX_16)   /* For stationary estimation */
+
+/* Constants for VAD threshold */
+#define VAD_THR_HIGH 1260 /* Highest threshold                 */
+#define VAD_THR_LOW  720  /* Lowest threshold                  */
+#define VAD_P1 0          /* Noise level for highest threshold */
+#define VAD_P2 6300       /* Noise level for lowest threshold  */
+#define VAD_SLOPE (Word16)(MAX_16*(float)(VAD_THR_LOW-VAD_THR_HIGH)/(float)(VAD_P2-VAD_P1))
+
+/* Parameters for background spectrum recovery function */
+#define STAT_COUNT 20         /* threshold of stationary detection counter         */
+#define STAT_COUNT_BY_2 10    /* threshold of stationary detection counter         */
+#define CAD_MIN_STAT_COUNT 5  /* threshold of stationary detection counter         */
+
+#define STAT_THR_LEVEL 184    /* Threshold level for stationarity detection        */
+#define STAT_THR 1000         /* Threshold for stationarity detection              */
+
+/* Limits for background noise estimate */
+#define NOISE_MIN 40          /* minimum */
+#define NOISE_MAX 16000       /* maximum */
+#define NOISE_INIT 150        /* initial */
+
+/* Constants for VAD hangover addition */
+#define HANG_NOISE_THR 100
+#define BURST_LEN_HIGH_NOISE 4
+#define HANG_LEN_HIGH_NOISE 7
+#define BURST_LEN_LOW_NOISE 5
+#define HANG_LEN_LOW_NOISE 4
+
+/* Thresholds for signal power */
+#define VAD_POW_LOW (Word32)15000     /* If input power is lower,                    */
+/*     VAD is set to 0                         */
+#define POW_PITCH_THR (Word32)343040  /* If input power is lower, pitch              */
+/*     detection is ignored                    */
+
+#define POW_COMPLEX_THR (Word32)15000 /* If input power is lower, complex            */
+/* flags  value for previous frame  is un-set  */
+
+
+/* Constants for the filter bank */
+#define LEVEL_SHIFT 0      /* scaling                                  */
+#define COEFF3   13363     /* coefficient for the 3rd order filter     */
+#define COEFF5_1 21955     /* 1st coefficient the for 5th order filter */
+#define COEFF5_2 6390      /* 2nd coefficient the for 5th order filter */
+
+/* Constants for pitch detection */
+#define LTHRESH 4
+#define NTHRESH 4
+
+/* Constants for complex signal VAD  */
+#define CVAD_THRESH_ADAPT_HIGH  (Word16)(0.6 * MAX_16) /* threshold for adapt stopping high    */
+#define CVAD_THRESH_ADAPT_LOW  (Word16)(0.5 * MAX_16)  /* threshold for adapt stopping low     */
+#define CVAD_THRESH_IN_NOISE  (Word16)(0.65 * MAX_16)  /* threshold going into speech on       */
+/* a short term basis                   */
+
+#define CVAD_THRESH_HANG  (Word16)(0.70 * MAX_16)      /* threshold                            */
+#define CVAD_HANG_LIMIT  (Word16)(100)                 /* 2 second estimation time             */
+#define CVAD_HANG_LENGTH  (Word16)(250)                /* 5 second hangover                    */
+
+#define CVAD_LOWPOW_RESET (Word16) (0.40 * MAX_16)     /* init in low power segment            */
+#define CVAD_MIN_CORR (Word16) (0.40 * MAX_16)         /* lowest adaptation value              */
+
+#define CVAD_BURST 20                                  /* speech burst length for speech reset */
+#define CVAD_ADAPT_SLOW (Word16)(( 1.0 - 0.98) * MAX_16)        /* threshold for slow adaption */
+#define CVAD_ADAPT_FAST (Word16)((1.0 - 0.92) * MAX_16)         /* threshold for fast adaption */
+#define CVAD_ADAPT_REALLY_FAST (Word16)((1.0 - 0.80) * MAX_16)  /* threshold for really fast   */
+/* adaption                    */
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/copy.h b/media/libstagefright/codecs/amrnb/common/include/copy.h
new file mode 100644
index 0000000..b539ebb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/copy.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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             : copy.h
+*      Purpose          : Copy vector x[] to y[]
+*
+********************************************************************************
+*/
+#ifndef copy_h
+#define copy_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : Copy
+    *  Purpose     : Copy vector x[] to y[], vector length L
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void Copy(
+        const Word16 x[],  /* i : input vector (L)    */
+        Word16 y[],        /* o : output vector (L)   */
+        Word16 L           /* i : vector length       */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_gain_c.h b/media/libstagefright/codecs/amrnb/common/include/d_gain_c.h
new file mode 100644
index 0000000..70868f4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/d_gain_c.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/d_gain_c.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File          : d_gain_c.h
+      Purpose       : Decode the fixed codebook gain using the received index.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _D_GAIN_C_H_
+#define _D_GAIN_C_H_
+#define d_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
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+     *  Function    : d_gain_code
+     *  Purpose     : Decode the fixed codebook gain using the received index.
+     *  Description : The received index gives the gain correction factor
+     *                gamma. The quantized gain is given by   g_q = g0 * gamma
+     *                where g0 is the predicted gain. To find g0, 4th order
+     *                MA prediction is applied to the mean-removed innovation
+     *                energy in dB.
+     *  Returns     : void
+     */
+    void d_gain_code(
+        gc_predState *pred_state, /* i/o : MA predictor state               */
+        enum Mode mode,           /* i   : AMR mode                         */
+        Word16 index,             /* i   : received quantization index      */
+        Word16 code[],            /* i   : innovation codevector            */
+        Word16 *gain_code,        /* o   : decoded innovation gain          */
+        Flag   *pOverflow
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _D_GAIN_C_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_gain_p.h b/media/libstagefright/codecs/amrnb/common/include/d_gain_p.h
new file mode 100644
index 0000000..fec072b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/d_gain_p.h
@@ -0,0 +1,80 @@
+/* ------------------------------------------------------------------
+ * 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             : d_gain_p.h
+*      Purpose          : Decodes the pitch gain using the received index.
+*
+********************************************************************************
+*/
+#ifndef d_gain_p_h
+#define d_gain_p_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+#include "mode.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : d_gain_pitch
+    *  Purpose     : Decodes the pitch gain using the received index.
+    *  Description : In case of no frame erasure, the gain is obtained
+    *                from the quantization table at the given index;
+    *                otherwise, a downscaled past gain is used.
+    *  Returns     : Quantized pitch gain
+    *
+    **************************************************************************
+    */
+    Word16 d_gain_pitch(       /* return value: gain (Q14)                */
+        enum Mode mode,        /* i : AMR mode                            */
+        Word16 index           /* i   : index of quantization             */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/d_plsf.h b/media/libstagefright/codecs/amrnb/common/include/d_plsf.h
new file mode 100644
index 0000000..0e5ca9a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/d_plsf.h
@@ -0,0 +1,199 @@
+/* ------------------------------------------------------------------
+ * 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/d_plsf.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the d_plsf_3.c and d_plsf_5.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef d_plsf_h
+#define d_plsf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.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 past_r_q[M];   /* Past quantized prediction error, Q15 */
+        Word16 past_lsf_q[M]; /* Past dequantized lsfs,           Q15 */
+    } D_plsfState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : D_plsf_reset
+    *  Purpose     : Resets state memory
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 D_plsf_reset(D_plsfState *st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : D_plsf_exit
+    *  Purpose     : The memory used for state memory is freed
+    *  Description : Stores NULL in *st
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void D_plsf_exit(D_plsfState **st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : D_plsf_5
+    *  Purpose     : Decodes the 2 sets of LSP parameters in a frame
+    *                using the received quantization indices.
+    *  Description : The two sets of LSFs are quantized using split by
+    *                5 matrix quantization (split-MQ) with 1st order MA
+    *                prediction.
+    *                See "q_plsf_5.c" for more details about the
+    *                quantization procedure
+    *  Returns     : 0
+    *
+    **************************************************************************
+    */
+    void D_plsf_5(
+        D_plsfState *st,  /* i/o: State variables                            */
+        Word16 bfi,       /* i  : bad frame indicator (set to 1 if a bad
+                              frame is received)                         */
+        Word16 *indice,   /* i  : quantization indices of 5 submatrices, Q0  */
+        Word16 *lsp1_q,   /* o  : quantized 1st LSP vector (M)           Q15 */
+        Word16 *lsp2_q,   /* o  : quantized 2nd LSP vector (M)           Q15 */
+        Flag  *pOverflow  /* o : Flag set when overflow occurs               */
+    );
+
+    /*************************************************************************
+     *
+     *  FUNCTION:   D_plsf_3()
+     *
+     *  PURPOSE: Decodes the LSP parameters using the received quantization
+     *           indices.1st order MA prediction and split by 3 matrix
+     *           quantization (split-MQ)
+     *
+     *************************************************************************/
+
+    void D_plsf_3(
+        D_plsfState *st,  /* i/o: State struct                               */
+        enum Mode mode,   /* i  : coder mode                                 */
+        Word16 bfi,       /* i  : bad frame indicator (set to 1 if a         */
+        /*      bad frame is received)                     */
+        Word16 * indice,  /* i  : quantization indices of 3 submatrices, Q0  */
+        Word16 * lsp1_q,  /* o  : quantized 1st LSP vector,              Q15 */
+        Flag  *pOverflow  /* o : Flag set when overflow occurs               */
+    );
+
+    /*************************************************************************
+     *
+     *  FUNCTION:   Init_D_plsf_3()
+     *
+     *  PURPOSE: Set the past_r_q[M] vector to one of the eight
+     *           past_rq_init vectors.
+     *
+     *************************************************************************/
+    void Init_D_plsf_3(D_plsfState *st,  /* i/o: State struct                */
+                       Word16 index      /* i  : past_rq_init[] index [0, 7] */
+                      );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _Q_PLSF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/div_32.h b/media/libstagefright/codecs/amrnb/common/include/div_32.h
new file mode 100644
index 0000000..28b726b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/div_32.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/div_32.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the Div_32 function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DIV_32_H
+#define DIV_32_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
+    ----------------------------------------------------------------------------*/
+    Word32 Div_32(Word32 L_num,
+    Word16 L_denom_hi,
+    Word16 L_denom_lo,
+    Flag   *pOverflow) ;
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _DIV_32_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/div_s.h b/media/libstagefright/codecs/amrnb/common/include/div_s.h
new file mode 100644
index 0000000..e8421db
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/div_s.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/div_s.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for div_s function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the div_s function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DIV_S_H
+#define DIV_S_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 div_s(Word16 var1, Word16 var2);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/dtx_common_def.h b/media/libstagefright/codecs/amrnb/common/include/dtx_common_def.h
new file mode 100644
index 0000000..c29b9e1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/dtx_common_def.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.
+****************************************************************************************/
+/*
+ Filename: /audio/gsm_amr/c/include/dtx_common_def.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+    File             : dtx_common_def.h
+    Purpose          : DTX definitions common to encoder and decoder
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DTX_COMMON_DEF_H
+#define DTX_COMMON_DEF_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define DTX_MAX_EMPTY_THRESH 50
+#define DTX_HIST_SIZE 8
+#define DTX_ELAPSED_FRAMES_THRESH (24 + 7 -1)
+#define DTX_HANG_CONST 7             /* yields eight frames of SP HANGOVER  */
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* DTX_COMMON_DEF_H */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/extract_h.h b/media/libstagefright/codecs/amrnb/common/include/extract_h.h
new file mode 100644
index 0000000..34a623f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/extract_h.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/extract_h.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for extract_h function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the extract_h function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef EXTRACT_H_H
+#define EXTRACT_H_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 extract_h(Word32 L_var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/extract_l.h b/media/libstagefright/codecs/amrnb/common/include/extract_l.h
new file mode 100644
index 0000000..ed7460d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/extract_l.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/extract_l.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for extract_l function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the extract_l function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef EXTRACT_L_H
+#define EXTRACT_L_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 extract_l(Word32 L_var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/frame.h b/media/libstagefright/codecs/amrnb/common/include/frame.h
new file mode 100644
index 0000000..1d0c6c1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/frame.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             : frame.h
+*      Purpose          : Declaration of received and transmitted frame types
+*
+*****************************************************************************
+*/
+#ifndef frame_h
+#define frame_h "$Id $"
+
+/*
+*****************************************************************************
+*                         INCLUDE FILES
+*****************************************************************************
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    *****************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    *****************************************************************************
+    * Note: The order of the TX and RX_Type identifiers has been chosen in
+    *       the way below to be compatible to an earlier version of the
+    *       AMR-NB C reference program.
+    *****************************************************************************
+    */
+
+    enum RXFrameType { RX_SPEECH_GOOD = 0,
+        RX_SPEECH_DEGRADED,
+        RX_ONSET,
+        RX_SPEECH_BAD,
+        RX_SID_FIRST,
+        RX_SID_UPDATE,
+        RX_SID_BAD,
+        RX_NO_DATA,
+        RX_N_FRAMETYPES     /* number of frame types */
+    };
+
+    enum TXFrameType { TX_SPEECH_GOOD = 0,
+                       TX_SID_FIRST,
+                       TX_SID_UPDATE,
+                       TX_NO_DATA,
+                       TX_SPEECH_DEGRADED,
+                       TX_SPEECH_BAD,
+                       TX_SID_BAD,
+                       TX_ONSET,
+                       TX_N_FRAMETYPES     /* number of frame types */
+                     };
+
+
+    /* Channel decoded frame type */
+    enum CHDECFrameType { CHDEC_SID_FIRST = 0,
+                          CHDEC_SID_FIRST_INCOMPLETE,
+                          CHDEC_SID_UPDATE_INCOMPLETE,
+                          CHDEC_SID_UPDATE,
+                          CHDEC_SPEECH,
+                          CHDEC_SPEECH_ONSET,
+                          CHDEC_ESCAPE_MARKER,
+                          CHDEC_ESCAPE_DATA,
+                          CHDEC_NO_DATA
+                        };
+
+    /* Channel decoded frame quality */
+    enum CHDECFrameQuality { CHDEC_GOOD = 0,
+                             CHDEC_PROBABLY_DEGRADED,
+                             CHDEC_PROBABLY_BAD,
+                             CHDEC_BAD
+                           };
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/frame_type_3gpp.h b/media/libstagefright/codecs/amrnb/common/include/frame_type_3gpp.h
new file mode 100644
index 0000000..0620367
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/frame_type_3gpp.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/c/include/frame_type_3gpp.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated to new PV C header template.
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the definition of the 3GPP frame types.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef FRAME_TYPE_3GPP_H
+#define FRAME_TYPE_3GPP_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+/*--------------------------------------------------------------------------*/
+#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
+    ----------------------------------------------------------------------------*/
+
+    enum Frame_Type_3GPP
+    {
+        AMR_475 = 0,
+        AMR_515,
+        AMR_59,
+        AMR_67,
+        AMR_74,
+        AMR_795,
+        AMR_102,
+        AMR_122,
+        AMR_SID,
+        GSM_EFR_SID,
+        TDMA_EFR_SID,
+        PDC_EFR_SID,
+        FOR_FUTURE_USE1,
+        FOR_FUTURE_USE2,
+        FOR_FUTURE_USE3,
+        AMR_NO_DATA
+    };
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* _FRAME_TYPE_3GPP_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/gc_pred.h b/media/libstagefright/codecs/amrnb/common/include/gc_pred.h
new file mode 100644
index 0000000..b82603c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/gc_pred.h
@@ -0,0 +1,176 @@
+/* ------------------------------------------------------------------
+ * 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/gc_pred.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : gc_pred.h
+      Purpose          : codebook gain MA prediction
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _GC_PRED_H_
+#define _GC_PRED_H_
+#define gc_pred_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 past_qua_en[4];         /* normal MA predictor memory,         Q10 */
+        /* (contains 20*log10(qua_err))            */
+        Word16 past_qua_en_MR122[4];   /* MA predictor memory for MR122 mode, Q10 */
+        /* (contains log2(qua_err))                */
+    } gc_predState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    Word16 gc_pred_reset(gc_predState *st);
+    /* reset of codebook gain MA predictor state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void gc_pred_exit(gc_predState **st);
+    /* de-initialize codebook gain MA predictor state (i.e. free state struct)
+       stores NULL in *st
+     */
+
+    void
+    gc_pred_copy(
+        gc_predState *st_src,  /* i : State struct                           */
+        gc_predState *st_dest  /* o : State struct                           */
+    );
+
+    /*
+     * FUNCTION:  gc_pred()
+     * PURPOSE: MA prediction of the innovation energy
+     *          (in dB/(20*log10(2))) with mean  removed).
+     */
+    void gc_pred(
+        gc_predState *st,   /* i/o: State struct                           */
+        enum Mode mode,     /* i  : AMR mode                               */
+        Word16 *code,       /* i  : innovative codebook vector (L_SUBFR)   */
+        /*      MR122: Q12, other modes: Q13           */
+        Word16 *exp_gcode0, /* o  : exponent of predicted gain factor, Q0  */
+        Word16 *frac_gcode0,/* o  : fraction of predicted gain factor  Q15 */
+        Word16 *exp_en,     /* o  : exponent of innovation energy,     Q0  */
+        /*      (only calculated for MR795)            */
+        Word16 *frac_en,    /* o  : fraction of innovation energy,     Q15 */
+        /*      (only calculated for MR795)            */
+        Flag   *pOverflow
+    );
+
+    /*
+     * FUNCTION:  gc_pred_update()
+     * PURPOSE: update MA predictor with last quantized energy
+     */
+    void gc_pred_update(
+        gc_predState *st,      /* i/o: State struct                     */
+        Word16 qua_ener_MR122, /* i  : quantized energy for update, Q10 */
+        /*      (log2(qua_err))                  */
+        Word16 qua_ener        /* i  : quantized energy for update, Q10 */
+        /*      (20*log10(qua_err))              */
+    );
+
+    /*
+     * FUNCTION:  gc_pred_average_limited()
+     * PURPOSE: get average of MA predictor state values (with a lower limit)
+     *          [used in error concealment]
+     */
+    void gc_pred_average_limited(
+        gc_predState *st,       /* i: State struct                    */
+        Word16 *ener_avg_MR122, /* o: averaged quantized energy,  Q10 */
+        /*    (log2(qua_err))                 */
+        Word16 *ener_avg,       /* o: averaged quantized energy,  Q10 */
+        /*    (20*log10(qua_err))             */
+        Flag   *pOverflow
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _GC_PRED_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/gmed_n.h b/media/libstagefright/codecs/amrnb/common/include/gmed_n.h
new file mode 100644
index 0000000..1c4ede2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/gmed_n.h
@@ -0,0 +1,80 @@
+/* ------------------------------------------------------------------
+ * 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             : gmed_n.h
+*      Purpose          : calculates N-point median.
+*
+********************************************************************************
+*/
+#ifndef gmed_n_h
+#define gmed_n_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    Word16 gmed_n(    /* o : index of the median value (0...N-1)      */
+        Word16 ind[], /* i : Past gain values                         */
+        Word16 n      /* i : The number of gains; this routine        */
+        /*     is only valid for a odd number of gains  */
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/gsm_amr_typedefs.h b/media/libstagefright/codecs/amrnb/common/include/gsm_amr_typedefs.h
new file mode 100644
index 0000000..4abcbbd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/gsm_amr_typedefs.h
@@ -0,0 +1,133 @@
+/* ------------------------------------------------------------------
+ * 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: codecs/audio/gsm_amr/gsm_two_way/c/include/gsm_amr_typedefs.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Removed unused defintions and corrected ifdef, that depended on
+              incorrect typedef
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the definition of the amr codec types.
+
+------------------------------------------------------------------------------
+*/
+#ifndef GSM_AMR_TYPEDEFS_H
+#define GSM_AMR_TYPEDEFS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include <stdint.h>
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+typedef int8_t        Word8;
+typedef uint8_t       UWord8;
+
+
+/*----------------------------------------------------------------------------
+; Define 16 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+typedef int16_t       Word16;
+typedef uint16_t      UWord16;
+
+/*----------------------------------------------------------------------------
+; Define 32 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+typedef int32_t       Word32;
+typedef uint32_t      UWord32;
+
+
+/*----------------------------------------------------------------------------
+; Define boolean type
+----------------------------------------------------------------------------*/
+typedef int     Bool;
+
+#ifndef FALSE
+#define FALSE       0
+#endif
+
+#ifndef TRUE
+#define TRUE        1
+#endif
+
+#ifndef OFF
+#define OFF     0
+#endif
+
+#ifndef ON
+#define ON      1
+#endif
+
+#ifndef NO
+#define NO      0
+#endif
+
+#ifndef YES
+#define YES     1
+#endif
+
+#ifndef SUCCESS
+#define SUCCESS     0
+#endif
+
+#ifndef  NULL
+#define  NULL       0
+#endif
+
+typedef int32_t     Flag;
+
+#endif   /*  GSM_AMR_TYPEDEFS_H */
diff --git a/media/libstagefright/codecs/amrnb/common/include/int_lpc.h b/media/libstagefright/codecs/amrnb/common/include/int_lpc.h
new file mode 100644
index 0000000..e95e6ca
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/int_lpc.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/lsp_avg.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the lsp_avg.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef int_lpc_h
+#define int_lpc_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
+    ----------------------------------------------------------------------------*/
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : Int_lpc_1and3
+    *  Purpose     : Interpolates the LSPs and converts to LPC parameters
+    *                to get a different LP filter in each subframe.
+    *  Description : The 20 ms speech frame is divided into 4 subframes.
+    *                The LSPs are quantized and transmitted at the 2nd and
+    *                4th subframes (twice per frame) and interpolated at the
+    *                1st and 3rd subframe.
+    *
+    *                      |------|------|------|------|
+    *                         sf1    sf2    sf3    sf4
+    *                   F0            Fm            F1
+    *
+    *                 sf1:   1/2 Fm + 1/2 F0         sf3:   1/2 F1 + 1/2 Fm
+    *                 sf2:       Fm                  sf4:       F1
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void Int_lpc_1and3(
+        Word16 lsp_old[],  /* i : LSP vector at the 4th subfr. of past frame (M) */
+        Word16 lsp_mid[],  /* i : LSP vector at the 2nd subfr. of
+                              present frame (M)                              */
+        Word16 lsp_new[],  /* i : LSP vector at the 4th subfr. of
+                              present frame (M)                              */
+        Word16 Az[],       /* o : interpolated LP parameters in all subfr.
+                              (AZ_SIZE)                                      */
+        Flag   *pOverflow
+    );
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : Int_lpc_1and3_2
+    *  Purpose     : Interpolation of the LPC parameters. Same as the Int_lpc
+    *                function but we do not recompute Az() for subframe 2 and
+    *                4 because it is already available.
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void Int_lpc_1and3_2(
+        Word16 lsp_old[],  /* i : LSP vector at the 4th subfr. of past frame (M) */
+        Word16 lsp_mid[],  /* i : LSP vector at the 2nd subframe of
+                             present frame (M)                                  */
+        Word16 lsp_new[],  /* i : LSP vector at the 4th subframe of
+                             present frame (M)                                  */
+        Word16 Az[],       /* o :interpolated LP parameters
+                             in subframes 1 and 3 (AZ_SIZE)                     */
+        Flag   *pOverflow
+    );
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : Int_lpc_1to3
+    *  Purpose     : Interpolates the LSPs and converts to LPC parameters
+    *                to get a different LP filter in each subframe.
+    *  Description : The 20 ms speech frame is divided into 4 subframes.
+    *                The LSPs are quantized and transmitted at the 4th
+    *                subframes (once per frame) and interpolated at the
+    *                1st, 2nd and 3rd subframe.
+    *
+    *                      |------|------|------|------|
+    *                         sf1    sf2    sf3    sf4
+    *                   F0                          F1
+    *
+    *                 sf1:   3/4 F0 + 1/4 F1         sf3:   1/4 F0 + 3/4 F1
+    *                 sf2:   1/2 F0 + 1/2 F1         sf4:       F1
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void Int_lpc_1to3(
+        Word16 lsp_old[], /* i : LSP vector at the 4th SF of past frame (M)      */
+        Word16 lsp_new[], /* i : LSP vector at the 4th SF of present frame (M)   */
+        Word16 Az[],      /* o : interpolated LP parameters in all SFs (AZ_SIZE) */
+        Flag   *pOverflow
+    );
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : Int_lpc_1to3_2
+    *  Purpose     : Interpolation of the LPC parameters. Same as the Int_lpc
+    *                function but we do not recompute Az() for subframe 4
+    *                because it is already available.
+    *  Returns     : void
+    *
+    **************************************************************************
+    */
+    void Int_lpc_1to3_2(
+        Word16 lsp_old[],  /* i : LSP vector at the 4th SF of past frame (M) */
+        Word16 lsp_new[],  /* i : LSP vector at the 4th SF present frame (M) */
+        Word16 Az[],       /* o :interpolated LP parameters in SFs 1, 2, 3
+                             (AZ_SIZE)                                   */
+        Flag   *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _INT_LPC_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/int_lsf.h b/media/libstagefright/codecs/amrnb/common/include/int_lsf.h
new file mode 100644
index 0000000..4e02ae6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/int_lsf.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.
+****************************************************************************************/
+/*
+
+ Filename: /audio/gsm_amr/c/include/int_lsf.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the int_lsf function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef int_lsf_h
+#define int_lsf_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 Int_lsf(
+        Word16 lsf_old[], /* i : LSF vector at the 4th SF of past frame         */
+        Word16 lsf_new[], /* i : LSF vector at the 4th SF of present frame      */
+        Word16 i_subfr,   /* i : Current sf (equal to 0,40,80 or 120)           */
+        Word16 lsf_out[], /* o : interpolated LSF parameters for current sf     */
+        Flag  *pOverflow  /* o : flag set if overflow occurs                    */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _INT_LSF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/inv_sqrt.h b/media/libstagefright/codecs/amrnb/common/include/inv_sqrt.h
new file mode 100644
index 0000000..4fb2b11
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/inv_sqrt.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/inv_sqrt.h
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Added an extern declaration for inv_sqrt_tbl[], now defined in
+              the file inv_sqrt_tbl.c
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                           Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the inv_sqrt() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef INV_SQRT_H
+#define INV_SQRT_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
+    ----------------------------------------------------------------------------*/
+    extern Word16 inv_sqrt_tbl[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word32 Inv_sqrt(        /* (o) : output value   */
+        Word32 L_x,         /* (i) : input value    */
+        Flag   *pOverflow  /* (i) : pointer to overflow flag */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _INV_SQRT_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_abs.h b/media/libstagefright/codecs/amrnb/common/include/l_abs.h
new file mode 100644
index 0000000..db57b82
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_abs.h
@@ -0,0 +1,111 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/l_abs.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_abs function.
+
+ Description: Moved _cplusplus #ifdef after Include section..
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_abs function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_ABS_H
+#define L_ABS_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_abs(Word32 L_var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_add.h b/media/libstagefright/codecs/amrnb/common/include/l_add.h
new file mode 100644
index 0000000..136b914
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_add.h
@@ -0,0 +1,171 @@
+/* ------------------------------------------------------------------
+ * 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/l_add.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_add function.
+
+ Description: Changed function prototype declaration. A pointer to the overflow
+              flag is being passed in as a parameter instead of using global
+              data.
+
+ Description: Updated template. Changed paramter name from overflow to
+              pOverflow
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Providing support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_add function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_ADD_H
+#define L_ADD_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+        __asm
+        {
+            QADD result, L_var1, L_var2
+        }
+        return(result);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    __inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("qadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb)
+                            );
+        return (result);
+
+    }
+
+#else /* C EQUIVALENT */
+
+
+    static inline Word32 L_add(register Word32 L_var1, register Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 L_sum;
+
+        L_sum = L_var1 + L_var2;
+
+        if ((L_var1 ^ L_var2) >= 0)
+        {
+            if ((L_sum ^ L_var1) < 0)
+            {
+                L_sum = (L_var1 < 0) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+
+        return (L_sum);
+    }
+
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_ADD_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_add_c.h b/media/libstagefright/codecs/amrnb/common/include/l_add_c.h
new file mode 100644
index 0000000..3585a3c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_add_c.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/l_add_c.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_add_c function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag and carry flag is passed into the
+              function. Updated template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_add_c function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_ADD_C_H
+#define L_ADD_C_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_add_c(Word32 L_var1, Word32 L_var2, Flag *pOverflow, Flag *pCarry);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_ADD_C_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_comp.h b/media/libstagefright/codecs/amrnb/common/include/l_comp.h
new file mode 100644
index 0000000..02a4bb7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_comp.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/l_comp.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Passing in pOverflow for EPOC changes.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_comp function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_COMP_H
+#define L_COMP_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_Comp(Word16 hi, Word16 lo, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_deposit_h.h b/media/libstagefright/codecs/amrnb/common/include/l_deposit_h.h
new file mode 100644
index 0000000..e58bc5f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_deposit_h.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/l_deposit_h.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_deposit_h function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_deposit_h function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_DEPOSIT_H_H
+#define L_DEPOSIT_H_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_deposit_h(Word16 var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_deposit_l.h b/media/libstagefright/codecs/amrnb/common/include/l_deposit_l.h
new file mode 100644
index 0000000..09fabfd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_deposit_l.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/l_deposit_l.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_deposit_l function.
+
+ Description: Updated template to make it build for Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_deposit_l function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_DEPOSIT_L_H
+#define L_DEPOSIT_L_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_deposit_l(Word16 var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_extract.h b/media/libstagefright/codecs/amrnb/common/include/l_extract.h
new file mode 100644
index 0000000..fdbe351
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_extract.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/l_extract.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_extract function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_EXTRACT_H
+#define L_EXTRACT_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 L_Extract(Word32 L_var,
+    Word16 *pL_var_hi,
+    Word16 *pL_var_lo,
+    Flag   *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_EXTRACT_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_mac.h b/media/libstagefright/codecs/amrnb/common/include/l_mac.h
new file mode 100644
index 0000000..b4af3aa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_mac.h
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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/l_mac.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_mac function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: 1. Updated the function to include ARM and Linux-ARM assembly
+                 instructions.
+              2. Added OSCL_UNUSED_ARG(pOverflow) to remove compiler warnings.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_mac function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_MAC_H
+#define L_MAC_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 L_sum;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm {SMULBB result, var1, var2}
+        __asm {QDADD L_sum, L_var3, result}
+        return (L_sum);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    static inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 ra = L_var3;
+        register Word32 rb = var1;
+        register Word32 rc = var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(result)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(rc)
+                             : "r"(ra), "r"(result)
+                            );
+
+        return (rc);
+    }
+
+#else /* C_EQUIVALENT */
+
+    __inline Word32 L_mac(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 L_sum;
+        result = (Word32) var1 * var2;
+        if (result != (Word32) 0x40000000L)
+        {
+            L_sum = (result << 1) + L_var3;
+
+            /* Check if L_sum and L_var_3 share the same sign */
+            if ((L_var3 ^ result) > 0)
+            {
+                if ((L_sum ^ L_var3) < 0)
+                {
+                    L_sum = (L_var3 < 0) ? MIN_32 : MAX_32;
+                    *pOverflow = 1;
+                }
+            }
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_sum = MAX_32;
+        }
+        return (L_sum);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_MAC_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_msu.h b/media/libstagefright/codecs/amrnb/common/include/l_msu.h
new file mode 100644
index 0000000..3bafb00
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_msu.h
@@ -0,0 +1,171 @@
+/* ------------------------------------------------------------------
+ * 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/l_msu.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_msu function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Providing support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_msu function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_MSU_H
+#define L_MSU_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "basicop_malloc.h"
+#include    "l_mult.h"
+#include    "l_sub.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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 product;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            QDSUB  result, L_var3, product
+        }
+
+        return (result);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    __inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 ra = L_var3;
+        register Word32 rb = var1;
+        register Word32 rc = var2;
+        Word32 product;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("qdsub %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(product)
+                            );
+
+        return (result);
+    }
+
+#else /* C EQUIVALENT */
+
+    static inline Word32 L_msu(Word32 L_var3, Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        result = L_mult(var1, var2, pOverflow);
+        result = L_sub(L_var3, result, pOverflow);
+
+        return (result);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_MSU_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_mult.h b/media/libstagefright/codecs/amrnb/common/include/l_mult.h
new file mode 100644
index 0000000..061df60
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_mult.h
@@ -0,0 +1,178 @@
+/* ------------------------------------------------------------------
+ * 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/l_mult.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_mult function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Providing support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_mult function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_MULT_H
+#define L_MULT_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
+    ----------------------------------------------------------------------------*/
+
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 result;
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            QADD   result, product, product
+        }
+
+        return (result);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    __inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 ra = var1;
+        register Word32 rb = var2;
+        Word32 result;
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product)
+                             : "r"(ra), "r"(rb)
+                            );
+
+        asm volatile("qadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(product), "r"(product)
+                            );
+
+        return(result);
+    }
+
+#else /* C EQUIVALENT */
+
+    static inline Word32 L_mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 L_product;
+
+        L_product = (Word32) var1 * var2;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;          /* Multiply by 2 */
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_product = MAX_32;
+        }
+
+        return (L_product);
+    }
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_MULT_H */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_negate.h b/media/libstagefright/codecs/amrnb/common/include/l_negate.h
new file mode 100644
index 0000000..11e14a8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_negate.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./gsm-amr/c/include/l_negate.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_negate function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_negate function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_NEGATE_H
+#define L_NEGATE_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_negate(Word32 L_var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shl.h b/media/libstagefright/codecs/amrnb/common/include/l_shl.h
new file mode 100644
index 0000000..7b9fdb1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_shl.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/l_shl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_shl function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_shl function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_SHL_H
+#define L_SHL_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_shl(Word32 L_var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_SHL_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shr.h b/media/libstagefright/codecs/amrnb/common/include/l_shr.h
new file mode 100644
index 0000000..ef22073
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_shr.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/l_shr.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_shr function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_shr function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_SHR_H
+#define L_SHR_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_shr(Word32 L_var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_SHR_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_shr_r.h b/media/libstagefright/codecs/amrnb/common/include/l_shr_r.h
new file mode 100644
index 0000000..1a1661f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_shr_r.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.
+****************************************************************************************/
+/*
+
+ Filename: /audio/gsm_amr/c/include/l_shr_r.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_shr_r function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_shr_r function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_SHR_R_H
+#define L_SHR_R_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
+    ----------------------------------------------------------------------------*/
+    Word32 L_shr_r(Word32 L_var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_SHR_R_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/l_sub.h b/media/libstagefright/codecs/amrnb/common/include/l_sub.h
new file mode 100644
index 0000000..97d7538
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/l_sub.h
@@ -0,0 +1,173 @@
+/* ------------------------------------------------------------------
+ * 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/l_sub.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for L_sub function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Providing support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the L_sub function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef L_SUB_H
+#define L_SUB_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 L_sub(Word32 L_var1, Word32 L_var2, Flag *pOverflow)
+    {
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            QSUB result, L_var1, L_var2
+        }
+
+        return(result);
+
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    __inline Word32 L_sub(Word32 L_var1, Word32 L_var2, Flag *pOverflow)
+    {
+        register Word32 ra = L_var1;
+        register Word32 rb = L_var2;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("qsub %0, %1, %2"
+             : "=r"(result)
+                             : "r"(ra), "r"(rb)
+                            );
+
+        return (result);
+    }
+
+#else /* C EQUIVALENT */
+
+    static inline Word32 L_sub(register Word32 L_var1, register Word32 L_var2,
+                               register Flag *pOverflow)
+    {
+        Word32 L_diff;
+
+        L_diff = L_var1 - L_var2;
+
+        if ((L_var1 ^ L_var2) < 0)
+        {
+            if ((L_diff ^ L_var1) & MIN_32)
+            {
+                L_diff = (L_var1 < 0L) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+
+        return (L_diff);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _L_SUB_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/log2.h b/media/libstagefright/codecs/amrnb/common/include/log2.h
new file mode 100644
index 0000000..e589b2f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/log2.h
@@ -0,0 +1,120 @@
+/* ------------------------------------------------------------------
+ * 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/log2.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. Deleted function
+          prototype for Log2_norm and put it in its own header file.
+          Added log2_norm.h in Include section for legacy files.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section..
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the function prototype definition for Log2 function.
+
+------------------------------------------------------------------------------
+*/
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LOG2_H
+#define LOG2_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+
+#include    "log2_norm.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 Log2(
+        Word32 L_x,         /* (i) : input value                                */
+        Word16 *pExponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30)*/
+        Word16 *pFraction,  /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+        Flag   *pOverflow   /* (i/o) : overflow flag                            */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LOG2_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/log2_norm.h b/media/libstagefright/codecs/amrnb/common/include/log2_norm.h
new file mode 100644
index 0000000..b104a69
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/log2_norm.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/log2_norm.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for Log2_norm function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template. Added extern declaration for log2_tbl[]
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the prototype declaration for Log2_norm function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LOG2_NORM_H
+#define LOG2_NORM_H
+
+#define log2_h "$Id $"              /* Used by legacy code */
+
+/*----------------------------------------------------------------------------
+; 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 log2_tbl[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void Log2_norm(
+        Word32 L_x,        /* (i) : input value (normalized)                    */
+        Word16 exp,        /* (i) : norm_l (L_x)                                */
+        Word16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        Word16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LOG2_NORM_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsfwt.h b/media/libstagefright/codecs/amrnb/common/include/lsfwt.h
new file mode 100644
index 0000000..d9a1f80
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/lsfwt.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/lsfwt.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the lsfwt.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef lsfwt_h
+#define lsfwt_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
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    void Lsf_wt(
+        Word16 *lsf,          /* input : LSF vector                    */
+        Word16 *wf,           /* output: square of weighting factors   */
+        Flag   * pOverflow);  /* o : Flag set when overflow occurs     */
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LSF_WT_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp.h b/media/libstagefright/codecs/amrnb/common/include/lsp.h
new file mode 100644
index 0000000..26a4b34
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/lsp.h
@@ -0,0 +1,186 @@
+/* ------------------------------------------------------------------
+ * 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/lsp.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the lsp.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef lsp_h
+#define lsp_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "q_plsf.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
+    {
+
+        /* Past LSPs */
+        Word16 lsp_old[M];
+        Word16 lsp_old_q[M];
+
+        /* Quantization state */
+        Q_plsfState *qSt;
+
+    } lspState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    /*
+    **************************************************************************
+    *
+    *  Function    : lsp_init
+    *  Purpose     : Allocates memory and initializes state variables
+    *  Description : Stores pointer to filter status struct in *st. This
+    *                pointer has to be passed to lsp in each call.
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 lsp_init(lspState **st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : lsp_reset
+    *  Purpose     : Resets state memory
+    *  Returns     : 0 on success
+    *
+    **************************************************************************
+    */
+    Word16 lsp_reset(lspState *st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : lsp_exit
+    *  Purpose     : The memory used for state memory is freed
+    *  Description : Stores NULL in *st
+    *
+    **************************************************************************
+    */
+    void lsp_exit(lspState **st);
+
+    /*
+    **************************************************************************
+    *
+    *  Function    : lsp
+    *  Purpose     : Conversion from LP coefficients to LSPs.
+    *                Quantization of LSPs.
+    *  Description : Generates 2 sets of LSPs from 2 sets of
+    *                LP coefficients for mode 12.2. For the other
+    *                modes 1 set of LSPs is generated from 1 set of
+    *                LP coefficients. These LSPs are quantized with
+    *                Matrix/Vector quantization (depending on the mode)
+    *                and interpolated for the subframes not yet having
+    *                their own LSPs.
+    *
+    **************************************************************************
+    */
+    void lsp(lspState *st,       /* i/o : State struct                            */
+             enum Mode req_mode, /* i   : requested coder mode                    */
+             enum Mode used_mode,/* i   : used coder mode                         */
+             Word16 az[],        /* i/o : interpolated LP parameters Q12          */
+             Word16 azQ[],       /* o   : quantization interpol. LP parameters Q12*/
+             Word16 lsp_new[],   /* o   : new lsp vector                          */
+             Word16 **anap,      /* o   : analysis parameters                     */
+             Flag   *pOverflow   /* o   : Flag set when overflow occurs           */
+            );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LSP_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_az.h b/media/libstagefright/codecs/amrnb/common/include/lsp_az.h
new file mode 100644
index 0000000..ae81507
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/lsp_az.h
@@ -0,0 +1,111 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_az.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the lsp_az function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LSP_AZ_H
+#define LSP_AZ_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 Lsp_Az(
+        Word16 lsp[],        /* (i)  : line spectral frequencies            */
+        Word16 a[],          /* (o)  : predictor coefficients (order = 10)  */
+        Flag  *pOverflow     /* (o)  : overflow flag                        */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LSP_AZ_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_lsf.h b/media/libstagefright/codecs/amrnb/common/include/lsp_lsf.h
new file mode 100644
index 0000000..186b4d3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/lsp_lsf.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/lsp_lsf.h
+
+------------------------------------------------------------------------------
+ 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 lsp_lsf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef lsp_lsf_h
+#define lsp_lsf_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 Lsf_lsp(
+        Word16 lsf[],      /* (i)    : lsf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 lsp[],      /* (o)    : lsp[m] (range: -1<=val<1)                */
+        Word16 m,          /* (i)    : LPC order                                */
+        Flag  *pOverflow   /* (o)    : Flag set when overflow occurs            */
+    );
+    void Lsp_lsf(
+        Word16 lsp[],      /* (i)    : lsp[m] (range: -1<=val<1)                */
+        Word16 lsf[],      /* (o)    : lsf[m] normalized (range: 0.0<=val<=0.5) */
+        Word16 m,          /* (i)    : LPC order                                */
+        Flag  *pOverflow   /* (o)    : Flag set when overflow occurs            */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LSP_LSF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/lsp_tab.h b/media/libstagefright/codecs/amrnb/common/include/lsp_tab.h
new file mode 100644
index 0000000..01b3317
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/lsp_tab.h
@@ -0,0 +1,111 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_tab.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a table lsp_init_data.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef LSP_TAB_H
+#define LSP_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 lsp_init_data[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/mac_32.h b/media/libstagefright/codecs/amrnb/common/include/mac_32.h
new file mode 100644
index 0000000..9e9ebe1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mac_32.h
@@ -0,0 +1,150 @@
+/* ------------------------------------------------------------------
+ * 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/mac_32.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Inlined the functions from mac_32.cpp. A performance improvement
+              change.
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the Mac_32 and Mac_32_16 functions
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MAC_32_H
+#define MAC_32_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
+    ----------------------------------------------------------------------------*/
+
+    static inline Word32 Mac_32(Word32 L_var3,
+    Word16 L_var1_hi,
+    Word16 L_var1_lo,
+    Word16 L_var2_hi,
+    Word16 L_var2_lo,
+    Flag *pOverflow)
+    {
+        Word16  product;
+
+        L_var3 = L_mac(L_var3, L_var1_hi, L_var2_hi, pOverflow);
+
+        product = mult(L_var1_hi, L_var2_lo, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        product = mult(L_var1_lo, L_var2_hi, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        return (L_var3);
+    }
+
+    static inline Word32 Mac_32_16(Word32 L_var3,
+                                   Word16 L_var1_hi,
+                                   Word16 L_var1_lo,
+                                   Word16 var2,
+                                   Flag  *pOverflow)
+    {
+        Word16  product;
+
+        L_var3 = L_mac(L_var3, L_var1_hi, var2, pOverflow);
+
+        product = mult(L_var1_lo, var2, pOverflow);
+        L_var3 = L_mac(L_var3, product, 1, pOverflow);
+
+        return (L_var3);
+    }
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _MAC_32_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/mode.h b/media/libstagefright/codecs/amrnb/common/include/mode.h
new file mode 100644
index 0000000..75f86cb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mode.h
@@ -0,0 +1,82 @@
+/* ------------------------------------------------------------------
+ * 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             : mode.h
+*      Purpose          : Declaration of mode type
+*
+********************************************************************************
+*/
+#ifndef mode_h
+#define mode_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+    enum Mode { MR475 = 0,
+        MR515,
+        MR59,
+        MR67,
+        MR74,
+        MR795,
+        MR102,
+        MR122,
+
+        MRDTX,
+
+        N_MODES     /* number of (SPC) modes */
+
+    };
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/mpy_32.h b/media/libstagefright/codecs/amrnb/common/include/mpy_32.h
new file mode 100644
index 0000000..03f36b2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mpy_32.h
@@ -0,0 +1,272 @@
+/* ------------------------------------------------------------------
+ * 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/mpy_32.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Updated the function to include ARM and Linux-ARM assembly
+              instructions.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the Mpy_32 function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MPY_32_H
+#define MPY_32_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 Mpy_32(Word16 L_var1_hi,
+    Word16 L_var1_lo,
+    Word16 L_var2_hi,
+    Word16 L_var2_lo,
+    Flag   *pOverflow)
+
+    {
+        /*----------------------------------------------------------------------------
+        ; Define all local variables
+        ----------------------------------------------------------------------------*/
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 product32;
+
+        OSCL_UNUSED_ARG(pOverflow);
+        /*----------------------------------------------------------------------------
+        ; Function body here
+        ----------------------------------------------------------------------------*/
+        /* L_product = L_mult (L_var1_hi, L_var2_hi, pOverflow);*/
+
+        __asm {SMULBB L_product, L_var1_hi, L_var2_hi}
+        __asm {QDADD L_product, 0, L_product}
+        __asm {SMULBB product32, L_var1_hi, L_var2_lo}
+        product32 >>= 15;
+        __asm {QDADD L_sum, L_product, product32}
+        L_product = L_sum;
+        __asm {SMULBB product32, L_var1_lo, L_var2_hi}
+        product32 >>= 15;
+        __asm {QDADD L_sum, L_product, product32}
+        return (L_sum);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    static inline Word32 Mpy_32(Word16 L_var1_hi,
+                                Word16 L_var1_lo,
+                                Word16 L_var2_hi,
+                                Word16 L_var2_lo,
+                                Flag   *pOverflow)
+    {
+        register Word32 product32;
+        register Word32 L_sum;
+        register Word32 L_product, result;
+        register Word32 ra = L_var1_hi;
+        register Word32 rb = L_var1_lo;
+        register Word32 rc = L_var2_hi;
+        register Word32 rd = L_var2_lo;
+
+
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(ra), "r"(rc)
+                            );
+        asm volatile("mov %0, #0"
+             : "=r"(result)
+                    );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_sum)
+                             : "r"(result), "r"(L_product)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product32)
+                             : "r"(ra), "r"(rd)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(ra)
+                             : "r"(product32)
+                            );
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(L_sum), "r"(ra)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product32)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(rb)
+                             : "r"(product32)
+                            );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_sum)
+                             : "r"(L_product), "r"(rb)
+                            );
+
+        return (L_sum);
+    }
+
+#else /* C_EQUIVALENT */
+
+    __inline Word32 Mpy_32(Word16 L_var1_hi,
+                           Word16 L_var1_lo,
+                           Word16 L_var2_hi,
+                           Word16 L_var2_lo,
+                           Flag   *pOverflow)
+    {
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 product32;
+
+        OSCL_UNUSED_ARG(pOverflow);
+        L_product = (Word32) L_var1_hi * L_var2_hi;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;
+        }
+        else
+        {
+            L_product = MAX_32;
+        }
+
+        /* result = mult (L_var1_hi, L_var2_lo, pOverflow); */
+        product32 = ((Word32) L_var1_hi * L_var2_lo) >> 15;
+
+        /* L_product = L_mac (L_product, result, 1, pOverflow); */
+        L_sum = L_product + (product32 << 1);
+
+        if ((L_product ^ product32) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+            }
+        }
+
+        L_product = L_sum;
+
+        /* result = mult (L_var1_lo, L_var2_hi, pOverflow); */
+        product32 = ((Word32) L_var1_lo * L_var2_hi) >> 15;
+
+        /* L_product = L_mac (L_product, result, 1, pOverflow); */
+        L_sum = L_product + (product32 << 1);
+
+        if ((L_product ^ product32) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+            }
+        }
+
+        /*----------------------------------------------------------------------------
+        ; Return nothing or data or data pointer
+        ----------------------------------------------------------------------------*/
+        return (L_sum);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _MPY_32_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/mpy_32_16.h b/media/libstagefright/codecs/amrnb/common/include/mpy_32_16.h
new file mode 100644
index 0000000..7eaa741
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mpy_32_16.h
@@ -0,0 +1,206 @@
+/* ------------------------------------------------------------------
+ * 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/mpy_32_16.h
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the Mpy_32_16 function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef MPY_32_16_H
+#define MPY_32_16_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5) /* Instructions for ARM Assembly on ADS*/
+
+    __inline Word32 Mpy_32_16(Word16 L_var1_hi,
+    Word16 L_var1_lo,
+    Word16 var2,
+    Flag *pOverflow)
+    {
+
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 result;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm {SMULBB L_product, L_var1_hi, var2}
+        __asm {QDADD L_product, 0, L_product}
+        __asm {SMULBB result, L_var1_lo, var2}
+        result >>= 15;
+        __asm {QDADD L_sum, L_product, result}
+        return (L_sum);
+    }
+
+#elif defined(PV_ARM_GCC_V5) /* Instructions for ARM-linux cross-compiler*/
+
+    static inline Word32 Mpy_32_16(Word16 L_var1_hi,
+                                   Word16 L_var1_lo,
+                                   Word16 var2,
+                                   Flag *pOverflow)
+    {
+
+        register Word32 ra = L_var1_hi;
+        register Word32 rb = L_var1_lo;
+        register Word32 rc = var2;
+        Word32 result, L_product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(ra), "r"(rc)
+                            );
+        asm volatile("mov %0, #0"
+             : "=r"(result)
+                    );
+
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(L_product)
+                             : "r"(result), "r"(L_product)
+                            );
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(result)
+                             : "r"(rb), "r"(rc)
+                            );
+
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(ra)
+                             : "r"(result)
+                            );
+        asm volatile("qdadd %0, %1, %2"
+             : "=r"(result)
+                             : "r"(L_product), "r"(ra)
+                            );
+
+        return (result);
+    }
+
+#else /* C_EQUIVALENT */
+    __inline Word32 Mpy_32_16(Word16 L_var1_hi,
+                              Word16 L_var1_lo,
+                              Word16 var2,
+                              Flag *pOverflow)
+    {
+
+        Word32 L_product;
+        Word32 L_sum;
+        Word32 result;
+        L_product = (Word32) L_var1_hi * var2;
+
+        if (L_product != (Word32) 0x40000000L)
+        {
+            L_product <<= 1;
+        }
+        else
+        {
+            *pOverflow = 1;
+            L_product = MAX_32;
+        }
+
+        result = ((Word32)L_var1_lo * var2) >> 15;
+
+        L_sum  =  L_product + (result << 1);
+
+        if ((L_product ^ result) > 0)
+        {
+            if ((L_sum ^ L_product) < 0)
+            {
+                L_sum = (L_product < 0) ? MIN_32 : MAX_32;
+                *pOverflow = 1;
+            }
+        }
+        return (L_sum);
+
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _MPY_32_16_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/mult.h b/media/libstagefright/codecs/amrnb/common/include/mult.h
new file mode 100644
index 0000000..6927eba
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mult.h
@@ -0,0 +1,190 @@
+/* ------------------------------------------------------------------
+ * 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/mult.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for mult function.
+
+ Description: Changed prototype of the mult() function. Instead of using global
+              a pointer to overflow flag is now passed into the function.
+
+ Description: Updated copyright information.
+              Updated variable name from "overflow" to "pOverflow" to match
+              with original function declaration.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Providing support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the mult function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef MULT_H
+#define MULT_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
+    ----------------------------------------------------------------------------*/
+#if defined(PV_ARM_V5)
+
+    __inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        Word32 product;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        __asm
+        {
+            SMULBB product, var1, var2
+            MOV    product, product, ASR #15
+            CMP    product, 0x7FFF
+            MOVGE  product, 0x7FFF
+        }
+
+        return ((Word16) product);
+    }
+
+#elif defined(PV_ARM_GCC_V5)
+
+    __inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 ra = var1;
+        register Word32 rb = var2;
+        Word32 product;
+        Word32 temp = 0x7FFF;
+
+        OSCL_UNUSED_ARG(pOverflow);
+
+        asm volatile("smulbb %0, %1, %2"
+             : "=r"(product)
+                             : "r"(ra), "r"(rb)
+                            );
+        asm volatile("mov %0, %1, ASR #15"
+             : "=r"(product)
+                             : "r"(product)
+                            );
+        asm volatile("cmp %0, %1"
+             : "=r"(product)
+                             : "r"(temp)
+                            );
+        asm volatile("movge %0, %1"
+             : "=r"(product)
+                             : "r"(temp)
+                            );
+
+        return ((Word16) product);
+    }
+
+#else /* C EQUIVALENT */
+
+    static inline Word16 mult(Word16 var1, Word16 var2, Flag *pOverflow)
+    {
+        register Word32 product;
+
+        product = ((Word32) var1 * var2) >> 15;
+
+        /* Saturate result (if necessary). */
+        /* var1 * var2 >0x00007fff is the only case */
+        /* that saturation occurs. */
+
+        if (product > 0x00007fffL)
+        {
+            *pOverflow = 1;
+            product = (Word32) MAX_16;
+        }
+
+
+        /* Return the product as a 16 bit value by type casting Word32 to Word16 */
+
+        return ((Word16) product);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _MULT_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/mult_r.h b/media/libstagefright/codecs/amrnb/common/include/mult_r.h
new file mode 100644
index 0000000..d7a1857
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/mult_r.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/mult_r.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for mult_r function.
+
+ Description: Changed prototype of the mult() function. Instead of using global
+              data, a pointer to overflow flag is now passed into the function.
+
+ Description: Made the following based on P2/P3 review
+              1) Changed the parameter name from "overflow" to "pOverflow"
+              in the function prototype declaration.
+              2) Updated template
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the mult_r function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef MULT_R__H
+#define MULT_R__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 mult_r(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* _MULT_R_H_ */
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/n_proc.h b/media/libstagefright/codecs/amrnb/common/include/n_proc.h
new file mode 100644
index 0000000..e5738c1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/n_proc.h
@@ -0,0 +1,31 @@
+/* ------------------------------------------------------------------
+ * 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.
+****************************************************************************************/
+/* $Id $ */
+
+void proc_head(char *mes);
diff --git a/media/libstagefright/codecs/amrnb/common/include/negate.h b/media/libstagefright/codecs/amrnb/common/include/negate.h
new file mode 100644
index 0000000..f67569e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/negate.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: ./gsm-amr/c/include/negate.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for negate function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the negate function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef NEGATE_H
+#define NEGATE_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 negate(register Word16 var1);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/norm_l.h b/media/libstagefright/codecs/amrnb/common/include/norm_l.h
new file mode 100644
index 0000000..533b105
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/norm_l.h
@@ -0,0 +1,153 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/norm_l.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for norm_l function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Support for ARM and Linux-ARM assembly.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the norm_l function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef NORM_L_H
+#define NORM_L_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
+    ----------------------------------------------------------------------------*/
+#if !( defined(PV_ARM_V5) || defined(PV_ARM_GCC_V5) )
+
+    /* C EQUIVALENT */
+    Word16 norm_l(Word32 L_var1);
+
+#elif defined(PV_ARM_V5)
+
+    __inline Word16 norm_l(Word32 L_var1)
+    {
+        register Word32 var_out = 0;
+
+        __asm
+        {
+            CMP    L_var1, #0
+            EORNE  L_var1, L_var1, L_var1, LSL #1
+            CLZNE  var_out, L_var1
+        }
+
+        return ((Word16)var_out);
+    }
+
+#elif defined(PV_ARM_GCC_V5)
+
+    static inline Word16 norm_l(Word32 L_var1)
+    {
+        register Word32 var_out = 0;
+        register Word32 ra = L_var1;
+        if (L_var1)
+        {
+            ra ^= (ra << 1);
+            asm volatile(
+                "clz %0, %1"
+    : "=r"(var_out)
+                        : "r"(ra)
+                    );
+        }
+        return (var_out);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/norm_s.h b/media/libstagefright/codecs/amrnb/common/include/norm_s.h
new file mode 100644
index 0000000..2e37a9f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/norm_s.h
@@ -0,0 +1,153 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/norm_s.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for norm_s function.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the norm_s function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef NORM_S_H
+#define NORM_S_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
+    ----------------------------------------------------------------------------*/
+#if !( defined(PV_ARM_V5) || defined(PV_ARM_GCC_V5) )
+
+    /* C EQUIVALENT */
+
+    Word16 norm_s(Word16 var1);
+
+#elif defined(PV_ARM_V5)
+
+    __inline Word16  norm_s(Word16 var)
+    {
+        register Word32 var_out = 0;
+        Word32 var1 = var << 16;
+
+        __asm
+        {
+            CMP    var1, #0
+            EORNE  var1, var1, var1, LSL #1
+            CLZNE  var_out, var1
+        }
+
+        return ((Word16)var_out);
+    }
+
+#elif defined(PV_ARM_GCC_V5)
+
+    static inline Word16 norm_s(Word16 var1)
+    {
+        register Word32 var_out = 0;
+        register Word32 ra = var1 << 16;
+        if (ra)
+        {
+            ra ^= (ra << 1);
+            asm volatile(
+                "clz %0, %1"
+    : "=r"(var_out)
+                        : "r"(ra)
+                    );
+        }
+        return (var_out);
+    }
+
+#endif
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/oper_32b.h b/media/libstagefright/codecs/amrnb/common/include/oper_32b.h
new file mode 100644
index 0000000..ec3fcfb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/oper_32b.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/oper_32b.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Deleted inclusion of files that were not part of the original
+          oper_32b.h file.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file includes all the oper_32b.c functions' header files.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef OPER_32B_H
+#define OPER_32B_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include        "typedef.h"
+
+#include        "div_32.h"
+#include        "l_comp.h"
+#include        "l_extract.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/p_ol_wgh.h b/media/libstagefright/codecs/amrnb/common/include/p_ol_wgh.h
new file mode 100644
index 0000000..6c277da
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/p_ol_wgh.h
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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/p_ol_wgh.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+       File             : p_ol_wgh.h
+       Purpose          : Compute the open loop pitch lag with weighting.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef P_OL_WGH_H
+#define P_OL_WGH_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]
+    ----------------------------------------------------------------------------*/
+    extern const Word16 corrweight[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    /* state variable */
+
+    typedef struct
+    {
+        Word16 old_T0_med;
+        Word16 ada_w;
+        Word16 wght_flg;
+    } pitchOLWghtState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 p_ol_wgh_init(pitchOLWghtState **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to p_ol_wgh in each call.
+       returns 0 on success
+     */
+
+    Word16 p_ol_wgh_reset(pitchOLWghtState *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void p_ol_wgh_exit(pitchOLWghtState **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    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                                  */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _P_OL_WGH_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/pow2.h b/media/libstagefright/codecs/amrnb/common/include/pow2.h
new file mode 100644
index 0000000..c96fbdd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/pow2.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/log2_norm.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template. Added extern declaration for pow2_tbl[]
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the prototype declaration for Pow2() function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef POW2_H
+#define POW2_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 Word16 pow2_tbl[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word32 Pow2(            /* (o)  : result       (range: 0<=val<=0x7fffffff) */
+        Word16 exponent,    /* (i)  : Integer part.      (range: 0<=val<=30)   */
+        Word16 fraction,    /* (i)  : Fractional part.  (range: 0.0<=val<1.0)  */
+        Flag *pOverflow     /* (i/o) : overflow flag                           */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _POW2_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/pred_lt.h b/media/libstagefright/codecs/amrnb/common/include/pred_lt.h
new file mode 100644
index 0000000..a2bfed2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/pred_lt.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.
+****************************************************************************************/
+/*
+ Filename: /audio/gsm_amr/c/include/pred_lt.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the pred_lt function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef pred_lt_h
+#define pred_lt_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 Pred_lt_3or6(
+        Word16 exc[],     /* in/out: excitation buffer                          */
+        Word16 T0,        /* input : integer pitch lag                          */
+        Word16 frac,      /* input : fraction of lag                            */
+        Word16 L_subfr,   /* input : subframe size                              */
+        Word16 flag3,     /* input : if set, upsampling rate = 3 (6 otherwise)  */
+        Flag  *pOverflow  /* output: if set, overflow occurred in this function */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PRED_LT_H */
diff --git a/media/libstagefright/codecs/amrnb/common/include/pvgsmamr.h b/media/libstagefright/codecs/amrnb/common/include/pvgsmamr.h
new file mode 100644
index 0000000..b697524
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/pvgsmamr.h
@@ -0,0 +1,63 @@
+/* ------------------------------------------------------------------
+ * 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.
+****************************************************************************************/
+#ifndef __PVGSMAMR_H
+#define __PVGSMAMR_H
+
+
+// includes
+#include <e32std.h>
+#include <e32base.h>
+
+#include "sp_dec.h"
+#include "pvglobals.h"
+
+
+// PVGsmDecoder AO
+class CPVGsmDecoder : public CBase
+{
+    public:
+        IMPORT_C static CPVGsmDecoder* NewL(void);
+        IMPORT_C ~CPVGsmDecoder();
+        IMPORT_C TInt StartL(void);
+
+        // only port the API's used in PVPlayer 2.0
+        IMPORT_C TInt DecodeFrame(enum Mode mode, unsigned char* compressedBlock, unsigned char* audioBuffer);
+        IMPORT_C TInt InitDecoder(void);
+        IMPORT_C void ExitDecoder(void);
+
+    private:
+        CPVGsmDecoder();
+        void ConstructL(void);
+
+        Speech_Decode_FrameState* decState;
+        enum RXFrameType rx_type;
+        struct globalDataStruct *gds;
+};
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf.h b/media/libstagefright/codecs/amrnb/common/include/q_plsf.h
new file mode 100644
index 0000000..431272a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/q_plsf.h
@@ -0,0 +1,169 @@
+/* ------------------------------------------------------------------
+ * 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_plsf.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the q_plsf_3.c and q_plsf_5.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef q_plsf_h
+#define q_plsf_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "mode.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define MR795_1_SIZE  512
+#define PAST_RQ_INIT_SIZE 8
+
+#define DICO1_SIZE  256
+#define DICO2_SIZE  512
+#define DICO3_SIZE  512
+
+#define DICO1_5_SIZE  128
+#define DICO2_5_SIZE  256
+#define DICO3_5_SIZE  256
+#define DICO4_5_SIZE  256
+#define DICO5_5_SIZE  64
+
+#define MR515_3_SIZE  128
+
+    /*----------------------------------------------------------------------------
+    ; 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_rq[M];    /* Past quantized prediction error, Q15 */
+
+    } Q_plsfState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 Q_plsf_init(Q_plsfState **st);
+    /* initialize one instance of the state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Q_plsf_5 / Q_plsf_3 in each call.
+       returns 0 on success
+     */
+
+    Word16 Q_plsf_reset(Q_plsfState *st);
+    /* reset of state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void Q_plsf_exit(Q_plsfState **st);
+    /* de-initialize state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void Q_plsf_3(
+        Q_plsfState *st,    /* i/o: state struct                             */
+        enum Mode mode,     /* i  : coder mode                               */
+        Word16 *lsp1,       /* i  : 1st LSP vector                      Q15  */
+        Word16 *lsp1_q,     /* o  : quantized 1st LSP vector            Q15  */
+        Word16 *indice,     /* o  : quantization indices of 3 vectors   Q0   */
+        Word16 *pred_init_i,/* o  : init index for MA prediction in DTX mode */
+        Flag  *pOverflow    /* o : Flag set when overflow occurs             */
+    );
+
+    void Q_plsf_5(
+        Q_plsfState *st,
+        Word16 *lsp1,      /* i  : 1st LSP vector,                     Q15 */
+        Word16 *lsp2,      /* i  : 2nd LSP vector,                     Q15 */
+        Word16 *lsp1_q,    /* o  : quantized 1st LSP vector,           Q15 */
+        Word16 *lsp2_q,    /* o  : quantized 2nd LSP vector,           Q15 */
+        Word16 *indice,    /* o  : quantization indices of 5 matrices, Q0  */
+        Flag  *pOverflow   /* o : Flag set when overflow occurs            */
+    );
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _Q_PLSF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf_3_tbl.h b/media/libstagefright/codecs/amrnb/common/include/q_plsf_3_tbl.h
new file mode 100644
index 0000000..2e43d10
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/q_plsf_3_tbl.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/src/q_plsf_3_tbl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, q_plsf_3_tbl.tab
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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.]
+    ----------------------------------------------------------------------------*/
+#define MR795_1_SIZE  512
+#define PAST_RQ_INIT_SIZE 8
+
+#define DICO1_SIZE  256
+#define DICO2_SIZE  512
+#define DICO3_SIZE  512
+
+#define MR515_3_SIZE  128
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; [Variable declaration - defined here and used outside this module]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /* Codebooks of LSF prediction residual */
+    extern const Word16 mean_lsf_3[];
+
+    extern const Word16 pred_fac_3[];
+
+    extern const Word16 dico1_lsf_3[];
+    extern const Word16 dico2_lsf_3[];
+    extern const Word16 dico3_lsf_3[];
+
+    extern const Word16 mr515_3_lsf[];
+    extern const Word16 mr795_1_lsf[];
+
+    extern const Word16 past_rq_init[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/q_plsf_5_tbl.h b/media/libstagefright/codecs/amrnb/common/include/q_plsf_5_tbl.h
new file mode 100644
index 0000000..245b5f4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/q_plsf_5_tbl.h
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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/q_plsf_5_tbl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                        Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares tables defined in q_plsf_5_tbl.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef Q_PLSF_5_TBL_H
+#define Q_PLSF_5_TBL_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 mean_lsf_5[];
+    extern const Word16 dico1_lsf_5[];
+    extern const Word16 dico2_lsf_5[];
+    extern const Word16 dico3_lsf_5[];
+    extern const Word16 dico4_lsf_5[];
+    extern const Word16 dico5_lsf_5[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/qgain475_tab.h b/media/libstagefright/codecs/amrnb/common/include/qgain475_tab.h
new file mode 100644
index 0000000..6c0d766
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/qgain475_tab.h
@@ -0,0 +1,107 @@
+/* ------------------------------------------------------------------
+ * 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/qgain475_tab.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                        Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares tables defined in qgain475_tab.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef QGAIN475_TAB_H
+#define QGAIN475_TAB_H
+
+#define MR475_VQ_SIZE 256
+
+/*----------------------------------------------------------------------------
+; 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 table_gain_MR475[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/qua_gain.h b/media/libstagefright/codecs/amrnb/common/include/qua_gain.h
new file mode 100644
index 0000000..65b35ee
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/qua_gain.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/qua_gain.h
+
+------------------------------------------------------------------------------
+ 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.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the file, qua_gain.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef qua_gain_h
+#define qua_gain_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.
+    ----------------------------------------------------------------------------*/
+#define VQ_SIZE_HIGHRATES 128
+#define VQ_SIZE_LOWRATES 64
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    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                     */
+    );
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* qua_gain_h */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/qua_gain_tbl.h b/media/libstagefright/codecs/amrnb/common/include/qua_gain_tbl.h
new file mode 100644
index 0000000..a7691e7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/qua_gain_tbl.h
@@ -0,0 +1,108 @@
+/* ------------------------------------------------------------------
+ * 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/qua_gain_tbl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                        Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares tables defined in qua_gain_tbl.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef QUA_GAIN_TBL_H
+#define QUA_GAIN_TBL_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 table_gain_highrates[];
+    extern const Word16 table_gain_lowrates[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/reorder.h b/media/libstagefright/codecs/amrnb/common/include/reorder.h
new file mode 100644
index 0000000..620cd0b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/reorder.h
@@ -0,0 +1,109 @@
+/* ------------------------------------------------------------------
+ * 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/reorder.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the Reorder_lsf() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef REORDER_H
+#define REORDER_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
+    ----------------------------------------------------------------------------*/
+    void Reorder_lsf(
+        Word16 *lsf,       /* (i/o)  : vector of LSFs   (range: 0<=val<=0.5)    */
+        Word16 min_dist,   /* (i)    : minimum required distance                */
+        Word16 n,          /* (i)    : LPC order                                */
+        Flag   *pOverflow  /* (i/o)  : overflow Flag                            */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _REORDER_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/residu.h b/media/libstagefright/codecs/amrnb/common/include/residu.h
new file mode 100644
index 0000000..f4d0041
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/residu.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             : residu.h
+*      Purpose          : Computes the LP residual.
+*      Description      : The LP residual is computed by filtering the input
+*                       : speech through the LP inverse filter A(z).
+*
+*
+********************************************************************************
+*/
+#ifndef residu_h
+#define residu_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Residu(
+        Word16 a[],        /* (i)  : prediction coefficients                    */
+        Word16 x[],        /* (i)  : speech signal                              */
+        Word16 y[],        /* (o)  : residual signal                            */
+        Word16 lg          /* (i)  : size of filtering                          */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/reverse_bits.h b/media/libstagefright/codecs/amrnb/common/include/reverse_bits.h
new file mode 100644
index 0000000..fcc8df6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/reverse_bits.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.
+****************************************************************************************/
+/*
+
+ Pathname: .audio/gsm-amr/c/include/reverse_bits.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Adding #include "mode.h" so that it compiles and works for the
+              ARM tools.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                        Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the reverse_bits function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef REVERSE_BITS_H
+#define REVERSE_BITS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#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 reverse_bits(enum Mode mode, unsigned char *pCompressedBlock);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/round.h b/media/libstagefright/codecs/amrnb/common/include/round.h
new file mode 100644
index 0000000..3129e27
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/round.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/round.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for round function.
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the pv_round function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ROUND_H
+#define ROUND_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 pv_round(Word32 L_var1, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ROUND_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/set_zero.h b/media/libstagefright/codecs/amrnb/common/include/set_zero.h
new file mode 100644
index 0000000..debd223
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/set_zero.h
@@ -0,0 +1,79 @@
+/* ------------------------------------------------------------------
+ * 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             : set_zero.h
+*      Description      : Set vector x[] to zero
+*
+*
+********************************************************************************
+*/
+#ifndef set_zero_h
+#define set_zero_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Set_zero(
+        Word16 x[],        /* (o)  : vector to clear                            */
+        Word16 L           /* (i)  : length of vector                           */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/shl.h b/media/libstagefright/codecs/amrnb/common/include/shl.h
new file mode 100644
index 0000000..84ca8d9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/shl.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/shl.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for shl function.
+
+ Description: Changed prototype of the mult() function. Instead of using global
+              a pointer to overflow flag is now passed into the function.
+
+ Description: Updated template. Changed the parameter name from "overflow" to
+              "pOverflow" in the function prototype declaration
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the shl function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SHL_H
+#define SHL_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 shl(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _SHL_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/shr.h b/media/libstagefright/codecs/amrnb/common/include/shr.h
new file mode 100644
index 0000000..e961c04
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/shr.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/shr.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for shr function.
+
+ Description: Changed the function prototype declaration.
+              Updated template.
+
+ Description: Updated template. Changed the parameter name from "overflow" to
+              "pOverflow" in the function prototype declaration
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the shr function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SHR_H
+#define SHR_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 shr(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _SHR_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/shr_r.h b/media/libstagefright/codecs/amrnb/common/include/shr_r.h
new file mode 100644
index 0000000..c4f9e2c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/shr_r.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/include/shr_r.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for shr_r function.
+
+ Description: Passing in pOverflow.
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #define after Include section.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the shr_r function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SHR_R_H
+#define SHR_R_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 shr_r(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/sqrt_l.h b/media/libstagefright/codecs/amrnb/common/include/sqrt_l.h
new file mode 100644
index 0000000..86209bd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/sqrt_l.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/sqrt_l.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Updated function prototype declaration to reflect new interface.
+              A pointer to overflow flag is passed into the function. Updated
+              template.
+
+ Description: Added extern declaration for sqrt_l_tbl[]
+
+ Description: Moved _cplusplus #ifdef before function prototype.
+
+ Who:                           Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the sqrt_l() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef SQRT_L_H
+#define SQRT_L_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
+    ----------------------------------------------------------------------------*/
+    extern Word16 sqrt_l_tbl[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word32 sqrt_l_exp(      /* o : output value,                          Q31 */
+        Word32 L_x,         /* i : input value,                           Q31 */
+        Word16 *pExp,       /* o : right shift to be applied to result,   Q1  */
+        Flag   *pOverflow   /* i : pointer to overflow flag */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _SQRT_L__H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/sub.h b/media/libstagefright/codecs/amrnb/common/include/sub.h
new file mode 100644
index 0000000..18dc456
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/sub.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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/sub.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate header file for sub function.
+
+ Description: Changed function prototype declaration.
+
+ Description: Updated copyright information.
+              Updated variable name from "overflow" to "pOverflow" to match
+              with original function declaration.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the sub function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef SUB_H
+#define SUB_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 sub(Word16 var1, Word16 var2, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _SUB_H_ */
diff --git a/media/libstagefright/codecs/amrnb/common/include/syn_filt.h b/media/libstagefright/codecs/amrnb/common/include/syn_filt.h
new file mode 100644
index 0000000..7fff112
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/syn_filt.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             : syn_filt.h
+*      Purpose          : Perform synthesis filtering through 1/A(z).
+*
+*
+********************************************************************************
+*/
+#ifndef syn_filt_h
+#define syn_filt_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Syn_filt(
+        Word16 a[],        /* (i)  : a[m+1] prediction coefficients   (m=10)    */
+        Word16 x[],        /* (i)  : input signal                               */
+        Word16 y[],        /* (o)  : output signal                              */
+        Word16 lg,         /* (i)  : size of filtering                          */
+        Word16 mem[],      /* (i/o): memory associated with this filtering.     */
+        Word16 update      /* (i)  : 0=no update, 1=update of memory.           */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/typedef.h b/media/libstagefright/codecs/amrnb/common/include/typedef.h
new file mode 100644
index 0000000..ee4d732
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/typedef.h
@@ -0,0 +1,73 @@
+/* ------------------------------------------------------------------
+ * 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             : typedef.c
+*      Purpose          : Basic types.
+*
+********************************************************************************
+*/
+#ifndef typedef_h
+#define typedef_h "$Id $"
+
+#undef ORIGINAL_TYPEDEF_H /* CHANGE THIS TO #define to get the      */
+/*  "original" ETSI version of typedef.h  */
+/* CHANGE TO #undef for PV version        */
+
+#ifdef ORIGINAL_TYPEDEF_H
+/*
+ * this is the original code from the ETSI file typedef.h
+ */
+
+#if   defined(__unix__) || defined(__unix)
+typedef signed char Word8;
+typedef short Word16;
+typedef int Word32;
+typedef int Flag;
+
+#else
+#error No System recognized
+#endif
+#else /* not original typedef.h */
+
+/*
+ * use (improved) type definition file typdefs.h
+ */
+#include "gsm_amr_typedefs.h"
+
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad.h b/media/libstagefright/codecs/amrnb/common/include/vad.h
new file mode 100644
index 0000000..b9ee89f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/vad.h
@@ -0,0 +1,76 @@
+/* ------------------------------------------------------------------
+ * 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             : vad.h
+*      Purpose          : Voice Activity Detection (VAD) for AMR
+*
+********************************************************************************
+*/
+#ifndef vad_h
+#define vad_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+
+#include "vad1.h"   /* for VAD option 1 */
+#include "vad2.h"   /* for VAD option 2 */
+
+/*
+********************************************************************************
+*                         LOCAL VARIABLES AND TABLES
+********************************************************************************
+*/
+
+/*
+********************************************************************************
+*                         DEFINITION OF DATA TYPES
+********************************************************************************
+*/
+
+#ifndef VAD2
+#define vadState vadState1
+#else
+#define vadState vadState2
+#endif
+
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad1.h b/media/libstagefright/codecs/amrnb/common/include/vad1.h
new file mode 100644
index 0000000..c144ea0
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/vad1.h
@@ -0,0 +1,197 @@
+/* ------------------------------------------------------------------
+ * 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/vad_1.h
+
+------------------------------------------------------------------------------
+ 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, prototype and structure
+ definitions needed by vad_1.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef vad_1_h
+#define vad_1_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst_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
+    ----------------------------------------------------------------------------*/
+    /* state variable */
+    typedef struct
+    {
+
+        Word16 bckr_est[COMPLEN];    /* background noise estimate                */
+        Word16 ave_level[COMPLEN];   /* averaged input components for stationary */
+        /*    estimation                            */
+        Word16 old_level[COMPLEN];   /* input levels of the previous frame       */
+        Word16 sub_level[COMPLEN];   /* input levels calculated at the end of
+                                      a frame (lookahead)                   */
+        Word16 a_data5[3][2];        /* memory for the filter bank               */
+        Word16 a_data3[5];           /* memory for the filter bank               */
+
+        Word16 burst_count;          /* counts length of a speech burst          */
+        Word16 hang_count;           /* hangover counter                         */
+        Word16 stat_count;           /* stationary counter                       */
+
+        /* Note that each of the following three variables (vadreg, pitch and tone)
+           holds 15 flags. Each flag reserves 1 bit of the variable. The newest
+           flag is in the bit 15 (assuming that LSB is bit 1 and MSB is bit 16). */
+        Word16 vadreg;               /* flags for intermediate VAD decisions     */
+        Word16 pitch;                /* flags for pitch detection                */
+        Word16 tone;                 /* flags for tone detection                 */
+        Word16 complex_high;         /* flags for complex detection              */
+        Word16 complex_low;          /* flags for complex detection              */
+
+        Word16 oldlag_count, oldlag; /* variables for pitch detection            */
+
+        Word16 complex_hang_count;   /* complex hangover counter, used by VAD    */
+        Word16 complex_hang_timer;   /* hangover initiator, used by CAD          */
+
+        Word16 best_corr_hp;         /* FIP filtered value Q15                   */
+
+        Word16 speech_vad_decision;  /* final decision                           */
+        Word16 complex_warning;      /* complex background warning               */
+
+        Word16 sp_burst_count;       /* counts length of a speech burst incl     */
+        Word16 corr_hp_fast;         /* filtered value                           */
+    } vadState1;
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16 vad1_init(vadState1 **st);
+    /* initialize one instance of the pre processing state.
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to vad in each call.
+       returns 0 on success
+     */
+
+    Word16 vad1_reset(vadState1 *st);
+    /* reset of pre processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void vad1_exit(vadState1 **st);
+    /* de-initialize pre processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void vad_complex_detection_update(vadState1 *st,       /* i/o : State struct     */
+                                      Word16 best_corr_hp /* i   : best Corr Q15    */
+                                     );
+
+    void vad_tone_detection(vadState1 *st,  /* i/o : State struct            */
+                            Word32 t0,     /* i   : autocorrelation maxima  */
+                            Word32 t1,     /* i   : energy                  */
+                            Flag   *pOverflow
+                           );
+
+    void vad_tone_detection_update(
+        vadState1 *st,             /* i/o : State struct              */
+        Word16 one_lag_per_frame,  /* i   : 1 if one open-loop lag is
+                                              calculated per each frame,
+                                              otherwise 0                     */
+        Flag *pOverflow
+    );
+
+    void vad_pitch_detection(vadState1 *st,   /* i/o : State struct                  */
+                             Word16 lags[],  /* i   : speech encoder open loop lags */
+                             Flag   *pOverflow
+                            );
+
+    Word16 vad1(vadState1 *st,   /* i/o : State struct                      */
+                Word16 in_buf[], /* i   : samples of the input frame
+                                inbuf[159] is the very last sample,
+                                incl lookahead                          */
+                Flag *pOverflow
+               );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _VAD1_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/vad2.h b/media/libstagefright/codecs/amrnb/common/include/vad2.h
new file mode 100644
index 0000000..3197b3a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/vad2.h
@@ -0,0 +1,203 @@
+/* ------------------------------------------------------------------
+ * 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/vad2.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.  Added
+ parameter pOverflow for the basic math ops.
+
+ Description: Added pOverflow to the r_fft function prototype.
+
+ Description: Added pOverflow to the LTP_flag_update prototype.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions, prototype and structure
+ definitions needed by vad_2.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef vad_2_h
+#define vad_2_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     YES     1
+#define     NO      0
+#define     ON      1
+#define     OFF     0
+#define     TRUE        1
+#define     FALSE       0
+
+#define     FRM_LEN                 80
+#define     DELAY                   24
+#define     FFT_LEN                 128
+
+#define     NUM_CHAN                16
+#define     LO_CHAN                 0
+#define     HI_CHAN                 15
+
+#define     UPDATE_THLD             35
+#define     HYSTER_CNT_THLD         6
+#define     UPDATE_CNT_THLD         50
+
+#define     SHIFT_STATE_0       0       /* channel energy scaled as 22,9 */
+#define     SHIFT_STATE_1       1       /* channel energy scaled as 27,4 */
+
+#define     NOISE_FLOOR_CHAN_0  512     /* 1.0    scaled as 22,9 */
+#define     MIN_CHAN_ENRG_0     32      /* 0.0625 scaled as 22,9 */
+#define     MIN_NOISE_ENRG_0    32      /* 0.0625 scaled as 22,9 */
+#define     INE_NOISE_0     8192        /* 16.0   scaled as 22,9 */
+#define     FRACTIONAL_BITS_0   9       /* used as input to fn10Log10() */
+
+#define     NOISE_FLOOR_CHAN_1  16      /* 1.0    scaled as 27,4 */
+#define     MIN_CHAN_ENRG_1     1       /* 0.0625 scaled as 27,4 */
+#define     MIN_NOISE_ENRG_1    1       /* 0.0625 scaled as 27,4 */
+#define     INE_NOISE_1     256     /* 16.0   scaled as 27,4 */
+#define     FRACTIONAL_BITS_1   4       /* used as input to fn10Log10() */
+
+#define     STATE_1_TO_0_SHIFT_R    (FRACTIONAL_BITS_1-FRACTIONAL_BITS_0)   /* state correction factor */
+#define     STATE_0_TO_1_SHIFT_R    (FRACTIONAL_BITS_0-FRACTIONAL_BITS_1)   /* state correction factor */
+
+#define         HIGH_ALPHA              29491       /* 0.9 scaled as 0,15 */
+#define         LOW_ALPHA               22938       /* 0.7 scaled as 0,15 */
+#define         ALPHA_RANGE             (HIGH_ALPHA - LOW_ALPHA)
+#define         DEV_THLD                7168        /* 28.0 scaled as 7,8 */
+
+#define         PRE_EMP_FAC             (-26214)    /* -0.8 scaled as 0,15 */
+
+#define         CEE_SM_FAC              18022       /* 0.55 scaled as 0,15 */
+#define         ONE_MINUS_CEE_SM_FAC    14746       /* 0.45 scaled as 0,15 */
+
+#define         CNE_SM_FAC              3277        /* 0.1 scaled as 0,15 */
+#define         ONE_MINUS_CNE_SM_FAC    29491       /* 0.9 scaled as 0,15 */
+
+#define         FFT_HEADROOM            2
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    typedef struct
+    {
+        Word16 pre_emp_mem;
+        Word16 update_cnt;
+        Word16 hyster_cnt;
+        Word16 last_update_cnt;
+        Word16 ch_enrg_long_db[NUM_CHAN];   /* scaled as 7,8  */
+
+        Word32 Lframe_cnt;
+        Word32 Lch_enrg[NUM_CHAN];  /* scaled as 22,9 or 27,4 */
+        Word32 Lch_noise[NUM_CHAN]; /* scaled as 22,9 */
+
+        Word16 last_normb_shift;    /* last block norm shift count */
+
+        Word16 tsnr;            /* total signal-to-noise ratio in dB (scaled as 7,8) */
+        Word16 hangover;
+        Word16 burstcount;
+        Word16 fupdate_flag;        /* forced update flag from previous frame */
+        Word16 negSNRvar;       /* Negative SNR variance (scaled as 7,8) */
+        Word16 negSNRbias;      /* sensitivity bias from negative SNR variance (scaled as 15,0) */
+
+        Word16 shift_state;     /* use 22,9 or 27,4 scaling for ch_enrg[] */
+
+        Word32 L_R0;
+        Word32 L_Rmax;
+        Flag   LTP_flag;        /* Use to indicate the the LTP gain is > LTP_THRESH */
+
+    } vadState2;
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    Word16  vad2(Word16 *farray_ptr, vadState2 *st, Flag *pOverflow);
+    Word16 vad2_init(vadState2 **st);
+    Word16 vad2_reset(vadState2 *st);
+    void    vad2_exit(vadState2 **state);
+
+    void    r_fft(Word16 *farray_ptr, Flag *pOverflow);
+
+    void    LTP_flag_update(vadState2 *st, Word16 mode, Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _VAD2_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/include/weight_a.h b/media/libstagefright/codecs/amrnb/common/include/weight_a.h
new file mode 100644
index 0000000..0358c85
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/weight_a.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             : weight_a.h
+*      Purpose          : Spectral expansion of LP coefficients.  (order==10)
+*      Description      : a_exp[i] = a[i] * fac[i-1]    ,i=1,10
+*
+*
+********************************************************************************
+*/
+#ifndef weight_a_h
+#define weight_a_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    void Weight_Ai(
+        Word16 a[],        /* (i)  : a[m+1]  LPC coefficients   (m=10)          */
+        const Word16 fac[],/* (i)  : Spectral expansion factors.                */
+        Word16 a_exp[]     /* (o)  : Spectral expanded LPC coefficients         */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/include/window_tab.h b/media/libstagefright/codecs/amrnb/common/include/window_tab.h
new file mode 100644
index 0000000..42233af
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/window_tab.h
@@ -0,0 +1,109 @@
+/* ------------------------------------------------------------------
+ * 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/window_tab.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file declares a tables in window_tab.c used in lpc.c.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef WINDOW_TAB_H
+#define WINDOW_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 window_200_40[];
+    extern const Word16 window_160_80[];
+    extern const Word16 window_232_8[];
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/include/wmf_to_ets.h b/media/libstagefright/codecs/amrnb/common/include/wmf_to_ets.h
new file mode 100644
index 0000000..8bcccc8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/include/wmf_to_ets.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.
+****************************************************************************************/
+/*
+
+ Pathname: ./audio/gsm-amr/include/src/wmf_to_ets.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed mode to frame_type_3gpp
+
+ Description: Updated template to make it build in Symbian. Updated copyright
+              year.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the wmf_to_ets function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef WMF_TO_ETS_H
+#define WMF_TO_ETS_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 wmf_to_ets(enum Frame_Type_3GPP frame_type_3gpp,
+    UWord8   *wmf_input_ptr,
+    Word16   *ets_output_ptr);
+
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/pvgsmamrdecoderinterface.h b/media/libstagefright/codecs/amrnb/common/pvgsmamrdecoderinterface.h
new file mode 100644
index 0000000..ccbed44
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/pvgsmamrdecoderinterface.h
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+//////////////////////////////////////////////////////////////////////////////////
+//                                                                              //
+//  File: pvgsmamrdecoderinterface.h                                            //
+//                                                                              //
+//////////////////////////////////////////////////////////////////////////////////
+
+#ifndef _PVGSMAMR_DECODER_INTERFACE_H
+#define _PVGSMAMR_DECODER_INTERFACE_H
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+typedef enum
+{
+    /*
+     *    One word (2-byte) to indicate type of frame type.
+     *    One word (2-byte) to indicate frame type.
+     *    One word (2-byte) to indicate mode.
+     *    N words (2-byte) containing N bits (bit 0 = 0xff81, bit 1 = 0x007f).
+     */
+    ETS = 0, /* Both AMR-Narrowband and AMR-Wideband */
+
+    /*
+     *    One word (2-byte) for sync word (good frames: 0x6b21, bad frames: 0x6b20)
+     *    One word (2-byte) for frame length N.
+     *    N words (2-byte) containing N bits (bit 0 = 0x007f, bit 1 = 0x0081).
+     */
+    ITU, /* AMR-Wideband */
+
+    /*
+     *   AMR-WB MIME/storage format, see RFC 3267 (sections 5.1 and 5.3) for details
+     */
+    MIME_IETF,
+
+    WMF, /* AMR-Narrowband */
+
+    IF2  /* AMR-Narrowband */
+
+} bitstream_format;
+
+
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+typedef struct
+{
+    int16_t prev_ft;
+    int16_t prev_mode;
+} RX_State;
+
+
+typedef struct tPVAmrDecoderExternal
+{
+    /*
+     * INPUT:
+     * Pointer to the input buffer that contains the encoded bistream data.
+     * The data is filled in such that the first bit transmitted is
+     * the most-significant bit (MSB) of the first array element.
+     * The buffer is accessed in a linear fashion for speed, and the number of
+     * bytes consumed varies frame to frame. This is use for mime/ietf data
+     */
+    uint8_t  *pInputBuffer;
+
+    /*
+     * INPUT:
+     * Pointer to the input buffer that contains the encoded stream data.
+     * The data is filled such that the first bit transmitted is
+     * in the  first int16_t element.
+     * The buffer is accessed in a linear fashion for speed, and the number of
+     * bytes consumed varies frame to frame.
+     */
+    int16_t  *pInputSampleBuffer;
+
+    /*
+     * INPUT: (but what is pointed to is an output)
+     * Pointer to the output buffer to hold the 16-bit PCM audio samples.
+     */
+    int16_t  *pOutputBuffer;
+
+    /*
+     * INPUT:
+     * Number of requested output audio channels. This relieves the calling
+     * environment from having to perform stereo-to-mono or mono-to-stereo
+     * conversions.
+     */
+    int32_t     desiredChannels;
+
+    /*
+         * INPUT:
+         * Format type of the encoded bitstream.
+         */
+    bitstream_format     input_format;
+
+    /*
+     * OUTPUT:
+     * The sampling rate decoded from the bitstream, in units of
+     * samples/second. For this release of the library this value does
+     * not change from frame to frame, but future versions will.
+     */
+    int32_t   samplingRate;
+
+    /*
+     * OUTPUT:
+     * This value is the bitrate in units of bits/second. IT
+     * is calculated using the number of bits consumed for the current frame,
+     * and then multiplying by the sampling_rate, divided by points in a frame.
+     * This value can changes frame to frame.
+     */
+    int32_t   bitRate;
+
+    /*
+     * OUTPUT:
+     * The number of channels decoded from the bitstream. The output data
+     * will have be the amount specified in the variable desiredChannels,
+     * this output is informative only, and can be ignored.
+     */
+    int32_t     encodedChannels;
+
+    /*
+     * OUTPUT:
+     * This value is the number of output PCM samples per channel.
+     * It is  320.
+     */
+    int16_t     frameLength;
+
+    /*
+     * OUTPUT:
+     * This value is the quality indicator. 1 (good)  0 (bad)
+    */
+    uint8_t     quality;
+
+
+    /*
+     * OUTPUT:
+     *  GSM AMR NB and WB mode (i.e. bit-rate )
+     */
+    int16_t     mode;
+    int16_t     mode_old;
+
+    /*
+     * OUTPUT:
+     *  GSM AMR NB and WB frame type ( speech_good, speech_bad, sid, etc.)
+     */
+    int16_t     frame_type;
+
+    int16_t reset_flag;
+    int16_t reset_flag_old;
+
+    /*
+     * OUTPUT:
+     *  Decoder  status
+     */
+    int32_t     status;
+
+    /*
+     * OUTPUT:
+     *  Rx status state
+     */
+    RX_State  rx_state;
+
+} tPVAmrDecoderExternal;
+
+#endif
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/add.cpp b/media/libstagefright/codecs/amrnb/common/src/add.cpp
new file mode 100644
index 0000000..d488ca5
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/add.cpp
@@ -0,0 +1,203 @@
+/* ------------------------------------------------------------------
+ * 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/add.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for add function. Sync'ed up with the
+          current template and fixed tabs.
+
+ Description: Changed all occurrences of L_sum with sum.
+
+ Description: Changed function protype to pass in pointer to Overflow flag
+                as a parameter.
+
+ Description: Removed code that updates MOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Summation function with overflow control
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; 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: add
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the add operation resulted in overflow
+
+ Returns:
+    sum = 16-bit limited sum of var1 and var2 (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the addition (var1+var2) with overflow control and
+ saturation; the 16 bit result is set at +32767 when overflow occurs or at
+ -32768 when underflow occurs.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] add.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Word16 add (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 sum;
+
+    sum = (Word32) var1 + var2;
+
+* The reference ETSI code uses a global flag for Overflow inside the function
+* saturate(). In the actual implementation a pointer to Overflow flag is passed in
+* as a parameter to the function
+
+    var_out = saturate (sum);
+#if (WMOPS)
+    multiCounter[currCounter].add++;
+#endif
+    return (var_out);
+}
+
+------------------------------------------------------------------------------
+ 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 add(Word16 var1, Word16 var2, Flag *pOverflow)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Word32 sum;
+    sum = (Word32) var1 + var2;
+
+    /* Saturate result (if necessary). */
+    /* Replaced function call with in-line code             */
+    /* to conserve MIPS, i.e., var_out = saturate (sum)  */
+
+    if (sum > 0X00007fffL)
+    {
+        *pOverflow = 1;
+        sum = MAX_16;
+    }
+    else if (sum < (Word32) 0xffff8000L)
+    {
+        *pOverflow = 1;
+        sum = MIN_16;
+    }
+
+    /* Return the sum as a 16 bit value by type casting Word32 to Word16 */
+
+    return ((Word16) sum);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp b/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
new file mode 100644
index 0000000..bd99b30
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/az_lsp.cpp
@@ -0,0 +1,740 @@
+/* ------------------------------------------------------------------
+ * 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/az_lsp.c
+ Funtions: Chebps
+           Chebps_Wrapper
+           Az_lsp
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Finished first pass of optimization.
+
+ Description: Made changes based on review comments.
+
+ Description: Made input to Chebps_Wrapper consistent with that of Chebps.
+
+ Description: Replaced current Pseudo-code with the UMTS code version 3.2.0.
+              Updated coding template.
+
+ Description: Replaced basic_op.h and oper_32b.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. Used "-" operator instead of calling sub function in the
+                 az_lsp() code.
+              2. Copied detailed function description of az_lsp from the
+                 header file.
+              3. Modified local variable definition to one per line.
+              4. Used NC in the definition of f1 and f2 arrays.
+              5. Added curly brackets in the IF statement.
+
+ Description: Changed function interface to pass in a pointer to overflow
+              flag into the function instead of using a global flag. Removed
+              inclusion of unneeded header files.
+
+ Description:  For Chebps() and Az_lsp()
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation.
+              4. Eliminated not needed variables
+              5. Eliminated if-else checks for saturation
+              6. Deleted unused function cheps_wraper
+
+ Description:  Added casting to eliminate warnings
+
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These modules compute the LSPs from the LP coefficients.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "az_lsp.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.
+----------------------------------------------------------------------------*/
+#define NC   M/2                  /* M = LPC order, NC = M/2 */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Chebps
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    x = input value (Word16)
+    f = polynomial (Word16)
+    n = polynomial order (Word16)
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the operations in the function resulted in saturation.
+
+ Returns:
+    cheb = Chebyshev polynomial for the input value x.(Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module evaluates the Chebyshev polynomial series.
+    - The polynomial order is   n = m/2 = 5
+    - The polynomial F(z) (F1(z) or F2(z)) is given by
+        F(w) = 2 exp(-j5w) C(x)
+        where
+        C(x) = T_n(x) + f(1)T_n-1(x) + ... +f(n-1)T_1(x) + f(n)/2
+        and T_m(x) = cos(mw) is the mth order Chebyshev
+        polynomial ( x=cos(w) )
+    - C(x) for the input x is returned.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ az_lsp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word16 Chebps (Word16 x,
+                      Word16 f[], // (n)
+                      Word16 n)
+{
+    Word16 i, cheb;
+    Word16 b0_h, b0_l, b1_h, b1_l, b2_h, b2_l;
+    Word32 t0;
+
+// The reference ETSI code uses a global flag for Overflow. However, in the
+// actual implementation a pointer to Overflow flag is passed in as a
+// parameter to the function. This pointer is passed into all the basic math
+// functions invoked
+
+    b2_h = 256; // b2 = 1.0
+    b2_l = 0;
+
+    t0 = L_mult (x, 512);          // 2*x
+    t0 = L_mac (t0, f[1], 8192);   // + f[1]
+    L_Extract (t0, &b1_h, &b1_l);  // b1 = 2*x + f[1]
+
+    for (i = 2; i < n; i++)
+    {
+        t0 = Mpy_32_16 (b1_h, b1_l, x);         // t0 = 2.0*x*b1
+        t0 = L_shl (t0, 1);
+        t0 = L_mac (t0, b2_h, (Word16) 0x8000); // t0 = 2.0*x*b1 - b2
+        t0 = L_msu (t0, b2_l, 1);
+        t0 = L_mac (t0, f[i], 8192);            // t0 = 2.0*x*b1 - b2 + f[i]
+
+        L_Extract (t0, &b0_h, &b0_l);           // b0 = 2.0*x*b1 - b2 + f[i]
+
+        b2_l = b1_l; // b2 = b1;
+        b2_h = b1_h;
+        b1_l = b0_l; // b1 = b0;
+        b1_h = b0_h;
+    }
+
+    t0 = Mpy_32_16 (b1_h, b1_l, x);             // t0 = x*b1;
+    t0 = L_mac (t0, b2_h, (Word16) 0x8000);     // t0 = x*b1 - b2
+    t0 = L_msu (t0, b2_l, 1);
+    t0 = L_mac (t0, f[i], 4096);                // t0 = x*b1 - b2 + f[i]/2
+
+    t0 = L_shl (t0, 6);
+
+    cheb = extract_h (t0);
+
+    return (cheb);
+}
+
+------------------------------------------------------------------------------
+ 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 Chebps(Word16 x,
+                     Word16 f[], /* (n) */
+                     Word16 n,
+                     Flag *pOverflow)
+{
+    Word16 i;
+    Word16 cheb;
+    Word16 b1_h;
+    Word16 b1_l;
+    Word32 t0;
+    Word32 L_temp;
+    Word16 *p_f = &f[1];
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    /* L_temp = 1.0 */
+
+    L_temp = 0x01000000L;
+
+    t0 = ((Word32) x << 10) + ((Word32) * (p_f++) << 14);
+
+    /* b1 = t0 = 2*x + f[1]  */
+
+    b1_h = (Word16)(t0 >> 16);
+    b1_l = (Word16)((t0 >> 1) - (b1_h << 15));
+
+
+    for (i = 2; i < n; i++)
+    {
+        /* t0 = 2.0*x*b1    */
+        t0  = ((Word32) b1_h * x);
+        t0 += ((Word32) b1_l * x) >> 15;
+        t0 <<= 2;
+
+        /* t0 = 2.0*x*b1 - b2   */
+        t0 -= L_temp;
+
+        /* t0 = 2.0*x*b1 - b2 + f[i] */
+        t0 += (Word32) * (p_f++) << 14;
+
+        L_temp = ((Word32) b1_h << 16) + ((Word32) b1_l << 1);
+
+        /* b0 = 2.0*x*b1 - b2 + f[i]*/
+        b1_h = (Word16)(t0 >> 16);
+        b1_l = (Word16)((t0 >> 1) - (b1_h << 15));
+
+    }
+
+    /* t0 = x*b1; */
+    t0  = ((Word32) b1_h * x);
+    t0 += ((Word32) b1_l * x) >> 15;
+    t0 <<= 1;
+
+
+    /* t0 = x*b1 - b2   */
+    t0 -= L_temp;
+
+    /* t0 = x*b1 - b2 + f[i]/2 */
+    t0 += (Word32) * (p_f) << 13;
+
+
+    if ((UWord32)(t0 - 0xfe000000L) < 0x01ffffffL -  0xfe000000L)
+    {
+        cheb = (Word16)(t0 >> 10);
+    }
+    else
+    {
+        if (t0 > (Word32) 0x01ffffffL)
+        {
+            cheb = MAX_16;
+
+        }
+        else
+        {
+            cheb = MIN_16;
+        }
+    }
+
+    return (cheb);
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Az_lsp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS FOR Az_lsp
+
+ Inputs:
+    a = predictor coefficients (Word16)
+    lsp = line spectral pairs (Word16)
+    old_lsp = old line spectral pairs (Word16)
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the operations in the function resulted in saturation.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the LSPs from the LP coefficients.
+
+ The sum and difference filters are computed and divided by 1+z^{-1} and
+ 1-z^{-1}, respectively.
+
+     f1[i] = a[i] + a[11-i] - f1[i-1] ;   i=1,...,5
+     f2[i] = a[i] - a[11-i] + f2[i-1] ;   i=1,...,5
+
+ The roots of F1(z) and F2(z) are found using Chebyshev polynomial evaluation.
+ The polynomials are evaluated at 60 points regularly spaced in the
+ frequency domain. The sign change interval is subdivided 4 times to better
+ track the root. The LSPs are found in the cosine domain [1,-1].
+
+ If less than 10 roots are found, the LSPs from the past frame are used.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ az_lsp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Az_lsp (
+    Word16 a[],         // (i)  : predictor coefficients (MP1)
+    Word16 lsp[],       // (o)  : line spectral pairs (M)
+    Word16 old_lsp[]    // (i)  : old lsp[] (in case not found 10 roots) (M)
+)
+{
+    Word16 i, j, nf, ip;
+    Word16 xlow, ylow, xhigh, yhigh, xmid, ymid, xint;
+    Word16 x, y, sign, exp;
+    Word16 *coef;
+    Word16 f1[M / 2 + 1], f2[M / 2 + 1];
+    Word32 t0;
+
+     *-------------------------------------------------------------*
+     *  find the sum and diff. pol. F1(z) and F2(z)                *
+     *    F1(z) <--- F1(z)/(1+z**-1) & F2(z) <--- F2(z)/(1-z**-1)  *
+     *                                                             *
+     * f1[0] = 1.0;                                                *
+     * f2[0] = 1.0;                                                *
+     *                                                             *
+     * for (i = 0; i< NC; i++)                                     *
+     * {                                                           *
+     *   f1[i+1] = a[i+1] + a[M-i] - f1[i] ;                       *
+     *   f2[i+1] = a[i+1] - a[M-i] + f2[i] ;                       *
+     * }                                                           *
+     *-------------------------------------------------------------*
+
+    f1[0] = 1024; // f1[0] = 1.0
+    f2[0] = 1024; // f2[0] = 1.0
+
+// The reference ETSI code uses a global flag for Overflow. However, in the
+// actual implementation a pointer to Overflow flag is passed in as a
+// parameter to the function. This pointer is passed into all the basic math
+// functions invoked
+
+    for (i = 0; i < NC; i++)
+    {
+        t0 = L_mult (a[i + 1], 8192);   // x = (a[i+1] + a[M-i]) >> 2
+        t0 = L_mac (t0, a[M - i], 8192);
+        x = extract_h (t0);
+        // f1[i+1] = a[i+1] + a[M-i] - f1[i]
+        f1[i + 1] = sub (x, f1[i]);
+
+        t0 = L_mult (a[i + 1], 8192);   // x = (a[i+1] - a[M-i]) >> 2
+        t0 = L_msu (t0, a[M - i], 8192);
+        x = extract_h (t0);
+        // f2[i+1] = a[i+1] - a[M-i] + f2[i]
+        f2[i + 1] = add (x, f2[i]);
+    }
+
+     *-------------------------------------------------------------*
+     * find the LSPs using the Chebychev pol. evaluation           *
+     *-------------------------------------------------------------*
+
+    nf = 0; // number of found frequencies
+    ip = 0; // indicator for f1 or f2
+
+    coef = f1;
+
+    xlow = grid[0];
+    ylow = Chebps (xlow, coef, NC);
+
+    j = 0;
+    // while ( (nf < M) && (j < grid_points) )
+    while ((sub (nf, M) < 0) && (sub (j, grid_points) < 0))
+    {
+        j++;
+        xhigh = xlow;
+        yhigh = ylow;
+        xlow = grid[j];
+        ylow = Chebps (xlow, coef, NC);
+
+        if (L_mult (ylow, yhigh) <= (Word32) 0L)
+        {
+
+            // divide 4 times the interval
+
+            for (i = 0; i < 4; i++)
+            {
+                // xmid = (xlow + xhigh)/2
+                xmid = add (shr (xlow, 1), shr (xhigh, 1));
+                ymid = Chebps (xmid, coef, NC);
+
+                if (L_mult (ylow, ymid) <= (Word32) 0L)
+                {
+                    yhigh = ymid;
+                    xhigh = xmid;
+                }
+                else
+                {
+                    ylow = ymid;
+                    xlow = xmid;
+                }
+            }
+
+             *-------------------------------------------------------------*
+             * Linear interpolation                                        *
+             *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *
+             *-------------------------------------------------------------*
+
+            x = sub (xhigh, xlow);
+            y = sub (yhigh, ylow);
+
+            if (y == 0)
+            {
+                xint = xlow;
+            }
+            else
+            {
+                sign = y;
+                y = abs_s (y);
+                exp = norm_s (y);
+                y = shl (y, exp);
+                y = div_s ((Word16) 16383, y);
+                t0 = L_mult (x, y);
+                t0 = L_shr (t0, sub (20, exp));
+                y = extract_l (t0);     // y= (xhigh-xlow)/(yhigh-ylow)
+
+                if (sign < 0)
+                    y = negate (y);
+
+                t0 = L_mult (ylow, y);
+                t0 = L_shr (t0, 11);
+                xint = sub (xlow, extract_l (t0)); // xint = xlow - ylow*y
+            }
+
+            lsp[nf] = xint;
+            xlow = xint;
+            nf++;
+
+            if (ip == 0)
+            {
+                ip = 1;
+                coef = f2;
+            }
+            else
+            {
+                ip = 0;
+                coef = f1;
+            }
+            ylow = Chebps (xlow, coef, NC);
+
+        }
+    }
+
+    // Check if M roots found
+
+    if (sub (nf, M) < 0)
+    {
+        for (i = 0; i < M; i++)
+        {
+            lsp[i] = old_lsp[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]
+
+------------------------------------------------------------------------------
+*/
+
+void Az_lsp(
+    Word16 a[],         /* (i)  : predictor coefficients (MP1)               */
+    Word16 lsp[],       /* (o)  : line spectral pairs (M)                    */
+    Word16 old_lsp[],   /* (i)  : old lsp[] (in case not found 10 roots) (M) */
+    Flag   *pOverflow   /* (i/o): overflow flag                              */
+)
+{
+    register Word16 i;
+    register Word16 j;
+    register Word16 nf;
+    register Word16 ip;
+    Word16 xlow;
+    Word16 ylow;
+    Word16 xhigh;
+    Word16 yhigh;
+    Word16 xmid;
+    Word16 ymid;
+    Word16 xint;
+    Word16 x;
+    Word16 y;
+    Word16 sign;
+    Word16 exp;
+    Word16 *coef;
+    Word16 f1[NC + 1];
+    Word16 f2[NC + 1];
+    Word32 L_temp1;
+    Word32 L_temp2;
+    Word16 *p_f1 = f1;
+    Word16 *p_f2 = f2;
+
+    /*-------------------------------------------------------------*
+     *  find the sum and diff. pol. F1(z) and F2(z)                *
+     *    F1(z) <--- F1(z)/(1+z**-1) & F2(z) <--- F2(z)/(1-z**-1)  *
+     *                                                             *
+     * f1[0] = 1.0;                                                *
+     * f2[0] = 1.0;                                                *
+     *                                                             *
+     * for (i = 0; i< NC; i++)                                     *
+     * {                                                           *
+     *   f1[i+1] = a[i+1] + a[M-i] - f1[i] ;                       *
+     *   f2[i+1] = a[i+1] - a[M-i] + f2[i] ;                       *
+     * }                                                           *
+     *-------------------------------------------------------------*/
+
+    *p_f1 = 1024;                       /* f1[0] = 1.0 */
+    *p_f2 = 1024;                       /* f2[0] = 1.0 */
+
+    for (i = 0; i < NC; i++)
+    {
+        L_temp1 = (Word32) * (a + i + 1);
+        L_temp2 = (Word32) * (a + M - i);
+        /* x = (a[i+1] + a[M-i]) >> 2  */
+        x = (Word16)((L_temp1 + L_temp2) >> 2);
+        /* y = (a[i+1] - a[M-i]) >> 2 */
+        y = (Word16)((L_temp1 - L_temp2) >> 2);
+        /* f1[i+1] = a[i+1] + a[M-i] - f1[i] */
+        x -= *(p_f1++);
+        *(p_f1) = x;
+        /* f2[i+1] = a[i+1] - a[M-i] + f2[i] */
+        y += *(p_f2++);
+        *(p_f2) = y;
+    }
+
+    /*-------------------------------------------------------------*
+     * find the LSPs using the Chebychev pol. evaluation           *
+     *-------------------------------------------------------------*/
+
+    nf = 0;                         /* number of found frequencies */
+    ip = 0;                         /* indicator for f1 or f2      */
+
+    coef = f1;
+
+    xlow = *(grid);
+    ylow = Chebps(xlow, coef, NC, pOverflow);
+
+    j = 0;
+
+    while ((nf < M) && (j < grid_points))
+    {
+        j++;
+        xhigh = xlow;
+        yhigh = ylow;
+        xlow = *(grid + j);
+        ylow = Chebps(xlow, coef, NC, pOverflow);
+
+        if (((Word32)ylow*yhigh) <= 0)
+        {
+            /* divide 4 times the interval */
+            for (i = 4; i != 0; i--)
+            {
+                /* xmid = (xlow + xhigh)/2 */
+                x = xlow >> 1;
+                y = xhigh >> 1;
+                xmid = x + y;
+
+                ymid = Chebps(xmid, coef, NC, pOverflow);
+
+                if (((Word32)ylow*ymid) <= 0)
+                {
+                    yhigh = ymid;
+                    xhigh = xmid;
+                }
+                else
+                {
+                    ylow = ymid;
+                    xlow = xmid;
+                }
+            }
+
+            /*-------------------------------------------------------------*
+             * Linear interpolation                                        *
+             *    xint = xlow - ylow*(xhigh-xlow)/(yhigh-ylow);            *
+             *-------------------------------------------------------------*/
+
+            x = xhigh - xlow;
+            y = yhigh - ylow;
+
+            if (y == 0)
+            {
+                xint = xlow;
+            }
+            else
+            {
+                sign = y;
+                y = abs_s(y);
+                exp = norm_s(y);
+                y <<= exp;
+                y = div_s((Word16) 16383, y);
+
+                y = ((Word32)x * y) >> (19 - exp);
+
+                if (sign < 0)
+                {
+                    y = -y;
+                }
+
+                /* xint = xlow - ylow*y */
+                xint = xlow - (((Word32) ylow * y) >> 10);
+            }
+
+            *(lsp + nf) = xint;
+            xlow = xint;
+            nf++;
+
+            if (ip == 0)
+            {
+                ip = 1;
+                coef = f2;
+            }
+            else
+            {
+                ip = 0;
+                coef = f1;
+            }
+
+            ylow = Chebps(xlow, coef, NC, pOverflow);
+
+        }
+    }
+
+    /* Check if M roots found */
+
+    if (nf < M)
+    {
+        for (i = NC; i != 0 ; i--)
+        {
+            *lsp++ = *old_lsp++;
+            *lsp++ = *old_lsp++;
+        }
+    }
+
+}
+
+Word16 Chebps_Wrapper(Word16 x,
+                      Word16 f[], /* (n) */
+                      Word16 n,
+                      Flag *pOverflow)
+{
+    return Chebps(x, f, n, pOverflow);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/bitno_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/bitno_tab.cpp
new file mode 100644
index 0000000..fed684d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/bitno_tab.cpp
@@ -0,0 +1,309 @@
+/* ------------------------------------------------------------------
+ * 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/bitno_tab.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Define "const Word16 *bitno[N_MODES]" as "const Word16 *const
+                      bitno[N_MODES]"
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ 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             : bitno.tab
+      Purpose          : Tables for bit2prm and prm2bit
+
+------------------------------------------------------------------------------
+ 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"   /* parameter sizes: MAX_PRM_SIZE */
+#include "mode.h"   /* N_MODES */
+#include "bitno_tab.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 parameters per modes (values must be <= MAX_PRM_SIZE!) */
+    extern const Word16 prmno[N_MODES] =
+    {
+        PRMNO_MR475,
+        PRMNO_MR515,
+        PRMNO_MR59,
+        PRMNO_MR67,
+        PRMNO_MR74,
+        PRMNO_MR795,
+        PRMNO_MR102,
+        PRMNO_MR122,
+        PRMNO_MRDTX
+    };
+
+    /* number of parameters to first subframe per modes */
+    extern const Word16 prmnofsf[N_MODES - 1] =
+    {
+        PRMNOFSF_MR475,
+        PRMNOFSF_MR515,
+        PRMNOFSF_MR59,
+        PRMNOFSF_MR67,
+        PRMNOFSF_MR74,
+        PRMNOFSF_MR795,
+        PRMNOFSF_MR102,
+        PRMNOFSF_MR122
+    };
+
+    /* parameter sizes (# of bits), one table per mode */
+    extern const Word16 bitno_MR475[PRMNO_MR475] =
+    {
+        8, 8, 7,                                 /* LSP VQ          */
+        8, 7, 2, 8,                              /* first subframe  */
+        4, 7, 2,                                 /* second subframe */
+        4, 7, 2, 8,                              /* third subframe  */
+        4, 7, 2,                                 /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR515[PRMNO_MR515] =
+    {
+        8, 8, 7,                                 /* LSP VQ          */
+        8, 7, 2, 6,                              /* first subframe  */
+        4, 7, 2, 6,                              /* second subframe */
+        4, 7, 2, 6,                              /* third subframe  */
+        4, 7, 2, 6,                              /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR59[PRMNO_MR59] =
+    {
+        8, 9, 9,                                 /* LSP VQ          */
+        8, 9, 2, 6,                              /* first subframe  */
+        4, 9, 2, 6,                              /* second subframe */
+        8, 9, 2, 6,                              /* third subframe  */
+        4, 9, 2, 6,                              /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR67[PRMNO_MR67] =
+    {
+        8, 9, 9,                                 /* LSP VQ          */
+        8, 11, 3, 7,                             /* first subframe  */
+        4, 11, 3, 7,                             /* second subframe */
+        8, 11, 3, 7,                             /* third subframe  */
+        4, 11, 3, 7,                             /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR74[PRMNO_MR74] =
+    {
+        8, 9, 9,                                 /* LSP VQ          */
+        8, 13, 4, 7,                             /* first subframe  */
+        5, 13, 4, 7,                             /* second subframe */
+        8, 13, 4, 7,                             /* third subframe  */
+        5, 13, 4, 7,                             /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR795[PRMNO_MR795] =
+    {
+        9, 9, 9,                                 /* LSP VQ          */
+        8, 13, 4, 4, 5,                          /* first subframe  */
+        6, 13, 4, 4, 5,                          /* second subframe */
+        8, 13, 4, 4, 5,                          /* third subframe  */
+        6, 13, 4, 4, 5,                          /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR102[PRMNO_MR102] =
+    {
+        8, 9, 9,                                 /* LSP VQ          */
+        8, 1, 1, 1, 1, 10, 10, 7, 7,             /* first subframe  */
+        5, 1, 1, 1, 1, 10, 10, 7, 7,             /* second subframe */
+        8, 1, 1, 1, 1, 10, 10, 7, 7,             /* third subframe  */
+        5, 1, 1, 1, 1, 10, 10, 7, 7,             /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MR122[PRMNO_MR122] =
+    {
+        7, 8, 9, 8, 6,                           /* LSP VQ          */
+        9, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 5,   /* first subframe  */
+        6, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 5,   /* second subframe */
+        9, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 5,   /* third subframe  */
+        6, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 5    /* fourth subframe */
+    };
+
+    extern const Word16 bitno_MRDTX[PRMNO_MRDTX] =
+    {
+        3,
+        8, 9, 9,
+        6
+    };
+
+    /* overall table with all parameter sizes for all modes */
+    extern const Word16 * const bitno[N_MODES] =
+    {
+        bitno_MR475,
+        bitno_MR515,
+        bitno_MR59,
+        bitno_MR67,
+        bitno_MR74,
+        bitno_MR795,
+        bitno_MR102,
+        bitno_MR122,
+        bitno_MRDTX
+    };
+    /*----------------------------------------------------------------------------
+    ; 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/common/src/bitreorder_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/bitreorder_tab.cpp
new file mode 100644
index 0000000..69b20fb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/bitreorder_tab.cpp
@@ -0,0 +1,421 @@
+/* ------------------------------------------------------------------
+ * 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/bitreorder.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed file name to bitreorder_tab.c and .h. Also, updated the
+              module description.
+
+ Description: Define "const Word16 *reorderBits[NUM_MODES-1]" as
+              "const Word16 *const reorderBits[NUM_MODES-1]".
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition. Removed corresponding header file from Include
+              section.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ 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
+
+ This function contains tables needed to reformat the encoded speech bits
+ into IF2, WMF, and ETS.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ 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.
+    ----------------------------------------------------------------------------*/
+#define NUM_MODES           16
+#define NUMBIT_MR475        95
+#define NUMBIT_MR515       103
+#define NUMBIT_MR59        118
+#define NUMBIT_MR67        134
+#define NUMBIT_MR74        148
+#define NUMBIT_MR795       159
+#define NUMBIT_MR102       204
+#define NUMBIT_MR122       244
+#define NUMBIT_AMR_SID      39
+#define NUMBIT_GSMEFR_SID   43
+#define NUMBIT_TDMAEFR_SID  38
+#define NUMBIT_PDCEFR_SID   37
+#define NUMBIT_UNUSED1       0
+#define NUMBIT_UNUSED2       0
+#define NUMBIT_UNUSED3       0
+#define NUMBIT_NO_DATA       0
+
+#define MAX_NUM_BITS       244
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    /* number of parameters per modes (values must be <= MAX_PRM_SIZE!) */
+    extern const Word16 numOfBits[NUM_MODES] =
+    {
+        NUMBIT_MR475,
+        NUMBIT_MR515,
+        NUMBIT_MR59,
+        NUMBIT_MR67,
+        NUMBIT_MR74,
+        NUMBIT_MR795,
+        NUMBIT_MR102,
+        NUMBIT_MR122,
+        NUMBIT_AMR_SID,
+        NUMBIT_GSMEFR_SID,
+        NUMBIT_TDMAEFR_SID,
+        NUMBIT_PDCEFR_SID,
+        NUMBIT_UNUSED1,
+        NUMBIT_UNUSED2,
+        NUMBIT_UNUSED3,
+        NUMBIT_NO_DATA
+    };
+
+    extern const Word16 reorderBits_MR475[NUMBIT_MR475] =
+    {
+        0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+        10, 11, 12, 13, 14, 15, 23, 24, 25, 26,
+        27, 28, 48, 49, 61, 62, 82, 83, 47, 46,
+        45, 44, 81, 80, 79, 78, 17, 18, 20, 22,
+        77, 76, 75, 74, 29, 30, 43, 42, 41, 40,
+        38, 39, 16, 19, 21, 50, 51, 59, 60, 63,
+        64, 72, 73, 84, 85, 93, 94, 32, 33, 35,
+        36, 53, 54, 56, 57, 66, 67, 69, 70, 87,
+        88, 90, 91, 34, 55, 68, 89, 37, 58, 71,
+        92, 31, 52, 65, 86
+    };
+
+    extern const Word16 reorderBits_MR515[NUMBIT_MR515] =
+    {
+        7,  6,  5,  4,  3,  2,  1,  0, 15, 14,
+        13, 12, 11, 10,  9,  8, 23, 24, 25, 26,
+        27, 46, 65, 84, 45, 44, 43, 64, 63, 62,
+        83, 82, 81, 102, 101, 100, 42, 61, 80, 99,
+        28, 47, 66, 85, 18, 41, 60, 79, 98, 29,
+        48, 67, 17, 20, 22, 40, 59, 78, 97, 21,
+        30, 49, 68, 86, 19, 16, 87, 39, 38, 58,
+        57, 77, 35, 54, 73, 92, 76, 96, 95, 36,
+        55, 74, 93, 32, 51, 33, 52, 70, 71, 89,
+        90, 31, 50, 69, 88, 37, 56, 75, 94, 34,
+        53, 72, 91
+    };
+
+    extern const Word16 reorderBits_MR59[NUMBIT_MR59] =
+    {
+        0,  1,  4,  5,  3,  6,  7,  2, 13, 15,
+        8,  9, 11, 12, 14, 10, 16, 28, 74, 29,
+        75, 27, 73, 26, 72, 30, 76, 51, 97, 50,
+        71, 96, 117, 31, 77, 52, 98, 49, 70, 95,
+        116, 53, 99, 32, 78, 33, 79, 48, 69, 94,
+        115, 47, 68, 93, 114, 46, 67, 92, 113, 19,
+        21, 23, 22, 18, 17, 20, 24, 111, 43, 89,
+        110, 64, 65, 44, 90, 25, 45, 66, 91, 112,
+        54, 100, 40, 61, 86, 107, 39, 60, 85, 106,
+        36, 57, 82, 103, 35, 56, 81, 102, 34, 55,
+        80, 101, 42, 63, 88, 109, 41, 62, 87, 108,
+        38, 59, 84, 105, 37, 58, 83, 104
+    };
+
+    extern const Word16 reorderBits_MR67[NUMBIT_MR67] =
+    {
+        0,  1,  4,  3,  5,  6, 13,  7,  2,  8,
+        9, 11, 15, 12, 14, 10, 28, 82, 29, 83,
+        27, 81, 26, 80, 30, 84, 16, 55, 109, 56,
+        110, 31, 85, 57, 111, 48, 73, 102, 127, 32,
+        86, 51, 76, 105, 130, 52, 77, 106, 131, 58,
+        112, 33, 87, 19, 23, 53, 78, 107, 132, 21,
+        22, 18, 17, 20, 24, 25, 50, 75, 104, 129,
+        47, 72, 101, 126, 54, 79, 108, 133, 46, 71,
+        100, 125, 128, 103, 74, 49, 45, 70, 99, 124,
+        42, 67, 96, 121, 39, 64, 93, 118, 38, 63,
+        92, 117, 35, 60, 89, 114, 34, 59, 88, 113,
+        44, 69, 98, 123, 43, 68, 97, 122, 41, 66,
+        95, 120, 40, 65, 94, 119, 37, 62, 91, 116,
+        36, 61, 90, 115
+    };
+
+    extern const Word16 reorderBits_MR74[NUMBIT_MR74] =
+    {
+        0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+        10, 11, 12, 13, 14, 15, 16, 26, 87, 27,
+        88, 28, 89, 29, 90, 30, 91, 51, 80, 112,
+        141, 52, 81, 113, 142, 54, 83, 115, 144, 55,
+        84, 116, 145, 58, 119, 59, 120, 21, 22, 23,
+        17, 18, 19, 31, 60, 92, 121, 56, 85, 117,
+        146, 20, 24, 25, 50, 79, 111, 140, 57, 86,
+        118, 147, 49, 78, 110, 139, 48, 77, 53, 82,
+        114, 143, 109, 138, 47, 76, 108, 137, 32, 33,
+        61, 62, 93, 94, 122, 123, 41, 42, 43, 44,
+        45, 46, 70, 71, 72, 73, 74, 75, 102, 103,
+        104, 105, 106, 107, 131, 132, 133, 134, 135, 136,
+        34, 63, 95, 124, 35, 64, 96, 125, 36, 65,
+        97, 126, 37, 66, 98, 127, 38, 67, 99, 128,
+        39, 68, 100, 129, 40, 69, 101, 130
+    };
+
+    extern const Word16 reorderBits_MR795[NUMBIT_MR795] =
+    {
+        8,  7,  6,  5,  4,  3,  2, 14, 16,  9,
+        10, 12, 13, 15, 11, 17, 20, 22, 24, 23,
+        19, 18, 21, 56, 88, 122, 154, 57, 89, 123,
+        155, 58, 90, 124, 156, 52, 84, 118, 150, 53,
+        85, 119, 151, 27, 93, 28, 94, 29, 95, 30,
+        96, 31, 97, 61, 127, 62, 128, 63, 129, 59,
+        91, 125, 157, 32, 98, 64, 130,  1,  0, 25,
+        26, 33, 99, 34, 100, 65, 131, 66, 132, 54,
+        86, 120, 152, 60, 92, 126, 158, 55, 87, 121,
+        153, 117, 116, 115, 46, 78, 112, 144, 43, 75,
+        109, 141, 40, 72, 106, 138, 36, 68, 102, 134,
+        114, 149, 148, 147, 146, 83, 82, 81, 80, 51,
+        50, 49, 48, 47, 45, 44, 42, 39, 35, 79,
+        77, 76, 74, 71, 67, 113, 111, 110, 108, 105,
+        101, 145, 143, 142, 140, 137, 133, 41, 73, 107,
+        139, 37, 69, 103, 135, 38, 70, 104, 136
+    };
+
+    extern const Word16 reorderBits_MR102[NUMBIT_MR102] =
+    {
+        7,  6,  5,  4,  3,  2,  1,  0, 16, 15,
+        14, 13, 12, 11, 10,  9,  8, 26, 27, 28,
+        29, 30, 31, 115, 116, 117, 118, 119, 120, 72,
+        73, 161, 162, 65, 68, 69, 108, 111, 112, 154,
+        157, 158, 197, 200, 201, 32, 33, 121, 122, 74,
+        75, 163, 164, 66, 109, 155, 198, 19, 23, 21,
+        22, 18, 17, 20, 24, 25, 37, 36, 35, 34,
+        80, 79, 78, 77, 126, 125, 124, 123, 169, 168,
+        167, 166, 70, 67, 71, 113, 110, 114, 159, 156,
+        160, 202, 199, 203, 76, 165, 81, 82, 92, 91,
+        93, 83, 95, 85, 84, 94, 101, 102, 96, 104,
+        86, 103, 87, 97, 127, 128, 138, 137, 139, 129,
+        141, 131, 130, 140, 147, 148, 142, 150, 132, 149,
+        133, 143, 170, 171, 181, 180, 182, 172, 184, 174,
+        173, 183, 190, 191, 185, 193, 175, 192, 176, 186,
+        38, 39, 49, 48, 50, 40, 52, 42, 41, 51,
+        58, 59, 53, 61, 43, 60, 44, 54, 194, 179,
+        189, 196, 177, 195, 178, 187, 188, 151, 136, 146,
+        153, 134, 152, 135, 144, 145, 105, 90, 100, 107,
+        88, 106, 89, 98, 99, 62, 47, 57, 64, 45,
+        63, 46, 55, 56
+    };
+
+    extern const Word16 reorderBits_MR122[NUMBIT_MR122] =
+    {
+        0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+        10, 11, 12, 13, 14, 23, 15, 16, 17, 18,
+        19, 20, 21, 22, 24, 25, 26, 27, 28, 38,
+        141, 39, 142, 40, 143, 41, 144, 42, 145, 43,
+        146, 44, 147, 45, 148, 46, 149, 47, 97, 150,
+        200, 48, 98, 151, 201, 49, 99, 152, 202, 86,
+        136, 189, 239, 87, 137, 190, 240, 88, 138, 191,
+        241, 91, 194, 92, 195, 93, 196, 94, 197, 95,
+        198, 29, 30, 31, 32, 33, 34, 35, 50, 100,
+        153, 203, 89, 139, 192, 242, 51, 101, 154, 204,
+        55, 105, 158, 208, 90, 140, 193, 243, 59, 109,
+        162, 212, 63, 113, 166, 216, 67, 117, 170, 220,
+        36, 37, 54, 53, 52, 58, 57, 56, 62, 61,
+        60, 66, 65, 64, 70, 69, 68, 104, 103, 102,
+        108, 107, 106, 112, 111, 110, 116, 115, 114, 120,
+        119, 118, 157, 156, 155, 161, 160, 159, 165, 164,
+        163, 169, 168, 167, 173, 172, 171, 207, 206, 205,
+        211, 210, 209, 215, 214, 213, 219, 218, 217, 223,
+        222, 221, 73, 72, 71, 76, 75, 74, 79, 78,
+        77, 82, 81, 80, 85, 84, 83, 123, 122, 121,
+        126, 125, 124, 129, 128, 127, 132, 131, 130, 135,
+        134, 133, 176, 175, 174, 179, 178, 177, 182, 181,
+        180, 185, 184, 183, 188, 187, 186, 226, 225, 224,
+        229, 228, 227, 232, 231, 230, 235, 234, 233, 238,
+        237, 236, 96, 199
+    };
+
+    /* overall table with all parameter sizes for all modes */
+    extern const Word16 * const reorderBits[NUM_MODES-1] =
+    {
+        reorderBits_MR475,
+        reorderBits_MR515,
+        reorderBits_MR59,
+        reorderBits_MR67,
+        reorderBits_MR74,
+        reorderBits_MR795,
+        reorderBits_MR102,
+        reorderBits_MR122
+    };
+
+    /* Number of Frames (16-bit segments sent for each mode */
+    extern const Word16 numCompressedBytes[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/common/src/bits2prm.cpp b/media/libstagefright/codecs/amrnb/common/src/bits2prm.cpp
new file mode 100644
index 0000000..1d6f7b1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/bits2prm.cpp
@@ -0,0 +1,292 @@
+/* ------------------------------------------------------------------
+ * 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/bits2prm.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Fixed a typo in the include section. Optimized some lines of
+              code as per review comments.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "bits2prm.h"
+#include "typedef.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.]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Bin2int
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    no_of_bits = number of bits associated with value
+    bitstream = pointer to buffer where bits are read
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function    : Bin2int
+  Purpose     : Read "no_of_bits" bits from the array bitstream[]
+                and convert to integer.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ bits2prm.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word16 Bin2int ( // Reconstructed parameter
+    Word16 no_of_bits,  // input : number of bits associated with value
+    Word16 *bitstream   // output: address where bits are written
+)
+{
+    Word16 value, i, bit;
+
+    value = 0;
+    for (i = 0; i < no_of_bits; i++)
+    {
+        value = shl (value, 1);
+        bit = *bitstream++;
+        if (sub (bit, BIT_1) == 0)
+            value = add (value, 1);
+    }
+    return (value);
+}
+
+------------------------------------------------------------------------------
+ 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 Word16 Bin2int(  /* Reconstructed parameter                      */
+    Word16 no_of_bits,  /* input : number of bits associated with value */
+    Word16 *bitstream   /* input: address where bits are read from      */
+)
+{
+    Word16 value;
+    Word16 i;
+    Word16 single_bit;
+
+    value = 0;
+    for (i = 0; i < no_of_bits; i++)
+    {
+        value <<= 1;
+        single_bit = *(bitstream++);
+        value |= single_bit;
+    }
+    return (value);
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: bits2prm
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode = AMR mode of type enum Mode
+    bits[] = pointer to serial bits of type Word16
+    prm[] = pointer to analysis parameters of type Word16
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function    : Bits2prm
+  Purpose     : Retrieves the vector of encoder parameters from
+                the received serial bits in a frame.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ bits2prm.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Bits2prm (
+    enum Mode mode,     // i : AMR mode
+    Word16 bits[],      // i : serial bits       (size <= MAX_SERIAL_SIZE)
+    Word16 prm[]        // o : analysis parameters  (size <= MAX_PRM_SIZE)
+)
+{
+    Word16 i;
+
+    for (i = 0; i < prmno[mode]; i++)
+    {
+        prm[i] = Bin2int (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
+----------------------------------------------------------------------------*/
+OSCL_EXPORT_REF void Bits2prm(
+    enum Mode mode,     /* i : AMR mode                                    */
+    Word16 bits[],      /* i : serial bits       (size <= MAX_SERIAL_SIZE) */
+    Word16 prm[]        /* o : analysis parameters  (size <= MAX_PRM_SIZE) */
+)
+{
+    Word16 i;
+
+    for (i = 0; i < prmno[mode]; i++)
+    {
+        prm[i] = Bin2int(bitno[mode][i], bits);
+        bits += bitno[mode][i];
+    }
+
+    return;
+}
+
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/bytesused.cpp b/media/libstagefright/codecs/amrnb/common/src/bytesused.cpp
new file mode 100644
index 0000000..9552206
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/bytesused.cpp
@@ -0,0 +1,208 @@
+/* ------------------------------------------------------------------
+ * 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/BytesUsed.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Corrected entries for all SID frames and updated function
+              description. Updated copyright year.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition. Removed corresponding header file from Include
+              section.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ 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
+
+ This function creates a table called BytesUsed that holds the value that
+ describes the number of bytes required to hold one frame worth of data in
+ the WMF (non-IF2) frame format. Each table entry is the sum of the frame
+ type byte and the number of bytes used up by the core speech data for each
+ 3GPP frame type.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] "AMR Speech Codec Frame Structure", 3GPP TS 26.101 version 4.1.0
+     Release 4, June 2001, page 13.
+
+------------------------------------------------------------------------------
+ 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 short BytesUsed[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 */
+    };
+    /*----------------------------------------------------------------------------
+    ; 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/common/src/c2_9pf_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/c2_9pf_tab.cpp
new file mode 100644
index 0000000..471bee8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/c2_9pf_tab.cpp
@@ -0,0 +1,165 @@
+/* ------------------------------------------------------------------
+ * 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/c2_9pf_tab.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1)    Corrected the module description
+ (2)    Corrected the filename in the template.
+ (3)    Removed embedded tabs.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for startPos[] used by the functions
+ c2_9pf.c and d2_9pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 startPos[2*4*2] = {0, 2, 0, 3,
+        0, 2, 0, 3,
+        1, 3, 2, 4,
+        1, 4, 1, 4
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] c2_9pf.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
+----------------------------------------------------------------------------*/
diff --git a/media/libstagefright/codecs/amrnb/common/src/copy.cpp b/media/libstagefright/codecs/amrnb/common/src/copy.cpp
new file mode 100644
index 0000000..75890b2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/copy.cpp
@@ -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             : copy.h
+*
+********************************************************************************
+*/
+
+/*
+********************************************************************************
+*                         MODULE INCLUDE FILE AND VERSION ID
+********************************************************************************
+*/
+#include "copy.h"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include <string.h>
+
+#include "typedef.h"
+#include "basic_op.h"
+
+/*
+********************************************************************************
+*                         PUBLIC PROGRAM CODE
+********************************************************************************
+*/
+/*************************************************************************
+ *
+ *   FUNCTION:   Copy
+ *
+ *   PURPOSE:   Copy vector x[] to y[]
+ *
+ *
+ *************************************************************************/
+/*
+**************************************************************************
+*
+*  Function    : Copy
+*  Purpose     : Copy vector x[] to y[]
+*
+**************************************************************************
+*/
+void Copy(
+    const Word16 x[],   /* i : input vector (L)  */
+    Word16 y[],         /* o : output vector (L) */
+    Word16 L            /* i : vector length     */
+)
+{
+    memmove(y, x, L*sizeof(*x));
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/div_32.cpp b/media/libstagefright/codecs/amrnb/common/src/div_32.cpp
new file mode 100644
index 0000000..143e37c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/div_32.cpp
@@ -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/div_32.c
+
+------------------------------------------------------------------------------
+ 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. Removed inclusion of unwanted header files. Changed
+              the name of input and output variables for clarity.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced l_extract functionality, code size and speed
+                 do not justify calling this function
+              3. Eliminated sub() function call, replace by (-), this knowing
+                 that the result will not saturate.
+
+ Description:  Added casting to eliminate warnings
+
+ Who:                           Date:
+ 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: div_32
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_num = 32 bit signed integer (Word32) whose value falls in the
+                range : 0x0000 0000 < L_num < L_denom
+    L_denom_hi = 16 bit positive normalized integer whose value falls in
+               the range : 0x4000 < hi < 0x7fff
+    L_denom_lo = 16 bit positive integer whose value falls in the range :
+               0 < lo < 0x7fff
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the 32 bit divide operation resulted in overflow
+
+ Returns:
+    result = 32-bit quotient of of the division of two 32 bit integers
+                L_num / L_denom (Word32)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is a fractional integer division of two 32 bit numbers, the
+ numerator L_num and the denominator L_denom. The denominator is formed by
+ combining denom_hi and denom_lo. Note that denom_hi is a normalized numbers.
+ The numerator and denominator must be positive and the numerator must be
+ less than the denominator.
+
+ The division is done as follows:
+ 1. Find 1/L_denom by first approximating: approx = 1 / denom_hi.
+ 2. 1/L_denom = approx * (2.0 - L_denom * approx ).
+ 3. result = L_num * (1/L_denom).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] div_32() 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
+----------------------------------------------------------------------------*/
+Word32 Div_32(Word32 L_num,
+              Word16 L_denom_hi,
+              Word16 L_denom_lo,
+              Flag   *pOverflow)
+{
+
+    Word16 approx;
+    Word16 hi;
+    Word16 lo;
+    Word16 n_hi;
+    Word16 n_lo;
+    Word32 result;
+
+    /* First approximation: 1 / L_denom = 1/L_denom_hi */
+
+    approx = div_s((Word16) 0x3fff, L_denom_hi);
+
+    /* 1/L_denom = approx * (2.0 - L_denom * approx) */
+
+    result = Mpy_32_16(L_denom_hi, L_denom_lo, approx, pOverflow);
+    /* result is > 0 , and less than 1.0 */
+    result =  0x7fffffffL - result;
+
+    hi = (Word16)(result >> 16);
+    lo = (result >> 1) - (hi << 15);
+
+    result = Mpy_32_16(hi, lo, approx, pOverflow);
+
+    /* L_num * (1/L_denom) */
+
+    hi = (Word16)(result >> 16);
+    lo = (result >> 1) - (hi << 15);
+
+    n_hi = (Word16)(L_num >> 16);
+    n_lo = (L_num >> 1) - (n_hi << 15);
+
+    result = Mpy_32(n_hi, n_lo, hi, lo, pOverflow);
+    result = L_shl(result, 2, pOverflow);
+
+    return (result);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/div_s.cpp b/media/libstagefright/codecs/amrnb/common/src/div_s.cpp
new file mode 100644
index 0000000..f3bed7e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/div_s.cpp
@@ -0,0 +1,277 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/div_s.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the div_s function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Making changes based on review meeting.
+
+ Description: Made changes based on P3 review meeting.
+
+ Description: Changing abort() to exit(0).
+
+ Description: Made the following changes
+              1. Unrolled the division loop to make three comparison per
+                 pass, using only five iterations of the loop and saving
+                 shifts cycles
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit signed integer (Word16) whose value falls in
+           the range : 0x0000 <= var1 <= 0x7fff.
+    var2 = 16 bit signed integer (Word16) whose value falls in
+           the range : 0x0000 <= var1 <= 0x7fff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var_out = quotient of var1 divided by var2 (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function produces a result which is the fractional integer division of
+ var1 by var2; var1 and var2 must be positive and var2 must be greater or equal
+ to var1; the result is positive (leading bit equal to 0) and truncated to 16
+ bits. If var1 = var2 then div(var1,var2) = 32767.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 div_s (Word16 var1, Word16 var2)
+{
+    Word16 var_out = 0;
+    Word16 iteration;
+    Word32 L_num;
+    Word32 L_denom;
+    Word16 abort_flag = 0;
+
+    if ((var1 > var2) || (var1 < 0))
+    {
+        printf ("Division Error var1=%d  var2=%d\n", var1, var2);
+        abort_flag = 1;
+        exit(0);
+    }
+    if ((var1 != 0) && (abort_flag == 0))
+    {
+        if (var1 == var2)
+        {
+            var_out = MAX_16;
+        }
+        else
+        {
+            L_num = (Word32) var1;
+            L_denom = (Word32) var2;
+
+            for (iteration = 15; iteration > 0; iteration--)
+            {
+                var_out <<= 1;
+                L_num <<= 1;
+
+                if (L_num >= L_denom)
+                {
+                    L_num -= L_denom;
+                    var_out += 1;
+                }
+            }
+        }
+    }
+
+#if (WMOPS)
+    multiCounter[currCounter].div_s++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+Word16 div_s(register Word16 var1, register Word16 var2)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Word16 var_out = 0;
+    register Word16 iteration;
+    Word32 L_num;
+    Word32 L_denom;
+    Word32 L_denom_by_2;
+    Word32 L_denom_by_4;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    if ((var1 > var2) || (var1 < 0))
+    {
+        return 0; // used to exit(0);
+    }
+    if (var1)
+    {
+        if (var1 != var2)
+        {
+
+            L_num = (Word32) var1;
+            L_denom = (Word32) var2;
+            L_denom_by_2 = (L_denom << 1);
+            L_denom_by_4 = (L_denom << 2);
+            for (iteration = 5; iteration > 0; iteration--)
+            {
+                var_out <<= 3;
+                L_num   <<= 3;
+
+                if (L_num >= L_denom_by_4)
+                {
+                    L_num -= L_denom_by_4;
+                    var_out |= 4;
+                }
+
+                if (L_num >= L_denom_by_2)
+                {
+                    L_num -= L_denom_by_2;
+                    var_out |=  2;
+                }
+
+                if (L_num >= (L_denom))
+                {
+                    L_num -= (L_denom);
+                    var_out |=  1;
+                }
+
+            }
+        }
+        else
+        {
+            var_out = MAX_16;
+        }
+    }
+
+#if (WMOPS)
+    multiCounter[currCounter].div_s++;
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (var_out);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/extract_h.cpp b/media/libstagefright/codecs/amrnb/common/src/extract_h.cpp
new file mode 100644
index 0000000..e538f9f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/extract_h.cpp
@@ -0,0 +1,177 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/extract_h.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the extract_h function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ 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 = Most significant word of input (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function returns the 16 MSB of the input, L_var1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 extract_h (Word32 L_var1)
+{
+    Word16 var_out;
+
+    var_out = (Word16) (L_var1 >> 16);
+#if (WMOPS)
+    multiCounter[currCounter].extract_h++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+Word16 extract_h(Word32 L_var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return ((Word16)(L_var1 >> 16));
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/extract_l.cpp b/media/libstagefright/codecs/amrnb/common/src/extract_l.cpp
new file mode 100644
index 0000000..dbb9a6e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/extract_l.cpp
@@ -0,0 +1,176 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/extract_l.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the extract_l function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ 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 = Most significant word of input (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function returns the 16 LSB of the input, L_var1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 extract_l (Word32 L_var1)
+{
+    Word16 var_out;
+
+    var_out = (Word16) L_var1;
+#if (WMOPS)
+    multiCounter[currCounter].extract_l++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+Word16 extract_l(Word32 L_var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return ((Word16) L_var1);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/gains_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/gains_tbl.cpp
new file mode 100644
index 0000000..a08dd2d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/gains_tbl.cpp
@@ -0,0 +1,217 @@
+/* ------------------------------------------------------------------
+ * 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/gains_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, gains.tab
+
+ Description: Added include of "typedef.h" to includes section.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                               Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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.]
+    ----------------------------------------------------------------------------*/
+#define NB_QUA_PITCH 16
+#define NB_QUA_CODE 32
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; [Variable declaration - defined here and used outside this module]
+    ----------------------------------------------------------------------------*/
+
+
+    extern const Word16 qua_gain_pitch[NB_QUA_PITCH] =
+    {
+        0, 3277, 6556, 8192, 9830, 11469, 12288, 13107,
+        13926, 14746, 15565, 16384, 17203, 18022, 18842, 19661
+    };
+
+
+    extern const Word16 qua_gain_code[(NB_QUA_CODE+1)*3] =
+    {
+        /* gain factor (g_fac) and quantized energy error (qua_ener_MR122, qua_ener)
+         * are stored:
+         *
+         * qua_ener_MR122 = log2(g_fac)      (not the rounded floating point value, but
+         *                                    the value the original EFR algorithm
+         *                                    calculates from g_fac [using Log2])
+         * qua_ener       = 20*log10(g_fac); (rounded floating point value)
+         *
+         *
+         * g_fac (Q11), qua_ener_MR122 (Q10), qua_ener (Q10)
+         */
+        159,                -3776,          -22731,
+        206,                -3394,          -20428,
+        268,                -3005,          -18088,
+        349,                -2615,          -15739,
+        419,                -2345,          -14113,
+        482,                -2138,          -12867,
+        554,                -1932,          -11629,
+        637,                -1726,          -10387,
+        733,                -1518,           -9139,
+        842,                -1314,           -7906,
+        969,                -1106,           -6656,
+        1114,                 -900,           -5416,
+        1281,                 -694,           -4173,
+        1473,                 -487,           -2931,
+        1694,                 -281,           -1688,
+        1948,                  -75,            -445,
+        2241,                  133,             801,
+        2577,                  339,            2044,
+        2963,                  545,            3285,
+        3408,                  752,            4530,
+        3919,                  958,            5772,
+        4507,                 1165,            7016,
+        5183,                 1371,            8259,
+        5960,                 1577,            9501,
+        6855,                 1784,           10745,
+        7883,                 1991,           11988,
+        9065,                 2197,           13231,
+        10425,                 2404,           14474,
+        12510,                 2673,           16096,
+        16263,                 3060,           18429,
+        21142,                 3448,           20763,
+        27485,                 3836,           23097,
+        27485,                 3836,           23097
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] gains.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/common/src/gc_pred.cpp b/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
new file mode 100644
index 0000000..3650f3c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/gc_pred.cpp
@@ -0,0 +1,1046 @@
+/* ------------------------------------------------------------------
+ * 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/gc_pred.c
+ Functions:
+            gc_pred_reset
+            gc_pred
+            gc_pred_update
+            gc_pred_average_limited
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that perform codebook gain MA prediction.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "gc_pred.h"
+#include "basicop_malloc.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "log2.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 */
+
+/* average innovation energy.                               */
+/* MEAN_ENER  = 36.0/constant, constant = 20*Log10(2)       */
+#define MEAN_ENER_MR122  783741L  /* 36/(20*log10(2)) (Q17) */
+
+/* minimum quantized energy: -14 dB */
+#define MIN_ENERGY       -14336       /* 14                 Q10 */
+#define MIN_ENERGY_MR122  -2381       /* 14 / (20*log10(2)) Q10 */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* MA prediction coefficients (Q13) */
+static const Word16 pred[NPRED] = {5571, 4751, 2785, 1556};
+
+/* MA prediction coefficients (Q6)  */
+static const Word16 pred_MR122[NPRED] = {44, 37, 22, 12};
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gc_pred_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type gc_predState
+
+ Outputs:
+    past_qua_en field in the structure pointed to by state is initialized
+      to MIN_ENERGY
+    past_qua_en_MR122 field in the structure pointed to by state is
+      initialized to MIN_ENERGY_MR122
+
+ 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 gc_pred to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gc_pred.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int gc_pred_reset (gc_predState *state)
+{
+   Word16 i;
+
+   if (state == (gc_predState *) NULL){
+      fprintf(stderr, "gc_pred_reset: invalid parameter\n");
+      return -1;
+   }
+
+   for(i = 0; i < NPRED; i++)
+   {
+      state->past_qua_en[i] = MIN_ENERGY;
+      state->past_qua_en_MR122[i] = MIN_ENERGY_MR122;
+   }
+  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 gc_pred_reset(gc_predState *state)
+{
+    Word16 i;
+
+    if (state == (gc_predState *) NULL)
+    {
+        /* fprintf(stderr, "gc_pred_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    for (i = 0; i < NPRED; i++)
+    {
+        state->past_qua_en[i] = MIN_ENERGY;
+        state->past_qua_en_MR122[i] = MIN_ENERGY_MR122;
+    }
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gc_pred
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type gc_predState
+    mode = AMR mode (enum Mode)
+    code = pointer to the innovative codebook vector; Q12 in MR122 mode,
+           otherwise, Q13 (Word16)
+    exp_gcode0 = pointer to the exponent part of predicted gain factor
+             (Q0) (Word16)
+    frac_gcode0 = pointer to the fractional part of predicted gain factor
+              (Q15) (Word16)
+    exp_en = pointer to the exponent part of the innovation energy; this
+         is calculated for MR795 mode, Q0 (Word16)
+    frac_en = pointer to the fractional part of the innovation energy;
+          this is calculated for MR795 mode, Q15 (Word16)
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    store pointed to by exp_gcode0 contains the exponent part of the
+      recently calculated predicted gain factor
+    store pointed to by frac_gcode0 contains the fractional part of the
+      recently calculated predicted gain factor
+    store pointed to by exp_en contains the exponent part of the
+      recently calculated innovation energy
+    store pointed to by frac_en contains the fractional part of the
+      recently calculated innovation energy
+    pOverflow = 1 if the math functions called by gc_pred
+                results in overflow else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    pred = table of MA prediction coefficients (Q13) (Word16)
+    pred_MR122 = table of MA prediction coefficients (Q6) (Word16)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the MA prediction of the innovation energy (in
+ dB/(20*log10(2))), with the mean removed.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gc_pred.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
+gc_pred(
+    gc_predState *st,   // i/o: State struct
+    enum Mode mode,     // i  : AMR mode
+    Word16 *code,       // i  : innovative codebook vector (L_SUBFR)
+                        //      MR122: Q12, other modes: Q13
+    Word16 *exp_gcode0, // o  : exponent of predicted gain factor, Q0
+    Word16 *frac_gcode0,// o  : fraction of predicted gain factor  Q15
+    Word16 *exp_en,     // o  : exponent of innovation energy,     Q0
+                        //      (only calculated for MR795)
+    Word16 *frac_en     // o  : fraction of innovation energy,     Q15
+                        //      (only calculated for MR795)
+)
+{
+    Word16 i;
+    Word32 ener_code;
+    Word16 exp, frac;
+
+     *-------------------------------------------------------------------*
+     *  energy of code:                                                  *
+     *  ~~~~~~~~~~~~~~~                                                  *
+     *  ener_code = sum(code[i]^2)                                       *
+     *-------------------------------------------------------------------*
+    ener_code = L_mac((Word32) 0, code[0], code[0]);
+                                                 // MR122:  Q12*Q12 -> Q25
+                                                 // others: Q13*Q13 -> Q27
+    for (i = 1; i < L_SUBFR; i++)
+        ener_code = L_mac(ener_code, code[i], code[i]);
+
+    if (sub (mode, MR122) == 0)
+    {
+        Word32 ener;
+
+        // ener_code = ener_code / lcode; lcode = 40; 1/40 = 26214 Q20
+        ener_code = L_mult (pv_round (ener_code), 26214);   // Q9  * Q20 -> Q30
+
+         *-------------------------------------------------------------------*
+         *  energy of code:                                                  *
+         *  ~~~~~~~~~~~~~~~                                                  *
+         *  ener_code(Q17) = 10 * Log10(energy) / constant                   *
+         *                 = 1/2 * Log2(energy)                              *
+         *                                           constant = 20*Log10(2)  *
+         *-------------------------------------------------------------------*
+        // ener_code = 1/2 * Log2(ener_code); Note: Log2=log2+30
+        Log2(ener_code, &exp, &frac);
+        ener_code = L_Comp (sub (exp, 30), frac);     // Q16 for log()
+                                                    // ->Q17 for 1/2 log()
+
+         *-------------------------------------------------------------------*
+         *  predicted energy:                                                *
+         *  ~~~~~~~~~~~~~~~~~                                                *
+         *  ener(Q24) = (Emean + sum{pred[i]*past_en[i]})/constant           *
+         *            = MEAN_ENER + sum(pred[i]*past_qua_en[i])              *
+         *                                           constant = 20*Log10(2)  *
+         *-------------------------------------------------------------------*
+
+        ener = MEAN_ENER_MR122;                      // Q24 (Q17)
+        for (i = 0; i < NPRED; i++)
+        {
+            ener = L_mac (ener, st->past_qua_en_MR122[i], pred_MR122[i]);
+                                                     // Q10 * Q13 -> Q24
+                                                     // Q10 * Q6  -> Q17
+        }
+
+         *-------------------------------------------------------------------*
+         *  predicted codebook gain                                          *
+         *  ~~~~~~~~~~~~~~~~~~~~~~~                                          *
+         *  gc0     = Pow10( (ener*constant - ener_code*constant) / 20 )     *
+         *          = Pow2(ener-ener_code)                                   *
+         *          = Pow2(int(d)+frac(d))                                   *
+         *                                                                   *
+         *  (store exp and frac for pow2())                                  *
+         *-------------------------------------------------------------------*
+
+        ener = L_shr (L_sub (ener, ener_code), 1);                // Q16
+        L_Extract(ener, exp_gcode0, frac_gcode0);
+    }
+    else // all modes except 12.2
+    {
+        Word32 L_tmp;
+        Word16 exp_code, gcode0;
+
+         *-----------------------------------------------------------------*
+         *  Compute: means_ener - 10log10(ener_code/ L_sufr)               *
+         *-----------------------------------------------------------------*
+
+        exp_code = norm_l (ener_code);
+        ener_code = L_shl (ener_code, exp_code);
+
+        // Log2 = log2 + 27
+        Log2_norm (ener_code, exp_code, &exp, &frac);
+
+        // fact = 10/log2(10) = 3.01 = 24660 Q13
+        L_tmp = Mpy_32_16(exp, frac, -24660); // Q0.Q15 * Q13 -> Q14
+
+         *   L_tmp = means_ener - 10log10(ener_code/L_SUBFR)
+         *         = means_ener - 10log10(ener_code) + 10log10(L_SUBFR)
+         *         = K - fact * Log2(ener_code)
+         *         = K - fact * log2(ener_code) - fact*27
+         *
+         *   ==> K = means_ener + fact*27 + 10log10(L_SUBFR)
+         *
+         *   means_ener =       33    =  540672    Q14  (MR475, MR515, MR59)
+         *   means_ener =       28.75 =  471040    Q14  (MR67)
+         *   means_ener =       30    =  491520    Q14  (MR74)
+         *   means_ener =       36    =  589824    Q14  (MR795)
+         *   means_ener =       33    =  540672    Q14  (MR102)
+         *   10log10(L_SUBFR) = 16.02 =  262481.51 Q14
+         *   fact * 27                = 1331640    Q14
+         *   -----------------------------------------
+         *   (MR475, MR515, MR59)   K = 2134793.51 Q14 ~= 16678 * 64 * 2
+         *   (MR67)                 K = 2065161.51 Q14 ~= 32268 * 32 * 2
+         *   (MR74)                 K = 2085641.51 Q14 ~= 32588 * 32 * 2
+         *   (MR795)                K = 2183945.51 Q14 ~= 17062 * 64 * 2
+         *   (MR102)                K = 2134793.51 Q14 ~= 16678 * 64 * 2
+
+
+        if (sub (mode, MR102) == 0)
+        {
+            // mean = 33 dB
+            L_tmp = L_mac(L_tmp, 16678, 64);     // Q14
+        }
+        else if (sub (mode, MR795) == 0)
+        {
+            // ener_code  = <xn xn> * 2^27*2^exp_code
+            // frac_en    = ener_code / 2^16
+            //            = <xn xn> * 2^11*2^exp_code
+            // <xn xn>    = <xn xn>*2^11*2^exp * 2^exp_en
+            //           := frac_en            * 2^exp_en
+
+            // ==> exp_en = -11-exp_code;
+
+            *frac_en = extract_h (ener_code);
+            *exp_en = sub (-11, exp_code);
+
+            // mean = 36 dB
+            L_tmp = L_mac(L_tmp, 17062, 64);     // Q14
+        }
+        else if (sub (mode, MR74) == 0)
+        {
+            // mean = 30 dB
+            L_tmp = L_mac(L_tmp, 32588, 32);     // Q14
+        }
+        else if (sub (mode, MR67) == 0)
+        {
+            // mean = 28.75 dB
+            L_tmp = L_mac(L_tmp, 32268, 32);     // Q14
+        }
+        else // MR59, MR515, MR475
+        {
+            // mean = 33 dB
+            L_tmp = L_mac(L_tmp, 16678, 64);     // Q14
+        }
+
+         *-----------------------------------------------------------------*
+         * Compute gcode0.                                                 *
+         *  = Sum(i=0,3) pred[i]*past_qua_en[i] - ener_code + mean_ener    *
+         *-----------------------------------------------------------------*
+
+        L_tmp = L_shl(L_tmp, 10);                // Q24
+        for (i = 0; i < 4; i++)
+            L_tmp = L_mac(L_tmp, pred[i], st->past_qua_en[i]);
+                                                 // Q13 * Q10 -> Q24
+
+        gcode0 = extract_h(L_tmp);               // Q8
+
+         *-----------------------------------------------------------------*
+         * gcode0 = pow(10.0, gcode0/20)                                   *
+         *        = pow(2, 3.3219*gcode0/20)                               *
+         *        = pow(2, 0.166*gcode0)                                   *
+         *-----------------------------------------------------------------*
+
+        // 5439 Q15 = 0.165985
+        // (correct: 1/(20*log10(2)) 0.166096 = 5443 Q15)
+        if (sub (mode, MR74) == 0) // For IS641 bitexactness
+            L_tmp = L_mult(gcode0, 5439);  // Q8 * Q15 -> Q24
+        else
+            L_tmp = L_mult(gcode0, 5443);  // Q8 * Q15 -> Q24
+
+        L_tmp = L_shr(L_tmp, 8);                   //          -> Q16
+        L_Extract(L_tmp, exp_gcode0, frac_gcode0); //       -> Q0.Q15
+    }
+}
+
+------------------------------------------------------------------------------
+ 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 gc_pred(
+    gc_predState *st,   /* i/o: State struct                           */
+    enum Mode mode,     /* i  : AMR mode                               */
+    Word16 *code,       /* i  : innovative codebook vector (L_SUBFR)   */
+    /*      MR122: Q12, other modes: Q13           */
+    Word16 *exp_gcode0, /* o  : exponent of predicted gain factor, Q0  */
+    Word16 *frac_gcode0,/* o  : fraction of predicted gain factor  Q15 */
+    Word16 *exp_en,     /* o  : exponent of innovation energy,     Q0  */
+    /*      (only calculated for MR795)            */
+    Word16 *frac_en,    /* o  : fraction of innovation energy,     Q15 */
+    /*      (only calculated for MR795)            */
+    Flag   *pOverflow
+)
+{
+    register Word16 i;
+    register Word32 L_temp1, L_temp2;
+    register Word32 L_tmp;
+    Word32 ener_code;
+    Word32 ener;
+    Word16 exp, frac;
+    Word16 exp_code, gcode0;
+    Word16 tmp;
+    Word16 *p_code = &code[0];
+
+    /*-------------------------------------------------------------------*
+     *  energy of code:                                                  *
+     *  ~~~~~~~~~~~~~~~                                                  *
+     *  ener_code = sum(code[i]^2)                                       *
+     *-------------------------------------------------------------------*/
+    ener_code = 0;
+
+    /* MR122:  Q12*Q12 -> Q25 */
+    /* others: Q13*Q13 -> Q27 */
+
+    for (i = L_SUBFR >> 2; i != 0; i--)
+    {
+        tmp = *(p_code++);
+        ener_code += ((Word32) tmp * tmp) >> 3;
+        tmp = *(p_code++);
+        ener_code += ((Word32) tmp * tmp) >> 3;
+        tmp = *(p_code++);
+        ener_code += ((Word32) tmp * tmp) >> 3;
+        tmp = *(p_code++);
+        ener_code += ((Word32) tmp * tmp) >> 3;
+    }
+
+    ener_code <<= 4;
+
+    if (ener_code < 0)      /*  Check for saturation */
+    {
+        ener_code = MAX_32;
+    }
+
+    if (mode == MR122)
+    {
+        /* ener_code = ener_code / lcode; lcode = 40; 1/40 = 26214 Q20 */
+        /* Q9  * Q20 -> Q30 */
+
+        ener_code = ((Word32)(pv_round(ener_code, pOverflow) * 26214)) << 1;
+
+        /*-------------------------------------------------------------*
+         *  energy of code:                                            *
+         *  ~~~~~~~~~~~~~~~                                            *
+         *  ener_code(Q17) = 10 * Log10(energy) / constant             *
+         *                 = 1/2 * Log2(energy)                        *
+         *  constant = 20*Log10(2)                                     *
+         *-------------------------------------------------------------*/
+        /* ener_code = 1/2 * Log2(ener_code); Note: Log2=log2+30 */
+        Log2(ener_code, &exp, &frac, pOverflow);
+
+        /* Q16 for log()    */
+        /* ->Q17 for 1/2 log()*/
+
+        L_temp1 = (Word32)(exp - 30) << 16;
+        ener_code = L_temp1 + ((Word32)frac << 1);
+
+        /*-------------------------------------------------------------*
+         *  predicted energy:                                          *
+         *  ~~~~~~~~~~~~~~~~~                                          *
+         *  ener(Q24) = (Emean + sum{pred[i]*past_en[i]})/constant     *
+         *            = MEAN_ENER + sum(pred[i]*past_qua_en[i])        *
+         *  constant = 20*Log10(2)                                     *
+         *-------------------------------------------------------------*/
+
+        ener = MEAN_ENER_MR122;                   /* Q24 (Q17) */
+        for (i = 0; i < NPRED; i++)
+        {
+            L_temp1 = (((Word32) st->past_qua_en_MR122[i]) *
+                       pred_MR122[i]) << 1;
+            ener = L_add(ener, L_temp1, pOverflow);
+
+            /* Q10 * Q13 -> Q24 */
+            /* Q10 * Q6  -> Q17 */
+        }
+
+        /*---------------------------------------------------------------*
+         *  predicted codebook gain                                      *
+         *  ~~~~~~~~~~~~~~~~~~~~~~~                                      *
+         *  gc0     = Pow10( (ener*constant - ener_code*constant) / 20 ) *
+         *          = Pow2(ener-ener_code)                               *
+         *          = Pow2(int(d)+frac(d))                               *
+         *                                                               *
+         *  (store exp and frac for pow2())                              *
+         *---------------------------------------------------------------*/
+        /* Q16 */
+
+        L_temp1 = L_sub(ener, ener_code, pOverflow);
+
+
+        *exp_gcode0 = (Word16)(L_temp1 >> 17);
+
+        L_temp2 = (Word32) * exp_gcode0 << 15;
+        L_temp1 >>= 2;
+
+        *frac_gcode0 = (Word16)(L_temp1 - L_temp2);
+
+    }
+    else /* all modes except 12.2 */
+    {
+        /*-----------------------------------------------------------------*
+         *  Compute: means_ener - 10log10(ener_code/ L_sufr)               *
+         *-----------------------------------------------------------------*/
+
+        exp_code = norm_l(ener_code);
+        ener_code = L_shl(ener_code, exp_code, pOverflow);
+
+        /* Log2 = log2 + 27 */
+        Log2_norm(ener_code, exp_code, &exp, &frac);
+
+        /* fact = 10/log2(10) = 3.01 = 24660 Q13 */
+        /* Q0.Q15 * Q13 -> Q14 */
+
+        L_temp2 = (((Word32) exp) * -24660) << 1;
+        L_tmp = (((Word32) frac) * -24660) >> 15;
+
+        /* Sign-extend resulting product */
+        if (L_tmp & (Word32) 0x00010000L)
+        {
+            L_tmp = L_tmp | (Word32) 0xffff0000L;
+        }
+
+        L_tmp = L_tmp << 1;
+        L_tmp = L_add(L_tmp, L_temp2, pOverflow);
+
+
+        /*   L_tmp = means_ener - 10log10(ener_code/L_SUBFR)
+         *         = means_ener - 10log10(ener_code) + 10log10(L_SUBFR)
+         *         = K - fact * Log2(ener_code)
+         *         = K - fact * log2(ener_code) - fact*27
+         *
+         *   ==> K = means_ener + fact*27 + 10log10(L_SUBFR)
+         *
+         *   means_ener =       33    =  540672    Q14  (MR475, MR515, MR59)
+         *   means_ener =       28.75 =  471040    Q14  (MR67)
+         *   means_ener =       30    =  491520    Q14  (MR74)
+         *   means_ener =       36    =  589824    Q14  (MR795)
+         *   means_ener =       33    =  540672    Q14  (MR102)
+         *   10log10(L_SUBFR) = 16.02 =  262481.51 Q14
+         *   fact * 27                = 1331640    Q14
+         *   -----------------------------------------
+         *   (MR475, MR515, MR59)   K = 2134793.51 Q14 ~= 16678 * 64 * 2
+         *   (MR67)                 K = 2065161.51 Q14 ~= 32268 * 32 * 2
+         *   (MR74)                 K = 2085641.51 Q14 ~= 32588 * 32 * 2
+         *   (MR795)                K = 2183945.51 Q14 ~= 17062 * 64 * 2
+         *   (MR102)                K = 2134793.51 Q14 ~= 16678 * 64 * 2
+         */
+
+        if (mode == MR102)
+        {
+            /* mean = 33 dB */
+            L_temp2 = (Word32) 16678 << 7;
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);     /* Q14 */
+        }
+        else if (mode == MR795)
+        {
+            /* ener_code  = <xn xn> * 2^27*2^exp_code
+               frac_en    = ener_code / 2^16
+                          = <xn xn> * 2^11*2^exp_code
+               <xn xn>    = <xn xn>*2^11*2^exp * 2^exp_en
+            :                 = frac_en            * 2^exp_en
+                          ==> exp_en = -11-exp_code;      */
+            *frac_en = (Word16)(ener_code >> 16);
+            *exp_en = sub(-11, exp_code, pOverflow);
+
+            /* mean = 36 dB */
+            L_temp2 = (Word32) 17062 << 7;
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);     /* Q14 */
+        }
+        else if (mode == MR74)
+        {
+            /* mean = 30 dB */
+            L_temp2 = (Word32) 32588 << 6;
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);     /* Q14 */
+        }
+        else if (mode == MR67)
+        {
+            /* mean = 28.75 dB */
+            L_temp2 = (Word32) 32268 << 6;
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);     /* Q14 */
+        }
+        else /* MR59, MR515, MR475 */
+        {
+            /* mean = 33 dB */
+            L_temp2 = (Word32) 16678 << 7;
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);     /* Q14 */
+        }
+
+        /*-------------------------------------------------------------*
+         * Compute gcode0.                                              *
+         *  = Sum(i=0,3) pred[i]*past_qua_en[i] - ener_code + mean_ener *
+         *--------------------------------------------------------------*/
+        /* Q24 */
+        if (L_tmp > (Word32) 0X001fffffL)
+        {
+            *pOverflow = 1;
+            L_tmp = MAX_32;
+        }
+        else if (L_tmp < (Word32) 0xffe00000L)
+        {
+            *pOverflow = 1;
+            L_tmp = MIN_32;
+        }
+        else
+        {
+            L_tmp = L_tmp << 10;
+        }
+
+        for (i = 0; i < 4; i++)
+        {
+            L_temp2 = ((((Word32) pred[i]) * st->past_qua_en[i]) << 1);
+            L_tmp = L_add(L_tmp, L_temp2, pOverflow);  /* Q13 * Q10 -> Q24 */
+        }
+
+        gcode0 = (Word16)(L_tmp >> 16);               /* Q8  */
+
+        /*-----------------------------------------------------------*
+         * gcode0 = pow(10.0, gcode0/20)                             *
+         *        = pow(2, 3.3219*gcode0/20)                         *
+         *        = pow(2, 0.166*gcode0)                             *
+         *-----------------------------------------------------------*/
+
+        /* 5439 Q15 = 0.165985                                       */
+        /* (correct: 1/(20*log10(2)) 0.166096 = 5443 Q15)            */
+
+        if (mode == MR74) /* For IS641 bitexactness */
+        {
+            L_tmp = (((Word32) gcode0) * 5439) << 1;  /* Q8 * Q15 -> Q24 */
+        }
+        else
+        {
+            L_tmp = (((Word32) gcode0) * 5443) << 1;  /* Q8 * Q15 -> Q24 */
+        }
+
+        if (L_tmp < 0)
+        {
+            L_tmp = ~((~L_tmp) >> 8);
+        }
+        else
+        {
+            L_tmp = L_tmp >> 8;     /* -> Q16 */
+        }
+
+        *exp_gcode0 = (Word16)(L_tmp >> 16);
+        if (L_tmp < 0)
+        {
+            L_temp1 = ~((~L_tmp) >> 1);
+        }
+        else
+        {
+            L_temp1 = L_tmp >> 1;
+        }
+        L_temp2 = (Word32) * exp_gcode0 << 15;
+        *frac_gcode0 = (Word16)(L_sub(L_temp1, L_temp2, pOverflow));
+        /* -> Q0.Q15 */
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gc_pred_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type gc_predState
+    qua_ener_MR122 = quantized energy for update (Q10); calculated as
+             (log2(qua_err)) (Word16)
+    qua_ener = quantized energy for update (Q10); calculated as
+           (20*log10(qua_err)) (Word16)
+
+ Outputs:
+    structure pointed to by st contains the calculated quantized energy
+      for update
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function updates the MA predictor with the last quantized energy.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gc_pred.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void gc_pred_update(
+    gc_predState *st,      // i/o: State struct
+    Word16 qua_ener_MR122, // i  : quantized energy for update, Q10
+                           //      (log2(qua_err))
+    Word16 qua_ener        // i  : quantized energy for update, Q10
+                           //      (20*log10(qua_err))
+)
+{
+    Word16 i;
+
+    for (i = 3; i > 0; i--)
+    {
+        st->past_qua_en[i] = st->past_qua_en[i - 1];
+        st->past_qua_en_MR122[i] = st->past_qua_en_MR122[i - 1];
+    }
+
+    st->past_qua_en_MR122[0] = qua_ener_MR122;  //    log2 (qua_err), Q10
+
+    st->past_qua_en[0] = qua_ener;              // 20*log10(qua_err), Q10
+
+}
+
+------------------------------------------------------------------------------
+ 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 gc_pred_update(
+    gc_predState *st,      /* i/o: State struct                     */
+    Word16 qua_ener_MR122, /* i  : quantized energy for update, Q10 */
+    /*      (log2(qua_err))                  */
+    Word16 qua_ener        /* i  : quantized energy for update, Q10 */
+    /*      (20*log10(qua_err))              */
+)
+{
+    st->past_qua_en[3] = st->past_qua_en[2];
+    st->past_qua_en_MR122[3] = st->past_qua_en_MR122[2];
+
+    st->past_qua_en[2] = st->past_qua_en[1];
+    st->past_qua_en_MR122[2] = st->past_qua_en_MR122[1];
+
+    st->past_qua_en[1] = st->past_qua_en[0];
+    st->past_qua_en_MR122[1] = st->past_qua_en_MR122[0];
+
+    st->past_qua_en_MR122[0] = qua_ener_MR122; /*    log2 (qua_err), Q10 */
+
+    st->past_qua_en[0] = qua_ener;            /* 20*log10(qua_err), Q10 */
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gc_pred_average_limited
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type gc_predState
+    ener_avg_MR122 = pointer to the averaged quantized energy (Q10);
+             calculated as (log2(qua_err)) (Word16)
+    ener_avg = pointer to the averaged quantized energy (Q10); calculated
+           as (20*log10(qua_err)) (Word16)
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    store pointed to by ener_avg_MR122 contains the new averaged quantized
+      energy
+    store pointed to by ener_avg contains the new averaged quantized
+      energy
+    pOverflow = 1 if the math functions called by gc_pred_average_limited
+            results in overflow else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the average of MA predictor state values (with a
+ lower limit) used in error concealment.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gc_pred.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 gc_pred_average_limited(
+    gc_predState *st,       // i: State struct
+    Word16 *ener_avg_MR122, // o: everaged quantized energy,  Q10
+                            //    (log2(qua_err))
+    Word16 *ener_avg        // o: averaged quantized energy,  Q10
+                            //    (20*log10(qua_err))
+)
+{
+    Word16 av_pred_en;
+    Word16 i;
+
+    // do average in MR122 mode (log2() domain)
+    av_pred_en = 0;
+    for (i = 0; i < NPRED; i++)
+    {
+        av_pred_en = add (av_pred_en, st->past_qua_en_MR122[i]);
+    }
+
+    // av_pred_en = 0.25*av_pred_en
+    av_pred_en = mult (av_pred_en, 8192);
+
+    // if (av_pred_en < -14/(20Log10(2))) av_pred_en = ..
+
+    if (sub (av_pred_en, MIN_ENERGY_MR122) < 0)
+    {
+        av_pred_en = MIN_ENERGY_MR122;
+    }
+    *ener_avg_MR122 = av_pred_en;
+
+    // do average for other modes (20*log10() domain)
+    av_pred_en = 0;
+    for (i = 0; i < NPRED; i++)
+    {
+        av_pred_en = add (av_pred_en, st->past_qua_en[i]);
+    }
+
+    // av_pred_en = 0.25*av_pred_en
+    av_pred_en = mult (av_pred_en, 8192);
+
+    // if (av_pred_en < -14) av_pred_en = ..
+
+    if (sub (av_pred_en, MIN_ENERGY) < 0)
+    {
+        av_pred_en = MIN_ENERGY;
+    }
+    *ener_avg = av_pred_en;
+}
+
+------------------------------------------------------------------------------
+ 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 gc_pred_average_limited(
+    gc_predState *st,       /* i: State struct                    */
+    Word16 *ener_avg_MR122, /* o: everaged quantized energy,  Q10 */
+    /*    (log2(qua_err))                 */
+    Word16 *ener_avg,       /* o: averaged quantized energy,  Q10 */
+    /*    (20*log10(qua_err))             */
+    Flag *pOverflow
+)
+{
+    Word16 av_pred_en;
+    register Word16 i;
+
+    /* do average in MR122 mode (log2() domain) */
+    av_pred_en = 0;
+    for (i = 0; i < NPRED; i++)
+    {
+        av_pred_en =
+            add(av_pred_en, st->past_qua_en_MR122[i], pOverflow);
+    }
+
+    /* av_pred_en = 0.25*av_pred_en  (with sign-extension)*/
+    if (av_pred_en < 0)
+    {
+        av_pred_en = (av_pred_en >> 2) | 0xc000;
+    }
+    else
+    {
+        av_pred_en >>= 2;
+    }
+
+    /* if (av_pred_en < -14/(20Log10(2))) av_pred_en = .. */
+    if (av_pred_en < MIN_ENERGY_MR122)
+    {
+        av_pred_en = MIN_ENERGY_MR122;
+    }
+    *ener_avg_MR122 = av_pred_en;
+
+    /* do average for other modes (20*log10() domain) */
+    av_pred_en = 0;
+    for (i = 0; i < NPRED; i++)
+    {
+        av_pred_en = add(av_pred_en, st->past_qua_en[i], pOverflow);
+    }
+
+    /* av_pred_en = 0.25*av_pred_en  (with sign-extension)*/
+    if (av_pred_en < 0)
+    {
+        av_pred_en = (av_pred_en >> 2) | 0xc000;
+    }
+    else
+    {
+        av_pred_en >>= 2;
+    }
+
+    /* if (av_pred_en < -14) av_pred_en = .. */
+    if (av_pred_en < MIN_ENERGY)
+    {
+        av_pred_en = MIN_ENERGY;
+    }
+    *ener_avg = av_pred_en;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/gmed_n.cpp b/media/libstagefright/codecs/amrnb/common/src/gmed_n.cpp
new file mode 100644
index 0000000..be76241
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/gmed_n.cpp
@@ -0,0 +1,218 @@
+/* ------------------------------------------------------------------
+ * 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/gmed_n.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put file into template and first pass at optimization.
+
+ Description: Made changes based on comments from the review meeting. Used
+    pointers instead of index addressing in the arrays.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unncessary include files.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "gmed_n.h"
+#include    "typedef.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NMAX    9   /* largest N used in median calculation */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: gmed_n
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    ind = input values (Word16)
+    n = number of inputs to find the median (Word16)
+
+ Returns:
+    median value.
+
+ Outputs:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates N-point median of a data set. This routine is only
+ valid for a odd number of gains (n <= NMAX).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ gmed_n.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 gmed_n (   // o : The median value (0...N-1)
+    Word16 ind[], // i : Past gain values
+    Word16 n      // i : The number of gains; this routine
+                  //     is only valid for a odd number of gains
+                  //     (n <= NMAX)
+)
+{
+    Word16 i, j, ix = 0;
+    Word16 max;
+    Word16 medianIndex;
+    Word16 tmp[NMAX];
+    Word16 tmp2[NMAX];
+
+    for (i = 0; i < n; i++)
+    {
+        tmp2[i] = ind[i];
+    }
+
+    for (i = 0; i < n; i++)
+    {
+        max = -32767;
+        for (j = 0; j < n; j++)
+        {
+            if (sub (tmp2[j], max) >= 0)
+            {
+                max = tmp2[j];
+                ix = j;
+            }
+        }
+        tmp2[ix] = -32768;
+        tmp[i] = ix;
+    }
+
+    medianIndex=tmp[ shr(n,1) ];  // account for complex addressing
+    return (ind[medianIndex]);
+}
+
+------------------------------------------------------------------------------
+ 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 gmed_n(            /* o : the median value    */
+    Word16 ind[],   /* i : input values        */
+    Word16 n        /* i : number of inputs    */
+)
+{
+    register Word16 i, j, ix = 0;
+    register Word16 max;
+    register Word16 medianIndex;
+    Word16  tmp[NMAX];
+    Word16  tmp2[NMAX];
+
+    for (i = 0; i < n; i++)
+    {
+        *(tmp2 + i) = *(ind + i);
+    }
+
+    for (i = 0; i < n; i++)
+    {
+        max = -32767;
+        for (j = 0; j < n; j++)
+        {
+            if (*(tmp2 + j) >= max)
+            {
+                max = *(tmp2 + j);
+                ix = j;
+            }
+        }
+        *(tmp2 + ix) = -32768;
+        *(tmp + i) = ix;
+    }
+
+    medianIndex = *(tmp + (n >> 1));  /* account for complex addressing */
+
+    return (*(ind + medianIndex));
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/gray_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/gray_tbl.cpp
new file mode 100644
index 0000000..99073d9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/gray_tbl.cpp
@@ -0,0 +1,160 @@
+/* ------------------------------------------------------------------
+ * 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/gray_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for the gray encoding and decoding tables,
+ gray_tbl[] and dgray_tbl[] used by the c1035pf and d1035pf module
+ respectively.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 gray[8]  = {0, 1, 3, 2, 6, 4, 5, 7};
+    extern const Word16 dgray[8] = {0, 1, 3, 2, 5, 6, 4, 7};
+
+    /*--------------------------------------------------------------------------*/
+#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] gray.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/common/src/grid_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/grid_tbl.cpp
new file mode 100644
index 0000000..cd81566
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/grid_tbl.cpp
@@ -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/src/grid_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for grid_tbl[] used by the az_lsp()
+ function.
+
+ //  Table for az_lsp()
+ //
+ // grid[0] = 1.0;
+ // grid[grid_points+1] = -1.0;
+ // for (i = 1; i < grid_points; i++)
+ //   grid[i] = cos((6.283185307*i)/(2.0*grid_points));
+ //
+ //
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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.]
+    ----------------------------------------------------------------------------*/
+#define grid_points 60
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; [Variable declaration - defined here and used outside this module]
+    ----------------------------------------------------------------------------*/
+    extern const Word16 grid[grid_points + 1] =
+    {
+        32760, 32723, 32588, 32364, 32051, 31651,
+        31164, 30591, 29935, 29196, 28377, 27481,
+        26509, 25465, 24351, 23170, 21926, 20621,
+        19260, 17846, 16384, 14876, 13327, 11743,
+        10125, 8480, 6812, 5126, 3425, 1714,
+        0, -1714, -3425, -5126, -6812, -8480,
+        -10125, -11743, -13327, -14876, -16384, -17846,
+        -19260, -20621, -21926, -23170, -24351, -25465,
+        -26509, -27481, -28377, -29196, -29935, -30591,
+        -31164, -31651, -32051, -32364, -32588, -32723,
+        -32760
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] grid.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/common/src/int_lpc.cpp b/media/libstagefright/codecs/amrnb/common/src/int_lpc.cpp
new file mode 100644
index 0000000..806474d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/int_lpc.cpp
@@ -0,0 +1,633 @@
+/* ------------------------------------------------------------------
+ * 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/int_lpc.c
+ Functions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Per review comments, replaced includes of "basic_op.h"
+ and "count.h" with "shr.h", "sub.h", and "add.h"
+
+ Description:  For Int_lpc_1and3()  and Int_lpc_1and3_2()
+              1. Replaced array addressing by pointers
+              2. Eliminated math operations that unnecessary checked for
+                 saturation
+              3. Unrolled loops to speed up processing
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "int_lpc.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "lsp_az.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: Int_lpc_1and3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp_old -- array of type Word16 -- LSP vector at the
+                                       4th subfr. of past frame (M)
+    lsp_mid -- array of type Word16 -- LSP vector at the 2nd subfr. of
+                                       present frame (M)
+    lsp_new -- array of type Word16 -- LSP vector at the 4th subfr. of
+                                       present frame (M)
+
+ Outputs:
+    Az -- array of type Word16 -- interpolated LP parameters in all subfr.
+                                  (AZ_SIZE)
+    pOverflow -- pointer to type Flag -- Overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose     : Interpolates the LSPs and converts to LPC parameters
+               to get a different LP filter in each subframe.
+ Description : The 20 ms speech frame is divided into 4 subframes.
+               The LSPs are quantized and transmitted at the 2nd and
+               4th subframes (twice per frame) and interpolated at the
+               1st and 3rd subframe.
+
+                     |------|------|------|------|
+                        sf1    sf2    sf3    sf4
+                  F0            Fm            F1
+
+                sf1:   1/2 Fm + 1/2 F0         sf3:   1/2 F1 + 1/2 Fm
+                sf2:       Fm                  sf4:       F1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ int_lpc.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 Int_lpc_1and3(
+    Word16 lsp_old[],  /* i : LSP vector at the 4th subfr. of past frame (M) */
+    Word16 lsp_mid[],  /* i : LSP vector at the 2nd subfr. of
+                              present frame (M)                              */
+    Word16 lsp_new[],  /* i : LSP vector at the 4th subfr. of
+                              present frame (M)                              */
+    Word16 Az[],       /* o : interpolated LP parameters in all subfr.
+                              (AZ_SIZE)                                      */
+    Flag  *pOverflow
+)
+{
+    Word16 i;
+    Word16 lsp[M];
+    Word16 *p_lsp_old = &lsp_old[0];
+    Word16 *p_lsp_mid = &lsp_mid[0];
+    Word16 *p_lsp_new = &lsp_new[0];
+    Word16 *p_lsp     = &lsp[0];
+
+    /*  lsp[i] = lsp_mid[i] * 0.5 + lsp_old[i] * 0.5 */
+
+    for (i = M >> 1; i != 0; i--)
+    {
+        *(p_lsp++) = (*(p_lsp_old++) >> 1) + (*(p_lsp_mid++) >> 1);
+        *(p_lsp++) = (*(p_lsp_old++) >> 1) + (*(p_lsp_mid++) >> 1);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);       /* Subframe 1 */
+
+    Az += MP1;
+
+    Lsp_Az(
+        lsp_mid,
+        Az,
+        pOverflow);       /* Subframe 2 */
+
+    Az += MP1;
+
+    p_lsp_mid = &lsp_mid[0];
+    p_lsp     = &lsp[0];
+
+    for (i = M >> 1; i != 0; i--)
+    {
+        *(p_lsp++) = (*(p_lsp_mid++) >> 1) + (*(p_lsp_new++) >> 1);
+        *(p_lsp++) = (*(p_lsp_mid++) >> 1) + (*(p_lsp_new++) >> 1);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);           /* Subframe 3 */
+
+    Az += MP1;
+
+    Lsp_Az(
+        lsp_new,
+        Az,
+        pOverflow);       /* Subframe 4 */
+
+    return;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Int_lpc_1and3_2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp_old -- array of type Word16 -- LSP vector at the
+                                       4th subfr. of past frame (M)
+    lsp_mid -- array of type Word16 -- LSP vector at the 2nd subfr. of
+                                       present frame (M)
+    lsp_new -- array of type Word16 -- LSP vector at the 4th subfr. of
+                                       present frame (M)
+
+ Outputs:
+    Az -- array of type Word16 -- interpolated LP parameters in.
+                                  subfr 1 and 2.
+    pOverflow -- pointer to type Flag -- Overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose : Interpolation of the LPC parameters. Same as the Int_lpc
+           function but we do not recompute Az() for subframe 2 and
+           4 because it is already available.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ int_lpc.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 Int_lpc_1and3_2(
+    Word16 lsp_old[],  /* i : LSP vector at the 4th subfr. of past frame (M) */
+    Word16 lsp_mid[],  /* i : LSP vector at the 2nd subframe of
+                             present frame (M)                               */
+    Word16 lsp_new[],  /* i : LSP vector at the 4th subframe of
+                             present frame (M)                               */
+    Word16 Az[],       /* o :interpolated LP parameters
+                             in subframes 1 and 3 (AZ_SIZE)                  */
+    Flag  *pOverflow
+)
+{
+    Word16 i;
+    Word16 lsp[M];
+    Word16 *p_lsp_old = &lsp_old[0];
+    Word16 *p_lsp_mid = &lsp_mid[0];
+    Word16 *p_lsp_new = &lsp_new[0];
+    Word16 *p_lsp     = &lsp[0];
+
+    /*  lsp[i] = lsp_mid[i] * 0.5 + lsp_old[i] * 0.5 */
+
+    for (i = M >> 1; i != 0; i--)
+    {
+        *(p_lsp++) = (*(p_lsp_old++) >> 1) + (*(p_lsp_mid++) >> 1);
+        *(p_lsp++) = (*(p_lsp_old++) >> 1) + (*(p_lsp_mid++) >> 1);
+    }
+    Lsp_Az(lsp, Az, pOverflow);            /* Subframe 1 */
+    Az += MP1 * 2;
+
+    p_lsp_mid = &lsp_mid[0];
+    p_lsp     = &lsp[0];
+
+    for (i = M >> 1; i != 0; i--)
+    {
+        *(p_lsp++) = (*(p_lsp_mid++) >> 1) + (*(p_lsp_new++) >> 1);
+        *(p_lsp++) = (*(p_lsp_mid++) >> 1) + (*(p_lsp_new++) >> 1);
+    }
+
+    Lsp_Az(lsp, Az, pOverflow);            /* Subframe 3 */
+
+    return;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp_old -- array of type Word16 -- LSP vector at the
+                                       4th subfr. of past frame (M)
+    lsp_new -- array of type Word16 -- LSP vector at the 4th subfr. of
+                                       present frame (M)
+
+ Outputs:
+    Az -- array of type Word16 -- interpolated LP parameters in.
+                                  all subframes.
+    pOverflow -- pointer to type Flag -- Overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Interpolates the LSPs and convert to LP parameters to get
+           a different LP filter in each subframe.
+
+ DESCRIPTION:
+    The 20 ms speech frame is divided into 4 subframes.
+    The LSPs are quantized and transmitted at the 4th subframe
+    (once per frame) and interpolated at the 1st, 2nd and 3rd subframe.
+
+         |------|------|------|------|
+            sf1    sf2    sf3    sf4
+      F0                          F1
+
+    sf1:   3/4 F0 + 1/4 F1         sf3:   1/4 F0 + 3/4 F1
+    sf2:   1/2 F0 + 1/2 F1         sf4:       F1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ int_lpc.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 Int_lpc_1to3(
+    Word16 lsp_old[], /* input : LSP vector at the 4th SF of past frame    */
+    Word16 lsp_new[], /* input : LSP vector at the 4th SF of present frame */
+    Word16 Az[],      /* output: interpolated LP parameters in all SFs     */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 temp;
+    Word16 temp2;
+
+    Word16 lsp[M];
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_old[i], 2, pOverflow);
+        temp = sub(lsp_old[i], temp, pOverflow);
+        temp2 = shr(lsp_new[i], 2, pOverflow);
+
+        lsp[i] = add(temp2, temp, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);        /* Subframe 1 */
+
+    Az += MP1;
+
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_new[i], 1, pOverflow);
+        temp2 = shr(lsp_old[i], 1, pOverflow);
+        lsp[i] = add(temp, temp2, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);        /* Subframe 2 */
+
+    Az += MP1;
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_new[i], 2, pOverflow);
+        temp = sub(lsp_new[i], temp, pOverflow);
+        temp2 = shr(lsp_old[i], 2, pOverflow);
+
+        lsp[i] = add(temp2, temp, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);       /* Subframe 3 */
+
+    Az += MP1;
+
+    Lsp_Az(
+        lsp_new,
+        Az,
+        pOverflow);        /* Subframe 4 */
+
+    return;
+}
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Int_lpc_1to3_2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp_old -- array of type Word16 -- LSP vector at the
+                                       4th subfr. of past frame (M)
+    lsp_new -- array of type Word16 -- LSP vector at the 4th subfr. of
+                                       present frame (M)
+
+ Outputs:
+    Az -- array of type Word16 -- interpolated LP parameters in.
+                                  subfr 1, 2, and 3.
+    pOverflow -- pointer to type Flag -- Overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Interpolation of the LPC parameters.
+ Same as the previous function but we do not recompute Az() for
+ subframe 4 because it is already available.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ int_lpc.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 Int_lpc_1to3_2(
+    Word16 lsp_old[],  /* input : LSP vector at the 4th SF of past frame    */
+    Word16 lsp_new[],  /* input : LSP vector at the 4th SF of present frame */
+    Word16 Az[],       /* output: interpolated LP parameters in SFs 1,2,3   */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 temp;
+    Word16 temp2;
+    Word16 lsp[M];
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_old[i], 2, pOverflow);
+
+        temp = sub(lsp_old[i], temp, pOverflow);
+
+        temp2 = shr(lsp_new[i], 2, pOverflow);
+
+        lsp[i] = add(temp2, temp, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);        /* Subframe 1 */
+
+    Az += MP1;
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_new[i], 1, pOverflow);
+        temp2 = shr(lsp_old[i], 1, pOverflow);
+
+        lsp[i] = add(temp2, temp, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);        /* Subframe 2 */
+
+    Az += MP1;
+
+    for (i = 0; i < M; i++)
+    {
+        temp = shr(lsp_new[i], 2, pOverflow);
+        temp = sub(lsp_new[i], temp, pOverflow);
+        temp2 = shr(lsp_old[i], 2, pOverflow);
+
+        lsp[i] = add(temp, temp2, pOverflow);
+    }
+
+    Lsp_Az(
+        lsp,
+        Az,
+        pOverflow);        /* Subframe 3 */
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/inv_sqrt.cpp b/media/libstagefright/codecs/amrnb/common/src/inv_sqrt.cpp
new file mode 100644
index 0000000..83f4d0c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/inv_sqrt.cpp
@@ -0,0 +1,270 @@
+/* ------------------------------------------------------------------
+ * 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/inv_sqrt.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put file into template.
+
+ 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. Defined one local variable per line.
+              2. Used "&=", ">>=", and "+=" in the code.
+
+ Description: Updated template. Changed function interface to pass in a
+              pointer to overflow flag into the function instead of using a
+              global flag.
+
+ Description: Removed inclusion of inv_sqrt.tab file. Changed array name
+              from "table" to "inv_sqrt_tbl"
+
+ Description: Removed math operations that were not needed as functions,
+             this because the numbers themselves will not saturate the
+             operators, so there is not need to check for saturation.
+
+ Description: Updated copyrigth year, according to code review comments.
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "inv_sqrt.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 STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Inv_sqrt
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_x = input value (Word32)
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    pOverflow -> if the Inv_sqrt operation resulted in an overflow.
+
+ Returns:
+    L_y = inverse squareroot of L_x (Word32)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes 1/sqrt(L_x), where L_x is positive.
+ If L_x is negative or zero, the result is 1 (3fff ffff).
+
+ The function 1/sqrt(L_x) is approximated by a table and linear
+ interpolation. The inverse square root is computed using the
+ following steps:
+    1- Normalization of L_x.
+    2- If (30-exponent) is even then shift right once.
+    3- exponent = (30-exponent)/2  +1
+    4- i = bit25-b31 of L_x;  16<=i<=63  because of normalization.
+    5- a = bit10-b24
+    6- i -=16
+    7- L_y = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+    8- L_y >>= exponent
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ inv_sqrt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 Inv_sqrt (       // (o) : output value
+    Word32 L_x          // (i) : input value
+)
+{
+    Word16 exp, i, a, tmp;
+    Word32 L_y;
+
+* The reference ETSI code uses a global Overflow flag. In the actual
+* implementation a pointer to the overflow flag is passed into the function.
+* This pointer is in turn passed into the basic math functions such as add(),
+* L_shl(), L_shr(), sub() called by this module.
+
+    if (L_x <= (Word32) 0)
+        return ((Word32) 0x3fffffffL);
+
+    exp = norm_l (L_x);
+    L_x = L_shl (L_x, exp);     // L_x is normalize
+
+    exp = sub (30, exp);
+
+    if ((exp & 1) == 0)         // If exponent even -> shift right
+    {
+        L_x = L_shr (L_x, 1);
+    }
+    exp = shr (exp, 1);
+    exp = add (exp, 1);
+
+    L_x = L_shr (L_x, 9);
+    i = extract_h (L_x);        // Extract b25-b31
+    L_x = L_shr (L_x, 1);
+    a = extract_l (L_x);        // Extract b10-b24
+    a = a & (Word16) 0x7fff;
+
+    i = sub (i, 16);
+
+    L_y = L_deposit_h (table[i]);       // table[i] << 16
+    tmp = sub (table[i], table[i + 1]); // table[i] - table[i+1])
+    L_y = L_msu (L_y, tmp, a);  // L_y -=  tmp*a*2
+
+    L_y = L_shr (L_y, exp);     // denormalization
+
+    return (L_y);
+}
+
+------------------------------------------------------------------------------
+ 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]
+
+------------------------------------------------------------------------------
+*/
+
+Word32 Inv_sqrt(        /* (o) : output value   */
+    Word32 L_x,         /* (i) : input value    */
+    Flag   * pOverflow  /* (i) : pointer to overflow flag */
+)
+{
+    Word16 exp;
+    Word16 i;
+    Word16 a;
+    Word16 tmp;
+    Word32 L_y;
+    OSCL_UNUSED_ARG(pOverflow);
+
+    if (L_x <= (Word32) 0)
+    {
+        return ((Word32) 0x3fffffffL);
+    }
+
+    exp = norm_l(L_x);
+    L_x <<= exp;         /* L_x is normalize */
+
+    exp = 30 - exp;
+
+    if ((exp & 1) == 0)             /* If exponent even -> shift right */
+    {
+        L_x >>= 1;
+    }
+    exp >>= 1;
+    exp += 1;
+
+    L_x >>= 9;
+    i = (Word16)(L_x >> 16);        /* Extract b25-b31 */
+    a = (Word16)(L_x >> 1);         /* Extract b10-b24 */
+    a &= (Word16) 0x7fff;
+
+    i -= 16;
+
+    L_y = (Word32)inv_sqrt_tbl[i] << 16;    /* inv_sqrt_tbl[i] << 16    */
+
+    /* inv_sqrt_tbl[i] - inv_sqrt_tbl[i+1])  */
+    tmp =  inv_sqrt_tbl[i] - inv_sqrt_tbl[i + 1];
+    /* always a positive number less than 200 */
+
+    L_y -= ((Word32)tmp * a) << 1;        /* L_y -=  tmp*a*2         */
+    /* always a positive minus a small negative number */
+
+    L_y >>= exp;                /* denormalization, exp always 0< exp < 31 */
+
+    return (L_y);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/inv_sqrt_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/inv_sqrt_tbl.cpp
new file mode 100644
index 0000000..bde2c4e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/inv_sqrt_tbl.cpp
@@ -0,0 +1,167 @@
+/* ------------------------------------------------------------------
+ * 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/inv_sqrt_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed table name to inv_sqrt_tbl
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for table[] used by the inv_sqrt function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 inv_sqrt_tbl[49] =
+    {
+
+        32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,
+        25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,
+        21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,
+        19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,
+        17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] inv_sqrt.tab file,  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/common/src/l_abs.cpp b/media/libstagefright/codecs/amrnb/common/src/l_abs.cpp
new file mode 100644
index 0000000..fd1c90d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/l_abs.cpp
@@ -0,0 +1,193 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/l_abs.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the L_abs function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ 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 = absolute value of input (Word32)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the absolute value of L_var1; saturate in case
+ where the input is -214783648.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 L_abs (Word32 L_var1)
+{
+    Word32 L_var_out;
+
+    if (L_var1 == MIN_32)
+    {
+        L_var_out = MAX_32;
+    }
+    else
+    {
+        if (L_var1 < 0)
+        {
+            L_var_out = -L_var1;
+        }
+        else
+        {
+            L_var_out = L_var1;
+        }
+    }
+
+#if (WMOPS)
+    multiCounter[currCounter].L_abs++;
+#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_abs(register Word32 L_var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    Word32 y = L_var1 - (L_var1 < 0);
+    y = y ^(y >> 31);
+    return (y);
+
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_deposit_h.cpp b/media/libstagefright/codecs/amrnb/common/src/l_deposit_h.cpp
new file mode 100644
index 0000000..e705ed1
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/l_deposit_h.cpp
@@ -0,0 +1,177 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/l_deposit_h.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the L_deposit_h function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var1 = deposit of var1 into MSWord of 32 bit value (Word32)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function deposits the 16 bit var1 into the 16 MS bits of the 32 bit
+ output. The 16 LS bits of the output are zeroed.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 L_deposit_h (Word16 var1)
+{
+    Word32 L_var_out;
+
+    L_var_out = (Word32) var1 << 16;
+#if (WMOPS)
+    multiCounter[currCounter].L_deposit_h++;
+#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_deposit_h(Word16 var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return ((Word32) var1 << 16);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_deposit_l.cpp b/media/libstagefright/codecs/amrnb/common/src/l_deposit_l.cpp
new file mode 100644
index 0000000..5064fdb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/l_deposit_l.cpp
@@ -0,0 +1,177 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/l_deposit_l.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the L_deposit_l function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var1 = deposit of var1 into LSWord of 32 bit value (Word32)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function deposits the 16 bit var1 into the 16 LS bits of the 32 bit
+ output. The 16 MS bits of the output are sign extended.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 L_deposit_l (Word16 var1)
+{
+    Word32 L_var_out;
+
+    L_var_out = (Word32) var1;
+#if (WMOPS)
+    multiCounter[currCounter].L_deposit_l++;
+#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_deposit_l(Word16 var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return ((Word32) var1);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/l_shr_r.cpp b/media/libstagefright/codecs/amrnb/common/src/l_shr_r.cpp
new file mode 100644
index 0000000..f609a73
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/l_shr_r.cpp
@@ -0,0 +1,214 @@
+/* ------------------------------------------------------------------
+ * 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_shr_r.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the L_shr_r function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Updated template. Changed function interface to pass in a
+              pointer to overflow flag into the function instead of using a
+              global flag. Removed code that updates MOPS counter. Changed
+              function return value name from "L_var_out" to "result".
+
+ Who:                       Date:
+ 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_shr_r
+------------------------------------------------------------------------------
+ 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.
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the 32 bit shift operation resulted in overflow
+
+ Returns:
+    result = Shifted result w/ rounding (Word32)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function arithmetically shifts the 32 bit input L_var1 right var2
+ positions with rounding. If var2 is negative, the function
+ arithmetically shifts L_var1 left by -var2 and zero fills the -var2 LSB of
+ the result. The result is saturated in case of underflows or overflows, i.e.,
+
+ - If var2 is greater than zero :
+    if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))
+    is equal to zero
+    then
+        L_shr_r(L_var1,var2) = L_shr(L_var1,var2)
+    else
+        L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1)
+ - If var2 is less than or equal to zero :
+    L_shr_r(L_var1,var2) = L_shr(L_var1,var2).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] L_shr_r() function in basic_op2.c,  UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 L_shr_r (Word32 L_var1, Word16 var2)
+{
+    Word32 L_var_out;
+
+* The reference ETSI code uses a global flag for Overflow. In the actual
+* implementation a pointer to Overflow flag is passed in as a parameter to the
+* function L_shr()
+
+    if (var2 > 31)
+    {
+        L_var_out = 0;
+    }
+    else
+    {
+        L_var_out = L_shr (L_var1, var2);
+#if (WMOPS)
+        multiCounter[currCounter].L_shr--;
+#endif
+        if (var2 > 0)
+        {
+            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
+            {
+                L_var_out++;
+            }
+        }
+    }
+#if (WMOPS)
+    multiCounter[currCounter].L_shr_r++;
+#endif
+    return (L_var_out);
+}
+
+------------------------------------------------------------------------------
+ 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
+----------------------------------------------------------------------------*/
+Word32 L_shr_r(register Word32 L_var1, register Word16 var2, Flag *pOverflow)
+{
+    Word32 result;
+
+    if (var2 > 31)
+    {
+        result = 0;
+    }
+    else
+    {
+        result = L_shr(L_var1, var2, pOverflow);
+
+        if (var2 > 0)
+        {
+            if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0)
+            {
+                result++;
+            }
+        }
+    }
+    return (result);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2.cpp b/media/libstagefright/codecs/amrnb/common/src/log2.cpp
new file mode 100644
index 0000000..0ada423
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/log2.cpp
@@ -0,0 +1,179 @@
+/* ------------------------------------------------------------------
+ * 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/log2.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. Moved Log2_norm
+          function to its own file.
+
+ Description: Changed l_shl.c to l_shl.h in Include section.
+
+ Description: Updated template. Changed function interface to pass in a
+              pointer to overflow flag into the function instead of using a
+              global flag. Changed input pointer names for clarity.
+
+ Description:
+              1. Eliminated l_shl function knowing that after normalization
+                 the left shift factor will not saturate.
+              2. Eliminated unused include files typedef.h and l_shl.h.
+
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "log2.h"
+#include "basic_op.h"
+#include "log2_norm.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: log2()
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_x = input value of type Word32
+    pExponent = pointer to the integer part of Log2 of type Word16 whose
+           valid range is: 0 <= value <= 30
+    pFraction = pointer to the fractional part of Log2 of type Word16
+           whose valid range is: 0 <= value < 1
+    pOverflow = pointer to overflow flag
+
+
+ Outputs:
+    pExponent -> integer part of the newly calculated Log2
+    pFraction -> fractional part of the newly calculated Log2
+    pOverflow -> 1 if the log2() operation resulted in saturation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes logarithm (base2) of the input L_x, where L_x is
+ positive. If L_x is negative or zero, the result is 0.
+
+ This function first normalizes the input L_x and calls the function Log2_norm
+ to calculate the logarithm.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] log2.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 Log2(
+    Word32 L_x,         /* (i) : input value                                */
+    Word16 *pExponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30)*/
+    Word16 *pFraction,  /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+    Flag   *pOverflow   /* (i/o) : overflow flag                            */
+)
+{
+    Word16 exp;
+    Word32 result;
+    OSCL_UNUSED_ARG(pOverflow);
+
+    exp = norm_l(L_x);
+    result = L_x << exp;
+    Log2_norm(result, exp, pExponent, pFraction);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2_norm.cpp b/media/libstagefright/codecs/amrnb/common/src/log2_norm.cpp
new file mode 100644
index 0000000..feda874
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/log2_norm.cpp
@@ -0,0 +1,238 @@
+/* ------------------------------------------------------------------
+ * 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/log2_norm.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for Log2_norm function.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Modified code to improve performance.
+              2. Fixed typecasting issue with TI C compiler.
+              3. Added more comments to the code.
+
+ Description: Removed unnecessary line of code (line 208).
+
+ Description: Removed inclusion of "log2.tab"
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "log2_norm.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: Log2_norm
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_x = normalized input value of type Word32
+    exp = number of shifts required to normalize L_x; it is of type Word16
+    exponent = pointer to the integer part of Log2 (of type Word16)
+           whose valid range is: 0 <= value <= 30
+    fraction = pointer to the fractional part of Log2 (of type Word16)
+           whose valid range is: 0 <= value < 1
+
+ Outputs:
+    exponent points to the newly calculated integer part of Log2
+    fraction points to the newly calculated fractional part of Log2
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    table = Log2 table of constants of type Word16
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ The function Log2(L_x) calculates the logarithm of the normalized input
+ buffer L_x. The logarithm is approximated by a table and linear
+ interpolation. The following steps are used to compute Log2(L_x):
+
+ 1. exponent = 30 - norm_exponent
+ 2. i = bit25-b31 of L_x;  32<=i<=63  (because of normalization).
+ 3. a = bit10-b24
+ 4. i = i - 32
+ 5. fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ log2.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Log2_norm (
+    Word32 L_x,         // (i) : input value (normalized)
+    Word16 exp,         // (i) : norm_l (L_x)
+    Word16 *exponent,   // (o) : Integer part of Log2.   (range: 0<=val<=30)
+    Word16 *fraction    // (o) : Fractional part of Log2. (range: 0<=val<1)
+)
+{
+    Word16 i, a, tmp;
+    Word32 L_y;
+
+    if (L_x <= (Word32) 0)
+    {
+        *exponent = 0;
+        *fraction = 0;
+        return;
+    }
+
+    *exponent = sub (30, exp);
+
+    L_x = L_shr (L_x, 9);
+    i = extract_h (L_x);                // Extract b25-b31
+    L_x = L_shr (L_x, 1);
+    a = extract_l (L_x);                // Extract b10-b24 of fraction
+    a = a & (Word16) 0x7fff;
+
+    i = sub (i, 32);
+
+    L_y = L_deposit_h (table[i]);       // table[i] << 16
+    tmp = sub (table[i], table[i + 1]); // table[i] - table[i+1]
+    L_y = L_msu (L_y, tmp, a);          // L_y -= tmp*a*2
+
+    *fraction = extract_h (L_y);
+
+    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 Log2_norm(
+    Word32 L_x,         /* (i) : input value (normalized)                   */
+    Word16 exp,         /* (i) : norm_l (L_x)                               */
+    Word16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30)*/
+    Word16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+)
+{
+    Word16 i, a, tmp;
+    Word32 L_y;
+
+    if (L_x <= (Word32) 0)
+    {
+        *exponent = 0;
+        *fraction = 0;
+    }
+    else
+    {
+        /* Calculate exponent portion of Log2 */
+        *exponent = 30 - exp;
+
+        /* At this point, L_x > 0       */
+        /* Shift L_x to the right by 10 to extract bits 10-31,  */
+        /* which is needed to calculate fractional part of Log2 */
+        L_x >>= 10;
+        i = (Word16)(L_x >> 15);    /* Extract b25-b31 */
+        a = L_x & 0x7fff;           /* Extract b10-b24 of fraction */
+
+        /* Calculate table index -> subtract by 32 is done for           */
+        /* proper table indexing, since 32<=i<=63 (due to normalization) */
+        i -= 32;
+
+        /* Fraction part of Log2 is approximated by using table[]    */
+        /* and linear interpolation, i.e.,                           */
+        /* fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2 */
+        L_y = (Word32) log2_tbl[i] << 16;  /* table[i] << 16        */
+        tmp = log2_tbl[i] - log2_tbl[i + 1];  /* table[i] - table[i+1] */
+        L_y -= (((Word32) tmp) * a) << 1; /* L_y -= tmp*a*2        */
+
+        *fraction = (Word16)(L_y >> 16);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/log2_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/log2_tbl.cpp
new file mode 100644
index 0000000..25d63b2
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/log2_tbl.cpp
@@ -0,0 +1,164 @@
+/* ------------------------------------------------------------------
+ * 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/log2_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for log2_tbl[] used by the log2() and
+ log2_norm() function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 log2_tbl[33] =
+    {
+        0, 1455, 2866, 4236, 5568, 6863, 8124, 9352, 10549, 11716,
+        12855, 13967, 15054, 16117, 17156, 18172, 19167, 20142, 21097, 22033,
+        22951, 23852, 24735, 25603, 26455, 27291, 28113, 28922, 29716, 30497,
+        31266, 32023, 32767
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] log2.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/common/src/lsfwt.cpp b/media/libstagefright/codecs/amrnb/common/src/lsfwt.cpp
new file mode 100644
index 0000000..6b511f7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsfwt.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/lsfwt.c
+ Functions: Lsf_wt
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated to accept new parameter, Flag *pOverflow.  Placed
+ file in the proper PV Software template.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation, by evaluating the operands
+              4. Unrolled loops to speed up processing, use decrement loops
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Who:                       Date:
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf -- Pointer to Word16 -- LSF vector
+
+ Outputs:
+    wf -- Pointer to Word16 -- square of weighting factors
+    pOverflow -- Pointer to type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+Compute LSF weighting factors
+
+ d[i] = lsf[i+1] - lsf[i-1]
+
+ The weighting factors are approximated by two line segment
+
+ First segment passes by the following 2 points:
+
+    d[i] = 0Hz     wf[i] = 3.347
+    d[i] = 450Hz   wf[i] = 1.8
+
+ Second segment passes by the following 2 points:
+
+    d[i] = 450Hz   wf[i] = 1.8
+    d[i] = 1500Hz  wf[i] = 1.0
+
+ if( d[i] < 450Hz )
+   wf[i] = 3.347 - ( (3.347-1.8) / (450-0)) *  d[i]
+ else
+   wf[i] = 1.8 - ( (1.8-1.0) / (1500-450)) *  (d[i] - 450)
+
+
+ if( d[i] < 1843)
+   wf[i] = 3427 - (28160*d[i])>>15
+ else
+   wf[i] = 1843 - (6242*(d[i]-1843))>>15
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsfwt.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 "lsfwt.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 Lsf_wt(
+    Word16 *lsf,         /* input : LSF vector                  */
+    Word16 *wf,          /* output: square of weighting factors */
+    Flag   *pOverflow
+)
+{
+    Word16 temp;
+    Word16 wgt_fct;
+    Word16 i;
+    Word16 *p_wf = wf;
+    Word16 *p_lsf   = &lsf[0];
+    Word16 *p_lsf_2 = &lsf[1];
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    /* wf[0] = lsf[1] - 0  */
+    *(p_wf++) = *(p_lsf_2++);
+
+    for (i = 4; i != 0 ; i--)
+    {
+        *(p_wf++) = *(p_lsf_2++) - *(p_lsf++);
+        *(p_wf++) = *(p_lsf_2++) - *(p_lsf++);
+    }
+    /*
+     *  wf[9] = 4000 - lsf[8]
+     */
+    *(p_wf) = 16384 - *(p_lsf);
+
+    p_wf = wf;
+
+    for (i = 10; i != 0; i--)
+    {
+        /*
+         *  (wf[i] - 450);
+         *  1843 == 450 Hz (Q15 considering 7FFF = 8000 Hz)
+         */
+        wgt_fct = *p_wf;
+        temp =  wgt_fct - 1843;
+
+        if (temp > 0)
+        {
+            temp = (Word16)(((Word32)temp * 6242) >> 15);
+            wgt_fct = 1843 - temp;
+        }
+        else
+        {
+            temp = (Word16)(((Word32)wgt_fct * 28160) >> 15);
+            wgt_fct = 3427 - temp;
+        }
+
+        *(p_wf++) = wgt_fct << 3;
+
+    } /* for (i = 10; i != 0; i--) */
+
+    return;
+
+} /* Lsf_wt() */
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp.cpp b/media/libstagefright/codecs/amrnb/common/src/lsp.cpp
new file mode 100644
index 0000000..0e3f772
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsp.cpp
@@ -0,0 +1,530 @@
+/* ------------------------------------------------------------------
+ * 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/lsp.c
+ Functions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Per review comments, added pOverflow flag to a few forgotten
+ functions.  Removed unnecessary include files.
+
+ Description:  For lsp_reset() and lsp()
+              1. Replaced copy() with more efficient memcpy().
+              2. Eliminated unused include file copy.h.
+
+ Description:  For lsp_reset()
+              1. Modified memcpy() operands order.
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+#include <string.h>
+
+#include "lsp.h"
+#include "typedef.h"
+#include "q_plsf.h"
+#include "az_lsp.h"
+#include "int_lpc.h"
+#include "lsp_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: lsp_init (lspState **st)
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = Pointer to type lspState
+
+ Outputs:
+    st = Pointer to type lspState -- values are initialized.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    lsp_init_data = Word16 array.
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Initializes lsp state data.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp.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 lsp_init(lspState **st)
+{
+    lspState* s;
+
+    if (st == (lspState **) NULL)
+    {
+        /* fprintf(stderr, "lsp_init: invalid parameter\n"); */
+        return -1;
+    }
+
+    *st = NULL;
+
+    /* allocate memory */
+    if ((s = (lspState *) malloc(sizeof(lspState))) == NULL)
+    {
+        /* fprintf(stderr, "lsp_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    /* Initialize quantization state */
+    if (0 != Q_plsf_init(&s->qSt))
+    {
+        return -1;
+    }
+
+    if (0 != lsp_reset(s))
+    {
+        return -1;
+    }
+
+    *st = s;
+
+    return 0;
+}
+
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = Pointer to type lspState
+
+ Outputs:
+    st = Pointer to type lspState -- values are reset.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    resets lsp_state data
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp.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 lsp_reset(lspState *st)
+{
+
+    if (st == (lspState *) NULL)
+    {
+        /* fprintf(stderr, "lsp_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    /* Init lsp_old[] */
+    memcpy(st->lsp_old,   lsp_init_data,   M*sizeof(Word16));
+
+    /* Initialize lsp_old_q[] */
+    memcpy(st->lsp_old_q,   st->lsp_old,  M*sizeof(Word16));
+
+    /* Reset quantization state */
+    Q_plsf_reset(st->qSt);
+
+    return 0;
+}
+
+
+
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = Pointer to type lspState
+
+ Outputs:
+    None
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Frees memory used by lspState.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp.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 lsp_exit(lspState **st)
+{
+    if (st == NULL || *st == NULL)
+        return;
+
+    /* Deallocate members */
+    Q_plsf_exit(&(*st)->qSt);
+
+    /* deallocate memory */
+    free(*st);
+    *st = NULL;
+
+    return;
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+
+ Inputs:
+    st = Pointer to type lspState -- State struct
+    req_mode = enum Mode -- requested coder mode
+    used_mode = enum Mode -- used coder mode
+    az = array of type Word16 -- interpolated LP parameters Q12
+
+ Outputs:
+    azQ = array of type Word16 -- quantization interpol. LP parameters Q12
+    lsp_new = array of type Word16 -- new lsp vector
+    anap = Double pointer of type Word16 -- analysis parameters
+    pOverflow = Pointer to type Flag -- Flag set when overflow occurs
+    st = Pointer to type lspState -- State struct
+    az = array of type Word16 -- interpolated LP parameters Q12
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp.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 lsp(lspState *st,       /* i/o : State struct                            */
+         enum Mode req_mode, /* i   : requested coder mode                    */
+         enum Mode used_mode,/* i   : used coder mode                         */
+         Word16 az[],        /* i/o : interpolated LP parameters Q12          */
+         Word16 azQ[],       /* o   : quantization interpol. LP parameters Q12*/
+         Word16 lsp_new[],   /* o   : new lsp vector                          */
+         Word16 **anap,      /* o   : analysis parameters                     */
+         Flag   *pOverflow)  /* o   : Flag set when overflow occurs           */
+
+{
+    Word16 lsp_new_q[M];    /* LSPs at 4th subframe           */
+    Word16 lsp_mid[M], lsp_mid_q[M];    /* LSPs at 2nd subframe           */
+
+    Word16 pred_init_i; /* init index for MA prediction in DTX mode */
+
+    if (req_mode == MR122)
+    {
+        Az_lsp(&az[MP1], lsp_mid, st->lsp_old, pOverflow);
+        Az_lsp(&az[MP1 * 3], lsp_new, lsp_mid, pOverflow);
+
+        /*--------------------------------------------------------------------*
+         * Find interpolated LPC parameters in all subframes (both quantized  *
+         * and unquantized).                                                  *
+         * The interpolated parameters are in array A_t[] of size (M+1)*4     *
+         * and the quantized interpolated parameters are in array Aq_t[]      *
+         *--------------------------------------------------------------------*/
+        Int_lpc_1and3_2(st->lsp_old, lsp_mid, lsp_new, az, pOverflow);
+
+        if (used_mode != MRDTX)
+        {
+            /* LSP quantization (lsp_mid[] and lsp_new[] jointly quantized) */
+            Q_plsf_5(
+                st->qSt,
+                lsp_mid,
+                lsp_new,
+                lsp_mid_q,
+                lsp_new_q,
+                *anap,
+                pOverflow);
+
+            Int_lpc_1and3(st->lsp_old_q, lsp_mid_q, lsp_new_q, azQ, pOverflow);
+
+            /* Advance analysis parameters pointer */
+            (*anap) += 5;
+        }
+    }
+    else
+    {
+        Az_lsp(&az[MP1 * 3], lsp_new, st->lsp_old, pOverflow);  /* From A(z) to lsp  */
+
+        /*--------------------------------------------------------------------*
+         * Find interpolated LPC parameters in all subframes (both quantized  *
+         * and unquantized).                                                  *
+         * The interpolated parameters are in array A_t[] of size (M+1)*4     *
+         * and the quantized interpolated parameters are in array Aq_t[]      *
+         *--------------------------------------------------------------------*/
+
+        Int_lpc_1to3_2(st->lsp_old, lsp_new, az, pOverflow);
+
+        if (used_mode != MRDTX)
+        {
+            /* LSP quantization */
+            Q_plsf_3(
+                st->qSt,
+                req_mode,
+                lsp_new,
+                lsp_new_q,
+                *anap,
+                &pred_init_i,
+                pOverflow);
+
+            Int_lpc_1to3(
+                st->lsp_old_q,
+                lsp_new_q,
+                azQ,
+                pOverflow);
+
+            /* Advance analysis parameters pointer */
+            (*anap) += 3;
+        }
+    }
+
+    /* update the LSPs for the next frame */
+    memcpy(st->lsp_old,   lsp_new,   M*sizeof(Word16));
+
+    if (used_mode != MRDTX)
+    {
+        memcpy(st->lsp_old_q, lsp_new_q, M*sizeof(Word16));
+    }
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_az.cpp b/media/libstagefright/codecs/amrnb/common/src/lsp_az.cpp
new file mode 100644
index 0000000..6b7b471
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsp_az.cpp
@@ -0,0 +1,555 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_az.c
+ Funtions: Get_lsp_pol
+           Lsp_Az
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Deleted all Local stores needed/modified. Optimized Lsp_Az
+          function by getting rid of call to L_shr_r function.
+
+ Description: Updated file per comments gathered from Phase 2/3 review.
+
+ Description: Added setting of Overflow flag in the inlined code.
+
+ Description: 1. Optimized Lsp_Az function code.
+              2. Changed Input/Output definitions by adding Word type.
+
+ Description: Made changes based on review meeting.
+              1. Removed pseudocode.
+
+ 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.
+
+ Description: Modified to pass overflow flag through to L_add and L_sub.  The
+ flag is passed back to the calling function by pointer reference.
+
+ Description: Removed the id line since it was removed in the header file by
+              Ken.
+
+ Description: Added the write-only variable, pOverflow, to the inputs section.
+
+ Description:  For lsp_az() and Get_lsp_pol()
+              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. Replaced mpy_32_16 by multpilcations in place
+              6. Eliminated if-else statements for sign extension when
+                 right-shifting
+
+ Description:  Added casting to eliminate warnings, and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains functions that convert line spectral pairs (LSP) to
+ linear predictive (LP) coefficients (filter order = 10). The functions
+ included in this file include Get_lsp_pol, which finds the coefficients of
+ F1(z) and F2(z), and Lsp_Az, which converts LSP to LPC by multiplying
+ F1(z) by 1+z^(-1) and F2(z) by 1-z^(-1), then calculating A(z) = (F1(z) +
+ F2(z))/2.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "lsp_az.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: Get_lsp_pol
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp = pointer to the buffer containing the line spectral pairs (LSP)
+          of type Word16
+    f = pointer to the polynomial of type Word32 to be generated
+
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Outputs:
+    buffer pointed to by f contains the polynomial generated
+
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function finds the polynomial F1(z) or F2(z) from the LSPs. If the LSP
+ vector is passed at address 0, F1(z) is computed and if it is passed at
+ address 1, F2(z) is computed.
+
+ This is performed by expanding the product polynomials:
+
+    F1(z) =   product   ( 1 - 2 lsp[i] z^-1 + z^-2 )
+        i=0,2,4,6,8
+    F2(z) =   product   ( 1 - 2 lsp[i] z^-1 + z^-2 )
+        i=1,3,5,7,9
+
+ where lsp[] is the LSP vector in the cosine domain.
+
+ The expansion is performed using the following recursion:
+
+    f[0] = 1
+    b = -2.0 * lsp[0]
+    f[1] = b
+    for i=2 to 5 do
+        b = -2.0 * lsp[2*i-2];
+        for j=i-1 down to 2 do
+            f[j] = f[j] + b*f[j-1] + f[j-2];
+        f[1] = f[1] + b;
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp_az.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static void Get_lsp_pol (Word16 *lsp, Word32 *f)
+{
+    Word16 i, j, hi, lo;
+    Word32 t0;
+
+    // f[0] = 1.0;
+    *f = L_mult (4096, 2048);
+    f++;
+    *f = L_msu ((Word32) 0, *lsp, 512);    // f[1] =  -2.0 * lsp[0];
+    f++;
+    lsp += 2;                              // Advance lsp pointer
+
+    for (i = 2; i <= 5; i++)
+    {
+        *f = f[-2];
+
+        for (j = 1; j < i; j++, f--)
+        {
+            L_Extract (f[-1], &hi, &lo);
+            t0 = Mpy_32_16 (hi, lo, *lsp); // t0 = f[-1] * lsp
+            t0 = L_shl (t0, 1);
+            *f = L_add (*f, f[-2]); // *f += f[-2]
+            *f = L_sub (*f, t0); // *f -= t0
+        }
+        *f = L_msu (*f, *lsp, 512); // *f -= lsp<<9
+        f += i;                            // Advance f pointer
+        lsp += 2;                          // Advance lsp pointer
+    }
+
+    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 Get_lsp_pol(
+    Word16 *lsp,
+    Word32 *f,
+    Flag   *pOverflow)
+{
+    register Word16 i;
+    register Word16 j;
+
+    Word16 hi;
+    Word16 lo;
+    Word32 t0;
+    OSCL_UNUSED_ARG(pOverflow);
+
+    /* f[0] = 1.0;             */
+    *f++ = (Word32) 0x01000000;
+    *f++ = (Word32) - *(lsp++) << 10;       /* f[1] =  -2.0 * lsp[0];  */
+    lsp++;                                  /* Advance lsp pointer     */
+
+    for (i = 2; i <= 5; i++)
+    {
+        *f = *(f - 2);
+
+        for (j = 1; j < i; j++)
+        {
+            hi = (Word16)(*(f - 1) >> 16);
+
+            lo = (Word16)((*(f - 1) >> 1) - ((Word32) hi << 15));
+
+            t0  = ((Word32)hi * *lsp);
+            t0 += ((Word32)lo * *lsp) >> 15;
+
+            *(f) +=  *(f - 2);          /*      *f += f[-2]      */
+            *(f--) -=  t0 << 2;         /*      *f -= t0         */
+
+        }
+
+        *f -= (Word32)(*lsp++) << 10;
+
+        f  += i;
+        lsp++;
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Get_lsp_pol_wrapper
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp = pointer to the buffer containing the line spectral pairs (LSP)
+          of type Word16
+    f = pointer to the polynomial of type Word32 to be generated
+
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Outputs:
+    buffer pointed to by f contains the polynomial generated
+
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function provides external access to the static function Get_lsp_pol.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ CALL Get_lsp_pol(lsp = lsp_ptr
+                  f = f_ptr )
+   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 Get_lsp_pol_wrapper(
+    Word16 *lsp,
+    Word32 *f,
+    Flag   *pOverflow)
+{
+    /*----------------------------------------------------------------------------
+     CALL Get_lsp_pol(lsp = lsp_ptr
+              f = f_ptr )
+    ----------------------------------------------------------------------------*/
+    Get_lsp_pol(lsp, f, pOverflow);
+
+    /*----------------------------------------------------------------------------
+       MODIFYING(nothing)
+       RETURNING(nothing)
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lsp_Az
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp = pointer to the buffer containing the line spectral pairs (LSP)
+          of type Word16
+
+      a = pointer to the buffer containing Linear Predictive (LP)
+          coefficients of type Word16 to be generated
+
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    pOverflow  = pointer set in case where one of the operations overflows.
+                 [data type Pointer to Flag]
+
+ Pointers and Buffers Modified:
+    a buffer contains the generated Linear Predictive (LP) coefficients
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+        None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function converts from the line spectral pairs (LSP) to LP coefficients
+ for a 10th order filter.
+
+ This is done by:
+    (1) Find the coefficients of F1(z) and F2(z) (see Get_lsp_pol)
+    (2) Multiply F1(z) by 1+z^{-1} and F2(z) by 1-z^{-1}
+    (3) A(z) = ( F1(z) + F2(z) ) / 2
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp_az.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Lsp_Az (
+    Word16 lsp[],        // (i)  : line spectral frequencies
+    Word16 a[]           // (o)  : predictor coefficients (order = 10)
+)
+{
+    Word16 i, j;
+    Word32 f1[6], f2[6];
+    Word32 t0;
+
+    Get_lsp_pol (&lsp[0], f1);
+    Get_lsp_pol (&lsp[1], f2);
+
+    for (i = 5; i > 0; i--)
+    {
+        f1[i] = L_add (f1[i], f1[i - 1]); // f1[i] += f1[i-1];
+        f2[i] = L_sub (f2[i], f2[i - 1]); // f2[i] -= f2[i-1];
+    }
+
+    a[0] = 4096;
+    for (i = 1, j = 10; i <= 5; i++, j--)
+    {
+        t0 = L_add (f1[i], f2[i]);           // f1[i] + f2[i]
+        a[i] = extract_l (L_shr_r (t0, 13));
+        t0 = L_sub (f1[i], f2[i]);           // f1[i] - f2[i]
+        a[j] = extract_l (L_shr_r (t0, 13));
+    }
+
+    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 Lsp_Az(
+    Word16 lsp[],        /* (i)  : line spectral frequencies            */
+    Word16 a[],          /* (o)  : predictor coefficients (order = 10)  */
+    Flag  *pOverflow     /* (o)  : overflow flag                        */
+)
+{
+    register Word16 i;
+    register Word16 j;
+
+    Word32 f1[6];
+    Word32 f2[6];
+    Word32 t0;
+    Word32 t1;
+    Word16 *p_a = &a[0];
+    Word32 *p_f1;
+    Word32 *p_f2;
+
+    Get_lsp_pol(&lsp[0], f1, pOverflow);
+
+    Get_lsp_pol(&lsp[1], f2, pOverflow);
+
+    p_f1 = &f1[5];
+    p_f2 = &f2[5];
+
+    for (i = 5; i > 0; i--)
+    {
+        *(p_f1--) += f1[i-1];
+        *(p_f2--) -= f2[i-1];
+    }
+
+    *(p_a++) = 4096;
+    p_f1 = &f1[1];
+    p_f2 = &f2[1];
+
+    for (i = 1, j = 10; i <= 5; i++, j--)
+    {
+        t0 = *(p_f1) + *(p_f2);               /* f1[i] + f2[i] */
+        t1 = *(p_f1++) - *(p_f2++);           /* f1[i] - f2[i] */
+
+        t0 = t0 + ((Word32) 1 << 12);
+        t1 = t1 + ((Word32) 1 << 12);
+
+        *(p_a++) = (Word16)(t0 >> 13);
+        a[j]     = (Word16)(t1 >> 13);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_lsf.cpp b/media/libstagefright/codecs/amrnb/common/src/lsp_lsf.cpp
new file mode 100644
index 0000000..39d6eda
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsp_lsf.cpp
@@ -0,0 +1,384 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_lsf.c
+ Functions: Lsp_lsf
+            Lsf_lsp
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+
+ Description: Deleted variables listed in the Local Stores Needed/Modified
+              section.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template and removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header file of the math functions
+              used in the file.
+
+ Description: Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Placed table declarations in a .c file, rather than an included
+ .tab.  The tables are now referenced via an extern in this file.
+
+ Description:  For Lsp_lsf()
+              1. Eliminated unused include file typedef.h.
+              2. Replaced array addressing by pointers
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that convert line spectral pairs (LSP) to
+ line spectral frequencies (LSF) and vice-versa.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "lsp_lsf.h"
+#include "basicop_malloc.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.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    extern const Word16 table[];
+    extern const Word16 slope[];
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lsf_lsp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf = buffer containing normalized line spectral frequencies; valid
+          range is between 0 and 0.5 (Word16)
+    lsp = buffer containing line spectral pairs; valid range is between
+          -1 and 1 (Word16)
+    m = LPC order (Word16)
+
+ Outputs:
+    lsp contains the newly calculated line spectral pairs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    table = cosine table
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the LSF to LSP transformation using the equation:
+
+    lsf[i] = arccos(lsp[i])/(2*pi)
+
+ The transformation from lsp[i] to lsf[i] is approximated by a look-up table
+ and interpolation.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp_lsf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Lsf_lsp (
+    Word16 lsf[],       // (i) : lsf[m] normalized (range: 0.0<=val<=0.5)
+    Word16 lsp[],       // (o) : lsp[m] (range: -1<=val<1)
+    Word16 m            // (i) : LPC order
+)
+{
+    Word16 i, ind, offset;
+    Word32 L_tmp;
+
+    for (i = 0; i < m; i++)
+    {
+        ind = shr (lsf[i], 8);      // ind    = b8-b15 of lsf[i]
+        offset = lsf[i] & 0x00ff;    // offset = b0-b7  of lsf[i]
+
+        // lsp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 256
+
+        L_tmp = L_mult (sub (table[ind + 1], table[ind]), offset);
+        lsp[i] = add (table[ind], extract_l (L_shr (L_tmp, 9)));
+
+    }
+    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 Lsf_lsp(
+    Word16 lsf[],       /* (i) : lsf[m] normalized (range: 0.0<=val<=0.5) */
+    Word16 lsp[],       /* (o) : lsp[m] (range: -1<=val<1)                */
+    Word16 m,           /* (i) : LPC order                                */
+    Flag   *pOverflow   /* (o) : Flag set when overflow occurs            */
+)
+{
+    Word16 i, ind, offset;
+    Word32 L_tmp;
+
+    for (i = 0; i < m; i++)
+    {
+        ind = lsf[i] >> 8;           /* ind    = b8-b15 of lsf[i] */
+        offset = lsf[i] & 0x00ff;    /* offset = b0-b7  of lsf[i] */
+
+        /* lsp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 256 */
+
+        L_tmp = ((Word32)(table[ind + 1] - table[ind]) * offset) >> 8;
+        lsp[i] = add(table[ind], (Word16) L_tmp, pOverflow);
+
+    }
+
+    return;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Lsp_lsf
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsp = buffer containing line spectral pairs; valid range is between
+          -1 and 1 (Word16)
+    lsf = buffer containing normalized line spectral frequencies; valid
+          range is between 0 and 0.5 (Word16)
+    m = LPC order (Word16)
+
+ Outputs:
+    lsf contains the newly calculated normalized line spectral frequencies
+
+ Returns:
+    None
+
+ Global Variables Used:
+    table = cosine table
+    slope = table to used to calculate inverse cosine
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the LSP to LSF transformation using the equation:
+
+    lsp[i] = cos(2*pi*lsf[i])
+
+ The transformation from lsf[i] to lsp[i] is approximated by a look-up table
+ and interpolation.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ lsp_lsf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Lsp_lsf (
+    Word16 lsp[],       // (i)  : lsp[m] (range: -1<=val<1)
+    Word16 lsf[],       // (o)  : lsf[m] normalized (range: 0.0<=val<=0.5)
+    Word16 m            // (i)  : LPC order
+)
+{
+    Word16 i, ind;
+    Word32 L_tmp;
+
+    ind = 63;                        // begin at end of table -1
+
+    for (i = m - 1; i >= 0; i--)
+    {
+        // find value in table that is just greater than lsp[i]
+
+        while (sub (table[ind], lsp[i]) < 0)
+        {
+            ind--;
+
+        }
+
+        // acos(lsp[i])= ind*256 + ( ( lsp[i]-table[ind] ) *
+           slope[ind] )/4096
+
+        L_tmp = L_mult (sub (lsp[i], table[ind]), slope[ind]);
+        //(lsp[i]-table[ind])*slope[ind])>>12
+        lsf[i] = pv_round (L_shl (L_tmp, 3));
+        lsf[i] = add (lsf[i], shl (ind, 8));
+    }
+    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 Lsp_lsf(
+    Word16 lsp[],       /* (i)  : lsp[m] (range: -1<=val<1)                */
+    Word16 lsf[],       /* (o)  : lsf[m] normalized (range: 0.0<=val<=0.5) */
+    Word16 m,           /* (i)  : LPC order                                */
+    Flag  *pOverflow    /* (o)  : Flag set when overflow occurs            */
+)
+{
+    Word16 i;
+    Word16 ind;
+    Word16 temp;
+    Word32 L_tmp;
+    Word16 *p_lsp = &lsp[m-1];
+    Word16 *p_lsf = &lsf[m-1];
+    OSCL_UNUSED_ARG(pOverflow);
+
+    ind = 63;                        /* begin at end of table -1 */
+
+    for (i = m - 1; i >= 0; i--)
+    {
+        /* find value in table that is just greater than lsp[i] */
+        temp = *(p_lsp--);
+        while (table[ind] < temp)
+        {
+            ind--;
+        }
+
+        /* acos(lsp[i])= ind*256 + ( ( lsp[i]-table[ind] ) *
+           slope[ind] )/4096 */
+
+        L_tmp = (Word32)(temp - table[ind]) * slope[ind];
+
+        /*(lsp[i]-table[ind])*slope[ind])>>12*/
+        L_tmp  = (L_tmp + 0x00000800) >> 12;
+
+        *(p_lsf--) = (Word16)(L_tmp) + (ind << 8);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_lsf_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/lsp_lsf_tbl.cpp
new file mode 100644
index 0000000..cee0f32
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsp_lsf_tbl.cpp
@@ -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.
+****************************************************************************************/
+/*
+ Filename: /audio/gsm_amr/c/src/lsp_lsf_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, lsp_lsf.tab
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 table[65] =
+    {
+        32767, 32729, 32610, 32413, 32138, 31786, 31357, 30853,
+        30274, 29622, 28899, 28106, 27246, 26320, 25330, 24279,
+        23170, 22006, 20788, 19520, 18205, 16846, 15447, 14010,
+        12540, 11039, 9512, 7962, 6393, 4808, 3212, 1608,
+        0, -1608, -3212, -4808, -6393, -7962, -9512, -11039,
+        -12540, -14010, -15447, -16846, -18205, -19520, -20788, -22006,
+        -23170, -24279, -25330, -26320, -27246, -28106, -28899, -29622,
+        -30274, -30853, -31357, -31786, -32138, -32413, -32610, -32729,
+        (Word16) 0x8000
+    };
+
+    /* 0x8000 = -32768 (used to silence the compiler) */
+
+    /* slope used to compute y = acos(x) */
+
+    extern const Word16 slope[64] =
+    {
+        -26887, -8812, -5323, -3813, -2979, -2444, -2081, -1811,
+        -1608, -1450, -1322, -1219, -1132, -1059, -998, -946,
+        -901, -861, -827, -797, -772, -750, -730, -713,
+        -699, -687, -677, -668, -662, -657, -654, -652,
+        -652, -654, -657, -662, -668, -677, -687, -699,
+        -713, -730, -750, -772, -797, -827, -861, -901,
+        -946, -998, -1059, -1132, -1219, -1322, -1450, -1608,
+        -1811, -2081, -2444, -2979, -3813, -5323, -8812, -26887
+    };
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/lsp_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/lsp_tab.cpp
new file mode 100644
index 0000000..deded93
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/lsp_tab.cpp
@@ -0,0 +1,187 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_tab.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition. Removed corresponding header file from Include
+              section.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ 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             : lsp.tab
+   Purpose          : Table for lsp init
+
+------------------------------------------------------------------------------
+ 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.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    extern const Word16 lsp_init_data[M] = {30000, 26000, 21000, 15000, 8000,
+        0, -8000, -15000, -21000, -26000
+    };
+
+    /*----------------------------------------------------------------------------
+    ; 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/common/src/mult_r.cpp b/media/libstagefright/codecs/amrnb/common/src/mult_r.cpp
new file mode 100644
index 0000000..0777e68
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/mult_r.cpp
@@ -0,0 +1,218 @@
+/* ------------------------------------------------------------------
+ * 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/mult_r.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the mult_r function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Passing in a pointer to the overflow flag instead of using
+          a global flag.
+
+ Description: Made the following changes based on P2/P3 review:
+              1) Simplified test to determine if sign extension is necessary
+              2) Changed the name of pointer "overflow" to "Poverflow"
+              3) Removed code that updates MOPS counter
+              4) Updated template and reference section
+
+ Who:                       Date:
+ Description:
+
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Multiplication function with rounding and overflow control
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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: mult_r
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the add operation resulted in overflow
+
+ Returns:
+    L_product_arr = 16-bit limited product of var1 and var2 (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the multiplication of var1 by var2 with rounding, and
+ gives a 16 bit result which is scaled, i.e.:
+    mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and  |
+    mult_r(-32768,-32768) = 32767
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] mult_r() function in basicop2.c, UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 mult_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+    Word32 L_product_arr;
+
+    L_product_arr = (Word32) var1 *(Word32) var2;
+    L_product_arr += (Word32) 0x00004000L;
+    L_product_arr &= (Word32) 0xffff8000L;
+    L_product_arr >>= 15;
+
+    if (L_product_arr & (Word32) 0x00010000L)
+    {
+        L_product_arr |= (Word32) 0xffff0000L;
+    }
+* The reference ETSI code uses a global flag for Overflow inside the function
+* saturate(). In the actual implementation a pointer to Overflow flag is passed in
+* as a parameter to the function
+
+    var_out = saturate (L_product_arr);
+
+#if (WMOPS)
+    multiCounter[currCounter].mult_r++;
+#endif
+
+    return (var_out);
+}
+
+------------------------------------------------------------------------------
+ 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 mult_r(Word16 var1, Word16 var2, Flag *pOverflow)
+{
+
+    register Word32 L_product_arr;
+
+    L_product_arr = ((Word32) var1) * var2;              /* product */
+    L_product_arr += (Word32) 0x00004000L;               /* round */
+    L_product_arr >>= 15;                                /* shift */
+
+    /* sign extend when necessary */
+    L_product_arr |= (Word32) - (L_product_arr & (Word32) 0x00010000L);
+
+    /* Saturate result (if necessary). */
+    /* Replaced function call with in-line code to conserve MIPS, */
+    /* i.e., var_out = saturate (L_product_arr)  */
+
+    if (L_product_arr > 0X00007fffL)
+    {
+        *pOverflow = 1;
+        L_product_arr = MAX_16;
+    }
+    else if (L_product_arr < (Word32) 0xffff8000L)
+    {
+        *pOverflow = 1;
+        L_product_arr = MIN_16;
+    }
+
+    return ((Word16) L_product_arr);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/negate.cpp b/media/libstagefright/codecs/amrnb/common/src/negate.cpp
new file mode 100644
index 0000000..be58d2b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/negate.cpp
@@ -0,0 +1,179 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/negate.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the negate function. Sync'ed up with
+          the current template and fixed tabs.
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var1 = negated value of input (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function negates var1 with saturation; saturate in the case where input
+ is -32768: negate(var1) = sub(0,var1).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 negate (Word16 var1)
+{
+    Word16 var_out;
+
+    var_out = (var1 == MIN_16) ? MAX_16 : -var1;
+#if (WMOPS)
+    multiCounter[currCounter].negate++;
+#endif
+    return (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    "negate.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
+----------------------------------------------------------------------------*/
+Word16 negate(register Word16 var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    var1 = (var1 == MIN_16) ? MAX_16 : -var1;
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (var1);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/norm_l.cpp b/media/libstagefright/codecs/amrnb/common/src/norm_l.cpp
new file mode 100644
index 0000000..132fed6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/norm_l.cpp
@@ -0,0 +1,247 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/norm_l.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the norm_l function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Updated module description to be the same as the equivalent
+          assembly file (norm_l.asm).
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Description: Made the following changes
+              1. Unrolled the search loop to make four comparison per
+                 pass, using only four iterations of the loop and saving
+                 shifts cycles
+              2. Updated header and copyright year
+
+ Description: 1. Support for ARM and Linux-ARM assembly instructions.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_var1 = 32 bit long signed integer (Word32) whose value falls
+             in the range : 0x8000 0000 <= var1 <= 0x7fff ffff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var_out = number of left shifts need to normalize input (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function produces the number of left shifts needed to normalize the 32
+ bit variable L_var1 for positive values on the interval with minimum of
+ 0x40000000 and maximum of 0x7fffffff, and for negative values on the interval
+ with minimum of 0x80000000 and maximum of 0xc0000000. Note that when L_var1
+ is equal to zero, the output var_out is set to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 norm_l (Word32 L_var1)
+{
+    Word16 var_out;
+
+    if (L_var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (L_var1 == (Word32) 0xffffffffL)
+        {
+            var_out = 31;
+        }
+        else
+        {
+            if (L_var1 < 0)
+            {
+                L_var1 = ~L_var1;
+            }
+            for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++)
+            {
+                L_var1 <<= 1;
+            }
+        }
+    }
+
+#if (WMOPS)
+    multiCounter[currCounter].norm_l++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+#if !( defined(PV_ARM_V5) || defined(PV_ARM_GCC_V5) )
+Word16 norm_l(register Word32 L_var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    register Word16 var_out = 0;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    if (L_var1)
+    {
+
+        Word32 y = L_var1 - (L_var1 < 0);
+        L_var1 = y ^(y >> 31);
+
+
+        while (!(0x40000000L & L_var1))
+        {
+            var_out++;
+            if ((0x20000000L & L_var1))
+            {
+                break;
+            }
+            var_out++;
+            if ((0x10000000L & L_var1))
+            {
+                break;
+            }
+            var_out++;
+            if ((0x08000000L & L_var1))
+            {
+                break;
+            }
+            var_out++;
+            L_var1 <<= 4;
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+
+
+    return (var_out);
+}
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/src/norm_s.cpp b/media/libstagefright/codecs/amrnb/common/src/norm_s.cpp
new file mode 100644
index 0000000..8cdcdb8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/norm_s.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: ./gsm-amr/c/src/norm_s.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the norm_s function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Updated input/output definition and module description to
+          be the same as the equivalent assembly file (norm_s.asm).
+
+ Description: Updated definition of var1 to be the same as that in the
+          assembly file (norm_s.asm).
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit signed integer of type Word16, whose value falls
+           in the range: 0x8000 <= var1 <= 0x7fff
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var_out = number of left shifts need to normalize var1 (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function produces the number of left shifts needed to normalize the 16
+ bit variable var1 for positive values on the interval with minimum of 0x4000
+ and maximum of 0x7fff, and for negative values on the interval with minimum
+ of 0x8000 and maximum of 0xc000. Note that when var1 is zero, the resulting
+ output var_out is set to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 norm_s (Word16 var1)
+{
+    Word16 var_out;
+
+    if (var1 == 0)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        if (var1 == (Word16) 0xffff)
+        {
+            var_out = 15;
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var1 = ~var1;
+            }
+            for (var_out = 0; var1 < 0x4000; var_out++)
+            {
+                var1 <<= 1;
+            }
+        }
+    }
+
+#if (WMOPS)
+    multiCounter[currCounter].norm_s++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+#if !( defined(PV_ARM_V5) || defined(PV_ARM_GCC_V5) )
+
+Word16 norm_s(register Word16 var1)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+
+    register Word16 var_out = 0;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+
+    if (var1)
+    {
+        Word16 y = var1 - (var1 < 0);
+        var1 = y ^(y >> 15);
+
+        while (!(0x4000 & var1))
+        {
+            var_out++;
+            if ((0x2000 & var1))
+            {
+                break;
+            }
+            var_out++;
+            if ((0x1000 & var1))
+            {
+                break;
+            }
+            var_out++;
+            if ((0x0800 & var1))
+            {
+                break;
+            }
+            var_out++;
+            var1 <<= 4;
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (var_out);
+}
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/common/src/overflow_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/overflow_tbl.cpp
new file mode 100644
index 0000000..e5d42d6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/overflow_tbl.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/overflow_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for overflow_tbl[] used by the l_shl()
+ and l_shr() functions.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 Word32 overflow_tbl [32]   = {0x7fffffffL, 0x3fffffffL,
+        0x1fffffffL, 0x0fffffffL,
+        0x07ffffffL, 0x03ffffffL,
+        0x01ffffffL, 0x00ffffffL,
+        0x007fffffL, 0x003fffffL,
+        0x001fffffL, 0x000fffffL,
+        0x0007ffffL, 0x0003ffffL,
+        0x0001ffffL, 0x0000ffffL,
+        0x00007fffL, 0x00003fffL,
+        0x00001fffL, 0x00000fffL,
+        0x000007ffL, 0x000003ffL,
+        0x000001ffL, 0x000000ffL,
+        0x0000007fL, 0x0000003fL,
+        0x0000001fL, 0x0000000fL,
+        0x00000007L, 0x00000003L,
+        0x00000001L, 0x00000000L
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] l_shl() function in basic_op2.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
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/ph_disp_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/ph_disp_tab.cpp
new file mode 100644
index 0000000..99725df
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/ph_disp_tab.cpp
@@ -0,0 +1,188 @@
+/* ------------------------------------------------------------------
+ * 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/ph_disp_tab.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the table of impulse responses of the phase dispersion
+ filters. All impulse responses are in Q15
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 ph_imp_low_MR795[40] =
+    {
+        26777,    801,   2505,   -683,  -1382,    582,    604,  -1274,   3511,  -5894,
+        4534,   -499,  -1940,   3011,  -5058,   5614,  -1990,  -1061,  -1459,   4442,
+        -700,  -5335,   4609,    452,   -589,  -3352,   2953,   1267,  -1212,  -2590,
+        1731,   3670,  -4475,   -975,   4391,  -2537,    949,  -1363,   -979,   5734
+    };
+    extern const Word16 ph_imp_mid_MR795[40] =
+    {
+        30274,   3831,  -4036,   2972,  -1048,  -1002,   2477,  -3043,   2815,  -2231,
+        1753,  -1611,   1714,  -1775,   1543,  -1008,    429,   -169,    472,  -1264,
+        2176,  -2706,   2523,  -1621,    344,    826,  -1529,   1724,  -1657,   1701,
+        -2063,   2644,  -3060,   2897,  -1978,    557,    780,  -1369,    842,    655
+    };
+
+    extern const Word16 ph_imp_low[40] =
+    {
+        14690,  11518,   1268,  -2761,  -5671,   7514,    -35,  -2807,  -3040,   4823,
+        2952,  -8424,   3785,   1455,   2179,  -8637,   8051,  -2103,  -1454,    777,
+        1108,  -2385,   2254,   -363,   -674,  -2103,   6046,  -5681,   1072,   3123,
+        -5058,   5312,  -2329,  -3728,   6924,  -3889,    675,  -1775,     29,  10145
+    };
+    extern const Word16 ph_imp_mid[40] =
+    {
+        30274,   3831,  -4036,   2972,  -1048,  -1002,   2477,  -3043,   2815,  -2231,
+        1753,  -1611,   1714,  -1775,   1543,  -1008,    429,   -169,    472,  -1264,
+        2176,  -2706,   2523,  -1621,    344,    826,  -1529,   1724,  -1657,   1701,
+        -2063,   2644,  -3060,   2897,  -1978,    557,    780,  -1369,    842,    655
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] ph_disp.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/common/src/pow2.cpp b/media/libstagefright/codecs/amrnb/common/src/pow2.cpp
new file mode 100644
index 0000000..a8686f8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/pow2.cpp
@@ -0,0 +1,202 @@
+/* ------------------------------------------------------------------
+ * 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/pow2.c
+
+------------------------------------------------------------------------------
+ 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. Removed inclusion of "pow2.tab"
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "pow2.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: Pow2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    exponent = Integer part whose valid range is: 0 <= value <= 30 (Word16)
+    fraction = Fractional part whose valid range is 0 <= value < 1
+
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    L_x = Result of the Pow2() computation (Word32)
+    pOverflow -> 1 if the Pow2() function results in saturation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes  L_x = pow(2.0, exponent.fraction)
+
+ The function Pow2(L_x) is approximated by a table and linear interpolation.
+
+ 1- i = bit10-b15 of fraction,   0 <= i <= 31
+ 2- a = bit0-b9   of fraction
+ 3- L_x = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+ 4- L_x = L_x >> (30-exponent)     (with rounding)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pow2.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 Pow2 (           // (o)  : result       (range: 0<=val<=0x7fffffff)
+    Word16 exponent,    // (i)  : Integer part.      (range: 0<=val<=30)
+    Word16 fraction     // (i)  : Fractional part.  (range: 0.0<=val<1.0)
+)
+{
+    Word16 exp, i, a, tmp;
+    Word32 L_x;
+
+    L_x = L_mult (fraction, 32);        // L_x = fraction<<6
+    i = extract_h (L_x);                // Extract b10-b16 of fraction
+    L_x = L_shr (L_x, 1);
+    a = extract_l (L_x);                // Extract b0-b9   of fraction
+    a = a & (Word16) 0x7fff;
+
+    L_x = L_deposit_h (table[i]);       // table[i] << 16
+    tmp = sub (table[i], table[i + 1]); // table[i] - table[i+1]
+    L_x = L_msu (L_x, tmp, a);          // L_x -= tmp*a*2
+
+    exp = sub (30, exponent);
+    L_x = L_shr_r (L_x, exp);
+
+    return (L_x);
+}
+
+------------------------------------------------------------------------------
+ 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
+----------------------------------------------------------------------------*/
+
+Word32 Pow2(            /* (o)  : result       (range: 0<=val<=0x7fffffff) */
+    Word16 exponent,    /* (i)  : Integer part.      (range: 0<=val<=30)   */
+    Word16 fraction,    /* (i)  : Fractional part.  (range: 0.0<=val<1.0)  */
+    Flag *pOverflow
+)
+{
+    Word16 exp, i, a, tmp;
+    Word32 L_x;
+
+    L_x = L_mult(fraction, 32, pOverflow);      /* L_x = fraction<<6    */
+
+    /* Extract b0-b16 of fraction */
+
+    i = ((Word16)(L_x >> 16)) & 31;             /* ensure index i is bounded */
+    a = (Word16)((L_x >> 1) & 0x7fff);
+
+    L_x = L_deposit_h(pow2_tbl[i]);             /* pow2_tbl[i] << 16       */
+
+    /* pow2_tbl[i] - pow2_tbl[i+1] */
+    tmp = sub(pow2_tbl[i], pow2_tbl[i + 1], pOverflow);
+    L_x = L_msu(L_x, tmp, a, pOverflow);        /* L_x -= tmp*a*2        */
+
+    exp = sub(30, exponent, pOverflow);
+    L_x = L_shr_r(L_x, exp, pOverflow);
+
+    return (L_x);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/pow2_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/pow2_tbl.cpp
new file mode 100644
index 0000000..e0183a6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/pow2_tbl.cpp
@@ -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/src/pow2_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for log2_tbl[] used by the Pow2() function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 pow2_tbl[33] =
+    {
+        16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,
+        20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,
+        25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,
+        31379, 32066, 32767
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] pow2.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/common/src/pred_lt.cpp b/media/libstagefright/codecs/amrnb/common/src/pred_lt.cpp
new file mode 100644
index 0000000..9163623
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/pred_lt.cpp
@@ -0,0 +1,349 @@
+/* ------------------------------------------------------------------
+ * 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/pred_lt.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Deleted variables listed in the Local Stores Needed/Modified
+          sections.
+
+ Description: Updated file per comments from Phase 2/3 review.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Fixed typecasting issue with TI C compiler. Updated copyright
+              year.
+
+ Description:
+ (1) Removed instance of static in the const table "inter_6"
+ (2) Changed Overflow from a global to a parameter passed via a pointer.
+ (3) Made numerous small changes to bring code more in line with PV standards.
+
+ Description:  For pred_ltp()
+              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,
+                 loaded into memory filter coefficient in linear order for
+                 faster execution in main loop.
+              5. Eliminated call to round by proper initialization
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pred_lt.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define UP_SAMP_MAX  6
+#define L_INTER10    (L_INTERPOL-1)
+#define FIR_SIZE     (UP_SAMP_MAX*L_INTER10+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 1/3 resolution filter is simply a subsampled
+ *       version of the 1/6 resolution filter, i.e. it uses
+ *       every second coefficient:
+ *
+ *          inter_3l[k] = inter_6[2*k], 0 <= k <= 3*L_INTER10
+ */
+
+const Word16 inter_6_pred_lt[FIR_SIZE] =
+{
+    29443,
+    28346, 25207, 20449, 14701,  8693,  3143,
+    -1352, -4402, -5865, -5850, -4673, -2783,
+    -672,  1211,  2536,  3130,  2991,  2259,
+    1170,     0, -1001, -1652, -1868, -1666,
+    -1147,  -464,   218,   756,  1060,  1099,
+    904,   550,   135,  -245,  -514,  -634,
+    -602,  -451,  -231,     0,   191,   308,
+    340,   296,   198,    78,   -36,  -120,
+    -163,  -165,  -132,   -79,   -19,    34,
+    73,    91,    89,    70,    38,     0
+};
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Pred_lt_3or6
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    exc = buffer containing the excitation (Word16)
+    T0 = integer pitch lag (Word16)
+    frac = fraction of lag (Word16)
+    L_subfr = number of samples per subframe (Word16)
+    flag3 = flag to indicate the upsampling rate; if set, upsampling
+            rate is 3, otherwise, upsampling rate is 6 (Word16)
+
+    pOverflow = pointer to overflow (Flag)
+
+ Returns:
+    None
+
+ Outputs:
+    exc buffer contains the newly formed adaptive codebook excitation
+    pOverflow -> 1 if the add operation resulted in overflow
+
+ Global Variables Used:
+    inter_6_pred_lt = (1/6) resolution interpolation filter table (Word16)
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the result of long term prediction with fractional
+ interpolation of resolution 1/3 or 1/6. (Interpolated past excitation).
+
+ The past excitation signal at the given delay is interpolated at
+ the given fraction to build the adaptive codebook excitation.
+ On return exc[0..L_subfr-1] contains the interpolated signal
+ (adaptive codebook excitation).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pred_lt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Pred_lt_3or6 (
+    Word16 exc[],     // in/out: excitation buffer
+    Word16 T0,        // input : integer pitch lag
+    Word16 frac,      // input : fraction of lag
+    Word16 L_subfr,   // input : subframe size
+    Word16 flag3      // input : if set, upsampling rate = 3 (6 otherwise)
+)
+{
+    Word16 i, j, k;
+    Word16 *pX0, *pX1, *pX2;
+    const Word16 *pC1, *pC2;
+    Word32 s;
+
+    pX0 = &exc[-T0];
+
+    frac = negate (frac);
+    if (flag3 != 0)
+    {
+      frac = shl (frac, 1);   // inter_3l[k] = inter_6[2*k] -> k' = 2*k
+    }
+
+    if (frac < 0)
+    {
+        frac = add (frac, UP_SAMP_MAX);
+        pX0--;
+    }
+
+    for (j = 0; j < L_subfr; j++)
+    {
+        pX1 = pX0++;
+        pX2 = pX0;
+        pC1 = &inter_6[frac];
+        pC2 = &inter_6[sub (UP_SAMP_MAX, frac)];
+
+        s = 0;
+        for (i = 0, k = 0; i < L_INTER10; i++, k += UP_SAMP_MAX)
+        {
+            s = L_mac (s, pX1[-i], pC1[k]);
+            s = L_mac (s, pX2[i], pC2[k]);
+        }
+
+        exc[j] = pv_round (s);
+    }
+
+    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 Pred_lt_3or6(
+    Word16 exc[],     /* in/out: excitation buffer                          */
+    Word16 T0,        /* input : integer pitch lag                          */
+    Word16 frac,      /* input : fraction of lag                            */
+    Word16 L_subfr,   /* input : subframe size                              */
+    Word16 flag3,     /* input : if set, upsampling rate = 3 (6 otherwise)  */
+    Flag  *pOverflow  /* output: if set, overflow occurred in this function */
+)
+{
+    register Word16 i;
+    register Word16 j;
+    register Word16 k;
+
+    Word16 *pX0;
+    Word16 *pX2;
+    Word16 *pX3;
+    Word16 *p_exc;
+    Word16 *pC1;
+    const Word16 *pC1_ref;
+    const Word16 *pC2_ref;
+
+    Word16 Coeff_1[(L_INTER10<<1)];
+
+    Word32 s1;
+    Word32 s2;
+    OSCL_UNUSED_ARG(pOverflow);
+
+    pX0 = &(exc[-T0]);
+
+    /* frac goes between -3 and 3 */
+
+    frac = -frac;
+
+    if (flag3 != 0)
+    {
+        frac <<= 1;   /* inter_3l[k] = inter_6[2*k] -> k' = 2*k */
+    }
+
+    if (frac < 0)
+    {
+        frac += UP_SAMP_MAX;
+        pX0--;
+    }
+
+    pC1_ref = &inter_6_pred_lt[frac];
+    pC2_ref = &inter_6_pred_lt[UP_SAMP_MAX-frac];
+
+
+    pC1 = Coeff_1;
+
+    k = 0;
+
+    for (i = L_INTER10 >> 1; i > 0; i--)
+    {
+        *(pC1++) = pC1_ref[k];
+        *(pC1++) = pC2_ref[k];
+        k += UP_SAMP_MAX;
+        *(pC1++) = pC1_ref[k];
+        *(pC1++) = pC2_ref[k];
+        k += UP_SAMP_MAX;
+
+    }
+
+    p_exc = exc;
+
+    for (j = (L_subfr >> 1); j != 0 ; j--)
+    {
+        pX0++;
+        pX2 = pX0;
+        pX3 = pX0++;
+
+        pC1 = Coeff_1;
+
+        s1  = 0x00004000L;
+        s2  = 0x00004000L;
+
+        for (i = L_INTER10 >> 1; i > 0; i--)
+        {
+            s2 += ((Word32) * (pX3--)) * *(pC1);
+            s1 += ((Word32) * (pX3)) * *(pC1++);
+            s1 += ((Word32) * (pX2++)) * *(pC1);
+            s2 += ((Word32) * (pX2)) * *(pC1++);
+            s2 += ((Word32) * (pX3--)) * *(pC1);
+            s1 += ((Word32) * (pX3)) * *(pC1++);
+            s1 += ((Word32) * (pX2++)) * *(pC1);
+            s2 += ((Word32) * (pX2)) * *(pC1++);
+
+        } /* for (i = L_INTER10>>1; i > 0; i--) */
+
+        *(p_exc++) = (Word16)(s1 >> 15);
+        *(p_exc++) = (Word16)(s2 >> 15);
+
+    } /* for (j = (L_subfr>>1); j != 0 ; j--) */
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf.cpp b/media/libstagefright/codecs/amrnb/common/src/q_plsf.cpp
new file mode 100644
index 0000000..5d96baa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/q_plsf.cpp
@@ -0,0 +1,144 @@
+/* ------------------------------------------------------------------
+ * 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             : q_plsf.c
+*      Purpose          : common part (init, exit, reset) of LSF quantization
+*                         module (rest in q_plsf_3.c and q_plsf_5.c)
+*
+********************************************************************************
+*/
+
+/*
+********************************************************************************
+*                         MODULE INCLUDE FILE AND VERSION ID
+********************************************************************************
+*/
+
+#include <stdlib.h>
+
+#include "q_plsf.h"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+#include "basic_op.h"
+
+
+/*
+********************************************************************************
+*                         PUBLIC PROGRAM CODE
+********************************************************************************
+*/
+
+/*
+**************************************************************************
+*
+*  Function    : Q_plsf_init
+*  Purpose     : Allocates memory and initializes state variables
+*
+**************************************************************************
+*/
+Word16 Q_plsf_init(Q_plsfState **state)
+{
+    Q_plsfState* s;
+
+    if (state == (Q_plsfState **) NULL)
+    {
+        /* fprintf(stderr, "Q_plsf_init: invalid parameter\n"); */
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (Q_plsfState *) malloc(sizeof(Q_plsfState))) == NULL)
+    {
+        /* fprintf(stderr, "Q_plsf_init: can not malloc state structure\n"); */
+        return -1;
+    }
+
+    Q_plsf_reset(s);
+    *state = s;
+
+    return 0;
+}
+
+/*
+**************************************************************************
+*
+*  Function    : Q_plsf_reset
+*  Purpose     : Resets state memory
+*
+**************************************************************************
+*/
+Word16 Q_plsf_reset(Q_plsfState *state)
+{
+    Word16 i;
+
+    if (state == (Q_plsfState *) NULL)
+    {
+        /* fprintf(stderr, "Q_plsf_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    for (i = 0; i < M; i++)
+        state->past_rq[i] = 0;
+
+    return 0;
+}
+
+/*
+**************************************************************************
+*
+*  Function    : Q_plsf_exit
+*  Purpose     : The memory used for state memory is freed
+*
+**************************************************************************
+*/
+void Q_plsf_exit(Q_plsfState **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_3.cpp b/media/libstagefright/codecs/amrnb/common/src/q_plsf_3.cpp
new file mode 100644
index 0000000..2b30bf4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/q_plsf_3.cpp
@@ -0,0 +1,1226 @@
+/* ------------------------------------------------------------------
+ * 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_plsf_3.c
+ Funtions: Vq_subvec4
+           Test_Vq_subvec4
+           Vq_subvec3
+           Test_Vq_subvec3
+           Q_plsf_3
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Updated modules per Phase 2/3 review comments. Updated
+          Vq_subvec3 pseudo-code to reflect the new restructured code.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header file of the math functions
+              used in the file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Fixed typecasting issue with TI C compiler.
+              2. Optimized IF stament in Vq_subvec3() function.
+              3. Updated copyright year.
+
+ Description: Removed redundancy in the Vq_subvec4 function.
+
+ Description: Updated to accept new parameter, Flag *pOverflow.
+
+ Description: Per review comments, added pOverflow flag description
+ to the input/outputs section.
+
+ Description: Corrected missed Overflow global variables -- changed to
+ proper pOverflow.
+
+ Description: Optimized all functions to further reduce clock cycle usage.
+              Updated copyright year.
+
+ Description: Added left shift by 1 in line 1050 of Q_plsf_3().
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that perform the quantization of LSF
+ parameters with first order MA prediction and split by 3 vector
+ quantization (split-VQ).
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include <string.h>
+
+#include "q_plsf.h"
+#include "typedef.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+#include "lsfwt.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 PAST_RQ_INIT_SIZE 8
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    /* Codebooks of LSF prediction residual */
+    extern const Word16 mean_lsf_3[];
+
+    extern const Word16 pred_fac_3[];
+
+    extern const Word16 dico1_lsf_3[];
+    extern const Word16 dico2_lsf_3[];
+    extern const Word16 dico3_lsf_3[];
+
+    extern const Word16 mr515_3_lsf[];
+    extern const Word16 mr795_1_lsf[];
+
+    extern const Word16 past_rq_init[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Vq_subvec4
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 = pointer to the first LSF residual vector (Q15) (Word16)
+    dico = pointer to the quantization codebook (Q15) (const Word16)
+    wf1 = pointer to the first LSF weighting factor (Q13) (Word16)
+    dico_size = size of quantization codebook (Q0) (Word16)
+
+ Outputs:
+    buffer pointed to by lsf_r1 contains the selected vector
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    index = quantization index (Q0) (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the quantization of a 4-dimensional subvector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_3.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word16
+Vq_subvec4(             // o: quantization index,            Q0
+    Word16 * lsf_r1,    // i: 1st LSF residual vector,       Q15
+    Word16 * dico,      // i: quantization codebook,         Q15
+    Word16 * wf1,       // i: 1st LSF weighting factors,     Q13
+    Word16 dico_size)   // i: size of quantization codebook, Q0
+{
+    Word16 i, index = 0;
+    Word16 *p_dico, temp;
+    Word32 dist_min, dist;
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+    for (i = 0; i < dico_size; i++)
+    {
+        temp = sub (lsf_r1[0], *p_dico++);
+        temp = mult (wf1[0], temp);
+        dist = L_mult (temp, temp);
+
+        temp = sub (lsf_r1[1], *p_dico++);
+        temp = mult (wf1[1], temp);
+        dist = L_mac (dist, temp, temp);
+
+        temp = sub (lsf_r1[2], *p_dico++);
+        temp = mult (wf1[2], temp);
+        dist = L_mac (dist, temp, temp);
+
+        temp = sub (lsf_r1[3], *p_dico++);
+        temp = mult (wf1[3], temp);
+        dist = L_mac (dist, temp, temp);
+
+
+        if (L_sub (dist, dist_min) < (Word32) 0)
+        {
+            dist_min = dist;
+            index = i;
+        }
+    }
+
+    // Reading the selected vector
+
+    p_dico = &dico[shl (index, 2)];
+    lsf_r1[0] = *p_dico++;
+    lsf_r1[1] = *p_dico++;
+    lsf_r1[2] = *p_dico++;
+    lsf_r1[3] = *p_dico;
+
+    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]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16 Vq_subvec4( /* o: quantization index,            Q0  */
+    Word16 * lsf_r1,      /* i: 1st LSF residual vector,       Q15 */
+    const Word16 * dico,  /* i: quantization codebook,         Q15 */
+    Word16 * wf1,         /* i: 1st LSF weighting factors,     Q13 */
+    Word16 dico_size,     /* i: size of quantization codebook, Q0  */
+    Flag  *pOverflow      /* o : Flag set when overflow occurs     */
+)
+{
+    register Word16 i;
+    Word16 temp;
+    const Word16 *p_dico;
+    Word16 index = 0;
+    Word32 dist_min;
+    Word32 dist;
+
+    Word16 lsf_r1_0;
+    Word16 lsf_r1_1;
+    Word16 lsf_r1_2;
+    Word16 lsf_r1_3;
+
+    Word16 wf1_0;
+    Word16 wf1_1;
+    Word16 wf1_2;
+    Word16 wf1_3;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+    lsf_r1_0 = lsf_r1[0];
+    lsf_r1_1 = lsf_r1[1];
+    lsf_r1_2 = lsf_r1[2];
+    lsf_r1_3 = lsf_r1[3];
+
+    wf1_0 = wf1[0];
+    wf1_1 = wf1[1];
+    wf1_2 = wf1[2];
+    wf1_3 = wf1[3];
+
+    for (i = 0; i < dico_size; i++)
+    {
+        temp = lsf_r1_0 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_0) * temp) >> 15);
+        dist = ((Word32) temp) * temp;
+
+        temp = lsf_r1_1 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_1) * temp) >> 15);
+        dist += ((Word32) temp) * temp;
+
+        temp = lsf_r1_2 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_2) * temp) >> 15);
+        dist += ((Word32) temp) * temp;
+
+        temp = lsf_r1_3 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_3) * temp) >> 15);
+        dist += ((Word32) temp) * temp;
+
+        if (dist < dist_min)
+        {
+            dist_min = dist;
+            index = i;
+        }
+    }
+
+    /* Reading the selected vector */
+
+    p_dico = dico + (index << 2);
+    *lsf_r1++ = *p_dico++;
+    *lsf_r1++ = *p_dico++;
+    *lsf_r1++ = *p_dico++;
+    *lsf_r1 = *p_dico;
+
+    return(index);
+
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Test_Vq_subvec4
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 = pointer to the first LSF residual vector (Q15) (Word16)
+    dico = pointer to the quantization codebook (Q15) (const Word16)
+    wf1 = pointer to the first LSF weighting factor (Q13) (Word16)
+    dico_size = size of quantization codebook (Q0) (Word16)
+
+ Outputs:
+    buffer pointed to by lsf_r1 contains the selected vector
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    index = quantization index (Q0) (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calls the static function Vq_subvec4. It is used for testing
+ purposes only
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+ CALL Vq_subvec4(lsf_r1 = lsf_r1
+                 dico = dico
+                 wf1 = wf1
+                 dico_size = dico_size)
+   MODIFYING(nothing)
+   RETURNING(index = tst_index4)
+
+------------------------------------------------------------------------------
+ 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_Vq_subvec4(
+    Word16 * lsf_r1,
+    const Word16 * dico,
+    Word16 * wf1,
+    Word16 dico_size,
+    Flag   *pOverflow)
+{
+    Word16  tst_index4 = 0;
+
+    /*------------------------------------------------------------------------
+     CALL Vq_subvec4(lsf_r1 = lsf_r1
+                     dico = dico
+                     wf1 = wf1
+                     dico_size = dico_size)
+       MODIFYING(nothing)
+       RETURNING(index = index)
+    ------------------------------------------------------------------------*/
+    tst_index4 =
+        Vq_subvec4(
+            lsf_r1,
+            dico,
+            wf1,
+            dico_size,
+            pOverflow);
+
+    return(tst_index4);
+
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Vq_subvec3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 = pointer to the first LSF residual vector (Q15) (Word16)
+    dico = pointer to the quantization codebook (Q15) (const Word16)
+    wf1 = pointer to the first LSF weighting factor (Q13) (Word16)
+    dico_size = size of quantization codebook (Q0) (Word16)
+    use_half = flag to indicate use of every second entry in the
+               codebook (Flag)
+
+ Outputs:
+    buffer pointed to by lsf_r1 contains the selected vector
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    index = quantization index (Q0) (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the quantization of a 3 dimensional subvector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_3.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word16
+Vq_subvec3(             // o: quantization index,            Q0
+    Word16 * lsf_r1,    // i: 1st LSF residual vector,       Q15
+    Word16 * dico,      // i: quantization codebook,         Q15
+    Word16 * wf1,       // i: 1st LSF weighting factors,     Q13
+    Word16 dico_size,   // i: size of quantization codebook, Q0
+    Flag use_half)      // i: use every second entry in codebook
+{
+    Word16 i, index = 0;
+    Word16 *p_dico, temp;
+    Word32 dist_min, dist;
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+    if (use_half == 0) {
+       for (i = 0; i < dico_size; i++)
+       {
+          temp = sub(lsf_r1[0], *p_dico++);
+          temp = mult(wf1[0], temp);
+          dist = L_mult(temp, temp);
+
+          temp = sub(lsf_r1[1], *p_dico++);
+          temp = mult(wf1[1], temp);
+          dist = L_mac(dist, temp, temp);
+
+          temp = sub(lsf_r1[2], *p_dico++);
+          temp = mult(wf1[2], temp);
+          dist = L_mac(dist, temp, temp);
+
+          if (L_sub(dist, dist_min) < (Word32) 0) {
+             dist_min = dist;
+             index = i;
+          }
+       }
+       p_dico = &dico[add(index, add(index, index))];
+    }
+    else
+    {
+       for (i = 0; i < dico_size; i++)
+       {
+          temp = sub(lsf_r1[0], *p_dico++);
+          temp = mult(wf1[0], temp);
+          dist = L_mult(temp, temp);
+
+          temp = sub(lsf_r1[1], *p_dico++);
+          temp = mult(wf1[1], temp);
+          dist = L_mac(dist, temp, temp);
+
+          temp = sub(lsf_r1[2], *p_dico++);
+          temp = mult(wf1[2], temp);
+          dist = L_mac(dist, temp, temp);
+
+          if (L_sub(dist, dist_min) < (Word32) 0)
+          {
+             dist_min = dist;
+             index = i;
+          }
+          p_dico = p_dico + 3; add(0,0);
+       }
+       p_dico = &dico[shl(add(index, add(index, index)),1)];
+    }
+
+
+    // Reading the selected vector
+    lsf_r1[0] = *p_dico++;
+    lsf_r1[1] = *p_dico++;
+    lsf_r1[2] = *p_dico++;
+
+    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]
+
+------------------------------------------------------------------------------
+*/
+
+static Word16 Vq_subvec3( /* o: quantization index,            Q0  */
+    Word16 * lsf_r1,      /* i: 1st LSF residual vector,       Q15 */
+    const Word16 * dico,  /* i: quantization codebook,         Q15 */
+    Word16 * wf1,         /* i: 1st LSF weighting factors,     Q13 */
+    Word16 dico_size,     /* i: size of quantization codebook, Q0  */
+    Flag use_half,        /* i: use every second entry in codebook */
+    Flag  *pOverflow)     /* o : Flag set when overflow occurs     */
+{
+    register Word16 i;
+    Word16 temp;
+
+    const Word16 *p_dico;
+
+    Word16 p_dico_index = 0;
+    Word16 index = 0;
+
+    Word32 dist_min;
+    Word32 dist;
+
+    Word16 lsf_r1_0;
+    Word16 lsf_r1_1;
+    Word16 lsf_r1_2;
+
+    Word16 wf1_0;
+    Word16 wf1_1;
+    Word16 wf1_2;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+    lsf_r1_0 = lsf_r1[0];
+    lsf_r1_1 = lsf_r1[1];
+    lsf_r1_2 = lsf_r1[2];
+
+    wf1_0 = wf1[0];
+    wf1_1 = wf1[1];
+    wf1_2 = wf1[2];
+
+    if (use_half != 0)
+    {
+        p_dico_index = 3;
+    }
+
+    for (i = 0; i < dico_size; i++)
+    {
+        temp = lsf_r1_0 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_0) * temp) >> 15);
+        dist = ((Word32) temp) * temp;
+
+        temp = lsf_r1_1 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_1) * temp) >> 15);
+        dist += ((Word32) temp) * temp;
+
+        temp = lsf_r1_2 - (*p_dico++);
+        temp = (Word16)((((Word32) wf1_2) * temp) >> 15);
+        dist += ((Word32) temp) * temp;
+
+        if (dist < dist_min)
+        {
+            dist_min = dist;
+            index = i;
+        }
+
+        p_dico = p_dico + p_dico_index;
+    }
+
+    p_dico = dico + (3 * index);
+
+    if (use_half != 0)
+    {
+        p_dico += (3 * index);
+    }
+
+    /* Reading the selected vector */
+    *lsf_r1++ = *p_dico++;
+    *lsf_r1++ = *p_dico++;
+    *lsf_r1 = *p_dico;
+
+    return(index);
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Test_Vq_subvec3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 = pointer to the first LSF residual vector (Q15) (Word16)
+    dico = pointer to the quantization codebook (Q15) (const Word16)
+    wf1 = pointer to the first LSF weighting factor (Q13) (Word16)
+    dico_size = size of quantization codebook (Q0) (Word16)
+    use_half = flag to indicate use of every second entry in the
+               codebook (Flag)
+
+ Outputs:
+    buffer pointed to by lsf_r1 contains the selected vector
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    index = quantization index (Q0) (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calls the static function Vq_subvec3. It is used for testing
+ purposes only
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ CALL Vq_subvec3(lsf_r1 = lsf_r1
+                 dico = dico
+                 wf1 = wf1
+                 dico_size = dico_size
+                 use_half = use_half)
+   MODIFYING(nothing)
+   RETURNING(index = tst_index3)
+
+------------------------------------------------------------------------------
+ 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_Vq_subvec3(
+    Word16 * lsf_r1,
+    const Word16 * dico,
+    Word16 * wf1,
+    Word16 dico_size,
+    Flag use_half,
+    Flag *pOverflow)
+{
+    Word16  tst_index3 = 0;
+
+    /*------------------------------------------------------------------------
+     CALL Vq_subvec3(lsf_r1 = lsf_r1
+                     dico = dico
+                     wf1 = wf1
+                     dico_size = dico_size
+                     use_half = use_half)
+       MODIFYING(nothing)
+       RETURNING(index = index)
+    ------------------------------------------------------------------------*/
+    tst_index3 =
+        Vq_subvec3(
+            lsf_r1,
+            dico,
+            wf1,
+            dico_size,
+            use_half,
+            pOverflow);
+
+    return(tst_index3);
+
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Q_plsf_3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type Q_plsfState (Q_plsfState)
+    mode = coder mode (enum)
+    lsp1 = pointer to the first LSP vector (Word16)
+    lsp1_q = pointer to the quantized first LSP vector (Word16)
+    indice = pointer to the quantization indices of 3 vectors (Word16)
+    pred_init_i = pointer to the index of the initial value for
+                  MA prediction in DTX mode (Word16)
+
+ Outputs:
+    lsp1_q points to a vector containing the new quantized LSPs
+    indice points to the new quantization indices of 3 vectors
+    pred_init_i points to the new initial index for MA prediction
+      in DTX mode
+    past_rq field of structure pointed to by st contains the current
+      quantized LSF parameters
+    pOverflow -- pointer to Flag -- Flag set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    pred_fac = table containing prediction factors (const Word16)
+    dico1_lsf = quantization table for split_MQ of 2 sets of LSFs
+                in a 20 ms frame (const Word16)
+    dico2_lsf = quantization table for split_MQ of 2 sets of LSFs
+                in a 20 ms frame (const Word16)
+    dico3_lsf = quantization table for split_MQ of 2 sets of LSFs
+                in a 20 ms frame (const Word16)
+    mr515_3_lsf = third codebook for MR475 and MR515 modes (const Word16)
+    mr795_1_lsf = first codebook for MR795 mode (const Word16)
+    mean_lsf = table of mean LSFs (const Word16)
+    past_rq_init = initalization table for MA predictor in DTX mode
+                   (const Word16)
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs quantization of LSF parameters with 1st order MA
+ prediction and split by 3 vector quantization (split-VQ)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_3.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Q_plsf_3(
+    Q_plsfState *st,    // i/o: state struct
+    enum Mode mode,     // i  : coder mode
+    Word16 *lsp1,       // i  : 1st LSP vector                      Q15
+    Word16 *lsp1_q,     // o  : quantized 1st LSP vector            Q15
+    Word16 *indice,     // o  : quantization indices of 3 vectors   Q0
+    Word16 *pred_init_i // o  : init index for MA prediction in DTX mode
+)
+{
+    Word16 i, j;
+    Word16 lsf1[M], wf1[M], lsf_p[M], lsf_r1[M];
+    Word16 lsf1_q[M];
+
+    Word32 L_pred_init_err;
+    Word32 L_min_pred_init_err;
+    Word16 temp_r1[M];
+    Word16 temp_p[M];
+
+    // convert LSFs to normalize frequency domain 0..16384
+
+    Lsp_lsf(lsp1, lsf1, M);
+
+    // compute LSF weighting factors (Q13)
+
+    Lsf_wt(lsf1, wf1);
+
+    // Compute predicted LSF and prediction error
+    if (test(), sub(mode, MRDTX) != 0)
+    {
+       for (i = 0; i < M; i++)
+       {
+          lsf_p[i] = add(mean_lsf[i],
+                         mult(st->past_rq[i],
+                              pred_fac[i]));
+          lsf_r1[i] = sub(lsf1[i], lsf_p[i]);
+      }
+    }
+    else
+    {
+       // DTX mode, search the init vector that yields
+       // lowest prediction resuidual energy
+       *pred_init_i = 0;
+       L_min_pred_init_err = 0x7fffffff; // 2^31 - 1
+       for (j = 0; j < PAST_RQ_INIT_SIZE; j++)
+       {
+          L_pred_init_err = 0;
+          for (i = 0; i < M; i++)
+          {
+             temp_p[i] = add(mean_lsf[i], past_rq_init[j*M+i]);
+             temp_r1[i] = sub(lsf1[i],temp_p[i]);
+             L_pred_init_err = L_mac(L_pred_init_err, temp_r1[i], temp_r1[i]);
+          }  // next i
+
+
+          if (L_sub(L_pred_init_err, L_min_pred_init_err) < (Word32) 0)
+          {
+             L_min_pred_init_err = L_pred_init_err;
+             Copy(temp_r1, lsf_r1, M);
+             Copy(temp_p, lsf_p, M);
+             // Set zerom
+             Copy(&past_rq_init[j*M], st->past_rq, M);
+             *pred_init_i = j;
+          } // endif
+       } // next j
+    } // endif MRDTX
+
+    //---- Split-VQ of prediction error ----
+    if (sub (mode, MR475) == 0 || sub (mode, MR515) == 0)
+    {   // MR475, MR515
+
+
+      indice[0] = Vq_subvec3(&lsf_r1[0], dico1_lsf, &wf1[0], DICO1_SIZE, 0);
+
+      indice[1] = Vq_subvec3(&lsf_r1[3], dico2_lsf, &wf1[3], DICO2_SIZE/2, 1);
+
+      indice[2] = Vq_subvec4(&lsf_r1[6], mr515_3_lsf, &wf1[6], MR515_3_SIZE);
+
+    }
+    else if (sub (mode, MR795) == 0)
+    {   // MR795
+
+
+      indice[0] = Vq_subvec3(&lsf_r1[0], mr795_1_lsf, &wf1[0], MR795_1_SIZE, 0);
+
+      indice[1] = Vq_subvec3(&lsf_r1[3], dico2_lsf, &wf1[3], DICO2_SIZE, 0);
+
+      indice[2] = Vq_subvec4(&lsf_r1[6], dico3_lsf, &wf1[6], DICO3_SIZE);
+
+    }
+    else
+    {   // MR59, MR67, MR74, MR102 , MRDTX
+
+
+      indice[0] = Vq_subvec3(&lsf_r1[0], dico1_lsf, &wf1[0], DICO1_SIZE, 0);
+
+      indice[1] = Vq_subvec3(&lsf_r1[3], dico2_lsf, &wf1[3], DICO2_SIZE, 0);
+
+      indice[2] = Vq_subvec4(&lsf_r1[6], dico3_lsf, &wf1[6], DICO3_SIZE);
+
+    }
+
+
+    // Compute quantized LSFs and update the past quantized residual
+
+    for (i = 0; i < M; i++)
+    {
+        lsf1_q[i] = add(lsf_r1[i], lsf_p[i]);
+        st->past_rq[i] = lsf_r1[i];
+    }
+
+    // verification that LSFs has mimimum distance of LSF_GAP Hz
+
+    Reorder_lsf(lsf1_q, LSF_GAP, M);
+
+    //  convert LSFs to the cosine domain
+
+    Lsf_lsp(lsf1_q, lsp1_q, M);
+}
+
+------------------------------------------------------------------------------
+ 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 Q_plsf_3(
+    Q_plsfState *st,    /* i/o: state struct                             */
+    enum Mode mode,     /* i  : coder mode                               */
+    Word16 *lsp1,       /* i  : 1st LSP vector                      Q15  */
+    Word16 *lsp1_q,     /* o  : quantized 1st LSP vector            Q15  */
+    Word16 *indice,     /* o  : quantization indices of 3 vectors   Q0   */
+    Word16 *pred_init_i,/* o  : init index for MA prediction in DTX mode */
+    Flag  *pOverflow    /* o : Flag set when overflow occurs             */
+)
+{
+    register Word16 i, j;
+    Word16 lsf1[M];
+    Word16 wf1[M];
+    Word16 lsf_p[M];
+    Word16 lsf_r1[M];
+    Word16 lsf1_q[M];
+
+    Word32 L_pred_init_err;
+    Word32 L_min_pred_init_err;
+    Word32 L_temp;
+    Word16 temp_r1[M];
+    Word16 temp_p[M];
+    Word16 temp;
+
+    /* convert LSFs to normalize frequency domain 0..16384 */
+
+    Lsp_lsf(
+        lsp1,
+        lsf1,
+        M,
+        pOverflow);
+
+    /* compute LSF weighting factors (Q13) */
+
+    Lsf_wt(
+        lsf1,
+        wf1,
+        pOverflow);
+
+    /* Compute predicted LSF and prediction error */
+    if (mode != MRDTX)
+    {
+        for (i = 0; i < M; i++)
+        {
+            temp = (Word16)((((Word32) st->past_rq[i]) *
+                             (*(pred_fac_3 + i))) >> 15);
+
+            *(lsf_p + i) = *(mean_lsf_3 + i) + temp;
+
+            *(lsf_r1 + i) = *(lsf1 + i) - *(lsf_p + i);
+        }
+    }
+    else
+    {
+        /* DTX mode, search the init vector that yields */
+        /* lowest prediction resuidual energy           */
+        *pred_init_i = 0;
+        L_min_pred_init_err = 0x7fffffff; /* 2^31 - 1 */
+
+        for (j = 0; j < PAST_RQ_INIT_SIZE; j++)
+        {
+            L_pred_init_err = 0;
+            for (i = 0; i < M; i++)
+            {
+                *(temp_p + i) = *(mean_lsf_3 + i) + *(past_rq_init + j * M + i);
+
+                *(temp_r1 + i) = *(lsf1 + i) - *(temp_p + i);
+
+                L_temp = ((Word32) * (temp_r1 + i)) * *(temp_r1 + i);
+
+                L_pred_init_err = L_pred_init_err + (L_temp << 1);
+
+            }  /* next i */
+
+
+            if (L_pred_init_err < L_min_pred_init_err)
+            {
+                L_min_pred_init_err = L_pred_init_err;
+
+                memcpy(
+                    lsf_r1,
+                    temp_r1,
+                    M*sizeof(Word16));
+
+                memcpy(
+                    lsf_p,
+                    temp_p,
+                    M*sizeof(Word16));
+
+                /* Set zerom */
+                memcpy(
+                    st->past_rq,
+                    &past_rq_init[j*M],
+                    M*sizeof(Word16));
+
+                *pred_init_i = j;
+
+            } /* endif */
+        } /* next j */
+    } /* endif MRDTX */
+
+    /*---- Split-VQ of prediction error ----*/
+    if ((mode == MR475) || (mode == MR515))
+    {   /* MR475, MR515 */
+
+        *indice =
+            Vq_subvec3(
+                lsf_r1,
+                dico1_lsf_3,
+                wf1,
+                DICO1_SIZE,
+                0,
+                pOverflow);
+
+        *(indice + 1) =
+            Vq_subvec3(
+                lsf_r1 + 3,
+                dico2_lsf_3,
+                wf1 + 3,
+                DICO2_SIZE / 2,
+                1,
+                pOverflow);
+
+        *(indice + 2) =
+            Vq_subvec4(
+                lsf_r1 + 6,
+                mr515_3_lsf,
+                wf1 + 6,
+                MR515_3_SIZE,
+                pOverflow);
+
+    }
+    else if (mode == MR795)
+    {   /* MR795 */
+
+        *indice =
+            Vq_subvec3(
+                lsf_r1,
+                mr795_1_lsf,
+                wf1,
+                MR795_1_SIZE,
+                0,
+                pOverflow);
+
+        *(indice + 1) =
+            Vq_subvec3(
+                lsf_r1 + 3,
+                dico2_lsf_3,
+                wf1 + 3,
+                DICO2_SIZE,
+                0,
+                pOverflow);
+
+        *(indice + 2) =
+            Vq_subvec4(
+                lsf_r1 + 6,
+                dico3_lsf_3,
+                wf1 + 6,
+                DICO3_SIZE,
+                pOverflow);
+
+    }
+    else
+    {   /* MR59, MR67, MR74, MR102 , MRDTX */
+
+        *indice =
+            Vq_subvec3(
+                lsf_r1,
+                dico1_lsf_3,
+                wf1,
+                DICO1_SIZE,
+                0,
+                pOverflow);
+
+        *(indice + 1) =
+            Vq_subvec3(
+                lsf_r1 + 3,
+                dico2_lsf_3,
+                wf1 + 3,
+                DICO2_SIZE,
+                0,
+                pOverflow);
+
+        *(indice + 2) =
+            Vq_subvec4(
+                lsf_r1 + 6,
+                dico3_lsf_3,
+                wf1 + 6,
+                DICO3_SIZE,
+                pOverflow);
+
+    }
+
+
+    /* Compute quantized LSFs and update the past quantized residual */
+
+    for (i = 0; i < M; i++)
+    {
+        *(lsf1_q + i) = *(lsf_r1 + i) + *(lsf_p + i);
+        st->past_rq[i] = *(lsf_r1 + i);
+    }
+
+    /* verification that LSFs has mimimum distance of LSF_GAP Hz */
+
+    Reorder_lsf(
+        lsf1_q,
+        LSF_GAP,
+        M,
+        pOverflow);
+
+    /*  convert LSFs to the cosine domain */
+
+    Lsf_lsp(
+        lsf1_q,
+        lsp1_q,
+        M,
+        pOverflow);
+
+    return;
+
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_3_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/q_plsf_3_tbl.cpp
new file mode 100644
index 0000000..56c13e7
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/q_plsf_3_tbl.cpp
@@ -0,0 +1,2096 @@
+/* ------------------------------------------------------------------
+ * 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/q_plsf_3_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, q_plsf_3_tbl.tab
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "q_plsf_3_tbl.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]
+----------------------------------------------------------------------------*/
+/*
+********************************************************************************
+*
+*      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             : q_plsf_3.tab
+*      Purpose          : Table for routine LSF VQ.
+*      $Id $
+*
+********************************************************************************
+*/
+
+
+/* initalization table for MA predictor in dtx mode */
+const Word16 past_rq_init[80] =
+{
+    -258, -318, -439, -634, -656, -773, -711, -502, -268, -193,
+    -2,  125,  122,  -39,   -9,  105,  129,  283,  372,  575,
+    -277, -324, -197, -487, -445, -362, -292,  -27,  177,  543,
+    342,  517,  516,  130,   27, -104, -120, -140,  -74,  -56,
+    -564, -943, -1520, -965, -814, -526, -322,   -2,  159,  657,
+    -312, -284, -386, -597, -493, -526, -418, -229,  105,  449,
+    -557, -870, -1075, -919, -950, -752, -709, -316,   62,  486,
+    -314, -191, -203, -330, -160, -103,  -51,  131,  338,  515
+};
+
+
+const Word16 mean_lsf_3[10] =
+{
+    1546,
+    2272,
+    3778,
+    5488,
+    6972,
+    8382,
+    10047,
+    11229,
+    12766,
+    13714
+};
+
+
+const Word16 pred_fac_3[10] =
+{
+    9556,
+    10769,
+    12571,
+    13292,
+    14381,
+    11651,
+    10588,
+    9767,
+    8593,
+    6484
+};
+
+
+
+/* first codebook from IS641 */
+
+const Word16 dico1_lsf_3[DICO1_SIZE*3] =
+{
+    6, 82, -131,
+    154, -56, -735,
+    183, -65, -265,
+    9, -210, -361,
+    113, 718, 1817,
+    1010, 1214, 1573,
+    857, 1333, 2276,
+    827, 1568, 1933,
+    717, 1989, 2206,
+    838, 1172, 1823,
+    721, 1000, 2154,
+    286, 476, 1509,
+    -247, -531, 230,
+    147, -82, 569,
+    26, -177, -944,
+    -27, -273, 692,
+    -164, -264, -183,
+    224, 790, 1039,
+    899, 946, 601,
+    485, 771, 1150,
+    524, 677, 903,
+    -140, 375, 778,
+    410, 676, 429,
+    301, 530, 1009,
+    719, 646, 38,
+    226, 367, 40,
+    145, -45, -505,
+    290, 121, -121,
+    302, 127, 166,
+    -124, -383, -956,
+    -358, -455, -977,
+    715, 878, 894,
+    978, 923, 211,
+    477, 272, 64,
+    188, -78, 17,
+    -143, -65, 38,
+    643, 586, 621,
+    -134, -426, -651,
+    347, 545, 2820,
+    1188, 2726, 2442,
+    142, -80, 1735,
+    283, 130, 461,
+    -262, -399, -1145,
+    -411, 155, 430,
+    329, 375, 779,
+    53, -226, -139,
+    -129, -236, 1682,
+    285, 744, 1327,
+    738, 697, 1664,
+    312, 409, 266,
+    325, 720, 135,
+    1, 221, 453,
+    8, 203, 145,
+    299, 640, 760,
+    29, 468, 638,
+    103, 429, 379,
+    420, 954, 932,
+    1326, 1210, 1258,
+    704, 1012, 1152,
+    -166, -444, -266,
+    -316, -130, -376,
+    191, 1151, 1904,
+    -240, -543, -1260,
+    -112, 268, 1207,
+    70, 1062, 1583,
+    278, 1360, 1574,
+    -258, -272, -768,
+    19, 563, 2240,
+    -3, -265, 135,
+    -295, -591, -388,
+    140, 354, -206,
+    -260, -504, -795,
+    -433, -718, -1319,
+    109, 331, 962,
+    -429, -87, 652,
+    -296, 426, 1019,
+    -239, 775, 851,
+    489, 1334, 1073,
+    -334, -332, 25,
+    543, 1206, 1807,
+    326, 61, 727,
+    578, 849, 1405,
+    -208, -277, 329,
+    -152, 64, 669,
+    -434, -678, -727,
+    -454, -71, 251,
+    605, 480, 254,
+    -482, 11, 996,
+    -289, 395, 486,
+    722, 1049, 1440,
+    -30, -316, -786,
+    -106, -115, -619,
+    861, 1474, 1412,
+    1055, 1366, 1184,
+    812, 1237, 925,
+    42, -251, -576,
+    342, 141, -454,
+    -168, -80, 1359,
+    -342, -656, -1763,
+    100, 821, 725,
+    990, 747, 800,
+    332, 440, 568,
+    663, 379, 852,
+    112, 165, -369,
+    597, 910, 282,
+    -8, 834, 1281,
+    -352, 572, 695,
+    462, 2246, 1806,
+    345, 190, 1374,
+    416, 915, 2166,
+    168, -82, 280,
+    -516, -446, 840,
+    47, 533, 44,
+    -362, -711, -1143,
+    22, 193, 1472,
+    -85, 233, 1813,
+    -62, 579, 1504,
+    550, 944, 1749,
+    723, 650, 1148,
+    972, 884, 1395,
+    -425, 643, 0,
+    1000, 952, 1098,
+    249, 1446, 672,
+    -334, -87, 2172,
+    -554, 1882, 2672,
+    140, 1826, 1853,
+    920, 1749, 2590,
+    1076, 1933, 2038,
+    -137, -443, -1555,
+    1269, 1174, 468,
+    -493, -122, 1521,
+    -451, 1033, 1214,
+    482, 1695, 1118,
+    815, 649, 384,
+    -446, -692, 107,
+    -319, -605, -118,
+    -207, -505, 525,
+    -468, -12, 2736,
+    75, 1934, 1305,
+    880, 2358, 2267,
+    1285, 1575, 2004,
+    -48, -304, -1186,
+    -435, -461, -251,
+    -366, -404, -547,
+    -289, -605, -597,
+    -538, -810, -165,
+    -120, 3, 356,
+    639, 1241, 1502,
+    96, 177, 750,
+    -435, -585, -1174,
+    -356, 109, -79,
+    -485, 288, 2005,
+    9, 1116, 731,
+    880, 2134, 946,
+    -265, 1585, 1065,
+    1157, 1210, 843,
+    -498, -668, 431,
+    374, 321, -229,
+    1440, 2101, 1381,
+    449, 461, 1155,
+    -105, 39, -384,
+    -263, 367, 182,
+    -371, -660, 773,
+    -188, 1151, 971,
+    1333, 1632, 1435,
+    774, 1267, 1221,
+    -482, -832, -1489,
+    -237, -210, 860,
+    890, 1615, 1064,
+    472, 1062, 1192,
+    185, 1077, 989,
+    -568, -992, -1704,
+    -449, -902, -2043,
+    -142, -377, -458,
+    -210, -554, -1029,
+    -11, 1133, 2265,
+    -329, -675, -893,
+    -250, 657, 1187,
+    519, 1510, 1779,
+    520, 539, 1403,
+    527, 1421, 1302,
+    -563, -871, -1248,
+    -147, -463, 879,
+    -76, 2334, 2840,
+    563, 2573, 2385,
+    632, 1926, 2920,
+    719, 2023, 1840,
+    -545, -723, 1108,
+    129, -125, 884,
+    1417, 1632, 925,
+    -94, 1566, 1751,
+    -341, 1533, 1551,
+    591, 395, -274,
+    -76, 981, 2831,
+    153, 2985, 1844,
+    1032, 2565, 2749,
+    1508, 2832, 1879,
+    791, 1199, 538,
+    -190, -453, 1489,
+    -278, -548, 1158,
+    -245, 1941, 2044,
+    1024, 1560, 1650,
+    512, 253, 466,
+    -62, -323, 1151,
+    -473, -376, 507,
+    -433, 1380, 2162,
+    899, 1943, 1445,
+    134, 704, 440,
+    460, 525, -28,
+    -450, 279, 1338,
+    0, 971, 252,
+    -445, -627, -991,
+    -348, -602, -1424,
+    398, 712, 1656,
+    -107, 314, -178,
+    93, 2226, 2238,
+    518, 849, 656,
+    -462, -711, -447,
+    174, -34, 1191,
+    -119, 42, 1005,
+    -372, 274, 758,
+    1036, 2352, 1838,
+    675, 1724, 1498,
+    430, 1286, 2133,
+    -129, -439, 0,
+    -373, 800, 2144,
+    6, 1587, 2478,
+    478, 596, 2128,
+    -428, -736, 1505,
+    385, 178, 980,
+    139, 449, 1225,
+    -526, -842, -982,
+    145, 1554, 1242,
+    623, 1448, 656,
+    349, 1016, 1482,
+    31, -280, 415,
+    -316, 724, 1641,
+    360, 1058, 556,
+    -436, -358, 1201,
+    -355, 1123, 1939,
+    401, 1584, 2248,
+    -527, -1012, 355,
+    233, 238, 2233,
+    -550, -897, -639,
+    -365, -501, 1957,
+    389, 1860, 1621,
+    162, 1132, 1264,
+    -237, 1174, 1390,
+    -640, -411, 116,
+    -228, 1694, 2298,
+    1639, 2186, 2267,
+    562, 1273, 2658,
+    323, 338, 1774,
+    578, 1107, 852,
+    22, 594, 934,
+    -143, 718, 446
+};
+
+
+/* second codebook from IS641 */
+
+const Word16 dico2_lsf_3[DICO2_SIZE*3] =
+{
+    50, 71, -9,
+    -338, -698, -1407,
+    102, -138, -820,
+    -310, -469, -1147,
+    414, 67, -267,
+    1060, 814, 1441,
+    1548, 1360, 1272,
+    1754, 1895, 1661,
+    2019, 2133, 1820,
+    1808, 2318, 1845,
+    644, -93, 454,
+    858, 329, -136,
+    489, -258, -128,
+    -198, -745, -41,
+    -52, -265, -985,
+    346, 137, 479,
+    -1741, -748, -684,
+    -1163, -1725, -367,
+    -895, -1145, -784,
+    -488, -946, -968,
+    -85, -390, -725,
+    215, -340, -171,
+    1020, 916, 1969,
+    564, 179, 746,
+    662, 977, 1734,
+    887, 622, 914,
+    939, 856, 1165,
+    309, 688, 803,
+    917, 161, 570,
+    118, -20, -283,
+    -816, -42, 204,
+    -1228, -325, -462,
+    -963, -202, -143,
+    -988, -484, -361,
+    -702, -978, -477,
+    -302, -790, -1188,
+    -100, -786, -1088,
+    -1054, -947, -1684,
+    -202, -843, -782,
+    -1039, -1378, -901,
+    -624, -110, -85,
+    356, 213, -10,
+    -493, 364, 774,
+    425, 822, 479,
+    -83, 557, 520,
+    -992, -1560, -572,
+    -603, -741, -26,
+    -502, -638, -903,
+    209, 306, 147,
+    -316, -593, -596,
+    -85, -211, -225,
+    -918, -529, 117,
+    233, -439, -738,
+    1101, 751, 633,
+    1457, 1716, 1511,
+    1765, 1457, 910,
+    1122, 1156, 849,
+    1354, 868, 470,
+    -871, -1150, -1796,
+    -871, -861, -992,
+    -118, 155, 212,
+    -1051, -849, -606,
+    -1117, -1849, -2750,
+    -1019, -1427, -1869,
+    370, -184, -414,
+    959, 493, 104,
+    958, 1039, 543,
+    154, 653, 201,
+    1249, 507, 150,
+    663, 503, 230,
+    623, 777, 675,
+    659, 88, -110,
+    843, 244, 224,
+    382, 541, 302,
+    724, 433, 666,
+    1166, 734, 341,
+    -138, 20, -397,
+    -1183, -424, -46,
+    -321, -352, -124,
+    1333, 1021, 1080,
+    262, 366, 723,
+    922, 283, -551,
+    31, -636, -611,
+    -689, -697, -415,
+    -952, -779, -201,
+    -1329, -598, -359,
+    -953, -1285, 166,
+    493, 305, 221,
+    846, 703, 610,
+    840, 936, 774,
+    -723, -1324, -1261,
+    -357, -1025, -1388,
+    -1096, -1376, -365,
+    -1416, -1881, -608,
+    -1798, -1727, -674,
+    -545, -1173, -703,
+    678, 786, 148,
+    -123, 696, 1288,
+    644, 350, -10,
+    414, 614, 15,
+    137, 344, -211,
+    -814, -1512, -819,
+    -391, -930, -588,
+    47, -591, -898,
+    -909, -1097, -163,
+    -1272, -1167, -157,
+    -1464, -1525, -389,
+    -1274, -1188, -624,
+    671, 213, 454,
+    124, -274, -525,
+    -729, -496, -152,
+    -1344, 122, 135,
+    -2905, -589, -394,
+    -1728, 441, -50,
+    1476, 904, 787,
+    316, 236, -440,
+    -347, 217, 413,
+    -911, -917, 121,
+    -455, -932, 202,
+    -92, -465, -375,
+    488, 390, 474,
+    876, 729, 316,
+    -1815, -1312, -669,
+    87, 962, 432,
+    563, -249, -1058,
+    250, 285, 1105,
+    1141, 427, 696,
+    -1038, -1664, -1582,
+    -948, 346, 160,
+    -309, -272, -858,
+    670, 624, 1250,
+    -944, -408, -666,
+    -606, -320, -384,
+    -492, 230, 65,
+    334, -50, -16,
+    -16, -690, -1397,
+    1791, 1716, 1399,
+    2478, 2063, 1404,
+    1245, 1471, 1426,
+    -382, -1037, -2,
+    173, -398, 1145,
+    1491, 2024, 1801,
+    772, 1274, 1506,
+    1429, 1735, 2001,
+    1079, 1218, 1273,
+    -1154, -1851, -1329,
+    -808, -1133, -1096,
+    -451, -1033, -1722,
+    65, 578, -84,
+    -1476, -2434, -1778,
+    -765, -1366, -494,
+    -218, -594, -931,
+    337, -236, 562,
+    2357, 2662, 1938,
+    1489, 1276, 874,
+    189, 358, 374,
+    -1519, -2281, -2346,
+    -967, -1271, -2095,
+    -628, -1188, -1542,
+    1661, 1043, 546,
+    565, 1061, 732,
+    -64, -836, -434,
+    -436, -96, 203,
+    1078, 1216, 1636,
+    907, 1534, 986,
+    326, 965, 845,
+    142, -84, 197,
+    470, 2379, 1570,
+    1133, 470, 1214,
+    395, 1376, 1200,
+    1125, 1042, 348,
+    -543, -1234, -376,
+    -215, -181, 481,
+    -1947, -1621, -210,
+    -750, -1185, 390,
+    29, -399, 27,
+    820, 1236, 755,
+    695, 979, 409,
+    -174, 1197, 1035,
+    912, 1356, 1846,
+    -992, -1437, 484,
+    -1485, -1700, 208,
+    -412, 1204, 1432,
+    -271, 896, 1144,
+    -416, 1777, 1434,
+    -1696, -2644, -204,
+    -1789, -1551, 1033,
+    -1656, -1559, 1303,
+    -1253, -1589, 1081,
+    -669, -1095, -66,
+    -682, 320, -345,
+    659, 305, 1069,
+    -1292, -804, -19,
+    -1635, -1291, 29,
+    -1683, -497, 71,
+    -287, -7, -100,
+    -494, -962, -237,
+    852, 1881, 1740,
+    -1217, -1387, 227,
+    -660, 302, 373,
+    96, 1087, 1257,
+    -1074, -1669, 160,
+    485, 2076, 1798,
+    -934, -220, 552,
+    -596, -612, 237,
+    336, 1720, 879,
+    643, 629, 434,
+    1267, 522, 1633,
+    15, 244, -441,
+    1475, 717, 184,
+    1819, 1590, 1709,
+    988, 261, 937,
+    2093, 2345, 1520,
+    2139, 1858, 1606,
+    -577, -579, -1203,
+    -956, 135, -488,
+    -464, 51, -338,
+    -629, -348, -723,
+    1146, 2073, 1442,
+    2192, 1466, 911,
+    -1444, -1572, -2278,
+    1400, 710, 1297,
+    1335, 633, 928,
+    1434, 2194, 2594,
+    2422, 2204, 1881,
+    982, 2242, 1854,
+    380, 792, 1145,
+    -63, -539, 414,
+    -252, -964, -314,
+    -1261, -683, -780,
+    -831, -526, -1005,
+    -1666, -1135, -424,
+    -1611, -452, -299,
+    1268, 1048, 642,
+    1147, 853, 856,
+    -675, -336, 139,
+    2268, 1343, 1418,
+    29, 768, 797,
+    -1224, 423, 564,
+    -1318, -1082, 245,
+    -1302, -812, 573,
+    -1298, -1617, 646,
+    -968, 834, 723,
+    993, 1652, 2027,
+    -191, -817, 432,
+    662, 60, 198,
+    626, 997, 1330,
+    1648, 1963, 1289,
+    -1597, -93, -45,
+    -1088, 37, -84,
+    1653, 2607, 2337,
+    1065, 2040, 2377,
+    1139, 2326, 2118,
+    859, 357, 1510,
+    664, 1227, 1099,
+    479, 1360, 912,
+    1897, 1754, 2019,
+    1168, 1909, 1784,
+    399, 34, 256,
+    -593, -304, -1053,
+    547, 1694, 1407,
+    647, -99, -341,
+    1492, 1647, 1190,
+    38, -644, -212,
+    395, 846, 222,
+    -704, -765, -716,
+    -724, -1964, -2804,
+    -150, 291, -82,
+    1233, 1459, 1007,
+    -140, -155, 153,
+    439, 297, 1568,
+    -1529, -410, -636,
+    1536, 455, -237,
+    -1328, -139, -260,
+    531, 554, 868,
+    269, 1264, 606,
+    -233, 883, 463,
+    742, 600, -120,
+    -73, 421, 212,
+    -439, -58, 804,
+    -1286, -1241, 728,
+    294, -490, 50,
+    -591, -905, -1254,
+    42, -687, 147,
+    -25, 273, 596,
+    -311, 1213, 601,
+    -754, 849, 584,
+    429, 607, 587,
+    -602, -166, 461,
+    -796, -823, 777,
+    1380, 910, 1755,
+    119, 1417, 972,
+    -219, -880, -1596,
+    -1049, -1010, 438,
+    -713, -1379, 78,
+    0, -447, -1179,
+    -1136, -1319, -1573,
+    2248, 1767, 1309,
+    946, 1583, 1432,
+    1150, 482, 436,
+    -469, -1108, 618,
+    -447, -966, 1088,
+    -1252, -1515, -114,
+    -1104, -2008, -579,
+    210, 613, 497,
+    -1975, -1437, 642,
+    -1269, -856, 1011,
+    -1646, -1185, 1063,
+    -1555, -672, 1204,
+    -1692, -1114, 623,
+    -979, -1326, -1277,
+    539, -147, 894,
+    -1354, -897, -434,
+    888, 475, 428,
+    153, -384, 338,
+    -1492, -511, 359,
+    -974, -1115, -470,
+    105, -550, 677,
+    -937, -1145, 877,
+    380, -260, 210,
+    1685, 924, 1256,
+    1775, 1190, 1095,
+    1419, 631, 533,
+    627, 299, -347,
+    -411, -534, 647,
+    -650, 29, -595,
+    -378, -1367, 1563,
+    1402, 1121, 1465,
+    1089, 1410, 648,
+    -2096, -1090, -6,
+    311, -194, -869,
+    -639, -831, 416,
+    -1162, -1224, 1349,
+    -1247, -941, 1813,
+    -2193, -1987, 453,
+    -619, -1367, -956,
+    -1606, -1972, -1507,
+    -1175, -1057, -1104,
+    -377, 601, 201,
+    1876, 825, 374,
+    -430, -1323, 29,
+    -1397, -1249, -1331,
+    -1007, -1504, 960,
+    -1401, -2009, 197,
+    -1379, -1949, -236,
+    -1077, 123, 422,
+    615, 1269, 546,
+    -306, 1526, 904,
+    1194, 1788, 1177,
+    -626, -884, -1526,
+    199, 766, 1504,
+    -1065, 862, 197,
+    -1034, -1773, -887,
+    -800, 145, 599,
+    -1134, -519, 626,
+    -1205, -1926, 500,
+    -910, -1041, -1395,
+    -1476, -1567, -969,
+    -523, 842, 34,
+    1794, 646, 862,
+    -1207, -1888, -1002,
+    -78, -9, -672,
+    1044, 759, 80,
+    -600, 1139, 1019,
+    57, 2000, 1422,
+    -833, 1414, 1121,
+    -1202, 1630, 1260,
+    -461, 1420, 1244,
+    1537, 975, 253,
+    -283, 324, -359,
+    599, -195, 106,
+    588, 62, -587,
+    -757, 645, 205,
+    51, 1201, 758,
+    -1209, 673, -390,
+    -624, 1581, 941,
+    -151, 1023, 735,
+    2820, 1301, 690,
+    -302, 524, -99,
+    -900, -1588, -1189,
+    1084, 251, 238,
+    2014, 1792, 1010,
+    1245, 1633, 1741,
+    -1227, -1540, -1208,
+    -621, 456, -109,
+    40, -65, 788,
+    -805, -699, -1350,
+    -583, 904, 832,
+    -801, 532, 594,
+    1972, 1408, 1351,
+    -1177, -1880, -2114,
+    -773, 568, 948,
+    -1015, 1079, 1260,
+    -1111, 482, -130,
+    1778, 1044, 780,
+    -1491, 245, 912,
+    -316, -1141, -917,
+    -536, -1442, -2346,
+    -785, -1546, -1988,
+    -2003, 257, 909,
+    -1849, -633, -1209,
+    -1538, -1918, -1054,
+    1606, 2239, 1576,
+    -567, -1500, -1544,
+    -1279, 195, 1369,
+    -817, 293, 1219,
+    -525, 630, 1197,
+    -1698, -2425, -1840,
+    -303, 731, 747,
+    -1169, -251, 269,
+    -950, -75, 1684,
+    -1182, -453, 1005,
+    -1599, 585, 378,
+    -2075, -571, -427,
+    -529, -1159, -1171,
+    -283, -205, -564,
+    -796, 1246, 717,
+    2277, 927, 539,
+    -454, 559, 440,
+    -717, 1460, 1615,
+    -1030, 1052, 1610,
+    -1169, -138, 847,
+    226, 39, -612,
+    -1251, -106, -729,
+    -651, 968, 1302,
+    -714, -636, 1727,
+    353, 1069, 410,
+    -798, -156, 1099,
+    -574, 918, 446,
+    -1310, 1012, 466,
+    1408, 1591, 765,
+    1429, 1380, 1757,
+    1949, 1956, 2378,
+    1578, 2047, 2148,
+    916, 98, -7,
+    1893, 1418, 2141,
+    348, 1405, 1579,
+    152, 1134, 1801,
+    -267, 154, 1395,
+    -1166, 469, 1054,
+    -1142, -405, -1073,
+    -1341, -2264, -1581,
+    -364, 869, 1706,
+    -1162, 549, 1550,
+    -1225, -1932, -1666,
+    -1485, -1977, -2055,
+    -1727, -906, -98,
+    -1897, 233, 1492,
+    892, 108, -331,
+    -1728, -1170, -1700,
+    -1060, 1980, 1790,
+    -1070, -1741, -1909,
+    -11, 1539, 1317,
+    -1600, 94, 497,
+    421, 443, -197,
+    -1578, -349, -994,
+    -599, -539, 1140,
+    -965, -1419, -129,
+    -1341, 175, -447,
+    -375, 1311, 2055,
+    -371, -650, -307,
+    -1073, 605, 365,
+    -2057, -113, 430,
+    652, 914, 967,
+    -1012, -1586, -2323,
+    1505, 1248, 559,
+    262, -486, -401,
+    -1727, 1342, 1546,
+    50, 56, 432,
+    -330, 119, -604,
+    -1517, -1080, -810,
+    946, 1127, 1055,
+    -1400, -1703, -1712,
+    -1270, -704, -1317,
+    807, 1821, 1143,
+    2760, 1606, 2171,
+    1120, 409, -150,
+    -147, 404, 959,
+    2439, 1911, 2189,
+    -906, -141, -866,
+    -904, -142, -458,
+    -557, -708, -1679,
+    -830, -1431, -1583,
+    -1842, -1346, -1086,
+    -1604, -272, 915,
+    -1196, 772, 1056,
+    -638, -1234, -1897,
+    -500, -81, -822,
+    -1289, -1613, -735,
+    -117, 785, 168,
+    -1090, 1133, 922,
+    -1096, -746, 1384,
+    287, -547, -1063,
+    -1376, -2201, -1204,
+    -2176, -1570, -1757,
+    -1511, -2241, -771,
+    -1737, 1099, 830,
+    -1588, 724, 1243,
+    -1542, 693, 805,
+    -1690, -240, 1665,
+    -1700, -4, -668,
+    2149, 816, 1042,
+    -818, -1841, 22,
+    -764, -507, 449,
+    -1151, -617, 289,
+    -843, -1596, -240,
+    498, -234, -657,
+    -752, 480, 1678,
+    -319, -481, 193,
+    -811, 171, -119,
+    -2128, -202, -848,
+    1717, 1140, 1700
+};
+
+
+/* third codebook from IS641 */
+
+const Word16 dico3_lsf_3[DICO3_SIZE*4] =
+{
+    67, -17, 66, -12,
+    -1690, -581, -104, -272,
+    -1076, -1186, -1845, -376,
+    -1140, -926, -420, -58,
+    -259, -656, -1134, -553,
+    1788, 1227, 455, 129,
+    462, 441, -240, -528,
+    840, 514, 130, -75,
+    1114, 623, 153, 216,
+    1068, 564, -6, -276,
+    1119, 727, 190, -68,
+    704, 306, 119, -264,
+    329, 61, -100, 156,
+    364, 123, 183, -208,
+    -171, -123, 220, -65,
+    -306, -62, 402, 17,
+    -660, -938, -266, 0,
+    385, 235, 276, 285,
+    320, 268, -336, -200,
+    -724, 17, -84, 381,
+    -544, 429, 494, 519,
+    -117, 288, 304, 329,
+    643, 157, 701, 508,
+    1200, 625, 796, 608,
+    998, 421, 492, 632,
+    1204, 780, 446, 132,
+    1257, 844, 547, 449,
+    829, 658, 541, 470,
+    1132, 1258, 918, 639,
+    547, 51, 423, 279,
+    9, 392, 83, 94,
+    542, 543, 229, -147,
+    -198, 129, 194, -185,
+    -863, -1321, -302, 30,
+    -597, -629, -19, 114,
+    -900, -1081, 466, 353,
+    -1483, -1573, 15, -143,
+    -1708, -2059, -751, 196,
+    -1876, -2067, -642, -258,
+    -2335, -1470, -450, -564,
+    -584, -186, -872, -414,
+    -1805, -988, -1125, -1310,
+    -726, -1129, 28, 169,
+    -1039, -864, -718, -246,
+    484, 36, -233, -49,
+    265, 67, 289, 467,
+    178, 543, 810, 540,
+    84, 282, 672, 703,
+    -975, -777, 129, 287,
+    -938, -227, 955, 595,
+    -1617, -289, 836, 649,
+    -1847, -215, 1106, 718,
+    -2034, -1085, 650, 440,
+    -2101, -529, 907, 575,
+    -2011, -336, 670, 204,
+    -2389, -692, 360, 137,
+    -2156, -2204, -9, 280,
+    -266, 119, 39, 193,
+    78, -59, -120, 226,
+    -975, -858, -781, -1095,
+    -619, -413, -451, -842,
+    -1216, -1321, -813, -883,
+    -1376, -1615, -394, -428,
+    -737, -1113, -549, -790,
+    -880, -975, -967, -642,
+    -985, -886, -1273, -1361,
+    -473, -804, -1401, -1407,
+    160, -265, -919, -275,
+    -248, -250, -718, -380,
+    97, -103, -375, -229,
+    -415, -193, -135, -555,
+    628, 361, 119, 216,
+    579, 364, 391, 209,
+    634, 522, -154, -148,
+    526, 389, 170, 33,
+    105, 267, 64, 380,
+    -1503, -1000, -30, -369,
+    -1070, 58, 647, 223,
+    -1520, -291, 621, 307,
+    -1531, 156, 762, 404,
+    -2029, 141, 734, 499,
+    -1849, -650, 306, 512,
+    -187, -104, -59, 438,
+    134, -230, 156, -186,
+    -61, -260, -16, 10,
+    -569, -3, -421, -297,
+    -1725, -521, -346, 178,
+    -1362, -59, -44, 157,
+    -2146, -461, -470, -349,
+    -2170, -1, -369, -121,
+    -1579, -373, -900, -1015,
+    -1117, -591, -613, -784,
+    -561, 122, -75, -449,
+    -4, -171, -123, -372,
+    192, 168, -76, -132,
+    252, -107, 340, 210,
+    392, 509, 272, 181,
+    -109, 145, 218, 119,
+    -416, -263, 485, 265,
+    -181, -8, -286, 226,
+    -244, -218, 69, -290,
+    -158, 191, -1, -64,
+    -592, -90, 213, -96,
+    255, 435, 178, -80,
+    -369, -18, -33, -80,
+    -42, 415, 140, -222,
+    1143, 651, 649, 329,
+    767, 556, 249, 235,
+    948, 413, 442, 279,
+    141, 339, 356, 557,
+    -470, -170, 99, 237,
+    -569, -800, 352, 565,
+    282, 473, 470, 332,
+    -199, -690, -1284, -917,
+    -193, -426, -800, -1122,
+    -26, -371, -490, -193,
+    637, 595, 519, 330,
+    408, -115, 79, 12,
+    477, 87, -103, -376,
+    -666, -347, -277, -291,
+    -510, -481, 169, 297,
+    -829, -738, -205, -171,
+    -320, -540, 328, 283,
+    -859, -958, 442, -2,
+    556, 686, 130, 56,
+    1383, 1012, 755, 427,
+    612, 741, 628, 553,
+    -339, -796, 134, 277,
+    -633, -1085, -2, -246,
+    -880, -1035, -1607, -1064,
+    -994, -474, -1138, -488,
+    -414, -795, 73, -206,
+    -8, -139, 439, 204,
+    -176, -578, 23, 131,
+    -269, -757, -191, 245,
+    -109, -338, 112, 316,
+    120, -406, -118, 611,
+    -180, -186, -645, 115,
+    -173, 34, -518, -489,
+    -151, 61, -583, -844,
+    220, -138, -681, -1020,
+    391, -17, -598, -321,
+    157, -295, 129, 155,
+    -926, -875, -987, 285,
+    241, -83, -125, -125,
+    620, 597, 432, 92,
+    393, 78, 409, 61,
+    -393, -739, -413, -748,
+    83, 54, 361, 27,
+    -1084, 130, -337, -694,
+    -1565, 297, 318, -19,
+    -1873, 36, 51, -317,
+    -2323, -246, 231, -84,
+    -2306, -783, 40, -179,
+    -2233, -930, -474, -462,
+    -754, -86, -288, -626,
+    -2411, -455, -63, 171,
+    -1099, -1094, -26, -143,
+    -1193, -455, -406, -381,
+    -605, -210, -96, -51,
+    -580, -476, -276, -15,
+    -1195, -634, -1203, -881,
+    -378, -221, -669, -952,
+    594, 178, -403, -676,
+    763, 327, 601, 290,
+    172, 300, 203, 157,
+    -56, -336, 356, 24,
+    -228, -296, -259, -29,
+    -186, 263, 416, 14,
+    -353, 373, -12, -216,
+    257, 96, 174, 57,
+    -1526, -616, -954, -499,
+    -497, -152, -333, 125,
+    105, 200, 179, -97,
+    -331, -224, 765, 697,
+    760, 256, 301, 59,
+    455, -85, 204, 288,
+    -514, 240, 251, -109,
+    256, 417, -34, -413,
+    101, 430, 384, 156,
+    -31, -10, 206, 426,
+    589, 145, 143, 71,
+    808, 906, 333, 349,
+    986, 938, 589, 331,
+    1300, 824, 187, 509,
+    1062, 653, 379, 466,
+    1462, 937, 401, 274,
+    787, 861, 265, 2,
+    609, 553, 28, 305,
+    926, 340, 106, 386,
+    241, -267, -147, 225,
+    -178, -534, 347, 502,
+    -643, -381, 397, 30,
+    -651, -733, -435, 398,
+    -407, -726, -484, -248,
+    -789, -914, -438, -476,
+    -498, -390, 75, -295,
+    -964, -590, -606, 150,
+    -121, -49, -155, -78,
+    935, 550, 389, 38,
+    -321, 127, 424, 315,
+    -285, -113, 283, 259,
+    658, 203, 322, 486,
+    903, 505, 748, 417,
+    611, 423, 555, 512,
+    239, -83, -578, -19,
+    -339, -731, 349, 13,
+    -934, -1399, -114, -360,
+    107, 692, 182, 90,
+    -1243, -1538, -1551, -725,
+    -568, -903, -1363, -525,
+    -517, -853, -861, -1004,
+    -168, -690, -835, 63,
+    -137, -556, -547, 144,
+    -286, -817, 485, 319,
+    -147, -408, 526, 246,
+    -347, -434, 297, -28,
+    -290, -471, -1110, -1285,
+    -460, -359, -988, -794,
+    1347, 1299, 690, 523,
+    1216, 1068, 1094, 757,
+    825, 1140, 752, 494,
+    1252, 1365, 1195, 898,
+    521, 1053, 532, 432,
+    -334, -216, -313, -263,
+    -160, 52, -472, -155,
+    127, 136, -380, 44,
+    851, 410, -162, -489,
+    123, -255, -796, -667,
+    1090, 917, 789, 493,
+    1397, 1197, 558, 202,
+    -51, -118, -342, -701,
+    83, 108, -42, -441,
+    61, 95, 287, 256,
+    -27, 89, 524, 531,
+    351, 227, 592, 545,
+    697, 155, -164, 307,
+    638, 274, -489, -50,
+    754, 240, -166, -124,
+    -116, -579, -1212, -63,
+    190, -295, -1040, -1296,
+    147, -376, -177, -113,
+    841, 1241, 1051, 668,
+    2, 293, 551, 304,
+    -1096, -953, -248, 376,
+    -750, -965, 87, 516,
+    -275, -516, 689, 391,
+    -379, -643, 876, 594,
+    -390, -1013, -645, 573,
+    -107, -568, -689, -826,
+    -1025, -27, -328, -203,
+    861, 749, 548, 233,
+    -1660, -1043, 451, 108,
+    -660, -620, 430, 236,
+    21, -396, -1158, -631,
+    1372, 1298, 967, 577,
+    1125, 1125, 589, 454,
+    -323, -865, -467, 153,
+    -468, -699, -804, -509,
+    -392, -718, -204, -35,
+    -603, -1093, -567, -162,
+    -505, -1004, -102, 350,
+    219, 224, 423, 252,
+    395, 591, 608, 363,
+    -746, -96, 373, 172,
+    171, 295, 714, 339,
+    233, 77, 107, 277,
+    157, 153, -499, -356,
+    1547, 1073, 576, 494,
+    -292, -339, -504, -592,
+    -903, -72, -619, -481,
+    -1594, -1117, -567, -254,
+    -793, -507, -564, -291,
+    -492, -532, 502, 560,
+    -382, 427, 600, 230,
+    -227, 477, 251, 75,
+    285, 842, 813, 476,
+    -1310, -1333, 186, 377,
+    -587, -917, 643, 381,
+    -1186, -553, 411, 82,
+    -1127, -820, -174, -540,
+    -604, 119, 543, 205,
+    -380, 657, 909, 567,
+    112, -298, -374, 114,
+    -857, -251, 56, 159,
+    401, 345, -34, -140,
+    -111, -607, 41, 614,
+    355, -114, -77, 474,
+    578, 56, 1450, 924,
+    1098, 1420, 741, 400,
+    246, 22, 588, 313,
+    -121, 327, 831, 472,
+    -1138, -608, 856, 552,
+    -1241, -1072, 638, 600,
+    -358, 254, -333, -303,
+    -646, 739, 358, 74,
+    1226, 1671, 1221, 849,
+    2241, 1624, 983, 636,
+    1841, 1477, 749, 384,
+    350, 263, 87, 128,
+    -1902, -941, -144, -64,
+    -1734, -255, 288, -31,
+    -2644, -1238, 366, 235,
+    -1643, -1092, -1344, -304,
+    -541, -1075, -1116, 123,
+    -1178, -252, -816, -180,
+    -1016, 533, 565, 233,
+    -487, -430, -188, 334,
+    867, 1236, 534, 171,
+    -1590, -1607, 635, 630,
+    -2196, 310, 924, 412,
+    -2358, -328, 956, 529,
+    -2639, -377, 630, 278,
+    -2602, 317, 799, 299,
+    -2406, 133, 340, 31,
+    -2156, -1468, 131, 125,
+    -1184, -490, -139, 46,
+    -744, 447, 891, 564,
+    67, -451, 646, 604,
+    -553, -429, -876, 396,
+    162, -66, 1305, 915,
+    479, 579, 1088, 794,
+    450, 278, 566, 324,
+    -1057, -154, 148, -177,
+    -2545, 168, 1070, 592,
+    -2351, -42, 819, 345,
+    -2344, -707, 721, 250,
+    -2175, -1497, -309, 122,
+    -78, -73, 120, 173,
+    -4, 262, -263, -261,
+    -431, -64, -405, -732,
+    -2609, 116, -83, -193,
+    -1525, -944, -477, -725,
+    -508, 307, 170, 172,
+    832, 417, 832, 686,
+    -225, 177, 894, 818,
+    -482, -389, 1279, 1039,
+    -383, 201, -350, 40,
+    730, 635, 226, 526,
+    503, 462, 338, 398,
+    535, 714, 40, -282,
+    1482, 1471, 1085, 731,
+    1561, 1072, 909, 693,
+    1419, 1282, 889, 879,
+    1153, 728, 1186, 840,
+    -226, 1130, 949, 689,
+    -494, -986, -1556, -128,
+    -568, -721, -713, -26,
+    317, 524, 70, 135,
+    -405, -865, -1766, -652,
+    -174, -801, 885, 773,
+    -153, -91, 1099, 751,
+    -506, -1149, 853, 646,
+    241, 782, 519, 539,
+    1853, 1700, 1101, 684,
+    -1249, -1486, -464, 188,
+    -893, -1409, -1312, -341,
+    -135, 438, -175, 18,
+    1111, 976, 319, 208,
+    -1430, -1768, 83, 458,
+    -530, -1000, 307, 129,
+    -840, -15, -29, -356,
+    -911, -924, -1147, -242,
+    -119, -528, 127, -133,
+    -761, -765, 190, -83,
+    -315, 895, 522, 231,
+    -222, 102, -63, -428,
+    316, 699, 379, 70,
+    25, 716, 314, -108,
+    507, 874, 566, 238,
+    108, 941, 519, 195,
+    425, -60, -427, 257,
+    139, -103, -630, 446,
+    334, 370, 412, 48,
+    -172, -690, -283, 557,
+    187, -286, 158, 483,
+    140, 270, -344, -631,
+    924, 579, -116, 132,
+    142, 466, -68, -64,
+    230, -145, -302, -542,
+    -803, -912, 1018, 737,
+    -773, 1015, 630, 297,
+    -2596, 95, 445, 336,
+    -2122, 491, 510, 191,
+    -1253, 161, -2, -324,
+    -1450, -633, -712, -105,
+    -842, -254, -411, 100,
+    -640, -290, 1010, 763,
+    -650, 313, 1169, 730,
+    140, 505, 1030, 766,
+    772, 287, 1067, 823,
+    495, 749, 305, 323,
+    -164, 462, 78, 399,
+    -342, -874, 69, 597,
+    -16, 620, 621, 337,
+    -138, -444, -265, 218,
+    84, -450, 953, 666,
+    -222, -803, 541, 604,
+    -921, -1376, 244, 116,
+    -841, -723, 630, 588,
+    140, 663, 294, 368,
+    935, 1046, 881, 759,
+    1746, 1464, 916, 628,
+    436, 963, 281, 1,
+    -119, 74, 542, 213,
+    1, -567, 301, 241,
+    260, 435, 222, 396,
+    936, 957, 1108, 703,
+    510, 506, 808, 478,
+    601, 694, 960, 620,
+    972, 741, 980, 600,
+    834, 717, 767, 684,
+    643, 972, 935, 638,
+    501, 661, 720, 851,
+    -105, -632, -303, -117,
+    -429, 130, 789, 442,
+    -522, -188, 704, 373,
+    -759, 42, 814, 523,
+    -531, -1137, 373, 578,
+    -682, -1203, -455, 285,
+    -1163, -1577, -1098, 44,
+    81, -82, 712, 363,
+    477, 246, 954, 622,
+    1604, 1622, 1277, 891,
+    1409, 859, 924, 892,
+    774, 1041, 947, 1142,
+    40, -546, -75, 288,
+    -616, -106, -697, -26,
+    -169, -160, -891, -739,
+    -279, -384, -1029, -350,
+    1781, 1308, 1046, 816,
+    1580, 1533, 1472, 1178,
+    1505, 1076, 1216, 899,
+    890, 904, 564, 654,
+    920, 692, 1021, 856,
+    -493, 132, 177, 505,
+    71, 195, -28, 97,
+    456, 351, -164, 88,
+    439, 278, -40, 350,
+    1395, 949, 234, -95,
+    -805, -472, 38, -163,
+    367, -98, 489, 523,
+    1025, 1178, 1212, 906,
+    319, 1314, 814, 461,
+    -123, -543, -804, 447,
+    -748, -324, -897, -1127,
+    -737, -501, -789, -713,
+    715, 777, 1239, 922,
+    1949, 1939, 1368, 865,
+    730, 880, 758, 388,
+    -871, 454, 17, -251,
+    -381, -810, -1583, 239,
+    -521, -966, -792, 259,
+    -890, -1358, -770, -73,
+    166, 349, -212, 323,
+    -840, -301, 473, 435,
+    -679, -464, 728, 351,
+    -156, -199, 667, 432,
+    29, -252, 415, 480,
+    -731, -379, 145, 559,
+    -528, -631, -1158, -159,
+    445, 273, 123, 639,
+    373, -126, 800, 568,
+    84, -162, 720, 712,
+    -830, -536, -185, 222,
+    408, 452, 501, 771,
+    -897, -1355, -67, 442,
+    -792, -1406, 566, 602,
+    167, -326, 509, 330,
+    -95, -626, -730, -344,
+    1668, 1217, 779, 455,
+    1316, 828, 584, 719,
+    404, -31, 1013, 789,
+    89, 107, 891, 549,
+    871, 1581, 917, 671,
+    866, 1479, 1289, 854,
+    391, 1068, 1122, 812,
+    78, -562, 345, 563,
+    429, -103, 417, 787,
+    -122, -437, 411, 788,
+    -913, -417, 602, 754,
+    -226, -16, 151, 760,
+    -700, 118, -104, -14,
+    -1128, 48, 284, 393,
+    -390, -419, -639, -116,
+    -910, 306, 316, -13,
+    1207, 984, 821, 669,
+    -1195, -693, 140, -213,
+    -884, -416, -199, -558,
+    -616, 245, -404, -664,
+    262, 56, -617, -724,
+    -85, -491, -320, -656,
+    -570, -831, -129, -528,
+    -1506, -63, -367, -385,
+    -358, -321, 4, 51,
+    -366, -214, 319, 511,
+    146, 671, -17, -291,
+    -110, 464, -139, -496,
+    -202, 220, -312, -631,
+    -660, -73, -655, -820,
+    -662, -653, -1288, -857,
+    -430, -953, -959, -264,
+    -49, -468, -72, -381,
+    -350, -563, -193, -407,
+    55, -408, -803, 11,
+    -309, 649, 188, -198,
+    -512, 461, -79, -458,
+    -1318, -263, -134, -523,
+    -1657, -435, -495, -765,
+    57, -347, -414, 434,
+    -1141, -242, -664, -857,
+    34, -68, -707, -338
+};
+
+
+
+/* third codebook for MR475, MR515 */
+
+const Word16 mr515_3_lsf[MR515_3_SIZE*4] =
+{
+    419,   163,   -30,  -262,
+    -455,  -789, -1430,  -721,
+    1006,   664,   269,    25,
+    619,   260,   183,    96,
+    -968, -1358,  -388,   135,
+    -693,   835,   456,   154,
+    1105,   703,   569,   363,
+    1625,  1326,   985,   748,
+    -220,   219,    76,  -208,
+    -1455, -1662,    49,   149,
+    -964,  -172,  -752,  -336,
+    625,   209,  -250,   -66,
+    -1017,  -838,    -2,   317,
+    -2168, -1485,  -138,   123,
+    -1876, -2099,  -521,    85,
+    -967,  -366,  -695,  -881,
+    -921, -1011,  -763,  -949,
+    -124,  -256,  -352,  -660,
+    178,   463,   354,   304,
+    -1744,  -591,  -282,    79,
+    -2249,   175,   867,   499,
+    -138,  -180,  -181,   -21,
+    -2291, -1241,  -460,  -520,
+    -771,   451,   -10,  -308,
+    271,   -65,     4,   214,
+    -279,  -435,   -43,  -348,
+    -670,    35,   -65,  -211,
+    806,   535,    85,   297,
+    57,   239,   722,   493,
+    225,   661,   840,   547,
+    -540,  -376,    14,   349,
+    469,   721,   331,   162,
+    -544,  -752,   -62,   -10,
+    398,   -88,   724,   701,
+    -19,  -533,   -94,   601,
+    136,   -71,  -681,  -747,
+    -166,  -344,   261,   -50,
+    161,   -52,   485,   337,
+    -1675,    50,   190,   -93,
+    -2282,  -231,  -194,   -82,
+    -95,  -595,  -154,   128,
+    894,   501,   588,   457,
+    -345,   206,   122,   110,
+    -631,  -227,  -569,     3,
+    408,   239,   397,   226,
+    -197,    -2,   128,   491,
+    1281,   904,   292,   215,
+    538,   306,   259,   509,
+    -677, -1047,    13,   321,
+    -679,  -588,  -358,  -212,
+    -558,   243,   646,   479,
+    486,   342,   634,   532,
+    107,   802,   331,   136,
+    -112,  -398, -1031,  -286,
+    -326,  -705,   288,   272,
+    1299,  1144,  1178,   860,
+    -423,   121,  -385,  -148,
+    -295,  -302,  -834,  -819,
+    16,   -24,  -201,  -476,
+    555,    91,  -245,   294,
+    -38,  -379,  -962, -1221,
+    -1191, -1518,  -273,  -395,
+    -390, -1013,  -645,   573,
+    -1843, -1030,   505,   468,
+    744,   947,   609,   493,
+    -689, -1172,  -628,  -135,
+    -1026,   195,   411,   196,
+    1582,  1147,   575,   337,
+    -1239,  -777,  -648,  -142,
+    595,   825,   967,   735,
+    -1206,  -970,   -81,  -342,
+    -745,    13,   -72,   375,
+    454,    19,  1407,   921,
+    -1647,  -172,   861,   562,
+    928,  1537,  1063,   740,
+    -2472,  -952,   264,    82,
+    -502,  -965, -1334,   123,
+    867,  1236,   534,   171,
+    -2320,  -460,   780,   363,
+    -1190,  -617,   252,   -61,
+    -174,    34,  1011,   788,
+    -2333,   247,   423,   153,
+    -16,  -355,   262,   449,
+    -1576, -1073,  -544,  -371,
+    -615,  -305,  1051,   805,
+    687,   528,     6,  -182,
+    935,   875,  1002,   809,
+    199,   257,   126,    76,
+    -584, -1138,   599,   556,
+    -1105, -1391, -1591,  -519,
+    -977, -1325,   108,   347,
+    -722,  -975,   365,   101,
+    -145,   681,   249,  -153,
+    0,  -334,  -570,   159,
+    412,   285,  -336,  -617,
+    -953,  -966,   887,   689,
+    -1251,    84,  -185,  -398,
+    -592,   433,  1044,   653,
+    85,   329,   -40,   361,
+    -433,  -705,   466,   574,
+    -154,   654,   592,   290,
+    -167,    72,   349,   175,
+    674,   297,   977,   720,
+    1235,  1204,   757,   488,
+    -400,  -269,   538,   372,
+    -1350, -1387, -1194,   -91,
+    1262,   876,   775,   700,
+    -599,   -38,  -430,  -722,
+    1976,  1630,   991,   608,
+    111,   276,  -226,   -96,
+    -947,  -388,   -11,    -7,
+    -303,  -531,  -839,   338,
+    1734,  1710,  1405,  1013,
+    -516,  -855,  -645,   210,
+    -688,  -416,   513,   230,
+    -822,  -637, -1146,  -320,
+    -952,  -658,  -694,   183,
+    -114,  -623,   818,   674,
+    -191,  -204,   731,   635,
+    51,  1221,   883,   576,
+    -954,  -431,   826,   598,
+    -342,  -755,  -900,  -407,
+    -1126,  -354,  -206,  -512,
+    -547,  -810,  -357,  -620,
+    66,   515,   -73,  -410,
+    -872,  -945, -1444, -1227,
+    191,   -17,  -544,  -231,
+    -1540,  -544,  -901,  -886
+};
+
+/* first codebook for MR795 */
+
+const Word16 mr795_1_lsf[MR795_1_SIZE*3] =
+{
+    -890, -1550, -2541,
+    -819,  -970,   175,
+    -826, -1234,  -762,
+    -599,   -22,   634,
+    -811,  -987,  -902,
+    -323,   203,    26,
+    -383,  -235,  -781,
+    -399,  1262,   906,
+    -932, -1399, -1380,
+    -624,    93,    87,
+    -414,  -539,  -691,
+    37,   633,   510,
+    -387,  -476, -1330,
+    399,    66,   263,
+    -407,   -49,  -335,
+    -417,  1041,  1865,
+    -779, -1089, -1440,
+    -746,  -858,   832,
+    -581,  -759,  -371,
+    -673,  -506,  2088,
+    -560,  -634, -1179,
+    271,   241,    14,
+    -438,  -244,  -397,
+    463,  1202,  1047,
+    -606,  -797, -1438,
+    -51,  -323,   481,
+    -224,  -584,  -527,
+    494,   881,   682,
+    -433,  -306, -1002,
+    554,   659,   222,
+    171,  -160,  -353,
+    681,  1798,  1565,
+    -852, -1181, -1695,
+    -336,  -666,   114,
+    -581,  -756,  -744,
+    -195,   375,   497,
+    -465,  -804, -1098,
+    154,   282,  -131,
+    -50,  -191,  -719,
+    323,   732,  1542,
+    -722,  -819, -1404,
+    105,  -250,   185,
+    -178,  -502,  -742,
+    321,   510,  1111,
+    -323,  -567,  -966,
+    127,   484,   338,
+    -160,    52,  -338,
+    732,  1367,  1554,
+    -626,  -802, -1696,
+    -286,  -586,   676,
+    -695,  -343,  -370,
+    -490,   295,  1893,
+    -630,  -574, -1014,
+    -80,   645,   -69,
+    -6,  -318,  -364,
+    782,  1450,  1038,
+    -313,  -733, -1395,
+    120,    60,   477,
+    -264,  -585,  -123,
+    711,  1245,   633,
+    -91,  -355, -1016,
+    771,   758,   261,
+    253,    81,  -474,
+    930,  2215,  1720,
+    -808, -1099, -1925,
+    -560,  -782,   169,
+    -804, -1074,  -188,
+    -626,   -55,  1405,
+    -694,  -716, -1194,
+    -660,   354,   329,
+    -514,   -55,  -543,
+    366,  1033,  1182,
+    -658,  -959, -1357,
+    -55,  -184,    93,
+    -605,  -286,  -662,
+    404,   449,   827,
+    -286,  -350, -1263,
+    628,   306,   227,
+    -16,   147,  -623,
+    186,   923,  2146,
+    -674,  -890, -1606,
+    -443,  -228,   339,
+    -369,  -790,  -409,
+    231,    86,  1469,
+    -448,  -581, -1061,
+    594,   450,  -177,
+    -124,  -170,  -447,
+    671,  1159,  1404,
+    -476,  -667, -1511,
+    -77,  -138,   716,
+    -177,  -372,  -381,
+    451,   934,   915,
+    -250,  -432,  -822,
+    272,   828,   446,
+    26,    19,   -31,
+    698,  1692,  2168,
+    -646,  -977, -1924,
+    -179,  -473,   268,
+    -379,  -745,  -691,
+    11,   127,  1033,
+    -488,  -917,  -825,
+    61,   323,   135,
+    147,  -145,  -686,
+    685,   786,  1682,
+    -506,  -848, -1297,
+    35,    90,   222,
+    -23,  -346,  -670,
+    455,   591,  1287,
+    -203,  -593, -1086,
+    652,   352,   437,
+    39,    63,  -457,
+    841,  1265,  2105,
+    -520,  -882, -1584,
+    -328,  -711,  1421,
+    -596,  -342,   -70,
+    209,   173,  1928,
+    -423,  -598,  -921,
+    421,   605,   -38,
+    -2,  -245,  -127,
+    896,  1969,  1135,
+    -379,  -518, -1579,
+    173,   118,   753,
+    -55,  -381,   -52,
+    985,  1021,   753,
+    -2,  -291,  -891,
+    753,   992,   423,
+    264,   131,  -196,
+    895,  2274,  2543,
+    -635, -1088, -2499,
+    -529,  -982,   526,
+    -764,  -830,  -548,
+    -436,   316,   599,
+    -675,  -940,  -746,
+    -57,   236,   -11,
+    -201,   -81,  -798,
+    16,   845,  1558,
+    -737,  -985, -1212,
+    -468,    17,   290,
+    -279,  -584,  -700,
+    183,   822,   705,
+    -265,  -492, -1187,
+    421,   152,   468,
+    -390,   166,  -268,
+    39,  1550,  1868,
+    -635,  -966, -1571,
+    -453,  -492,   910,
+    -284, -1027,   -75,
+    -181,  -133,  1852,
+    -445,  -624, -1174,
+    420,   367,   -49,
+    -389,  -212,  -169,
+    707,  1073,  1208,
+    -539,  -710, -1449,
+    83,  -163,   484,
+    -236,  -543,  -355,
+    338,  1175,   814,
+    -246,  -309,  -958,
+    606,   760,    60,
+    166,    -8,  -163,
+    -306,  1849,  2563,
+    -747, -1025, -1783,
+    -419,  -446,   209,
+    -718,  -566,  -534,
+    -506,   693,   857,
+    -463,  -697, -1082,
+    325,   431,  -206,
+    -15,    -8,  -763,
+    545,   919,  1518,
+    -611,  -783, -1313,
+    256,   -55,   208,
+    -165,  -348,  -662,
+    321,   680,   930,
+    -326,  -429,  -951,
+    484,   446,   570,
+    -197,    72,   -73,
+    909,  1455,  1741,
+    -563,  -737, -1974,
+    -124,  -416,   718,
+    -478,  -404,  -314,
+    -16,   446,  1636,
+    -551,  -537,  -750,
+    -58,   638,   214,
+    55,  -185,  -271,
+    1148,  1301,  1212,
+    -483,  -671, -1264,
+    117,   285,   543,
+    -204,  -391,  -111,
+    513,  1538,   854,
+    -114,  -190,  -978,
+    877,   595,   464,
+    260,   260,  -311,
+    748,  2283,  2216,
+    -517,  -945, -2171,
+    -326,  -708,   378,
+    -812,  -691,  -232,
+    -560,   687,  1409,
+    -732,  -690,  -836,
+    -359,   645,   386,
+    -265,    62,  -678,
+    145,  1644,  1208,
+    -555,  -988, -1233,
+    -78,    14,   114,
+    -327,  -358,  -489,
+    392,   677,   697,
+    -201,  -236, -1140,
+    693,   449,   178,
+    -243,   256,  -433,
+    611,  1385,  2456,
+    -612,  -901, -1464,
+    -307,   -17,   499,
+    -315,  -667,  -254,
+    256,   428,  1463,
+    -486,  -422, -1056,
+    655,   370,    18,
+    -102,  -185,  -276,
+    755,  1578,  1335,
+    -488,  -603, -1418,
+    182,   -93,   870,
+    -73,  -458,  -348,
+    835,   862,   957,
+    -282,  -333,  -746,
+    547,   839,   428,
+    273,   -89,    13,
+    940,  1708,  2576,
+    -418, -1084, -1758,
+    -44,  -358,   259,
+    -497,  -643,  -560,
+    99,   557,   961,
+    -421,  -766,  -917,
+    295,   326,   184,
+    175,    15,  -626,
+    532,   878,  1981,
+    -443,  -768, -1275,
+    221,   156,   268,
+    39,  -363,  -505,
+    695,   772,  1140,
+    -162,  -459,  -912,
+    709,   444,   658,
+    25,   303,  -312,
+    1268,  1410,  1715,
+    -297,  -766, -1836,
+    -263,  -108,  1070,
+    -406,   -13,  -129,
+    57,   438,  2734,
+    -374,  -487,  -835,
+    304,   696,   164,
+    104,  -235,     5,
+    1611,  1900,  1399,
+    -229,  -582, -1325,
+    405,   192,   817,
+    -87,  -438,   111,
+    1028,  1199,   993,
+    68,  -175,  -934,
+    1033,  1117,   451,
+    478,   200,  -248,
+    2127,  2696,  2042,
+    -835, -1323, -2131,
+    -799,  -692,   466,
+    -812, -1032,  -469,
+    -622,   288,   920,
+    -701,  -841, -1070,
+    -411,   512,     8,
+    -390,   -91,  -744,
+    -30,  1043,  1161,
+    -822, -1148, -1156,
+    -294,   -46,   110,
+    -411,  -374,  -678,
+    214,   531,   668,
+    -406,  -420, -1194,
+    487,   232,   303,
+    -318,    91,  -472,
+    123,  1232,  2445,
+    -722,  -952, -1495,
+    -738,  -675,  1332,
+    -543,  -606,  -211,
+    -95,   -98,  1508,
+    -549,  -514, -1193,
+    473,   211,    73,
+    -288,  -112,  -389,
+    537,  1332,  1258,
+    -567,  -755, -1545,
+    71,  -283,   632,
+    -170,  -481,  -493,
+    681,  1002,   817,
+    -356,  -331,  -877,
+    419,   706,   346,
+    241,   -34,  -326,
+    377,  1950,  1883,
+    -727, -1075, -1625,
+    -233,  -543,   116,
+    -524,  -806,  -585,
+    -73,   478,   729,
+    -288,  -925, -1143,
+    173,   447,   -52,
+    68,  -229,  -606,
+    449,   529,  1797,
+    -591,  -875, -1363,
+    183,  -144,   324,
+    -103,  -452,  -666,
+    623,   488,  1176,
+    -238,  -511, -1004,
+    326,   552,   458,
+    136,   108,  -319,
+    626,  1343,  1883,
+    -490,  -646, -1730,
+    -186,  -449,   984,
+    -738,   -76,  -170,
+    -550,   755,  2560,
+    -496,  -510,  -947,
+    210,   694,   -52,
+    84,  -322,  -199,
+    1090,  1625,  1224,
+    -376,  -603, -1396,
+    343,    74,   632,
+    -175,  -502,   -32,
+    972,  1332,   734,
+    52,  -295, -1113,
+    1065,   918,   160,
+    393,   107,  -397,
+    1214,  2649,  1741,
+    -632, -1201, -1891,
+    -719,  -277,   353,
+    -651,  -880,  -122,
+    -211,   209,  1338,
+    -562,  -714, -1059,
+    -208,   388,   159,
+    -320,   -61,  -551,
+    293,  1092,  1443,
+    -648,  -865, -1253,
+    -49,  -143,   305,
+    -401,  -227,  -585,
+    561,   532,   927,
+    -117,  -443, -1188,
+    507,   436,   292,
+    -79,   233,  -458,
+    671,  1025,  2396,
+    -633,  -842, -1525,
+    -308,  -286,   640,
+    -373,  -621,  -407,
+    418,   253,  1305,
+    -315,  -581, -1137,
+    572,   685,  -281,
+    61,   -68,  -371,
+    991,  1101,  1498,
+    -493,  -683, -1362,
+    -47,   164,   704,
+    -256,  -314,  -268,
+    631,   949,  1052,
+    -118,  -348,  -833,
+    68,  1180,   568,
+    152,   117,    34,
+    1113,  1902,  2239,
+    -601,  -959, -1706,
+    -143,  -489,   480,
+    -332,  -655,  -574,
+    54,   353,  1192,
+    -462,  -652,  -796,
+    150,   549,   112,
+    195,  -111,  -515,
+    679,  1108,  1647,
+    -558,  -749, -1217,
+    -9,   272,   341,
+    -53,  -265,  -535,
+    489,   843,  1298,
+    -120,  -482, -1032,
+    632,   543,   408,
+    179,   306,  -526,
+    1124,  1464,  2244,
+    -417,  -786, -1562,
+    -224,  -384,  1364,
+    -377,  -459,   -25,
+    385,   489,  2174,
+    -332,  -651,  -829,
+    544,   553,    61,
+    22,  -113,   -89,
+    1128,  1725,  1524,
+    -216,  -373, -1653,
+    161,   316,   908,
+    -165,  -222,   -67,
+    1362,  1175,   789,
+    73,  -252,  -767,
+    738,   932,   616,
+    362,   246,  -126,
+    787,  2654,  3027,
+    -691, -1106, -2190,
+    -565,  -588,   524,
+    -590,  -979,  -490,
+    -263,   397,   982,
+    -577,  -837,  -945,
+    -22,   435,   -49,
+    -190,  -118,  -629,
+    -88,  1240,  1513,
+    -636, -1051, -1019,
+    -291,   189,   259,
+    -257,  -470,  -629,
+    145,   945,   894,
+    -326,  -364, -1094,
+    543,   260,   630,
+    -202,   189,  -209,
+    357,  1379,  2091,
+    -569, -1075, -1449,
+    -714,  -239,   919,
+    -420,  -705,   -84,
+    -109,  -114,  2407,
+    -413,  -529, -1177,
+    482,   368,   131,
+    -186,   -72,  -131,
+    861,  1255,  1220,
+    -611,  -658, -1341,
+    227,  -121,   631,
+    -176,  -489,  -218,
+    745,  1175,   957,
+    -321,  -148,  -936,
+    671,   966,   216,
+    340,    -3,  -143,
+    469,  1848,  2437,
+    -729,  -961, -1683,
+    -213,  -254,   321,
+    -511,  -438,  -521,
+    -126,   725,   903,
+    -340,  -685, -1032,
+    316,   480,    20,
+    23,   -89,  -551,
+    353,  1051,  1789,
+    -544,  -757, -1364,
+    298,   -25,   436,
+    -100,  -392,  -519,
+    467,   754,  1078,
+    -210,  -398, -1078,
+    620,   658,   630,
+    33,   147,  -178,
+    921,  1687,  1921,
+    -325,  -528, -1978,
+    2,  -285,   910,
+    -371,  -490,  -230,
+    0,   597,  2010,
+    -496,  -395,  -834,
+    37,   945,   245,
+    181,  -160,  -144,
+    1481,  1373,  1357,
+    -355,  -601, -1270,
+    298,   322,   672,
+    -193,  -336,    77,
+    1089,  1533,   922,
+    177,   -39, -1125,
+    996,   781,   536,
+    456,   366,  -432,
+    1415,  2440,  2279,
+    -466,  -758, -2325,
+    -303,  -509,   387,
+    -727,  -557,    66,
+    -145,   643,  1248,
+    -544,  -676,  -916,
+    -225,   862,   588,
+    -152,    40,  -533,
+    423,  1423,  1558,
+    -572,  -843, -1145,
+    -128,    85,   461,
+    -238,  -257,  -584,
+    605,   748,   861,
+    24,  -202, -1409,
+    797,   487,   303,
+    -181,   364,  -182,
+    616,  1378,  2942,
+    -494,  -852, -1441,
+    -292,    61,   812,
+    -84,  -723,  -182,
+    555,   532,  1506,
+    -365,  -493, -1057,
+    822,   588,    11,
+    -14,   -18,  -230,
+    1001,  1401,  1451,
+    -474,  -569, -1292,
+    302,    62,  1062,
+    -70,  -376,  -222,
+    982,   974,  1149,
+    -196,  -234,  -795,
+    479,  1098,   499,
+    362,    58,    70,
+    1147,  2069,  2857,
+    -487,  -878, -1824,
+    73,  -288,   348,
+    -358,  -500,  -508,
+    199,   721,  1242,
+    -78,  -697,  -795,
+    361,   536,   196,
+    374,   110,  -735,
+    847,  1051,  1896,
+    -366,  -713, -1182,
+    315,   320,   429,
+    72,  -215,  -450,
+    759,   886,  1363,
+    -30,  -428,  -834,
+    861,   627,   796,
+    118,   468,  -279,
+    1355,  1883,  1893,
+    -188,  -642, -1612,
+    63,  -175,  1198,
+    -418,  -211,    51,
+    414,   587,  2601,
+    -234,  -557,  -858,
+    424,   889,   222,
+    136,  -101,    83,
+    1413,  2278,  1383,
+    -84,  -445, -1389,
+    414,   313,  1045,
+    29,  -343,    65,
+    1552,  1647,   980,
+    183,   -91,  -829,
+    1273,  1413,   360,
+    553,   272,  -107,
+    1587,  3149,  2603
+};
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_5.cpp b/media/libstagefright/codecs/amrnb/common/src/q_plsf_5.cpp
new file mode 100644
index 0000000..2f9e40e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/q_plsf_5.cpp
@@ -0,0 +1,691 @@
+/* ------------------------------------------------------------------
+ * 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_plsf_5.c
+ Funtions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed code in the PV standard template format.
+ Updated to accept new parameter, Flag *pOverflow.
+
+ Description:
+              Eliminated unused include files.
+              For Vq_subvec()
+              1. Eliminated math operations that unnecessary checked for
+                 saturation (number are bounded to 2^12)
+              2. Eliminated access to (slow) memory by using axiliar variables
+              3. Because this routine is looking for the minimum distance,
+                 introduced 3 check conditions inside the loop, so when the
+                 partial distance is bigger than the minimun distance, the
+                 loop is not completed and process continue with next iteration
+              For Vq_subvec_s()
+              1. Eliminated math operations that unnecessary checked for
+                 saturation (number are bounded to 2^12)
+              2. Combined increasing and decreasing loops to avoid double
+                 accesses to the same table element
+              3. Eliminated access to (slow) memory by using axiliar variables
+              4. Because this routine is looking for the minimum distance,
+                 introduced 2 check conditions inside the loop, so when the
+                 partial distance is bigger than the minimun distance, the
+                 loop is not completed and process continue with next iteration
+              For Q_plsf_5()
+              1. Eliminated math operations that unnecessary checked for
+                 saturation (number are bounded to 2^12)
+              2. Replaced array addressing by pointers
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "q_plsf.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+#include "lsfwt.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
+    ----------------------------------------------------------------------------*/
+    /* Codebooks of LSF prediction residual */
+    extern const Word16 mean_lsf_5[];
+
+    extern const Word16 dico1_lsf_5[];
+    extern const Word16 dico2_lsf_5[];
+    extern const Word16 dico3_lsf_5[];
+    extern const Word16 dico4_lsf_5[];
+    extern const Word16 dico5_lsf_5[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Vq_subvec
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 -- array of type Word16 -- 1st LSF residual vector,  Q15
+    lsf_r2 -- array of type Word16 -- 2nd LSF residual vector,  Q15
+    dico -- pointer to const Word16 -- quantization codebook,   Q15
+    wf1 -- array of type Word16 -- 1st LSF weighting factors,   Q13
+    wf2 -- array of type Word16 -- 2nd LSF weighting factors,   Q13
+    dico_size -- Word16 -- size of quantization codebook,       Q0
+ Outputs:
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    Word16 -- quantization index, Q0
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the quantization of a 4-dimensional subvector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_5.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]
+
+------------------------------------------------------------------------------
+*/
+/* Quantization of a 4 dimensional subvector */
+
+static Word16 Vq_subvec( /* o : quantization index,            Q0  */
+    Word16 *lsf_r1,      /* i : 1st LSF residual vector,       Q15 */
+    Word16 *lsf_r2,      /* i : 2nd LSF residual vector,       Q15 */
+    const Word16 *dico,  /* i : quantization codebook,         Q15 */
+    Word16 *wf1,         /* i : 1st LSF weighting factors      Q13 */
+    Word16 *wf2,         /* i : 2nd LSF weighting factors      Q13 */
+    Word16 dico_size,    /* i : size of quantization codebook, Q0  */
+    Flag   *pOverflow    /* o : overflow indicator                 */
+)
+{
+    Word16 index = 0; /* initialization only needed to keep gcc silent */
+    Word16 i;
+    Word16 temp;
+    const Word16 *p_dico;
+    Word32 dist_min;
+    Word32 dist;
+    Word16 wf1_0;
+    Word16 wf1_1;
+    Word16 wf2_0;
+    Word16 wf2_1;
+    Word32 aux1;
+    Word32 aux2;
+    Word32 aux3;
+    Word32 aux4;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+    wf1_0 = wf1[0];
+    wf1_1 = wf1[1];
+    wf2_0 = wf2[0];
+    wf2_1 = wf2[1];
+
+    aux1 = ((Word32) lsf_r1[0] * wf1_0);
+    aux2 = ((Word32) lsf_r1[1] * wf1_1);
+    aux3 = ((Word32) lsf_r2[0] * wf2_0);
+    aux4 = ((Word32) lsf_r2[1] * wf2_1);
+
+    for (i = 0; i < dico_size; i++)
+    {
+        temp  = (aux1 - ((Word32)wf1_0 * *(p_dico++))) >> 15;
+        dist  = ((Word32)temp * temp);
+
+        if (dist >= dist_min)
+        {
+            p_dico += 3;
+            continue;
+        }
+
+        temp  = (aux2 - ((Word32)wf1_1 * *(p_dico++))) >> 15;
+        dist += ((Word32)temp * temp);
+
+        if (dist >= dist_min)
+        {
+            p_dico += 2;
+            continue;
+        }
+
+        temp  = (aux3 - ((Word32)wf2_0 * *(p_dico++))) >> 15;
+        dist += ((Word32)temp * temp);
+
+        if (dist >= dist_min)
+        {
+            p_dico += 1;
+            continue;
+        }
+
+        temp  = (aux4 - ((Word32)wf2_1 * *(p_dico++))) >> 15;
+        dist += ((Word32)temp * temp);
+
+
+        if (dist < dist_min)
+        {
+            dist_min = dist;
+            index = i;
+        }
+    }
+
+
+
+    /* Reading the selected vector */
+
+    p_dico = &dico[ index<<2];
+    lsf_r1[0] = *p_dico++;
+    lsf_r1[1] = *p_dico++;
+    lsf_r2[0] = *p_dico++;
+    lsf_r2[1] = *p_dico;
+
+    return index;
+
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Vq_subvec_s
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_r1 -- array of type Word16 -- 1st LSF residual vector,  Q15
+    lsf_r2 -- array of type Word16 -- 2nd LSF residual vector,  Q15
+    dico -- pointer to const Word16 -- quantization codebook,   Q15
+    wf1 -- array of type Word16 -- 1st LSF weighting factors,   Q13
+    wf2 -- array of type Word16 -- 2nd LSF weighting factors,   Q13
+    dico_size -- Word16 -- size of quantization codebook,       Q0
+
+ Outputs:
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    Word16 -- quantization index, Q0
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the quantization of a 4-dimensional subvector.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_5.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]
+
+------------------------------------------------------------------------------
+*/
+
+
+/* Quantization of a 4 dimensional subvector with a signed codebook */
+
+static Word16 Vq_subvec_s(  /* o : quantization index            Q0  */
+    Word16 *lsf_r1,         /* i : 1st LSF residual vector       Q15 */
+    Word16 *lsf_r2,         /* i : and LSF residual vector       Q15 */
+    const Word16 *dico,     /* i : quantization codebook         Q15 */
+    Word16 *wf1,            /* i : 1st LSF weighting factors     Q13 */
+    Word16 *wf2,            /* i : 2nd LSF weighting factors     Q13 */
+    Word16 dico_size,       /* i : size of quantization codebook Q0  */
+    Flag   *pOverflow)      /* o : overflow indicator                */
+{
+    Word16 index = 0;  /* initialization only needed to keep gcc silent */
+    Word16 sign = 0;   /* initialization only needed to keep gcc silent */
+    Word16 i;
+    Word16 temp;
+    Word16 temp1;
+    Word16 temp2;
+    const Word16 *p_dico;
+    Word32 dist_min;
+    Word32 dist1;
+    Word32 dist2;
+
+    Word16 lsf_r1_0;
+    Word16 lsf_r1_1;
+    Word16 lsf_r2_0;
+    Word16 lsf_r2_1;
+
+    Word16 wf1_0;
+    Word16 wf1_1;
+    Word16 wf2_0;
+    Word16 wf2_1;
+
+    OSCL_UNUSED_ARG(pOverflow);
+
+    dist_min = MAX_32;
+    p_dico = dico;
+
+
+    lsf_r1_0 = lsf_r1[0];
+    lsf_r1_1 = lsf_r1[1];
+    lsf_r2_0 = lsf_r2[0];
+    lsf_r2_1 = lsf_r2[1];
+
+    wf1_0 = wf1[0];
+    wf1_1 = wf1[1];
+    wf2_0 = wf2[0];
+    wf2_1 = wf2[1];
+
+    for (i = 0; i < dico_size; i++)
+    {
+        /* test positive */
+        temp = *p_dico++;
+        temp1 = lsf_r1_0 - temp;
+        temp2 = lsf_r1_0 + temp;
+        temp1 = ((Word32)wf1_0 * temp1) >> 15;
+        temp2 = ((Word32)wf1_0 * temp2) >> 15;
+        dist1 = ((Word32)temp1 * temp1);
+        dist2 = ((Word32)temp2 * temp2);
+
+        temp = *p_dico++;
+        temp1 = lsf_r1_1 - temp;
+        temp2 = lsf_r1_1 + temp;
+        temp1 = ((Word32)wf1_1 * temp1) >> 15;
+        temp2 = ((Word32)wf1_1 * temp2) >> 15;
+        dist1 += ((Word32)temp1 * temp1);
+        dist2 += ((Word32)temp2 * temp2);
+
+        if ((dist1 >= dist_min) && (dist2 >= dist_min))
+        {
+            p_dico += 2;
+            continue;
+        }
+
+        temp = *p_dico++;
+        temp1 = lsf_r2_0 - temp;
+        temp2 = lsf_r2_0 + temp;
+        temp1 = ((Word32)wf2_0 * temp1) >> 15;
+        temp2 = ((Word32)wf2_0 * temp2) >> 15;
+        dist1 += ((Word32)temp1 * temp1);
+        dist2 += ((Word32)temp2 * temp2);
+
+        temp = *p_dico++;
+        temp1 = lsf_r2_1 - temp;
+        temp2 = lsf_r2_1 + temp;
+        temp1 = ((Word32)wf2_1 * temp1) >> 15;
+        temp2 = ((Word32)wf2_1 * temp2) >> 15;
+        dist1 += ((Word32)temp1 * temp1);
+        dist2 += ((Word32)temp2 * temp2);
+
+        if (dist1 < dist_min)
+        {
+            dist_min = dist1;
+            index = i;
+            sign = 0;
+        }
+
+        /* test negative */
+
+        if (dist2 < dist_min)
+        {
+            dist_min = dist2;
+            index = i;
+            sign = 1;
+        }
+    }
+
+    /* Reading the selected vector */
+
+    p_dico = &dico[index<<2];
+    index <<= 1;
+    if (sign)
+    {
+        lsf_r1[0] = - (*p_dico++);
+        lsf_r1[1] = - (*p_dico++);
+        lsf_r2[0] = - (*p_dico++);
+        lsf_r2[1] = - (*p_dico);
+        index +=  1;
+    }
+    else
+    {
+        lsf_r1[0] = *p_dico++;
+        lsf_r1[1] = *p_dico++;
+        lsf_r2[0] = *p_dico++;
+        lsf_r2[1] = *p_dico;
+    }
+
+    return index;
+
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Q_plsf_5
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+ Inputs:
+    st   -- pointer to Q_plsfState -- state information
+    lsp1 -- array of type Word16 -- 1st LSP vector,  Q15
+    lsp2 -- array of type Word16 -- 2nd LSP vector,  Q15
+
+ Outputs:
+    lps1_q -- array of type Word16 -- quantized 1st LSP vector,   Q15
+    lps2_q -- array of type Word16 -- quantized 2nd LSP vector,   Q15
+    indices -- array of type Word16 -- quantization indices of 5 matrics, Q0
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    mean_lsf_5[];
+
+    dico1_lsf_5[];
+    dico2_lsf_5[];
+    dico3_lsf_5[];
+    dico4_lsf_5[];
+    dico5_lsf_5[];
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Quantization of 2 sets of LSF parameters using 1st order MA
+           prediction and split by 5 matrix quantization (split-MQ)
+
+ DESCRIPTION:
+
+      p[i] = pred_factor*past_rq[i];   i=0,...,m-1
+      r1[i]= lsf1[i] - p[i];           i=0,...,m-1
+      r2[i]= lsf2[i] - p[i];           i=0,...,m-1
+ where:
+      lsf1[i]           1st mean-removed LSF vector.
+      lsf2[i]           2nd mean-removed LSF vector.
+      r1[i]             1st residual prediction vector.
+      r2[i]             2nd residual prediction vector.
+      past_r2q[i]       Past quantized residual (2nd vector).
+
+ The residual vectors r1[i] and r2[i] are jointly quantized using
+ split-MQ with 5 codebooks. Each 4th dimension submatrix contains 2
+ elements from each residual vector. The 5 submatrices are as follows:
+   {r1[0], r1[1], r2[0], r2[1]};  {r1[2], r1[3], r2[2], r2[3]};
+   {r1[4], r1[5], r2[4], r2[5]};  {r1[6], r1[7], r2[6], r2[7]};
+                  {r1[8], r1[9], r2[8], r2[9]}
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ q_plsf_5.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 Q_plsf_5(
+    Q_plsfState *st,
+    Word16 *lsp1,      /* i : 1st LSP vector,                     Q15 */
+    Word16 *lsp2,      /* i : 2nd LSP vector,                     Q15 */
+    Word16 *lsp1_q,    /* o : quantized 1st LSP vector,           Q15 */
+    Word16 *lsp2_q,    /* o : quantized 2nd LSP vector,           Q15 */
+    Word16 *indice,    /* o : quantization indices of 5 matrices, Q0  */
+    Flag   *pOverflow  /* o : overflow indicator                      */
+)
+{
+    Word16 i;
+    Word16 lsf1[M];
+    Word16 lsf2[M];
+    Word16 wf1[M];
+    Word16 wf2[M];
+    Word16 lsf_p[M];
+    Word16 lsf_r1[M];
+    Word16 lsf_r2[M];
+    Word16 lsf1_q[M];
+    Word16 lsf2_q[M];
+
+    Word16 *p_lsf_p;
+    Word16 *p_lsf1;
+    Word16 *p_lsf2;
+    Word16 *p_lsf_r1;
+    Word16 *p_lsf_r2;
+
+    /* convert LSFs to normalize frequency domain 0..16384  */
+
+    Lsp_lsf(lsp1, lsf1, M, pOverflow);
+    Lsp_lsf(lsp2, lsf2, M, pOverflow);
+
+    /* Compute LSF weighting factors (Q13) */
+
+    Lsf_wt(lsf1, wf1, pOverflow);
+    Lsf_wt(lsf2, wf2, pOverflow);
+
+    /* Compute predicted LSF and prediction error */
+
+    p_lsf_p  = &lsf_p[0];
+    p_lsf1   = &lsf1[0];
+    p_lsf2   = &lsf2[0];
+    p_lsf_r1 = &lsf_r1[0];
+    p_lsf_r2 = &lsf_r2[0];
+
+    for (i = 0; i < M; i++)
+    {
+        *(p_lsf_p) = mean_lsf_5[i] +
+                     (((Word32)st->past_rq[i] * LSP_PRED_FAC_MR122) >> 15);
+
+        *(p_lsf_r1++) = *(p_lsf1++) - *(p_lsf_p);
+        *(p_lsf_r2++) = *(p_lsf2++) - *(p_lsf_p++);
+    }
+
+    /*---- Split-MQ of prediction error ----*/
+
+    indice[0] = Vq_subvec(&lsf_r1[0], &lsf_r2[0], dico1_lsf_5,
+                          &wf1[0], &wf2[0], DICO1_5_SIZE, pOverflow);
+
+    indice[1] = Vq_subvec(&lsf_r1[2], &lsf_r2[2], dico2_lsf_5,
+                          &wf1[2], &wf2[2], DICO2_5_SIZE, pOverflow);
+
+    indice[2] = Vq_subvec_s(&lsf_r1[4], &lsf_r2[4], dico3_lsf_5,
+                            &wf1[4], &wf2[4], DICO3_5_SIZE, pOverflow);
+
+    indice[3] = Vq_subvec(&lsf_r1[6], &lsf_r2[6], dico4_lsf_5,
+                          &wf1[6], &wf2[6], DICO4_5_SIZE, pOverflow);
+
+    indice[4] = Vq_subvec(&lsf_r1[8], &lsf_r2[8], dico5_lsf_5,
+                          &wf1[8], &wf2[8], DICO5_5_SIZE, pOverflow);
+
+    /* Compute quantized LSFs and update the past quantized residual */
+
+    p_lsf_r1 = &lsf_r1[0];
+    p_lsf_r2 = &lsf_r2[0];
+    p_lsf_p  = &lsf_p[0];
+    p_lsf1   = &lsf1_q[0];
+    p_lsf2   = &lsf2_q[0];
+
+
+    for (i = 0; i < M; i++)
+    {
+        *(p_lsf1++) = *(p_lsf_r1++) + *(p_lsf_p);
+        *(p_lsf2++) = *(p_lsf_r2) + *(p_lsf_p++);
+        st->past_rq[i] = *(p_lsf_r2++);
+    }
+
+    /* verification that LSFs has minimum distance of LSF_GAP */
+
+    Reorder_lsf(lsf1_q, LSF_GAP, M, pOverflow);
+    Reorder_lsf(lsf2_q, LSF_GAP, M, pOverflow);
+
+    /*  convert LSFs to the cosine domain */
+
+    Lsf_lsp(lsf1_q, lsp1_q, M, pOverflow);
+    Lsf_lsp(lsf2_q, lsp2_q, M, pOverflow);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.cpp
new file mode 100644
index 0000000..ceb1e1e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/q_plsf_5_tbl.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.
+****************************************************************************************/
+/*
+
+ Filename: /audio/gsm_amr/c/src/q_plsf_5_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, q_plsf_5_tbl.tab
+
+ Description: Changed #defines of DICO_SIZE to DICO_5_SIZE, to avoid name
+ conflicts.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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.]
+    ----------------------------------------------------------------------------*/
+#define NB_QUA_PITCH 16
+#define NB_QUA_CODE 32
+
+
+#define DICO1_5_SIZE  128
+#define DICO2_5_SIZE  256
+#define DICO3_5_SIZE  256
+#define DICO4_5_SIZE  256
+#define DICO5_5_SIZE  64
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; [Variable declaration - defined here and used outside this module]
+    ----------------------------------------------------------------------------*/
+    /* LSF means ->normalize frequency domain */
+
+    extern const Word16 mean_lsf_5[10] =
+    {
+        1384,
+        2077,
+        3420,
+        5108,
+        6742,
+        8122,
+        9863,
+        11092,
+        12714,
+        13701
+    };
+
+    extern const Word16 dico1_lsf_5[DICO1_5_SIZE * 4] =
+    {
+        -451, -1065, -529, -1305,
+        -450, -756, -497, -863,
+        -384, -619, -413, -669,
+        -317, -538, -331, -556,
+        -414, -508, -424, -378,
+        -274, -324, -434, -614,
+        -226, -500, -232, -514,
+        -263, -377, -298, -410,
+        -151, -710, -174, -818,
+        -149, -412, -156, -429,
+        -288, -462, -186, -203,
+        -170, -302, -191, -321,
+        -131, -147, -297, -395,
+        -228, -214, -245, -192,
+        -67, -316, -71, -327,
+        -104, -205, -94, -183,
+        -143, -38, -193, -95,
+        16, -76, -124, -248,
+        23, -237, 24, -244,
+        18, -136, 44, -111,
+        -33, -24, -25, 0,
+        149, 19, 23, -143,
+        158, -169, 174, -181,
+        133, -55, 165, -26,
+        111, 84, 98, 75,
+        87, 183, -115, -11,
+        -8, 130, 11, 170,
+        254, 77, 205, 17,
+        183, 112, 262, 194,
+        202, 287, 95, 189,
+        -42, -105, 234, 179,
+        39, 186, 163, 345,
+        332, 199, 299, 161,
+        -54, 285, -78, 281,
+        -133, 141, -182, 111,
+        249, 341, 271, 364,
+        93, 403, 75, 391,
+        92, 510, -138, 220,
+        -185, -29, -34, 361,
+        -115, 320, 3, 554,
+        99, 286, 218, 591,
+        -245, 406, -268, 453,
+        0, 580, 25, 606,
+        275, 532, 148, 450,
+        -73, 739, -285, 518,
+        -288, 94, -203, 674,
+        -140, -74, 205, 714,
+        -114, 299, 176, 923,
+        182, 557, 240, 705,
+        -16, 513, 485, 593,
+        293, 384, 451, 617,
+        -38, 50, 563, 529,
+        303, 209, 459, 363,
+        433, 452, 450, 454,
+        367, 606, 477, 741,
+        432, 353, 368, 267,
+        361, 716, 273, 583,
+        453, 166, 510, 172,
+        201, 629, 274, 191,
+        568, 639, 302, 298,
+        634, 387, 643, 350,
+        587, 560, 612, 565,
+        600, 788, 487, 672,
+        512, 1015, 321, 333,
+        357, 854, -125, 413,
+        474, 712, 17, -151,
+        564, 285, 270, -241,
+        971, 889, 489, 220,
+        510, 896, 549, 924,
+        327, 825, 290, 911,
+        540, 1108, 158, 805,
+        199, 957, 511, 730,
+        100, 874, 13, 791,
+        435, 632, 676, 972,
+        249, 900, 467, 1218,
+        781, 1074, 585, 785,
+        -23, 669, 267, 1043,
+        619, 1084, 615, 1145,
+        622, 905, 916, 1049,
+        80, 331, 584, 1075,
+        89, 639, 988, 961,
+        770, 720, 798, 699,
+        492, 447, 899, 627,
+        271, 1188, 725, 1333,
+        87, 603, 832, 1603,
+        616, 1127, 890, 1505,
+        1000, 1156, 866, 1009,
+        995, 827, 1149, 858,
+        817, 1450, 773, 1320,
+        500, 1389, 312, 1153,
+        -20, 1084, 64, 1283,
+        2, 1172, 399, 1869,
+        514, 1706, 502, 1636,
+        886, 1522, 416, 600,
+        1131, 1350, 1275, 1390,
+        889, 1795, 914, 1766,
+        227, 1183, 1250, 1826,
+        505, 1854, 919, 2353,
+        -199, 431, 152, 1735,
+        -213, -28, 392, 1334,
+        -153, -52, 978, 1151,
+        -323, -400, 813, 1703,
+        -136, 84, 1449, 2015,
+        -331, -143, -137, 1192,
+        -256, 534, -157, 1031,
+        -307, -439, 542, 731,
+        -329, -420, -97, 616,
+        -362, -168, -322, 366,
+        -247, -110, -211, 89,
+        -196, -309, 20, 59,
+        -364, -463, -286, 89,
+        -336, 175, -432, 141,
+        -379, -190, -434, -196,
+        -79, 150, -278, -227,
+        -280, 166, -555, -422,
+        -155, 541, -366, 54,
+        -29, -83, -301, -774,
+        186, 628, -397, -264,
+        242, 293, -197, -585,
+        124, 410, 53, -133,
+        10, 340, -570, -1065,
+        65, -446, 68, -493,
+        383, 937, -357, -711,
+        -359, -250, -677, -1068,
+        292, -26, 363, 6,
+        607, 1313, -127, -10,
+        1513, 1886, 713, 972,
+        1469, 2181, 1443, 2016
+    };
+
+    extern const Word16 dico2_lsf_5[DICO2_5_SIZE * 4] =
+    {
+        -1631, -1600, -1796, -2290,
+        -1027, -1770, -1100, -2025,
+        -1277, -1388, -1367, -1534,
+        -947, -1461, -972, -1524,
+        -999, -1222, -1020, -1172,
+        -815, -987, -992, -1371,
+        -1216, -1006, -1289, -1094,
+        -744, -1268, -755, -1293,
+        -862, -923, -905, -984,
+        -678, -1051, -685, -1050,
+        -1087, -985, -1062, -679,
+        -989, -641, -1127, -976,
+        -762, -654, -890, -806,
+        -833, -1091, -706, -629,
+        -621, -806, -640, -812,
+        -775, -634, -779, -543,
+        -996, -565, -1075, -580,
+        -546, -611, -572, -619,
+        -760, -290, -879, -526,
+        -823, -462, -795, -253,
+        -553, -415, -589, -439,
+        -533, -340, -692, -935,
+        -505, -772, -702, -1131,
+        -263, -306, -971, -483,
+        -445, -74, -555, -548,
+        -614, -129, -693, -234,
+        -396, -246, -475, -250,
+        -265, -404, -376, -514,
+        -417, -510, -300, -313,
+        -334, -664, -463, -814,
+        -386, -704, -337, -615,
+        -234, -201, -233, -239,
+        -167, -567, -203, -619,
+        -147, -415, -115, -352,
+        -166, -750, -171, -761,
+        -270, -879, -264, -903,
+        -367, -744, 43, -475,
+        14, -653, 43, -670,
+        11, -448, -59, -521,
+        -126, -119, -155, -613,
+        -42, -863, -27, -931,
+        136, -483, 183, -468,
+        55, -298, 55, -304,
+        313, -609, 313, -720,
+        322, -167, 100, -541,
+        -3, -119, -111, -187,
+        233, -236, 260, -234,
+        26, -165, 134, -45,
+        -40, -549, 360, -203,
+        378, -388, 450, -383,
+        275, 20, 182, -103,
+        246, -111, 431, 37,
+        462, -146, 487, -157,
+        -284, -59, 503, -184,
+        24, 53, -3, 54,
+        122, 259, 333, 66,
+        484, 104, 436, 68,
+        195, 116, 190, 206,
+        269, -9, 482, 352,
+        382, 285, 399, 277,
+        452, 256, 69, 186,
+        13, 297, -13, 259,
+        -95, 30, 56, 394,
+        196, 425, 205, 456,
+        281, 577, 15, 191,
+        375, 290, 407, 576,
+        -56, 227, 544, 405,
+        0, 549, -92, 528,
+        -229, 351, -245, 338,
+        -362, 435, 167, 527,
+        -75, 302, 91, 824,
+        129, 599, 496, 679,
+        186, 749, 153, 737,
+        -281, 600, -348, 615,
+        -236, 769, 41, 881,
+        38, 890, -220, 841,
+        -357, 883, -393, 903,
+        -634, 474, -444, 850,
+        -175, 678, -493, 242,
+        -519, 785, -714, 582,
+        -541, 366, -543, 434,
+        -597, 500, -765, 222,
+        -702, 917, -743, 962,
+        -869, 501, -899, 548,
+        -379, 200, -435, 157,
+        -819, 214, -861, 157,
+        -614, 40, -632, 94,
+        -883, -54, -741, 516,
+        -501, 298, -614, -171,
+        -870, -161, -865, -23,
+        -818, 93, -1015, -267,
+        -662, -359, -549, 2,
+        -442, -121, -377, 0,
+        -227, 33, -414, -126,
+        -129, 212, -934, 34,
+        -1082, -282, -1119, -268,
+        -710, -825, -420, -191,
+        -1076, -928, -917, -93,
+        -628, -358, 97, 7,
+        -206, -393, -101, 24,
+        -203, 38, -168, 83,
+        -599, -423, -279, 426,
+        -700, 118, -75, 206,
+        -981, -673, -680, 417,
+        -367, 37, -279, 474,
+        -129, -318, 319, 296,
+        -626, -39, 343, 602,
+        -696, -39, -303, 940,
+        104, 233, -380, 137,
+        -36, 269, -75, -214,
+        120, 43, -529, -477,
+        459, 164, -202, -229,
+        -49, -167, 609, 792,
+        98, -220, 915, 148,
+        293, 283, 869, 91,
+        575, 394, 326, -78,
+        717, 67, 365, -323,
+        616, -36, 731, 27,
+        619, 238, 632, 273,
+        448, 99, 801, 476,
+        869, 273, 685, 64,
+        789, 72, 1021, 217,
+        793, 459, 734, 360,
+        646, 480, 360, 322,
+        429, 464, 638, 430,
+        756, 363, 1000, 404,
+        683, 528, 602, 615,
+        655, 413, 946, 687,
+        937, 602, 904, 604,
+        555, 737, 786, 662,
+        467, 654, 362, 589,
+        929, 710, 498, 478,
+        415, 420, 693, 883,
+        813, 683, 781, 925,
+        913, 939, 726, 732,
+        491, 853, 531, 948,
+        734, 963, 315, 808,
+        761, 755, 1144, 760,
+        655, 1076, 826, 1057,
+        1091, 838, 1003, 808,
+        1047, 1133, 659, 1101,
+        992, 1050, 1074, 1075,
+        971, 694, 1226, 1054,
+        571, 841, 884, 1404,
+        1379, 1096, 1080, 861,
+        1231, 735, 1284, 760,
+        1272, 991, 1367, 1053,
+        1257, 700, 1050, 534,
+        988, 453, 1264, 599,
+        1140, 679, 1621, 815,
+        1384, 521, 1317, 393,
+        1564, 805, 1448, 686,
+        1068, 648, 875, 307,
+        1083, 361, 1047, 317,
+        1417, 964, 675, 571,
+        1152, 79, 1114, -47,
+        1530, 311, 1721, 314,
+        1166, 689, 514, -94,
+        349, 282, 1412, 328,
+        1025, 487, -65, 57,
+        805, 970, 36, 62,
+        769, -263, 791, -346,
+        637, 699, -137, 620,
+        534, 541, -735, 194,
+        711, 300, -268, -863,
+        926, 769, -708, -428,
+        506, 174, -892, -630,
+        435, 547, -1435, -258,
+        621, 471, -1018, -1368,
+        -393, 521, -920, -686,
+        -25, 20, -982, -1156,
+        340, 9, -1558, -1135,
+        -352, 48, -1579, -402,
+        -887, 6, -1156, -888,
+        -548, -352, -1643, -1168,
+        -159, 610, -2024, -963,
+        -225, 193, -1656, -1960,
+        -245, -493, -964, -1680,
+        -936, -635, -1299, -1744,
+        -1388, -604, -1540, -835,
+        -1397, -135, -1588, -290,
+        -1670, -712, -2011, -1632,
+        -1663, -27, -2258, -811,
+        -1157, 184, -1265, 189,
+        -1367, 586, -2011, 201,
+        -790, 712, -1210, 3,
+        -1033, 808, -1251, 830,
+        -111, 635, -1636, 447,
+        -463, -949, -445, -928,
+        -504, -1162, -501, -1211,
+        144, -351, -372, -1052,
+        -283, -1059, -279, -1123,
+        -575, -1438, -587, -1614,
+        -935, -984, 229, 690,
+        -921, -719, -403, 1362,
+        -685, -465, 874, 397,
+        -509, -46, 317, 1334,
+        -485, 456, 813, 439,
+        -411, 339, 898, 1067,
+        -425, 46, 1441, 497,
+        -909, -800, 1465, 1046,
+        -254, -321, 1430, 1165,
+        68, 350, 1034, 666,
+        370, 11, 1311, 790,
+        143, 232, 1041, 1562,
+        -114, 663, 1616, 1078,
+        454, 579, 1275, 1040,
+        -76, 909, 752, 1067,
+        153, 512, 348, 1214,
+        614, 385, 1843, 808,
+        269, 1034, 203, 1086,
+        652, 1017, 1783, 1130,
+        429, 1327, 387, 1384,
+        -49, 1183, -72, 1215,
+        -416, 1001, 544, 1749,
+        -352, 1223, -502, 1199,
+        -589, 569, -227, 1630,
+        -142, 1578, -230, 1715,
+        -714, 1288, -838, 1398,
+        1131, 1357, -208, 1232,
+        437, 965, -929, 818,
+        811, 1410, 859, 1507,
+        164, 1212, 1387, 1793,
+        484, 1874, 456, 2063,
+        996, 1170, 1326, 1402,
+        1316, 1360, 1135, 1262,
+        1234, 1618, 1361, 1768,
+        1421, 1227, 1584, 1347,
+        854, 672, 1685, 1566,
+        1139, 1270, 2016, 1825,
+        1773, 1581, 1532, 1460,
+        1487, 946, 1659, 1021,
+        1744, 1212, 1392, 977,
+        1772, 1161, 1826, 1164,
+        1718, 1429, 1973, 1591,
+        1185, 864, 2132, 1061,
+        1799, 814, 1838, 757,
+        2104, 1315, 2054, 1258,
+        2113, 915, 2331, 930,
+        1467, 1147, 2590, 1439,
+        2245, 1744, 2090, 1620,
+        2358, 1454, 2666, 1506,
+        1876, 1837, 2070, 1975,
+        1739, 1577, 682, 1289,
+        1584, 2045, 1454, 2098,
+        2498, 2004, 2711, 2066,
+        726, 1588, 2756, 2336,
+        228, 847, 2456, 1659,
+        36, 301, 1942, 1957,
+        -446, -96, 2154, 1396,
+        1533, 1101, 14, 608,
+        -923, -732, 1383, 1982,
+        1345, 952, -680, 321,
+        1281, 1268, -1594, 365,
+        941, 946, -1737, -822,
+        2374, 2787, 1821, 2788
+    };
+
+    extern const Word16 dico3_lsf_5[DICO3_5_SIZE * 4] =
+    {
+        -1812, -2275, -1879, -2537,
+        -1640, -1848, -1695, -2004,
+        -1220, -1912, -1221, -2106,
+        -1559, -1588, -1573, -1556,
+        -1195, -1615, -1224, -1727,
+        -1359, -1151, -1616, -1948,
+        -1274, -1391, -1305, -1403,
+        -1607, -1179, -1676, -1311,
+        -1443, -1478, -1367, -898,
+        -1256, -1059, -1331, -1134,
+        -982, -1133, -1149, -1504,
+        -1080, -1308, -1020, -1183,
+        -980, -1486, -967, -1495,
+        -988, -922, -1047, -1077,
+        -838, -1179, -858, -1222,
+        -1131, -1041, -1064, -767,
+        -872, -1157, -701, -880,
+        -706, -906, -774, -1016,
+        -578, -1080, -801, -1478,
+        -591, -1111, -592, -1146,
+        -713, -1388, -640, -1376,
+        -597, -1059, -416, -903,
+        -686, -832, -661, -708,
+        -444, -868, -490, -921,
+        -374, -776, -619, -1170,
+        -585, -549, -769, -795,
+        -435, -659, -530, -741,
+        -498, -837, -357, -597,
+        -279, -871, -243, -887,
+        -282, -665, -280, -667,
+        -165, -560, -394, -903,
+        -362, -410, -448, -583,
+        -409, -574, -313, -357,
+        -637, -548, -570, -436,
+        -896, -504, -382, -757,
+        -58, -481, -165, -618,
+        -191, -374, -234, -382,
+        -222, -683, -25, -480,
+        -418, -359, -730, -353,
+        -324, -157, -432, -322,
+        -394, -303, -284, -104,
+        -601, -289, -556, -196,
+        -588, -150, -659, -608,
+        -473, -24, -68, -448,
+        -474, -8, -506, -45,
+        -748, -184, -844, -252,
+        -901, -91, -584, -97,
+        -652, 138, -764, -131,
+        -678, -12, -670, 165,
+        -259, -3, -840, -107,
+        -909, 37, -992, 44,
+        -854, -415, -839, 13,
+        -1001, -271, -1026, -309,
+        -798, -478, -832, -488,
+        -943, 168, -1112, -387,
+        -1185, -101, -1183, -40,
+        -941, -316, -1030, -770,
+        -1044, -625, -1081, -538,
+        -1224, -299, -1312, -436,
+        -1197, -663, -1167, -161,
+        -1216, -690, -1237, -831,
+        -1432, -720, -1403, -493,
+        -898, -740, -922, -801,
+        -1102, -402, -1579, -964,
+        -1061, -638, -1269, -1438,
+        -1499, -934, -1502, -895,
+        -1598, -564, -1723, -717,
+        -606, -597, -1166, -1085,
+        -1369, -468, -1946, -1493,
+        -1838, -953, -1932, -931,
+        -1499, -188, -1635, -421,
+        -1457, -338, -1448, -22,
+        -1942, -422, -2006, -249,
+        -496, -114, -1910, -755,
+        -1289, 174, -1451, -109,
+        -482, -257, -1221, -508,
+        -1617, 151, -1694, 208,
+        -654, 107, -1651, 29,
+        -1141, 279, -1215, 306,
+        -1228, -506, -730, -175,
+        -1236, -101, -969, 551,
+        -870, 278, -823, 315,
+        -563, 376, -1051, 228,
+        -507, 280, -599, 281,
+        -758, 253, -305, 379,
+        -755, -134, -611, 660,
+        -824, 536, -817, 646,
+        -413, 49, -341, 177,
+        -453, 526, -482, 589,
+        -71, 339, -657, 264,
+        -244, 295, -237, 315,
+        -387, 569, -506, -9,
+        -377, 14, -160, 661,
+        -216, 40, -308, -46,
+        95, 214, -242, 167,
+        -86, 192, -56, 27,
+        -76, 31, 36, 309,
+        -106, -182, -113, 74,
+        -441, -22, 23, 139,
+        81, -11, 44, 15,
+        -87, -137, -118, -207,
+        -158, -58, 272, -92,
+        -156, -441, 8, -136,
+        128, -221, 101, -218,
+        40, -197, -76, -456,
+        9, -445, 33, -423,
+        226, 60, 73, -222,
+        156, -399, 280, -318,
+        245, -341, 166, -499,
+        339, -190, 327, -219,
+        325, -137, -89, -596,
+        100, -627, 144, -677,
+        487, 28, 252, -391,
+        214, -41, 282, -28,
+        99, -286, 331, 49,
+        459, -388, 565, -369,
+        436, 28, 336, -9,
+        397, -167, 618, 34,
+        596, -17, 561, -140,
+        299, 79, 522, 125,
+        203, 2, 244, 288,
+        255, 211, 175, 82,
+        596, 187, 517, 108,
+        381, 255, 365, 297,
+        497, 352, 327, -82,
+        25, 210, 371, 245,
+        261, 3, 545, 449,
+        140, 294, 44, 295,
+        212, 347, 244, 494,
+        331, 528, 201, 307,
+        349, 411, 613, 284,
+        614, 413, 464, 322,
+        624, 397, 97, 200,
+        -160, 384, 149, 362,
+        495, 525, 269, 585,
+        33, 491, -121, 433,
+        427, 611, 498, 516,
+        171, 443, 497, 666,
+        440, 275, 566, 575,
+        146, 639, 155, 670,
+        -33, 173, 212, 696,
+        -166, 601, -191, 695,
+        -489, 503, 175, 742,
+        214, 476, 372, 1083,
+        578, 530, 586, 777,
+        425, 874, 315, 841,
+        374, 848, -165, 565,
+        35, 991, -39, 1062,
+        329, 712, 786, 840,
+        645, 795, 661, 676,
+        571, 918, 632, 1079,
+        673, 817, 318, 388,
+        874, 1012, 564, 848,
+        880, 620, 557, 479,
+        671, 453, 692, 468,
+        840, 642, 844, 645,
+        506, 428, 897, 567,
+        837, 387, 962, 499,
+        691, 561, 939, 926,
+        783, 296, 790, 268,
+        1028, 530, 874, 329,
+        548, 143, 675, 291,
+        503, 66, 1041, 359,
+        786, 97, 805, 33,
+        837, 470, 511, 49,
+        1092, 327, 1174, 323,
+        3, 242, 872, 474,
+        689, 429, 1329, 678,
+        1042, 620, 1109, 664,
+        321, 193, 889, 950,
+        1153, 874, 893, 635,
+        877, 862, 948, 913,
+        1293, 665, 1320, 639,
+        997, 793, 1402, 1030,
+        1176, 1012, 1110, 959,
+        1410, 925, 1403, 915,
+        543, 862, 1116, 1222,
+        835, 1190, 835, 1190,
+        959, 1148, 1147, 1376,
+        1300, 1193, 1415, 1231,
+        1335, 1341, 746, 1092,
+        1711, 1283, 1389, 1073,
+        1334, 1566, 1153, 1475,
+        1645, 1137, 1825, 1220,
+        1056, 1382, 1521, 1730,
+        1632, 1545, 1620, 1542,
+        855, 1596, 865, 1667,
+        693, 885, 1716, 1519,
+        1167, 1296, 2209, 1760,
+        1952, 1493, 2020, 1482,
+        1534, 1866, 1694, 2008,
+        1566, 748, 1761, 825,
+        294, 1392, 1084, 2058,
+        621, 1315, 365, 1287,
+        198, 1028, 488, 1408,
+        249, 403, 1014, 1561,
+        324, 363, 1645, 1044,
+        193, 367, 2034, 1859,
+        -251, 579, 750, 994,
+        -243, 30, 1325, 879,
+        -28, -169, 624, 917,
+        -453, 159, 186, 1370,
+        -614, 6, 537, 392,
+        -94, -291, 781, 229,
+        -128, -298, 245, 491,
+        -701, -648, 972, 789,
+        -501, -640, 178, 255,
+        -365, -390, -255, 317,
+        -958, -294, -191, 228,
+        -775, -447, 157, -237,
+        -657, -720, -407, 92,
+        -117, -611, 334, -230,
+        -679, -1084, -144, -317,
+        -901, -861, -738, -360,
+        -85, -727, -90, -787,
+        100, -22, -391, -263,
+        -56, -73, -337, -754,
+        5, -189, -706, -624,
+        89, -344, -135, -1113,
+        -353, -237, -684, -1135,
+        -275, -1102, -269, -1203,
+        152, 145, -722, -1232,
+        49, 80, -1248, -776,
+        -248, 391, -732, -547,
+        469, 218, -255, -864,
+        69, 366, -166, -485,
+        -688, 191, -1212, -1196,
+        -170, -169, -1308, -1631,
+        321, 470, -1419, -1243,
+        -64, 272, -1361, -248,
+        492, 565, -721, -609,
+        195, 485, -573, -133,
+        427, 202, -171, -118,
+        199, 575, 2, -31,
+        694, 755, -1366, -39,
+        552, 557, -489, 271,
+        680, 537, 13, -453,
+        855, 954, -133, -52,
+        -81, 738, -1169, 637,
+        1055, 1059, -95, 676,
+        1259, 1081, 489, 305,
+        -449, 954, -534, 996,
+        -969, 866, -1058, 1059,
+        -1294, 618, -1416, 617,
+        -458, 1366, -159, 1821,
+        -774, -528, -14, 1110,
+        -1202, -901, -772, 433,
+        -1256, -1255, -1011, -302,
+        -602, -585, -759, -1618,
+        -760, -1549, -840, -1921,
+        -816, -539, -1769, -2235,
+        -227, -36, -2034, -1831,
+        -2107, -1126, -2471, -1816,
+        -1470, 252, -2701, -415,
+        -571, -467, 1509, 1554,
+        2180, 1975, 2326, 2020
+    };
+
+    extern const Word16 dico4_lsf_5[DICO4_5_SIZE * 4] =
+    {
+        -1857, -1681, -1857, -1755,
+        -2056, -1150, -2134, -1654,
+        -1619, -1099, -1704, -1131,
+        -1345, -1608, -1359, -1638,
+        -1338, -1293, -1325, -1265,
+        -1664, -1649, -1487, -851,
+        -1346, -1832, -1413, -2188,
+        -1282, -681, -1785, -1649,
+        -966, -1082, -1183, -1676,
+        -1054, -1073, -1142, -1158,
+        -1207, -744, -1274, -997,
+        -934, -1383, -927, -1416,
+        -1010, -1305, -783, -955,
+        -1049, -900, -993, -817,
+        -737, -823, -972, -1189,
+        -738, -1094, -738, -1154,
+        -784, -801, -810, -786,
+        -892, -520, -1000, -818,
+        -644, -965, -577, -882,
+        -541, -694, -671, -917,
+        -595, -642, -646, -615,
+        -956, -621, -925, -515,
+        -727, -483, -815, -485,
+        -840, -578, -440, -713,
+        -578, -325, -657, -670,
+        -386, -570, -441, -666,
+        -514, -787, -392, -529,
+        -522, -453, -487, -423,
+        -616, -585, -617, -157,
+        -662, -268, -680, -348,
+        -322, -323, -632, -444,
+        -304, -430, -332, -458,
+        -277, -468, -659, -793,
+        -319, -636, -227, -554,
+        -373, -347, -334, -210,
+        -456, -192, -530, -242,
+        -216, -198, -366, -370,
+        -338, -161, -409, -748,
+        -107, -380, -294, -643,
+        -223, -665, -234, -741,
+        -141, -496, -130, -510,
+        -139, -327, -172, -305,
+        -306, -580, -164, -263,
+        -262, -172, -67, -402,
+        31, -366, -10, -436,
+        -86, -527, 71, -377,
+        -22, -609, -12, -678,
+        -67, -319, 63, -191,
+        35, -181, -39, -242,
+        126, -167, -140, -544,
+        155, -297, 174, -297,
+        38, -8, 117, -380,
+        197, -452, 240, -522,
+        223, -103, 110, -187,
+        87, -155, 169, -47,
+        157, 26, -83, -100,
+        128, 80, 209, -62,
+        6, 7, 22, 5,
+        318, -20, 248, -45,
+        -200, -63, 156, -69,
+        250, -183, 369, -126,
+        -113, -76, -142, -122,
+        -64, -254, -31, 35,
+        -177, -71, -7, 171,
+        93, 27, 108, 212,
+        -330, -209, -123, -70,
+        -279, 95, -96, 20,
+        -188, -61, -314, 87,
+        -300, -78, -354, -134,
+        11, 122, -140, 122,
+        -275, 152, -293, 140,
+        -82, 138, -321, -111,
+        -480, -156, -359, 76,
+        -254, -40, -635, -96,
+        -522, 79, -507, 8,
+        -268, 303, -539, 68,
+        -446, 61, -522, 306,
+        111, 189, -435, 122,
+        -379, 166, -571, -398,
+        -632, -74, -747, -95,
+        -455, 194, -952, 83,
+        -798, 192, -755, 192,
+        -781, -162, -619, 234,
+        -663, -297, -488, -109,
+        -964, -132, -838, -68,
+        -843, 58, -1112, -86,
+        -805, -299, -944, -253,
+        -778, -50, -965, -549,
+        -352, -98, -992, -343,
+        -1117, -315, -1117, -307,
+        -1155, -374, -637, -230,
+        -1166, -43, -1299, -100,
+        -925, -393, -1274, -600,
+        -689, -130, -1479, -312,
+        -1321, -254, -1464, -442,
+        -1292, -613, -1261, -503,
+        -1501, -368, -1322, 26,
+        -1432, -66, -1743, -161,
+        -1644, -467, -1760, -548,
+        -1393, -568, -1556, -871,
+        -1495, -1034, -1387, -571,
+        -1917, -528, -1783, -123,
+        -1897, -231, -2054, -323,
+        -2052, -906, -1976, -567,
+        -1917, -620, -2047, -989,
+        -1077, -370, -2031, -704,
+        -2355, -749, -2740, -1089,
+        -1909, 159, -2012, 248,
+        -626, -123, -2339, -962,
+        -669, -408, -1379, -1174,
+        -452, -364, -1044, -735,
+        -132, 183, -1620, -752,
+        -547, -307, -777, -1261,
+        -98, 41, -880, -1091,
+        -257, 97, -1602, -1833,
+        31, -26, -644, -561,
+        -180, -546, -385, -1095,
+        -410, -802, -414, -827,
+        -457, -970, -490, -1109,
+        -215, -916, -144, -937,
+        -493, -1269, -517, -1507,
+        181, 101, -332, -889,
+        -836, -937, -559, -429,
+        -629, -547, -183, -337,
+        -545, -82, -250, -286,
+        5, -132, -348, -252,
+        -293, -472, -158, 100,
+        -29, 197, -236, -424,
+        -861, -213, -140, -7,
+        -427, -443, 187, -97,
+        -684, -736, -293, 258,
+        -368, -152, -150, 392,
+        -609, 175, -142, 299,
+        -138, 152, -119, 329,
+        -486, -52, 293, 198,
+        -183, 117, 175, 331,
+        -58, -274, 231, 300,
+        -288, 330, -305, 372,
+        -111, 409, -9, 423,
+        83, 256, 67, 367,
+        -19, 248, 91, 113,
+        -35, 406, -191, 154,
+        238, 296, 5, 197,
+        141, 221, 313, 198,
+        211, 421, 244, 334,
+        88, 426, -243, 454,
+        202, 552, -5, 403,
+        291, 185, 219, 301,
+        251, 138, 128, 69,
+        197, 288, -140, -61,
+        188, 361, 197, 598,
+        442, 273, 290, 143,
+        472, 482, 157, 370,
+        415, 321, 372, 385,
+        402, 552, 155, 24,
+        550, 263, -11, 21,
+        360, 227, 147, -254,
+        424, 97, 366, -13,
+        375, 141, 449, 232,
+        396, 507, 474, 272,
+        701, 324, 362, -47,
+        587, 148, 543, 69,
+        400, -51, 561, 59,
+        220, -10, 352, 147,
+        206, 211, 653, 185,
+        563, 297, 565, 284,
+        594, 121, 766, 192,
+        398, 118, 642, 434,
+        233, 264, 481, 467,
+        129, -165, 699, 239,
+        90, 26, 342, 474,
+        -55, 27, 388, 94,
+        -172, 0, 725, 379,
+        -60, 337, 370, 465,
+        95, 319, 806, 595,
+        78, 260, 497, 851,
+        210, 560, 458, 574,
+        -464, 202, 497, 625,
+        -202, 152, 48, 712,
+        -20, 566, 100, 715,
+        455, 468, 411, 605,
+        319, 646, 195, 615,
+        401, 538, 680, 739,
+        201, 667, 434, 954,
+        454, 425, 646, 491,
+        606, 681, 416, 508,
+        497, 822, 426, 815,
+        660, 647, 628, 716,
+        697, 466, 618, 457,
+        685, 460, 365, 309,
+        721, 567, 836, 601,
+        609, 300, 825, 459,
+        943, 687, 681, 533,
+        915, 598, 591, 243,
+        876, 451, 874, 420,
+        786, 317, 732, 220,
+        922, 317, 1108, 367,
+        531, 466, 1028, 649,
+        1053, 615, 1034, 553,
+        829, 602, 1021, 799,
+        927, 803, 878, 763,
+        799, 496, 1373, 773,
+        585, 770, 803, 930,
+        1099, 793, 1222, 862,
+        1209, 895, 1025, 727,
+        772, 845, 1172, 1115,
+        867, 1021, 830, 1013,
+        841, 910, 506, 703,
+        1239, 1077, 620, 819,
+        1196, 1083, 1155, 1081,
+        1142, 907, 1547, 1121,
+        1309, 648, 1343, 612,
+        1484, 988, 1479, 937,
+        985, 1328, 955, 1341,
+        429, 910, 841, 1338,
+        564, 1179, 412, 1156,
+        1427, 1320, 1434, 1330,
+        640, 760, 1726, 1410,
+        190, 555, 1073, 1005,
+        426, 257, 839, 980,
+        235, 231, 1520, 1167,
+        109, 293, 1014, 1569,
+        305, 142, 1148, 539,
+        -291, -108, 1213, 972,
+        22, -216, 667, 828,
+        -482, 438, 453, 1431,
+        -581, -422, 789, 387,
+        -358, -454, 174, 780,
+        -36, -372, 390, -134,
+        -629, 160, -306, 751,
+        -1258, -331, 177, 522,
+        -248, 574, -251, 639,
+        -531, 407, -596, 394,
+        -419, 789, -617, 801,
+        -986, 399, -857, 727,
+        -7, 518, -703, 310,
+        -1143, -24, -1002, 287,
+        -960, 363, -1299, 312,
+        -1534, 245, -1557, 305,
+        28, 153, -859, -175,
+        -33, 332, -1398, -154,
+        212, 410, -593, -197,
+        -1092, -704, -904, -65,
+        282, 367, -918, -686,
+        345, 93, -258, -357,
+        696, 644, -693, -28,
+        448, 493, -273, 193,
+        527, 546, -243, -513,
+        384, -136, 273, -353,
+        512, -142, 537, -198,
+        941, 750, 83, 248,
+        578, 861, -56, 592,
+        842, 44, 892, 24,
+        33, 890, -16, 982,
+        831, 1398, 1535, 1898,
+        1716, 1376, 1948, 1465
+    };
+
+    extern const Word16 dico5_lsf_5[DICO5_5_SIZE * 4] =
+    {
+        -1002, -929, -1096, -1203,
+        -641, -931, -604, -961,
+        -779, -673, -835, -788,
+        -416, -664, -458, -766,
+        -652, -521, -662, -495,
+        -1023, -509, -1023, -428,
+        -444, -552, -368, -449,
+        -479, -211, -1054, -903,
+        -316, -249, -569, -591,
+        -569, -275, -541, -191,
+        -716, -188, -842, -264,
+        -333, -248, -318, -228,
+        -275, 1, -567, -228,
+        -115, -221, -238, -374,
+        -197, -507, -222, -579,
+        -258, -432, -61, -244,
+        -345, 2, -338, 39,
+        -215, -169, -58, 0,
+        -56, -6, -203, -131,
+        1, -186, -5, -211,
+        6, -380, 11, -418,
+        -116, 131, -134, 113,
+        89, -4, 71, -2,
+        -19, -192, 262, 24,
+        189, 151, -133, -109,
+        186, -153, 166, -219,
+        37, 139, 193, 171,
+        337, 124, 158, -61,
+        141, 226, -13, 190,
+        231, 34, 354, 109,
+        316, 201, 244, 164,
+        330, -85, 390, -84,
+        254, 327, 257, 335,
+        491, 147, 476, 105,
+        54, 77, 437, 370,
+        421, 314, 449, 342,
+        329, 126, 673, 292,
+        571, 388, 243, 193,
+        653, 320, 621, 280,
+        194, 380, 517, 581,
+        45, 323, 111, 422,
+        489, 395, 734, 534,
+        622, 546, 486, 502,
+        318, 572, 189, 550,
+        385, 422, -157, 153,
+        -125, 382, -197, 386,
+        -263, 334, 228, 697,
+        -188, 1, 51, 297,
+        -507, 213, -376, 397,
+        -24, 255, -547, 89,
+        -502, -94, 387, 179,
+        -620, 68, -684, 112,
+        -642, -350, -260, 172,
+        -438, -324, 264, 648,
+        -964, -4, -1121, 7,
+        -134, 134, -1133, -306,
+        143, 96, -420, -497,
+        -1221, -350, -1527, -685,
+        -161, 72, 873, 691,
+        732, 283, 921, 353,
+        334, 475, 1095, 821,
+        864, 524, 843, 497,
+        714, 711, 788, 750,
+        1076, 714, 1204, 753
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] q_plsf_5.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/common/src/qua_gain_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/qua_gain_tbl.cpp
new file mode 100644
index 0000000..52f77e9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/qua_gain_tbl.cpp
@@ -0,0 +1,390 @@
+/* ------------------------------------------------------------------
+ * 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/qua_gain_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, qua_gain.tab
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                               Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "qua_gain.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]
+    ----------------------------------------------------------------------------*/
+
+    /* The tables contains the following data:
+     *
+     *    g_pitch        (Q14),
+     *    g_fac          (Q12), (g_code = g_code0*g_fac),
+     *    qua_ener_MR122 (Q10), (log2(g_fac))
+     *    qua_ener       (Q10)  (20*log10(g_fac))
+     *
+     *    The log2() and log10() values are calculated on the fixed point value
+     *    (g_fac Q12) and not on the original floating point value of g_fac
+     *    to make the quantizer/MA predictdor use corresponding values.
+     */
+
+    /* table used in 'high' rates: MR67 MR74 */
+
+    extern const Word16 table_gain_highrates[VQ_SIZE_HIGHRATES*4] =
+    {
+
+        /*
+         * Note: column 4 (qua_ener) contains the original values from IS641
+         *       to ensure bit-exactness; however, they are not exactly the
+         *       rounded value of (20*log10(g_fac))
+         *
+         */
+
+        /*g_pit,    g_fac,  qua_ener_MR122, qua_ener */
+        577,      662,           -2692,   -16214,
+        806,     1836,           -1185,    -7135,
+        3109,     1052,           -2008,   -12086,
+        4181,     1387,           -1600,    -9629,
+        2373,     1425,           -1560,    -9394,
+        3248,     1985,           -1070,    -6442,
+        1827,     2320,            -840,    -5056,
+        941,     3314,            -313,    -1885,
+        2351,     2977,            -471,    -2838,
+        3616,     2420,            -777,    -4681,
+        3451,     3096,            -414,    -2490,
+        2955,     4301,              72,      434,
+        1848,     4500,             139,      836,
+        3884,     5416,             413,     2484,
+        1187,     7210,             835,     5030,
+        3083,     9000,            1163,     7002,
+        7384,      883,           -2267,   -13647,
+        5962,     1506,           -1478,    -8900,
+        5155,     2134,            -963,    -5800,
+        7944,     2009,           -1052,    -6335,
+        6507,     2250,            -885,    -5327,
+        7670,     2752,            -588,    -3537,
+        5952,     3016,            -452,    -2724,
+        4898,     3764,            -125,     -751,
+        6989,     3588,            -196,    -1177,
+        8174,     3978,             -43,     -260,
+        6064,     4404,             107,      645,
+        7709,     5087,             320,     1928,
+        5523,     6021,             569,     3426,
+        7769,     7126,             818,     4926,
+        6060,     7938,             977,     5885,
+        5594,    11487,            1523,     9172,
+        10581,     1356,           -1633,    -9831,
+        9049,     1597,           -1391,    -8380,
+        9794,     2035,           -1033,    -6220,
+        8946,     2415,            -780,    -4700,
+        10296,     2584,            -681,    -4099,
+        9407,     2734,            -597,    -3595,
+        8700,     3218,            -356,    -2144,
+        9757,     3395,            -277,    -1669,
+        10177,     3892,             -75,     -454,
+        9170,     4528,             148,      891,
+        10152,     5004,             296,     1781,
+        9114,     5735,             497,     2993,
+        10500,     6266,             628,     3782,
+        10110,     7631,             919,     5534,
+        8844,     8727,            1117,     6728,
+        8956,    12496,            1648,     9921,
+        12924,      976,           -2119,   -12753,
+        11435,     1755,           -1252,    -7539,
+        12138,     2328,            -835,    -5024,
+        11388,     2368,            -810,    -4872,
+        10700,     3064,            -429,    -2580,
+        12332,     2861,            -530,    -3192,
+        11722,     3327,            -307,    -1848,
+        11270,     3700,            -150,     -904,
+        10861,     4413,             110,      663,
+        12082,     4533,             150,      902,
+        11283,     5205,             354,     2132,
+        11960,     6305,             637,     3837,
+        11167,     7534,             900,     5420,
+        12128,     8329,            1049,     6312,
+        10969,    10777,            1429,     8604,
+        10300,    17376,            2135,    12853,
+        13899,     1681,           -1316,    -7921,
+        12580,     2045,           -1026,    -6179,
+        13265,     2439,            -766,    -4610,
+        14033,     2989,            -465,    -2802,
+        13452,     3098,            -413,    -2482,
+        12396,     3658,            -167,    -1006,
+        13510,     3780,            -119,     -713,
+        12880,     4272,              62,      374,
+        13533,     4861,             253,     1523,
+        12667,     5457,             424,     2552,
+        13854,     6106,             590,     3551,
+        13031,     6483,             678,     4084,
+        13557,     7721,             937,     5639,
+        12957,     9311,            1213,     7304,
+        13714,    11551,            1532,     9221,
+        12591,    15206,            1938,    11667,
+        15113,     1540,           -1445,    -8700,
+        15072,     2333,            -832,    -5007,
+        14527,     2511,            -723,    -4352,
+        14692,     3199,            -365,    -2197,
+        15382,     3560,            -207,    -1247,
+        14133,     3960,             -50,     -300,
+        15102,     4236,              50,      298,
+        14332,     4824,             242,     1454,
+        14846,     5451,             422,     2542,
+        15306,     6083,             584,     3518,
+        14329,     6888,             768,     4623,
+        15060,     7689,             930,     5602,
+        14406,     9426,            1231,     7413,
+        15387,     9741,            1280,     7706,
+        14824,    14271,            1844,    11102,
+        13600,    24939,            2669,    16067,
+        16396,     1969,           -1082,    -6517,
+        16817,     2832,            -545,    -3283,
+        15713,     2843,            -539,    -3248,
+        16104,     3336,            -303,    -1825,
+        16384,     3963,             -49,     -294,
+        16940,     4579,             165,      992,
+        15711,     4599,             171,     1030,
+        16222,     5448,             421,     2537,
+        16832,     6382,             655,     3945,
+        15745,     7141,             821,     4944,
+        16326,     7469,             888,     5343,
+        16611,     8624,            1100,     6622,
+        17028,    10418,            1379,     8303,
+        15905,    11817,            1565,     9423,
+        16878,    14690,            1887,    11360,
+        16515,    20870,            2406,    14483,
+        18142,     2083,            -999,    -6013,
+        19401,     3178,            -375,    -2257,
+        17508,     3426,            -264,    -1589,
+        20054,     4027,             -25,     -151,
+        18069,     4249,              54,      326,
+        18952,     5066,             314,     1890,
+        17711,     5402,             409,     2461,
+        19835,     6192,             610,     3676,
+        17950,     7014,             795,     4784,
+        21318,     7877,             966,     5816,
+        17910,     9289,            1210,     7283,
+        19144,     9290,            1210,     7284,
+        20517,    11381,            1510,     9089,
+        18075,    14485,            1866,    11234,
+        19999,    17882,            2177,    13108,
+        18842,    32764,            3072,    18494
+    };
+
+
+    /* table used in 'low' rates: MR475, MR515, MR59 */
+
+    extern const Word16 table_gain_lowrates[VQ_SIZE_LOWRATES*4] =
+    {
+        /*g_pit,    g_fac,  qua_ener_MR122, qua_ener */
+        10813,    28753,            2879,    17333,
+        20480,     2785,            -570,    -3431,
+        18841,     6594,             703,     4235,
+        6225,     7413,             876,     5276,
+        17203,    10444,            1383,     8325,
+        21626,     1269,           -1731,   -10422,
+        21135,     4423,             113,      683,
+        11304,     1556,           -1430,    -8609,
+        19005,    12820,            1686,    10148,
+        17367,     2498,            -731,    -4398,
+        17858,     4833,             244,     1472,
+        9994,     2498,            -731,    -4398,
+        17530,     7864,             964,     5802,
+        14254,     1884,           -1147,    -6907,
+        15892,     3153,            -387,    -2327,
+        6717,     1802,           -1213,    -7303,
+        18186,    20193,            2357,    14189,
+        18022,     3031,            -445,    -2678,
+        16711,     5857,             528,     3181,
+        8847,     4014,             -30,     -180,
+        15892,     8970,            1158,     6972,
+        18022,     1392,           -1594,    -9599,
+        16711,     4096,               0,        0,
+        8192,      655,           -2708,   -16305,
+        15237,    13926,            1808,    10884,
+        14254,     3112,            -406,    -2444,
+        14090,     4669,             193,     1165,
+        5406,     2703,            -614,    -3697,
+        13434,     6553,             694,     4180,
+        12451,      901,           -2237,   -13468,
+        12451,     2662,            -637,    -3833,
+        3768,      655,           -2708,   -16305,
+        14745,    23511,            2582,    15543,
+        19169,     2457,            -755,    -4546,
+        20152,     5079,             318,     1913,
+        6881,     4096,               0,        0,
+        20480,     8560,            1089,     6556,
+        19660,      737,           -2534,   -15255,
+        19005,     4259,              58,      347,
+        7864,     2088,            -995,    -5993,
+        11468,    12288,            1623,     9771,
+        15892,     1474,           -1510,    -9090,
+        15728,     4628,             180,     1086,
+        9175,     1433,           -1552,    -9341,
+        16056,     7004,             793,     4772,
+        14827,      737,           -2534,   -15255,
+        15073,     2252,            -884,    -5321,
+        5079,     1228,           -1780,   -10714,
+        13271,    17326,            2131,    12827,
+        16547,     2334,            -831,    -5002,
+        15073,     5816,             518,     3118,
+        3932,     3686,            -156,     -938,
+        14254,     8601,            1096,     6598,
+        16875,      778,           -2454,   -14774,
+        15073,     3809,            -107,     -646,
+        6062,      614,           -2804,   -16879,
+        9338,     9256,            1204,     7251,
+        13271,     1761,           -1247,    -7508,
+        13271,     3522,            -223,    -1343,
+        2457,     1966,           -1084,    -6529,
+        11468,     5529,             443,     2668,
+        10485,      737,           -2534,   -15255,
+        11632,     3194,            -367,    -2212,
+        1474,      778,           -2454,   -14774
+    };
+
+    /*--------------------------------------------------------------------------*/
+#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] qua_gain.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/common/src/reorder.cpp b/media/libstagefright/codecs/amrnb/common/src/reorder.cpp
new file mode 100644
index 0000000..b1e4711
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/reorder.cpp
@@ -0,0 +1,199 @@
+/* ------------------------------------------------------------------
+ * 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/reorder.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+              1. Eliminated unused include file add.h.
+              2. Replaced array addressing by pointers
+              3. Eliminated math operations that unnecessary checked for
+                 saturation
+              4. Replaced loop counter with decrement loops
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "reorder.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: Reorder_lsf
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf = vector of LSFs   (range: 0<=val<=0.5)(Word16)
+    min_dist = minimum required distance (Word16)
+    n = LPC order (Word16)
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the add operation called by Reorder_lsf() results in
+     overflow
+    lsf -> reordered vector of LSFs (Word16)
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function makes sure that the LSFs are properly ordered keeps a certain
+ minimum distance between adjacent LSFs.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] reorder.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Reorder_lsf (
+    Word16 *lsf,        // (i/o)     : vector of LSFs   (range: 0<=val<=0.5)
+    Word16 min_dist,    // (i)       : minimum required distance
+    Word16 n            // (i)       : LPC order
+)
+{
+    Word16 i;
+    Word16 lsf_min;
+
+// The reference ETSI code uses a global flag for Overflow. In the actual
+// implementation a pointer to Overflow flag is passed into the function
+// for use by the math functions add() and sub()
+
+    lsf_min = min_dist;
+    for (i = 0; i < n; i++)
+    {
+        if (sub (lsf[i], lsf_min) < 0)
+        {
+            lsf[i] = lsf_min;
+        }
+        lsf_min = add (lsf[i], min_dist);
+    }
+}
+
+------------------------------------------------------------------------------
+ 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 Reorder_lsf(
+    Word16 *lsf,        /* (i/o)    : vector of LSFs   (range: 0<=val<=0.5) */
+    Word16 min_dist,    /* (i)      : minimum required distance             */
+    Word16 n,           /* (i)      : LPC order                             */
+    Flag   *pOverflow   /* (i/o)    : Overflow flag                         */
+)
+{
+    Word16 i;
+    Word16 lsf_min;
+    Word16 *p_lsf = &lsf[0];
+    OSCL_UNUSED_ARG(pOverflow);
+
+    lsf_min = min_dist;
+    for (i = 0; i < n; i++)
+    {
+        if (*(p_lsf) < lsf_min)
+        {
+            *(p_lsf++) = lsf_min;
+            lsf_min +=  min_dist;
+        }
+        else
+        {
+            lsf_min = *(p_lsf++) + min_dist;
+        }
+    }
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/residu.cpp b/media/libstagefright/codecs/amrnb/common/src/residu.cpp
new file mode 100644
index 0000000..b25d3be
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/residu.cpp
@@ -0,0 +1,255 @@
+/* ------------------------------------------------------------------
+ * 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/residu.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing code.
+
+ Description: Deleted stores listed in the Local Stores Needed/Modified
+          section.
+
+ Description: Updated file per comments gathered from Phase 2/3 review.
+
+ Description: Updating to reflect variable name changes made in residu.asm
+
+ 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. Modified FOR loops to count down.
+              2. Fixed typecasting issue with TI C compiler.
+
+ Description: Made the following changes
+              1. Unrolled the convolutional loop.
+              2. Performed 4 convolution per pass to avoid recalling the same
+                 filter coefficient as many times.
+              2. Eliminated math operations that check for saturation.
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "residu.h"
+#include "typedef.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
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Residu
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    coef_ptr = pointer to buffer containing the prediction coefficients
+    input_ptr = pointer to buffer containing the speech signal
+    input_len = filter order
+    residual_ptr = pointer to buffer of residual signal
+
+ Outputs:
+    residual_ptr buffer contains the newly calculated the residual signal
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes the LP residual by filtering the input speech through
+ the LP inverse filter A(z).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ residu.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: Input argument names were changed to be more descriptive. Shown below
+       are the original names. Shown below are the name changes:
+           a[]  <-->  coef_ptr[]
+           x[]  <-->  input_ptr[]
+           y[]  <-->  residual_ptr[]
+           lg   <-->  input_len
+
+
+void Residu (
+    Word16 a[], // (i)     : prediction coefficients
+    Word16 x[], // (i)     : speech signal
+    Word16 y[], // (o)     : residual signal
+    Word16 lg   // (i)     : size of filtering
+)
+{
+    Word16 i, j;
+    Word32 s;
+
+    for (i = 0; i < lg; i++)
+    {
+        s = L_mult (x[i], a[0]);
+        for (j = 1; j <= M; j++)
+        {
+            s = L_mac (s, a[j], x[i - j]);
+        }
+        s = L_shl (s, 3);
+        y[i] = pv_round (s);
+    }
+    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 Residu(
+    Word16 coef_ptr[],      /* (i)     : prediction coefficients*/
+    Word16 input_ptr[],     /* (i)     : speech signal          */
+    Word16 residual_ptr[],  /* (o)     : residual signal        */
+    Word16 input_len        /* (i)     : size of filtering      */
+)
+{
+
+
+    register Word16 i, j;
+    Word32 s1;
+    Word32 s2;
+    Word32 s3;
+    Word32 s4;
+    Word16 *p_input1;
+    Word16 *p_input2;
+    Word16 *p_input3;
+    Word16 *p_input4;
+    Word16 *p_coef;
+    Word16 *p_residual_ptr = &residual_ptr[input_len-1];
+    Word16 *p_input_ptr    = &input_ptr[input_len-1-M];
+
+    for (i = input_len >> 2; i != 0; i--)
+    {
+        s1       = 0x0000800L;
+        s2       = 0x0000800L;
+        s3       = 0x0000800L;
+        s4       = 0x0000800L;
+        p_coef  = &coef_ptr[M];
+        p_input1 = p_input_ptr--;
+        p_input2 = p_input_ptr--;
+        p_input3 = p_input_ptr--;
+        p_input4 = p_input_ptr--;
+
+        for (j = M >> 1; j != 0; j--)
+        {
+            s1 += ((Word32) * (p_coef) * *(p_input1++));
+            s2 += ((Word32) * (p_coef) * *(p_input2++));
+            s3 += ((Word32) * (p_coef) * *(p_input3++));
+            s4 += ((Word32) * (p_coef--) * *(p_input4++));
+            s1 += ((Word32) * (p_coef) * *(p_input1++));
+            s2 += ((Word32) * (p_coef) * *(p_input2++));
+            s3 += ((Word32) * (p_coef) * *(p_input3++));
+            s4 += ((Word32) * (p_coef--) * *(p_input4++));
+        }
+
+        s1 += (((Word32) * (p_coef)) * *(p_input1));
+        s2 += (((Word32) * (p_coef)) * *(p_input2));
+        s3 += (((Word32) * (p_coef)) * *(p_input3));
+        s4 += (((Word32) * (p_coef)) * *(p_input4));
+
+        *(p_residual_ptr--) = (Word16)(s1 >> 12);
+        *(p_residual_ptr--) = (Word16)(s2 >> 12);
+        *(p_residual_ptr--) = (Word16)(s3 >> 12);
+        *(p_residual_ptr--) = (Word16)(s4 >> 12);
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/round.cpp b/media/libstagefright/codecs/amrnb/common/src/round.cpp
new file mode 100644
index 0000000..71d1702
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/round.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.
+****************************************************************************************/
+/*
+
+ Filename: /audio/gsm_amr/c/src/round.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the round function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Made changes based on review meeting:
+              1. Removed long in Inputs Definitions.
+              2. Changed L_var1 to var_out and description in
+                 Output Definitions.
+
+ Description: Added a parameter to the function interface, pOverflow which is
+              a pointer to the overflow flag. This flag is required by the
+              L_add() function invoked by round().
+              Removed code that updates the MOPS counter.
+              Created a new return variable result.
+
+ Description: Removed embedded tabs. Included comment in the Pseudo code
+              Section about using pointer to overflow flag in the actual
+              implementation instead of using a global flag.
+
+ Description: Changed function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Rounding function with saturation.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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: pv_round
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_var1 = 32 bit signed integer (Word32) whose value falls
+             in the range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    None
+
+ Returns:
+        result = MS 16 bits of rounded input L_var1.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function rounds the lower 16 bits of the 32 bit input number into the
+ MS 16 bits with saturation. Shift the resulting bits right by 16 and return
+ the 16 bit number:
+    pv_round(L_var1) = extract_h(L_add(L_var1,32768))
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] round() function in basic_op2.c,  UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 pv_round (Word32 L_var1)
+{
+    Word16 var_out;
+    Word32 L_rounded;
+
+* The reference ETSI code uses a global flag for Overflow in the L_add() function.
+* In the actual implementation a pointer to Overflow flag is passed in as a
+* parameter to the function.
+
+    L_rounded = L_add (L_var1, (Word32) 0x00008000L);
+#if (WMOPS)
+    multiCounter[currCounter].L_add--;
+#endif
+    var_out = extract_h (L_rounded);
+#if (WMOPS)
+    multiCounter[currCounter].extract_h--;
+    multiCounter[currCounter].round++;
+#endif
+    return (var_out);
+}
+
+------------------------------------------------------------------------------
+ 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 pv_round(register Word32 L_var1, Flag *pOverflow)
+{
+    Word16  result;
+
+    L_var1 = L_add(L_var1, (Word32) 0x00008000L, pOverflow);
+    result = (Word16)(L_var1 >> 16);
+
+    return (result);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/set_zero.cpp b/media/libstagefright/codecs/amrnb/common/src/set_zero.cpp
new file mode 100644
index 0000000..be23b25
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/set_zero.cpp
@@ -0,0 +1,74 @@
+/* ------------------------------------------------------------------
+ * 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             : set_zero.h
+*
+********************************************************************************
+*/
+/*
+********************************************************************************
+*                         MODULE INCLUDE FILE AND VERSION ID
+********************************************************************************
+*/
+#include "set_zero.h"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+#include "basic_op.h"
+
+/*
+********************************************************************************
+*                         PUBLIC PROGRAM CODE
+********************************************************************************
+*/
+void Set_zero(
+    Word16 x[],         /* (o)    : vector to clear     */
+    Word16 L            /* (i)    : length of vector    */
+)
+{
+    Word16 i;
+
+    for (i = 0; i < L; i++)
+    {
+        x[i] = 0;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/shr.cpp b/media/libstagefright/codecs/amrnb/common/src/shr.cpp
new file mode 100644
index 0000000..775dc69
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/shr.cpp
@@ -0,0 +1,258 @@
+/* ------------------------------------------------------------------
+ * 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/shr.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the shr function. Sync'ed up with
+          the current template and fixed tabs.
+
+ Description: 1. Modified code by seperating var2=0 condition.
+              2. Changed Input range definitions.
+
+ Description: Made changes based on review meeting.
+              1. Changed Overflow definition.
+              2. Removed pseudo-code.
+              3. Deleted (var2>15&&var1!=0) condition.
+              4. Moved var2>0 condition in front of var2<0 condition.
+
+ Description: Changed the function prototype to pass in a pointer to the
+              overflow flag instead of using global data.
+
+ Description: Made changes per formal review. Updated template.
+              Removed code that updates MOPS counter.
+              Changed parameter name from "overflow" and "pOverflow".
+              Optimized code by eliminating unnecessary typecasting.
+              Filled in the PSEUDO CODE section
+
+ Description: Further optimized typecasting for overflow case
+
+ Who:                       Date:
+ Description:
+------------------------------------------------------------------------------
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+ Shift right function with overflow control
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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: shr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the shift operation resulted in overflow
+
+ Returns:
+    product = Shifted result limited to 16 bits (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function arithmetically shifts the 16 bit input var1 right var2 positions
+ with sign extension. If var2 is negative, arithmetically shift var1 left by
+ -var2 with sign extension. Saturate the result in case of underflows or
+ overflows.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+ None
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] shr() function in basic_op2.c,  UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 shr_std (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    if (var2 < 0)
+    {
+        if (var2 < -16)
+            var2 = -16;
+        var_out = shl_std (var1, -var2);
+#if (WMOPS)
+        mult_stdiCounter[currCounter].shl_std--;
+#endif
+    }
+    else
+    {
+        if (var2 >= 15)
+        {
+            var_out = (var1 < 0) ? -1 : 0;
+        }
+        else
+        {
+            if (var1 < 0)
+            {
+                var_out = ~((~var1) >> var2);
+            }
+            else
+            {
+                var_out = var1 >> var2;
+            }
+        }
+    }
+
+#if (WMOPS)
+    mult_stdiCounter[currCounter].shr_std++;
+#endif
+    return (var_out);
+}
+------------------------------------------------------------------------------
+ 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 shr(register Word16 var1, register Word16 var2, Flag *pOverflow)
+{
+    register Word16 result;
+    register Word32 temp_res;
+
+    if (var2 != 0)
+    {
+        if (var2 > 0)
+        {
+            if (var2 >= 15)
+            {
+                result = ((var1 < 0) ? -1 : 0);
+            }
+            else
+            {
+                if (var1 < 0)
+                {
+                    result = (~((~var1) >> var2));
+                }
+                else
+                {
+                    result = (var1 >> var2);
+                }
+            }
+        }
+        else
+        {
+            if (var2 < -16)
+            {
+                var2 = -16;
+            }
+
+            var2 = -var2;   /* Shift right negative is equivalent */
+            /*   to shifting left positive.       */
+
+            temp_res = ((Word32) var1) << var2;
+            result = (Word16)(temp_res);
+
+            if (temp_res != (Word32) result)
+            {
+                *pOverflow = 1;
+                result = ((var1 > 0) ? MAX_16 : MIN_16);
+            }
+        }
+
+    }
+    else
+    {
+        result = var1;
+    }
+
+    return (result);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/shr_r.cpp b/media/libstagefright/codecs/amrnb/common/src/shr_r.cpp
new file mode 100644
index 0000000..6656f93
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/shr_r.cpp
@@ -0,0 +1,226 @@
+/* ------------------------------------------------------------------
+ * 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: ./gsm-amr/c/src/shr_r.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the shr_r function. Sync'ed up
+          with the current template and fixed tabs.
+
+ Description: Passing around pOverflow as per EPOC changes.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    var_out = shifted input w/ rounding (Word16)
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function arithmetically shifts the 16 bit input var1 right var2 positions
+ with rounding. If var2 is negative, arithmetically shift var1 left by
+ -var2 with rounding. Saturate the result in case of underflows or
+ overflows.
+
+    - If var2 is greater than zero :
+        if (sub(shl(shr(var1,var2),1),shr(var1,sub(var2,1))))
+        is equal to zero
+        then
+            shr_r(var1,var2) = shr(var1,var2)
+        else
+            shr_r(var1,var2) = add(shr(var1,var2),1)
+    - If var2 is less than or equal to zero :
+        shr_r(var1,var2) = shr(var1,var2).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] basicop2.c, ETS Version 2.0.0, February 8, 1999
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 shr_r (Word16 var1, Word16 var2)
+{
+    Word16 var_out;
+
+    if (var2 > 15)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        var_out = shr (var1, var2);
+#if (WMOPS)
+        multiCounter[currCounter].shr--;
+#endif
+
+        if (var2 > 0)
+        {
+            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
+            {
+                var_out++;
+            }
+        }
+    }
+#if (WMOPS)
+    multiCounter[currCounter].shr_r++;
+#endif
+    return (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
+----------------------------------------------------------------------------*/
+Word16 shr_r(register Word16 var1, register Word16 var2, Flag *pOverflow)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    Word16 var_out;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    if (var2 > 15)
+    {
+        var_out = 0;
+    }
+    else
+    {
+        var_out = shr(var1, var2, pOverflow);
+        if (var2 > 0)
+        {
+            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
+            {
+                var_out++;
+            }
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (var_out);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/sqrt_l.cpp b/media/libstagefright/codecs/amrnb/common/src/sqrt_l.cpp
new file mode 100644
index 0000000..8f74aa6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/sqrt_l.cpp
@@ -0,0 +1,266 @@
+/* ------------------------------------------------------------------
+ * 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/sqrt_l.c
+
+------------------------------------------------------------------------------
+ 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 name of an input pointer from "exp" to "pExp"
+              for clarity. Removed inclusion of unwanted header files.
+
+ Description: Removed inclusion of sqrt_l.tab file. Changed the array name
+              "table" to "sqrt_l_tbl". Fixed typos.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "sqrt_l.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 STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: sqrt_l_exp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    L_x = input value (Word32)
+    pExp = pointer to right shift to be applied to result
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    pOverflow -> if the Inv_sqrt operation resulted in an overflow.
+
+ Returns:
+    L_y = squareroot of L_x (Word32)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function computes sqrt(L_x),  where  L_x is positive.
+ If L_var is negative or zero, the result is 0
+
+ The function sqrt(L_x) is approximated by a table and linear
+ interpolation. The square root is computed using the
+ following steps:
+    1- Normalization of L_x.
+    2- If exponent is even then shift right once.
+    3- exponent = exponent/2
+    4- i = bit25-b31 of L_x;  16<=i<=63  because of normalization.
+    5- a = bit10-b24
+    6- i -=16
+    7- L_y = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+    8- return L_y and exponent so caller can do denormalization
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sqrt_l.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word32 sqrt_l_exp (     // o : output value
+    Word32 L_x,         // i : input value
+    Word16 *exp         // o : right shift to be applied to result
+)
+{
+
+//          y = sqrt(x)
+//          x = f * 2^-e,   0.5 <= f < 1   (normalization)
+//          y = sqrt(f) * 2^(-e/2)
+//
+//          a) e = 2k   --> y = sqrt(f)   * 2^-k  (k = e div 2,
+//                                                 0.707 <= sqrt(f) < 1)
+//          b) e = 2k+1 --> y = sqrt(f/2) * 2^-k  (k = e div 2,
+                                                 0.5 <= sqrt(f/2) < 0.707)
+
+
+    Word16 e, i, a, tmp;
+    Word32 L_y;
+
+    if (L_x <= (Word32) 0)
+    {
+        *exp = 0;
+        return (Word32) 0;
+    }
+
+* The reference ETSI code uses a global Overflow flag. In the actual
+* implementation a pointer to the overflow flag is passed into the function.
+* This pointer is in turn passed into the basic math functions such as add(),
+* L_shl(), L_shr(), sub() called by this module.
+
+    e = norm_l (L_x) & 0xFFFE;              // get next lower EVEN norm. exp
+    L_x = L_shl (L_x, e);                   // L_x is normalized to [0.25..1)
+    *exp = e;                               // return 2*exponent (or Q1)
+
+    L_x = L_shr (L_x, 9);
+    i = extract_h (L_x);                    // Extract b25-b31, 16 <= i <= 63
+                                                because of normalization
+    L_x = L_shr (L_x, 1);
+    a = extract_l (L_x);                    // Extract b10-b24
+    a = a & (Word16) 0x7fff;
+
+    i = sub (i, 16);                        // 0 <= i <= 47
+
+    L_y = L_deposit_h (table[i]);           // table[i] << 16
+    tmp = sub (table[i], table[i + 1]);     // table[i] - table[i+1])
+    L_y = L_msu (L_y, tmp, a);              // L_y -= tmp*a*2
+
+    return (L_y);
+}
+
+------------------------------------------------------------------------------
+ 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]
+
+------------------------------------------------------------------------------
+*/
+
+Word32 sqrt_l_exp(      /* o : output value,                          Q31 */
+    Word32 L_x,         /* i : input value,                           Q31 */
+    Word16 *pExp,       /* o : right shift to be applied to result,   Q1  */
+    Flag   *pOverflow   /* i : pointer to overflow flag */
+)
+
+{
+    Word16 e;
+    Word16 i;
+    Word16 a;
+    Word16 tmp;
+    Word32 L_y;
+
+    /*
+          y = sqrt(x)
+          x = f * 2^-e,   0.5 <= f < 1   (normalization)
+          y = sqrt(f) * 2^(-e/2)
+          a) e = 2k   --> y = sqrt(f)   * 2^-k  (k = e div 2,
+                                                 0.707 <= sqrt(f) < 1)
+          b) e = 2k+1 --> y = sqrt(f/2) * 2^-k  (k = e div 2,
+                                                 0.5 <= sqrt(f/2) < 0.707)
+     */
+
+    if (L_x <= (Word32) 0)
+    {
+        *pExp = 0;
+        return (Word32) 0;
+    }
+
+    e = norm_l(L_x) & 0xFFFE;               /* get next lower EVEN norm. exp  */
+    L_x = L_shl(L_x, e, pOverflow);         /* L_x is normalized to [0.25..1) */
+    *pExp = e;                              /* return 2*exponent (or Q1)      */
+
+    L_x >>= 10;
+    i = (Word16)(L_x >> 15) & 63;            /* Extract b25-b31, 16<= i <=63  */
+    /* because of normalization       */
+
+    a = (Word16)(L_x);                      /* Extract b10-b24 */
+    a &= (Word16) 0x7fff;
+
+    if (i > 15)
+    {
+        i -= 16;                              /* 0 <= i <= 47                   */
+    }
+
+    L_y = L_deposit_h(sqrt_l_tbl[i]);       /* sqrt_l_tbl[i] << 16            */
+
+    /* sqrt_l_tbl[i] - sqrt_l_tbl[i+1]) */
+    tmp = sub(sqrt_l_tbl[i], sqrt_l_tbl[i + 1], pOverflow);
+
+    L_y = L_msu(L_y, tmp, a, pOverflow);    /* L_y -= tmp*a*2                 */
+
+    /* L_y = L_shr (L_y, *exp); */          /* denormalization done by caller */
+
+    return (L_y);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/sqrt_l_tbl.cpp b/media/libstagefright/codecs/amrnb/common/src/sqrt_l_tbl.cpp
new file mode 100644
index 0000000..5e9898c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/sqrt_l_tbl.cpp
@@ -0,0 +1,170 @@
+/* ------------------------------------------------------------------
+ * 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/sqrt_l_tbl.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed the table name to sqrt_l_tbl.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the declaration for sqrt_l_table[] used by the sqrt_l_exp
+ function.
+
+    sqrt_l_tbl[i] = sqrt((i+16)*2^-6) * 2^15, i.e. sqrt(x) scaled Q15
+
+ ------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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 sqrt_l_tbl[50] =
+    {
+        16384, 16888, 17378, 17854, 18318, 18770, 19212, 19644, 20066, 20480,
+        20886, 21283, 21674, 22058, 22435, 22806, 23170, 23530, 23884, 24232,
+        24576, 24915, 25249, 25580, 25905, 26227, 26545, 26859, 27170, 27477,
+        27780, 28081, 28378, 28672, 28963, 29251, 29537, 29819, 30099, 30377,
+        30652, 30924, 31194, 31462, 31727, 31991, 32252, 32511, 32767, 32767
+    };
+
+
+    /*--------------------------------------------------------------------------*/
+#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] inv_sqrt.tab file,  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/common/src/sub.cpp b/media/libstagefright/codecs/amrnb/common/src/sub.cpp
new file mode 100644
index 0000000..d936128
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/sub.cpp
@@ -0,0 +1,218 @@
+/* ------------------------------------------------------------------
+ * 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/sub.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created separate file for the sub function. Sync'ed up with the
+          current template and fixed tabs.
+
+ Description: Changed all occurrences of L_diff to diff, deleted "short" in
+          the definition of var1 and var2, and fixed the range values.
+
+ Description: Changed function prototype passing in a pointer to overflow flag
+              instead of using global data.
+
+ Description: Changes made per formal review comments.
+              1. Changed the parameter name fron "overflow" to "pOverflow"
+              2. Updated template
+              3. Updated reference section
+
+ Description: Removed conditional code that updates WMOPS counter
+
+ Description:
+              1. Modified if-else structure to save cycles by processing
+                 the most common case faster.
+
+ Who:                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Subtraction function with overflow control
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; 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: sub
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    var1 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+    var2 = 16 bit short signed integer (Word16) whose value falls in
+           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.
+
+    pOverflow = pointer to overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the subtract operation resulted in overflow
+
+ Returns:
+    diff = 16-bit limited difference between var1 and var2 (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the subtraction (var1-var2) with overflow control and
+ saturation; the 16 bit result is set at +32767 when overflow occurs or at
+ -32768 when underflow occurs.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] sub() function in basicop2.c, UMTS GSM AMR speech codec, R99 -
+ Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+
+ PSEUDO-CODE
+
+ Word16 sub (Word16 var1, Word16 var2)
+ {
+    Word16 var_out;
+    Word32 diff;
+
+    diff = (Word32) var1 - var2;
+
+* The reference ETSI code uses a global flag for Overflow inside the function
+* saturate(). In the actual implementation a pointer to Overflow flag is passed
+* in as a parameter to the function
+
+    var_out = saturate (diff);
+
+ #if (WMOPS)
+    multiCounter[currCounter].sub++;
+ #endif
+
+    return (var_out);
+ }
+
+------------------------------------------------------------------------------
+ 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 sub(Word16 var1, Word16 var2, Flag *pOverflow)
+{
+
+    Word32 diff;
+
+    diff = (Word32) var1 - var2;
+
+    /* Saturate result (if necessary). */
+    /* Replaced function call with in-line code             */
+    /*  to conserve MIPS, i.e., var_out = saturate (diff)  */
+
+
+    if ((UWord32)(diff - 0xFFFF8000L) > 0x000FFFF)
+    {
+        if (diff > (Word32) 0x0007FFFL)
+        {
+            diff = MAX_16;
+        }
+        else
+        {
+            diff = MIN_16;
+        }
+
+        *pOverflow = 1;
+    }
+
+
+    return ((Word16) diff);
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp b/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
new file mode 100644
index 0000000..bcdc696
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/syn_filt.cpp
@@ -0,0 +1,399 @@
+/* ------------------------------------------------------------------
+ * 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/syn_filt.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Making changes based on comments from the review meeting.
+
+ Description: Added typedef to Input/Output Definition section.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template.
+
+ Description: Fixed typecasting issue with the TI C compiler.
+
+ Description: Modified FOR loops to count down.
+
+ Description: Modified FOR loop to count up again so that the correct values
+              are stored in the tmp buffer. Updated copyright year.
+
+ Description:
+        - Modified for loop and introduced pointers to avoid adding
+          offsets
+        - Eliminated check for saturation given that the max values of input
+          data and coefficients will not saturate the multiply and
+          accumulation
+        - eliminated memcpy to update history buffer in every pass. This is
+          done now just updating the pointers.
+
+ Description:
+              1. Eliminated unused include files.
+              2. Unrolled loops to process twice as many samples as before,
+                 this saves on memory accesses to the vector coeff. a[] and
+                 elements in the history buffer of this recursive filter
+
+ Description:
+              1. Added overflow check inside both loops. (this is needed just
+                 to satisfy bit exactness on the decoder, a faster
+                 implementation will add an extra shift, do the same,
+                 but will not be bit exact, and it may have better audio
+                 quality because will avoid clipping)
+              2. Added include file for constant definitions
+
+ 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 fxp_arithmetic.h that includes inline assembly functions
+              for ARM and linux-arm.
+
+ Description: Replacing fxp_arithmetic.h with basic_op.h.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include <string.h>
+
+#include    "syn_filt.h"
+#include    "cnst.h"
+#include    "basic_op.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: Syn_filt
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    a = buffer containing the prediction coefficients (Word16)  max 2^12
+    x = input signal buffer (Word16)                            max 2^15
+    y = output signal buffer (Word16)
+    lg = size of filtering (Word16)
+    mem = memory buffer associated with this filtering (Word16)
+    update = flag to indicate memory update; 0=no update, 1=update memory
+             (Word16)
+
+ Outputs:
+    mem buffer is changed to be the last M data points of the output signal
+      if update was set to 1
+    y buffer contains the newly calculated filter output
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Perform synthesis filtering through 1/A(z)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ syn_filt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Syn_filt (
+    Word16 a[],     // (i)     : a[M+1] prediction coefficients   (M=10)
+    Word16 x[],     // (i)     : input signal
+    Word16 y[],     // (o)     : output signal
+    Word16 lg,      // (i)     : size of filtering
+    Word16 mem[],   // (i/o)   : memory associated with this filtering.
+    Word16 update   // (i)     : 0=no update, 1=update of memory.
+)
+{
+    Word16 i, j;
+    Word32 s;
+    Word16 tmp[80];   // This is usually done by memory allocation (lg+M)
+    Word16 *yy;
+
+    // Copy mem[] to yy[]
+
+    yy = tmp;
+
+    for (i = 0; i < M; i++)
+    {
+        *yy++ = mem[i];
+    }
+
+    // Do the filtering.
+
+    for (i = 0; i < lg; i++)
+    {
+        s = L_mult (x[i], a[0]);
+        for (j = 1; j <= M; j++)
+        {
+            s = L_msu (s, a[j], yy[-j]);
+        }
+        s = L_shl (s, 3);
+        *yy++ = pv_round (s);
+    }
+
+    for (i = 0; i < lg; i++)
+    {
+        y[i] = tmp[i + M];
+    }
+
+    // Update of memory if update==1
+
+    if (update != 0)
+    {
+        for (i = 0; i < M; i++)
+        {
+            mem[i] = y[lg - M + 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]
+
+------------------------------------------------------------------------------
+*/
+
+void Syn_filt(
+    Word16 a[],     /* (i)   : a[M+1] prediction coefficients   (M=10)  */
+    Word16 x[],     /* (i)   : input signal                             */
+    Word16 y[],     /* (o)   : output signal                            */
+    Word16 lg,      /* (i)   : size of filtering   (40)                 */
+    Word16 mem[],   /* (i/o) : memory associated with this filtering.   */
+    Word16 update   /* (i)   : 0=no update, 1=update of memory.         */
+)
+{
+    Word16 i, j;
+    Word32 s1;
+    Word32 s2;
+    Word16 tmp[2*M]; /* This is usually done by memory allocation (lg+M) */
+    Word16 *yy;
+
+    Word16 *p_a;
+    Word16 *p_yy1;
+    Word16 *p_y;
+    Word16 *p_x;
+    Word16 temp;
+    /* Copy mem[] to yy[] */
+
+    yy = tmp;
+
+    memcpy(yy, mem, M*sizeof(Word16));
+
+    yy = yy + M;
+
+    /* Do the filtering. */
+
+    p_y  = y;
+    p_x  = x;
+    p_yy1 = &yy[-1];
+
+    for (i = M >> 1; i != 0; i--)
+    {
+        p_a  = a;
+
+        s1 = amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_a), 0x00000800L);
+        s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_a++), 0x00000800L);
+        s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+
+        for (j = (M >> 1) - 2; j != 0; j--)
+        {
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+        }
+
+        /* check for overflow on s1 */
+        if ((UWord32)(s1 - 0xf8000000L) < 0x0fffffffL)
+        {
+            temp = (Word16)(s1 >> 12);
+        }
+        else if (s1 > 0x07ffffffL)
+        {
+            temp = MAX_16;
+        }
+        else
+        {
+            temp = MIN_16;
+        }
+
+        s2 = amrnb_fxp_msu_16_by_16bb((Word32)a[1], (Word32)temp, s2);
+
+        *(yy++)  = temp;
+        *(p_y++) = temp;
+
+        p_yy1 = yy;
+
+        /* check for overflow on s2 */
+        if ((UWord32)(s2 - 0xf8000000L) < 0x0fffffffL)
+        {
+            temp = (Word16)(s2 >> 12);
+        }
+        else if (s2 > 0x07ffffffL)
+        {
+            temp = MAX_16;
+        }
+        else
+        {
+            temp = MIN_16;
+        }
+
+        *(yy++)  = temp;
+        *(p_y++) = temp;
+    }
+
+    p_yy1 = &y[M-1];
+
+    for (i = (lg - M) >> 1; i != 0; i--)
+    {
+        p_a  = a;
+
+        s1 = amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_a), 0x00000800L);
+        s2 = amrnb_fxp_mac_16_by_16bb((Word32) * (p_x++), (Word32) * (p_a++), 0x00000800L);
+        s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+
+        for (j = (M >> 1) - 2; j != 0; j--)
+        {
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+            s2 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a), (Word32) * (p_yy1--), s2);
+            s1 = amrnb_fxp_msu_16_by_16bb((Word32) * (p_a++), (Word32) * (p_yy1), s1);
+        }
+
+        if ((UWord32)(s1 - 0xf8000000L) < 0x0fffffffL)
+        {
+            temp = (Word16)(s1 >> 12);
+        }
+        else if (s1 > 0x07ffffffL)
+        {
+            temp = MAX_16;
+        }
+        else
+        {
+            temp = MIN_16;
+        }
+
+        s2 = amrnb_fxp_msu_16_by_16bb((Word32)a[1], (Word32)temp, s2);
+
+        *(p_y++) = temp;
+        p_yy1 = p_y;
+
+        if ((UWord32)(s2 - 0xf8000000L) < 0x0fffffffL)
+        {
+            *(p_y++) = (Word16)(s2 >> 12);
+        }
+        else if (s2 > 0x07ffffffL)
+        {
+            *(p_y++) = MAX_16;
+        }
+        else
+        {
+            *(p_y++) = MIN_16;
+        }
+    }
+
+    /* Update of memory if update==1 */
+    if (update != 0)
+    {
+        memcpy(mem, &y[lg-M], M*sizeof(Word16));
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/common/src/vad1.cpp b/media/libstagefright/codecs/amrnb/common/src/vad1.cpp
new file mode 100644
index 0000000..a6e1131
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/vad1.cpp
@@ -0,0 +1,2330 @@
+/* ------------------------------------------------------------------
+ * 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/vad1.c
+ Functions:
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template.
+ Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Made changes per review comments
+ (1) Removed include of "count.h"
+ (2) Replaced "basic_op.h" with individual include files
+ (3) Removed some unnecessary instances of sub().
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "vad.h"
+#include "typedef.h"
+#include "shr.h"
+#include "basic_op.h"
+#include "cnst_vad.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: first_filter_stage
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    data -- array of type Word16 -- filter memory
+    in   -- array of type Word16 -- input signal
+
+ Outputs:
+    data -- array of type Word16 -- filter memory
+    out  -- array of type Word16 -- output values, every other
+                                    output is low-pass part and
+                                    other is high-pass part every
+
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Scale input down by one bit. Calculate 5th order
+                half-band lowpass/highpass filter pair with
+                decimation.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 first_filter_stage(
+    Word16 in[],      /* i   : input signal                  */
+    Word16 out[],     /* o   : output values, every other    */
+    /*       output is low-pass part and   */
+    /*       other is high-pass part every */
+    Word16 data[],    /* i/o : filter memory                 */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs   */
+)
+{
+    Word16 temp0;
+    Word16 temp1;
+    Word16 temp2;
+    Word16 temp3;
+    Word16 i;
+    Word16 data0;
+    Word16 data1;
+
+    data0 = data[0];
+    data1 = data[1];
+
+    for (i = 0; i < FRAME_LEN / 4; i++)
+    {
+        temp0 = mult(COEFF5_1, data0, pOverflow);
+        temp1 = shr(in[4*i+0], 2, pOverflow);
+        temp0 = sub(temp1, temp0, pOverflow);
+
+        temp1 = mult(COEFF5_1, temp0, pOverflow);
+        temp1 = add(data0, temp1, pOverflow);
+
+        temp3 = mult(COEFF5_2, data1, pOverflow);
+        temp2 = shr(in[4*i+1], 2, pOverflow);
+
+        temp3 = sub(temp2, temp3, pOverflow);
+
+        temp2 = mult(COEFF5_2, temp3, pOverflow);
+        temp2 = add(data1, temp2, pOverflow);
+
+        out[4*i+0] = add(temp1, temp2, pOverflow);
+        out[4*i+1] = sub(temp1, temp2, pOverflow);
+
+        temp1 = mult(COEFF5_1, temp0, pOverflow);
+        temp2 = shr(in[4*i+2], 2, pOverflow);
+        data0 = sub(temp2, temp1, pOverflow);
+
+        temp1 = mult(COEFF5_1, data0, pOverflow);
+        temp1 = add(temp0, temp1, pOverflow);
+
+        data1 = mult(COEFF5_2, temp3, pOverflow);
+        temp2 = shr(in[4*i+3], 2, pOverflow);
+        data1 = sub(temp2, data1, pOverflow);
+
+        temp2 = mult(COEFF5_2, data1, pOverflow);
+        temp2 = add(temp3, temp2, pOverflow);
+
+        out[4*i+2] = add(temp1, temp2, pOverflow);
+        out[4*i+3] = sub(temp1, temp2, pOverflow);
+    }
+
+    data[0] = data0;
+    data[1] = data1;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: filter5
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    in0 -- array of type Word16 -- input values; output low-pass part
+    in1 -- array of type Word16 -- input values; output high-pass part
+    data -- array of type Word16 -- updated filter memory
+
+ Outputs:
+    in0 -- array of type Word16 -- input values; output low-pass part
+    in1 -- array of type Word16 -- input values; output high-pass part
+    data -- array of type Word16 -- updated filter memory
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Fifth-order half-band lowpass/highpass filter pair with
+                decimation.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 filter5(Word16 *in0,    /* i/o : input values; output low-pass part  */
+                    Word16 *in1,    /* i/o : input values; output high-pass part */
+                    Word16 data[],  /* i/o : updated filter memory               */
+                    Flag  *pOverflow  /* o : Flag set when overflow occurs       */
+                   )
+{
+    Word16 temp0;
+    Word16 temp1;
+    Word16 temp2;
+
+    temp0 = mult(COEFF5_1, data[0], pOverflow);
+    temp0 = sub(*in0, temp0, pOverflow);
+
+    temp1 = mult(COEFF5_1, temp0, pOverflow);
+    temp1 = add(data[0], temp1, pOverflow);
+    data[0] = temp0;
+
+    temp0 = mult(COEFF5_2, data[1], pOverflow);
+    temp0 = sub(*in1, temp0, pOverflow);
+
+    temp2 = mult(COEFF5_2, temp0, pOverflow);
+    temp2 = add(data[1], temp2, pOverflow);
+
+    data[1] = temp0;
+
+    temp0 = add(temp1, temp2, pOverflow);
+    *in0 = shr(temp0, 1, pOverflow);
+
+    temp0 = sub(temp1, temp2, pOverflow);
+    *in1 = shr(temp0, 1, pOverflow);
+}
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: filter3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+ Inputs:
+    in0 -- array of type Word16 -- input values; output low-pass part
+    in1 -- array of type Word16 -- input values; output high-pass part
+    data -- array of type Word16 -- updated filter memory
+
+ Outputs:
+    in0 -- array of type Word16 -- input values; output low-pass part
+    in1 -- array of type Word16 -- input values; output high-pass part
+    data -- array of type Word16 -- updated filter memory
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Third-order half-band lowpass/highpass filter pair with
+                decimation.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 filter3(
+    Word16 *in0,      /* i/o : input values; output low-pass part  */
+    Word16 *in1,      /* i/o : input values; output high-pass part */
+    Word16 *data,     /* i/o : updated filter memory               */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs         */
+)
+{
+    Word16 temp1;
+    Word16 temp2;
+
+    temp1 = mult(COEFF3, *data, pOverflow);
+    temp1 = sub(*in1, temp1, pOverflow);
+
+    temp2 = mult(COEFF3, temp1, pOverflow);
+    temp2 = add(*data, temp2, pOverflow);
+
+    *data = temp1;
+
+    temp1 = sub(*in0, temp2, pOverflow);
+
+    *in1 = shr(temp1, 1, pOverflow);
+
+    temp1 = add(*in0, temp2, pOverflow);
+
+    *in0 = shr(temp1, 1, pOverflow);
+}
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: level_calculation
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    data -- array of type Word16 -- signal buffer
+    sub_level -- pointer to type Word16 -- level calculated at the end of
+                                           the previous frame
+
+    count1 -- Word16 -- number of samples to be counted
+    count2 -- Word16 -- number of samples to be counted
+    ind_m  -- Word16 -- step size for the index of the data buffer
+    ind_a  -- Word16 -- starting index of the data buffer
+    scale  -- Word16 -- scaling for the level calculation
+
+ Outputs:
+    sub_level -- pointer to tyep Word16 -- level of signal calculated from the
+                                           last (count2 - count1) samples.
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    signal level
+
+ Global Variables Used:
+
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Calculate signal level in a sub-band. Level is calculated
+                by summing absolute values of the input data.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 level_calculation(
+    Word16 data[],     /* i   : signal buffer                                */
+    Word16 *sub_level, /* i   : level calculate at the end of                */
+    /*       the previous frame                           */
+    /* o   : level of signal calculated from the last     */
+    /*       (count2 - count1) samples                    */
+    Word16 count1,     /* i   : number of samples to be counted              */
+    Word16 count2,     /* i   : number of samples to be counted              */
+    Word16 ind_m,      /* i   : step size for the index of the data buffer   */
+    Word16 ind_a,      /* i   : starting index of the data buffer            */
+    Word16 scale,      /* i   : scaling for the level calculation            */
+    Flag  *pOverflow   /* o : Flag set when overflow occurs                  */
+)
+{
+    Word32 l_temp1;
+    Word32 l_temp2;
+    Word16 level;
+    Word16 i;
+
+    l_temp1 = 0L;
+
+    for (i = count1; i < count2; i++)
+    {
+        l_temp1 = L_mac(l_temp1, 1, abs_s(data[ind_m*i+ind_a]), pOverflow);
+    }
+
+    l_temp2 = L_add(l_temp1, L_shl(*sub_level, sub(16, scale, pOverflow), pOverflow), pOverflow);
+    *sub_level = extract_h(L_shl(l_temp1, scale, pOverflow));
+
+    for (i = 0; i < count1; i++)
+    {
+        l_temp2 = L_mac(l_temp2, 1, abs_s(data[ind_m*i+ind_a]), pOverflow);
+    }
+    level = extract_h(L_shl(l_temp2, scale, pOverflow));
+
+    return level;
+}
+
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: filter_bank
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    in -- array of type Word16 -- input frame
+
+ Outputs:
+    level -- array of type Word16 -- signal levels at each band
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Divides input signal into 9-bands and calculas level of
+                the signal in each band
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 filter_bank(
+    vadState1 *st,    /* i/o : State struct                    */
+    Word16 in[],      /* i   : input frame                     */
+    Word16 level[],   /* 0   : signal levels at each band      */
+    Flag  *pOverflow  /* o   : Flag set when overflow occurs   */
+)
+{
+    Word16 i;
+    Word16 tmp_buf[FRAME_LEN];
+
+    /* calculate the filter bank */
+
+    first_filter_stage(in, tmp_buf, st->a_data5[0], pOverflow);
+
+    for (i = 0; i < FRAME_LEN / 4; i++)
+    {
+        filter5(&tmp_buf[4*i], &tmp_buf[4*i+2], st->a_data5[1], pOverflow);
+        filter5(&tmp_buf[4*i+1], &tmp_buf[4*i+3], st->a_data5[2], pOverflow);
+    }
+    for (i = 0; i < FRAME_LEN / 8; i++)
+    {
+        filter3(&tmp_buf[8*i+0], &tmp_buf[8*i+4], &st->a_data3[0], pOverflow);
+        filter3(&tmp_buf[8*i+2], &tmp_buf[8*i+6], &st->a_data3[1], pOverflow);
+        filter3(&tmp_buf[8*i+3], &tmp_buf[8*i+7], &st->a_data3[4], pOverflow);
+    }
+
+    for (i = 0; i < FRAME_LEN / 16; i++)
+    {
+        filter3(&tmp_buf[16*i+0], &tmp_buf[16*i+8], &st->a_data3[2], pOverflow);
+        filter3(&tmp_buf[16*i+4], &tmp_buf[16*i+12], &st->a_data3[3], pOverflow);
+    }
+
+    /* calculate levels in each frequency band */
+
+    /* 3000 - 4000 Hz*/
+    level[8] = level_calculation(tmp_buf, &st->sub_level[8], FRAME_LEN / 4 - 8,
+                                 FRAME_LEN / 4, 4, 1, 15, pOverflow);
+    /* 2500 - 3000 Hz*/
+    level[7] = level_calculation(tmp_buf, &st->sub_level[7], FRAME_LEN / 8 - 4,
+                                 FRAME_LEN / 8, 8, 7, 16, pOverflow);
+    /* 2000 - 2500 Hz*/
+    level[6] = level_calculation(tmp_buf, &st->sub_level[6], FRAME_LEN / 8 - 4,
+                                 FRAME_LEN / 8, 8, 3, 16, pOverflow);
+    /* 1500 - 2000 Hz*/
+    level[5] = level_calculation(tmp_buf, &st->sub_level[5], FRAME_LEN / 8 - 4,
+                                 FRAME_LEN / 8, 8, 2, 16, pOverflow);
+    /* 1000 - 1500 Hz*/
+    level[4] = level_calculation(tmp_buf, &st->sub_level[4], FRAME_LEN / 8 - 4,
+                                 FRAME_LEN / 8, 8, 6, 16, pOverflow);
+    /* 750 - 1000 Hz*/
+    level[3] = level_calculation(tmp_buf, &st->sub_level[3], FRAME_LEN / 16 - 2,
+                                 FRAME_LEN / 16, 16, 4, 16, pOverflow);
+    /* 500 - 750 Hz*/
+    level[2] = level_calculation(tmp_buf, &st->sub_level[2], FRAME_LEN / 16 - 2,
+                                 FRAME_LEN / 16, 16, 12, 16, pOverflow);
+    /* 250 - 500 Hz*/
+    level[1] = level_calculation(tmp_buf, &st->sub_level[1], FRAME_LEN / 16 - 2,
+                                 FRAME_LEN / 16, 16, 8, 16, pOverflow);
+    /* 0 - 250 Hz*/
+    level[0] = level_calculation(tmp_buf, &st->sub_level[0], FRAME_LEN / 16 - 2,
+                                 FRAME_LEN / 16, 16, 0, 16, pOverflow);
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: update_cntrl
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    level -- array of type Word16 -- sub-band levels of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose    : Control update of the background noise estimate.
+ Inputs     : pitch:      flags for pitch detection
+              stat_count: stationary counter
+              tone:       flags indicating presence of a tone
+              complex:      flags for complex  detection
+              vadreg:     intermediate VAD flags
+ Output     : stat_count: stationary counter
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 update_cntrl(
+    vadState1 *st,   /* i/o : State struct                       */
+    Word16 level[],  /* i   : sub-band levels of the input frame */
+    Flag  *pOverflow /* o   : Flag set when overflow occurs      */
+)
+{
+    Word16 i;
+    Word16 temp;
+    Word16 stat_rat;
+    Word16 exp;
+    Word16 num;
+    Word16 denom;
+    Word16 alpha;
+
+    /* handle highband complex signal input  separately       */
+    /* if ther has been highband correlation for some time    */
+    /* make sure that the VAD update speed is low for a while */
+    if (st->complex_warning != 0)
+    {
+        if (st->stat_count < CAD_MIN_STAT_COUNT)
+        {
+            st->stat_count = CAD_MIN_STAT_COUNT;
+        }
+    }
+    /* NB stat_count is allowed to be decreased by one below again  */
+    /* deadlock in speech is not possible unless the signal is very */
+    /* complex and need a high rate                                 */
+
+    /* if fullband pitch or tone have been detected for a while, initialize stat_count */
+    if (((Word16)(st->pitch & 0x6000) == 0x6000) ||
+            ((Word16)(st->tone & 0x7c00) == 0x7c00))
+    {
+        st->stat_count = STAT_COUNT;
+    }
+    else
+    {
+        /* if 8 last vad-decisions have been "0", reinitialize stat_count */
+        if ((st->vadreg & 0x7f80) == 0)
+        {
+            st->stat_count = STAT_COUNT;
+        }
+        else
+        {
+            stat_rat = 0;
+            for (i = 0; i < COMPLEN; i++)
+            {
+                if (level[i] > st->ave_level[i])
+                {
+                    num = level[i];
+                    denom = st->ave_level[i];
+                }
+                else
+                {
+                    num = st->ave_level[i];
+                    denom = level[i];
+                }
+                /* Limit nimimum value of num and denom to STAT_THR_LEVEL */
+                if (num < STAT_THR_LEVEL)
+                {
+                    num = STAT_THR_LEVEL;
+                }
+                if (denom < STAT_THR_LEVEL)
+                {
+                    denom = STAT_THR_LEVEL;
+                }
+
+                exp = norm_s(denom);
+
+                denom = shl(denom, exp, pOverflow);
+
+                /* stat_rat = num/denom * 64 */
+                temp = shr(num, 1, pOverflow);
+                temp = div_s(temp, denom);
+
+                stat_rat = add(stat_rat, shr(temp, sub(8, exp, pOverflow), pOverflow), pOverflow);
+            }
+
+            /* compare stat_rat with a threshold and update stat_count */
+            if (stat_rat > STAT_THR)
+            {
+                st->stat_count = STAT_COUNT;
+            }
+            else
+            {
+                if ((st->vadreg & 0x4000) != 0)
+                {
+                    if (st->stat_count != 0)
+                    {
+                        st->stat_count = sub(st->stat_count, 1, pOverflow);
+                    }
+                }
+            }
+        }
+    }
+
+    /* Update average amplitude estimate for stationarity estimation */
+    alpha = ALPHA4;
+    if (st->stat_count == STAT_COUNT)
+    {
+        alpha = 32767;
+    }
+    else if ((st->vadreg & 0x4000) == 0)
+    {
+        alpha = ALPHA5;
+    }
+
+    for (i = 0; i < COMPLEN; i++)
+    {
+        temp = sub(level[i], st->ave_level[i], pOverflow);
+        temp = mult_r(alpha, temp, pOverflow);
+
+        st->ave_level[i] =
+            add(
+                st->ave_level[i],
+                temp,
+                pOverflow);
+    }
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: hangover_addition
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    noise_level -- Word16 -- average level of the noise estimates
+    low_power   -- Word16 -- flag power of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicato
+
+ Returns:
+    VAD_flag indicating final VAD decision (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Function     : hangover_addition
+ Purpose      : Add hangover for complex signal or after speech bursts
+ Inputs       : burst_count:  counter for the length of speech bursts
+                hang_count:   hangover counter
+                vadreg:       intermediate VAD decision
+ Outputs      : burst_count:  counter for the length of speech bursts
+                hang_count:   hangover counter
+ Return value : VAD_flag indicating final VAD decision
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 hangover_addition(
+    vadState1 *st,      /* i/o : State struct                     */
+    Word16 noise_level, /* i   : average level of the noise       */
+    /*       estimates                        */
+    Word16 low_power,   /* i   : flag power of the input frame    */
+    Flag  *pOverflow    /* o   : Flag set when overflow occurs    */
+)
+{
+    Word16 hang_len;
+    Word16 burst_len;
+
+    /*
+       Calculate burst_len and hang_len
+       burst_len: number of consecutive intermediate vad flags with "1"-decision
+                  required for hangover addition
+       hang_len:  length of the hangover
+       */
+
+    if (noise_level > HANG_NOISE_THR)
+    {
+        burst_len = BURST_LEN_HIGH_NOISE;
+        hang_len = HANG_LEN_HIGH_NOISE;
+    }
+    else
+    {
+        burst_len = BURST_LEN_LOW_NOISE;
+        hang_len = HANG_LEN_LOW_NOISE;
+    }
+
+    /* if the input power (pow_sum) is lower than a threshold, clear
+       counters and set VAD_flag to "0"  "fast exit"                 */
+    if (low_power != 0)
+    {
+        st->burst_count = 0;
+        st->hang_count = 0;
+        st->complex_hang_count = 0;
+        st->complex_hang_timer = 0;
+        return 0;
+    }
+
+    if (st->complex_hang_timer > CVAD_HANG_LIMIT)
+    {
+        if (st->complex_hang_count < CVAD_HANG_LENGTH)
+        {
+            st->complex_hang_count = CVAD_HANG_LENGTH;
+        }
+    }
+
+    /* long time very complex signal override VAD output function */
+    if (st->complex_hang_count != 0)
+    {
+        st->burst_count = BURST_LEN_HIGH_NOISE;
+        st->complex_hang_count = sub(st->complex_hang_count, 1, pOverflow);
+        return 1;
+    }
+    else
+    {
+        /* let hp_corr work in from a noise_period indicated by the VAD */
+        if (((st->vadreg & 0x3ff0) == 0) &&
+                (st->corr_hp_fast > CVAD_THRESH_IN_NOISE))
+        {
+            return 1;
+        }
+    }
+
+    /* update the counters (hang_count, burst_count) */
+    if ((st->vadreg & 0x4000) != 0)
+    {
+        st->burst_count = add(st->burst_count, 1, pOverflow);
+
+        if (st->burst_count >= burst_len)
+        {
+            st->hang_count = hang_len;
+        }
+        return 1;
+    }
+    else
+    {
+        st->burst_count = 0;
+        if (st->hang_count > 0)
+        {
+            st->hang_count = sub(st->hang_count, 1, pOverflow);
+            return 1;
+        }
+    }
+    return 0;
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: noise_estimate_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    level -- array of type Word16 -- sub-band levels of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose    : Update of background noise estimate
+ Inputs     : bckr_est:   background noise estimate
+              pitch:      flags for pitch detection
+              stat_count: stationary counter
+ Outputs    : bckr_est:   background noise estimate
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 noise_estimate_update(
+    vadState1 *st,    /* i/o : State struct                       */
+    Word16 level[],   /* i   : sub-band levels of the input frame */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs        */
+)
+{
+    Word16 i;
+    Word16 alpha_up;
+    Word16 alpha_down;
+    Word16 bckr_add;
+
+    /* Control update of bckr_est[] */
+    update_cntrl(st, level, pOverflow);
+
+    /* Choose update speed */
+    bckr_add = 2;
+
+    if (((0x7800 & st->vadreg) == 0) &&
+            ((st->pitch & 0x7800) == 0)
+            && (st->complex_hang_count == 0))
+    {
+        alpha_up = ALPHA_UP1;
+        alpha_down = ALPHA_DOWN1;
+    }
+    else
+    {
+        if ((st->stat_count == 0)
+                && (st->complex_hang_count == 0))
+        {
+            alpha_up = ALPHA_UP2;
+            alpha_down = ALPHA_DOWN2;
+        }
+        else
+        {
+            alpha_up = 0;
+            alpha_down = ALPHA3;
+            bckr_add = 0;
+        }
+    }
+
+    /* Update noise estimate (bckr_est) */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        Word16 temp;
+
+        temp = sub(st->old_level[i], st->bckr_est[i], pOverflow);
+
+        if (temp < 0)
+        { /* update downwards*/
+            temp = mult_r(alpha_down, temp, pOverflow);
+            temp = add(st->bckr_est[i], temp, pOverflow);
+
+            st->bckr_est[i] = add(-2, temp, pOverflow);
+
+            /* limit minimum value of the noise estimate to NOISE_MIN */
+            if (st->bckr_est[i] < NOISE_MIN)
+            {
+                st->bckr_est[i] = NOISE_MIN;
+            }
+        }
+        else
+        { /* update upwards */
+            temp = mult_r(alpha_up, temp, pOverflow);
+            temp = add(st->bckr_est[i], temp, pOverflow);
+            st->bckr_est[i] = add(bckr_add, temp, pOverflow);
+
+            /* limit maximum value of the noise estimate to NOISE_MAX */
+            if (st->bckr_est[i] > NOISE_MAX)
+            {
+                st->bckr_est[i] = NOISE_MAX;
+            }
+        }
+    }
+
+    /* Update signal levels of the previous frame (old_level) */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        st->old_level[i] = level[i];
+    }
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: complex_estimate_adapt
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    low_power -- Word16 -- very low level flag of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Function   : complex_estimate_adapt
+ Purpose    : Update/adapt of complex signal estimate
+ Inputs     : low_power:   low signal power flag
+ Outputs    : st->corr_hp_fast:   long term complex signal estimate
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 complex_estimate_adapt(
+    vadState1 *st,      /* i/o : VAD state struct                       */
+    Word16 low_power,   /* i   : very low level flag of the input frame */
+    Flag  *pOverflow    /* o : Flag set when overflow occurs            */
+)
+{
+    Word16 alpha;            /* Q15 */
+    Word32 L_tmp;            /* Q31 */
+
+
+    /* adapt speed on own state */
+    if (st->best_corr_hp < st->corr_hp_fast) /* decrease */
+    {
+        if (st->corr_hp_fast < CVAD_THRESH_ADAPT_HIGH)
+        {  /* low state  */
+            alpha = CVAD_ADAPT_FAST;
+        }
+        else
+        {  /* high state */
+            alpha = CVAD_ADAPT_REALLY_FAST;
+        }
+    }
+    else  /* increase */
+    {
+        if (st->corr_hp_fast < CVAD_THRESH_ADAPT_HIGH)
+        {
+            alpha = CVAD_ADAPT_FAST;
+        }
+        else
+        {
+            alpha = CVAD_ADAPT_SLOW;
+        }
+    }
+
+    L_tmp = L_deposit_h(st->corr_hp_fast);
+    L_tmp = L_msu(L_tmp, alpha, st->corr_hp_fast, pOverflow);
+    L_tmp = L_mac(L_tmp, alpha, st->best_corr_hp, pOverflow);
+    st->corr_hp_fast = pv_round(L_tmp, pOverflow);           /* Q15 */
+
+    if (st->corr_hp_fast < CVAD_MIN_CORR)
+    {
+        st->corr_hp_fast = CVAD_MIN_CORR;
+    }
+
+    if (low_power != 0)
+    {
+        st->corr_hp_fast = CVAD_MIN_CORR;
+    }
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: complex_vad
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    low_power -- Word16 -- flag power of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+
+ Returns:
+    the complex background decision
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : complex background decision
+ Return value : the complex background decision
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 complex_vad(
+    vadState1 *st,    /* i/o : VAD state struct              */
+    Word16 low_power, /* i   : flag power of the input frame */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs   */
+)
+{
+    st->complex_high = shr(st->complex_high, 1, pOverflow);
+    st->complex_low = shr(st->complex_low, 1, pOverflow);
+
+    if (low_power == 0)
+    {
+        if (st->corr_hp_fast > CVAD_THRESH_ADAPT_HIGH)
+        {
+            st->complex_high |= 0x4000;
+        }
+
+        if (st->corr_hp_fast > CVAD_THRESH_ADAPT_LOW)
+        {
+            st->complex_low |= 0x4000;
+        }
+    }
+
+    if (st->corr_hp_fast > CVAD_THRESH_HANG)
+    {
+        st->complex_hang_timer = add(st->complex_hang_timer, 1, pOverflow);
+    }
+    else
+    {
+        st->complex_hang_timer =  0;
+    }
+
+    return ((Word16)(st->complex_high & 0x7f80) == 0x7f80 ||
+            (Word16)(st->complex_low & 0x7fff) == 0x7fff);
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad_decision
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    level -- array of type Word16 -- sub-band levels of the input frame
+    pow_sum -- Word32 -- power of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    VAD_flag (Word16)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Calculates VAD_flag
+ Inputs       : bckr_est:    background noise estimate
+                vadreg:      intermediate VAD flags
+ Outputs      : noise_level: average level of the noise estimates
+                vadreg:      intermediate VAD flags
+ Return value : VAD_flag
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad_decision(
+    vadState1 *st,         /* i/o : State struct                       */
+    Word16 level[COMPLEN], /* i   : sub-band levels of the input frame */
+    Word32 pow_sum,        /* i   : power of the input frame           */
+    Flag  *pOverflow       /* o : Flag set when overflow occurs        */
+)
+{
+    Word16 i;
+    Word16 snr_sum;
+    Word32 L_temp;
+    Word16 vad_thr;
+    Word16 temp;
+    Word16 noise_level;
+    Word16 low_power_flag;
+    Word16 temp1;
+
+    /*
+       Calculate squared sum of the input levels (level)
+       divided by the background noise components (bckr_est).
+       */
+    L_temp = 0;
+
+    for (i = 0; i < COMPLEN; i++)
+    {
+        Word16 exp;
+
+        exp = norm_s(st->bckr_est[i]);
+        temp = shl(st->bckr_est[i], exp, pOverflow);
+        temp = div_s(shr(level[i], 1, pOverflow), temp);
+        temp = shl(temp, sub(exp, UNIRSHFT - 1, pOverflow), pOverflow);
+        L_temp = L_mac(L_temp, temp, temp, pOverflow);
+    }
+
+    snr_sum = extract_h(L_shl(L_temp, 6, pOverflow));
+    snr_sum = mult(snr_sum, INV_COMPLEN, pOverflow);
+
+    /* Calculate average level of estimated background noise */
+    L_temp = 0;
+    for (i = 0; i < COMPLEN; i++)
+    {
+        L_temp = L_add(L_temp, st->bckr_est[i], pOverflow);
+    }
+
+    noise_level = extract_h(L_shl(L_temp, 13, pOverflow));
+
+    /* Calculate VAD threshold */
+    temp1 = sub(noise_level, VAD_P1, pOverflow);
+    temp1 = mult(VAD_SLOPE, temp1, pOverflow);
+    vad_thr = add(temp1, VAD_THR_HIGH, pOverflow);
+
+    if (vad_thr < VAD_THR_LOW)
+    {
+        vad_thr = VAD_THR_LOW;
+    }
+
+    /* Shift VAD decision register */
+    st->vadreg = shr(st->vadreg, 1, pOverflow);
+
+    /* Make intermediate VAD decision */
+    if (snr_sum > vad_thr)
+    {
+        st->vadreg |= 0x4000;
+    }
+    /* primary vad decsion made */
+
+    /* check if the input power (pow_sum) is lower than a threshold" */
+    if (L_sub(pow_sum, VAD_POW_LOW, pOverflow) < 0)
+    {
+        low_power_flag = 1;
+    }
+    else
+    {
+        low_power_flag = 0;
+    }
+
+    /* update complex signal estimate st->corr_hp_fast and hangover reset timer using */
+    /* low_power_flag and corr_hp_fast  and various adaptation speeds                 */
+    complex_estimate_adapt(st, low_power_flag, pOverflow);
+
+    /* check multiple thresholds of the st->corr_hp_fast value */
+    st->complex_warning = complex_vad(st, low_power_flag, pOverflow);
+
+    /* Update speech subband vad background noise estimates */
+    noise_estimate_update(st, level, pOverflow);
+
+    /*  Add speech and complex hangover and return speech VAD_flag */
+    /*  long term complex hangover may be added */
+    st->speech_vad_decision = hangover_addition(st, noise_level, low_power_flag, pOverflow);
+
+    return (st->speech_vad_decision);
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad1_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state -- double pointer to type vadState1 -- pointer to memory to
+                                                 be initialized.
+
+ Outputs:
+    state -- points to initalized area in memory.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Allocates state memory and initializes state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad1_init(vadState1 **state)
+{
+    vadState1* s;
+
+    if (state == (vadState1 **) NULL)
+    {
+        return -1;
+    }
+    *state = NULL;
+
+    /* allocate memory */
+    if ((s = (vadState1 *) malloc(sizeof(vadState1))) == NULL)
+    {
+        return -1;
+    }
+
+    vad1_reset(s);
+
+    *state = s;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad1_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state -- pointer to type vadState1 --  State struct
+
+ Outputs:
+    state -- pointer to type vadState1 --  State struct
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose:    Resets state memory to zero
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad1_reset(vadState1 *state)
+{
+    Word16 i;
+    Word16 j;
+
+    if (state == (vadState1 *) NULL)
+    {
+        return -1;
+    }
+
+    /* Initialize pitch detection variables */
+    state->oldlag_count = 0;
+    state->oldlag = 0;
+    state->pitch = 0;
+    state->tone = 0;
+
+    state->complex_high = 0;
+    state->complex_low = 0;
+    state->complex_hang_timer = 0;
+
+    state->vadreg = 0;
+
+    state->stat_count = 0;
+    state->burst_count = 0;
+    state->hang_count = 0;
+    state->complex_hang_count = 0;
+
+    /* initialize memory used by the filter bank */
+    for (i = 0; i < 3; i++)
+    {
+        for (j = 0; j < 2; j++)
+        {
+            state->a_data5[i][j] = 0;
+        }
+    }
+
+    for (i = 0; i < 5; i++)
+    {
+        state->a_data3[i] = 0;
+    }
+
+    /* initialize the rest of the memory */
+    for (i = 0; i < COMPLEN; i++)
+    {
+        state->bckr_est[i] = NOISE_INIT;
+        state->old_level[i] = NOISE_INIT;
+        state->ave_level[i] = NOISE_INIT;
+        state->sub_level[i] = 0;
+    }
+
+    state->best_corr_hp = CVAD_LOWPOW_RESET;
+
+    state->speech_vad_decision = 0;
+    state->complex_warning = 0;
+    state->sp_burst_count = 0;
+
+    state->corr_hp_fast = CVAD_LOWPOW_RESET;
+
+    return 0;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad1_exit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state -- pointer to type vadState1 --  State struct
+
+ 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
+
+ vad1.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 vad1_exit(vadState1 **state)
+{
+    if (state == NULL || *state == NULL)
+        return;
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad_complex_detection_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    best_corr_hp -- Word16 -- best Corr
+    state -- pointer to type vadState1 --  State struct
+
+ Outputs:
+    state -- pointer to type vadState1 --  State struct
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : update vad->bestCorr_hp  complex signal feature state
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad_complex_detection_update(
+    vadState1 *st,       /* i/o : State struct */
+    Word16 best_corr_hp) /* i   : best Corr    */
+{
+    st->best_corr_hp = best_corr_hp;
+}
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad_tone_detection
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    t0 -- Word32 -- autocorrelation maxima
+    t1 -- Word32 -- energy
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Set tone flag if pitch gain is high. This is used to detect
+                signaling tones and other signals with high pitch gain.
+ Inputs       : tone: flags indicating presence of a tone
+ Outputs      : tone: flags indicating presence of a tone
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad_tone_detection(
+    vadState1 *st,    /* i/o : State struct                       */
+    Word32 t0,        /* i   : autocorrelation maxima             */
+    Word32 t1,        /* i   : energy                             */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs        */
+)
+{
+    Word16 temp;
+    /*
+       if (t0 > TONE_THR * t1)
+       set tone flag
+       */
+    temp = pv_round(t1, pOverflow);
+
+    if ((temp > 0) && (L_msu(t0, temp, TONE_THR, pOverflow) > 0))
+    {
+        st->tone |= 0x4000;
+    }
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad_tone_detection_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    one_lag_per_frame -- Word16 -- 1 if one open-loop lag is calculated per
+                                   each frame, otherwise 0
+    st -- pointer to type vadState1 --  State struct
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Update the tone flag register. Tone flags are shifted right
+                by one bit. This function should be called from the speech
+                encoder before call to Vad_tone_detection() function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad_tone_detection_update(
+    vadState1 *st,              /* i/o : State struct           */
+    Word16 one_lag_per_frame,   /* i   : 1 if one open-loop lag */
+    /*       is calculated per each */
+    /*       frame, otherwise 0     */
+    Flag *pOverflow             /* o   : Flags overflow         */
+)
+{
+    /* Shift tone flags right by one bit */
+    st->tone = shr(st->tone, 1, pOverflow);
+
+    /* If open-loop lag is calculated only once in each frame, do extra update
+       and assume that the other tone flag of the frame is one. */
+    if (one_lag_per_frame != 0)
+    {
+        st->tone = shr(st->tone, 1, pOverflow);
+        st->tone |= 0x2000;
+    }
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad_pitch_detection
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    T_op -- array of type Word16 -- speech encoder open loop lags
+    st -- pointer to type vadState1 --  State struct
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Test whether signal contains pitch or other periodic
+                component.
+ Return value : Boolean voiced / unvoiced decision in state variable
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad_pitch_detection(
+    vadState1 *st,    /* i/o : State struct                  */
+    Word16 T_op[],    /* i   : speech encoder open loop lags */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs   */
+)
+{
+    Word16 lagcount;
+    Word16 i;
+    Word16 temp;
+
+    lagcount = 0;
+
+    for (i = 0; i < 2; i++)
+    {
+        temp = sub(st->oldlag, T_op[i], pOverflow);
+        temp = abs_s(temp);
+
+        if (temp < LTHRESH)
+        {
+            lagcount = add(lagcount, 1, pOverflow);
+        }
+
+        /* Save the current LTP lag */
+        st->oldlag = T_op[i];
+    }
+
+    /* Make pitch decision.
+       Save flag of the pitch detection to the variable pitch.
+       */
+    st->pitch = shr(st->pitch, 1, pOverflow);
+
+    temp =
+        add(
+            st->oldlag_count,
+            lagcount,
+            pOverflow);
+
+    if (temp >= NTHRESH)
+    {
+        st->pitch |= 0x4000;
+    }
+
+    /* Update oldlagcount */
+    st->oldlag_count = lagcount;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: vad1
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- pointer to type vadState1 --  State struct
+    in_buf -- array of type Word16 -- samples of the input frame
+
+ Outputs:
+    st -- pointer to type vadState1 --  State struct
+    pOverflow -- pointer to type Flag -- overflow indicator
+
+ Returns:
+    VAD Decision, 1 = speech, 0 = noise
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Purpose      : Main program for Voice Activity Detection (VAD) for AMR
+ Return value : VAD Decision, 1 = speech, 0 = noise
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ vad1.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 vad1(
+    vadState1 *st,    /* i/o : State struct                       */
+    Word16 in_buf[],  /* i   : samples of the input frame         */
+    Flag  *pOverflow  /* o   : Flag set when overflow occurs      */
+)
+{
+    Word16 level[COMPLEN];
+    Word32 pow_sum;
+    Word16 i;
+
+    /* Calculate power of the input frame. */
+    pow_sum = 0L;
+
+    for (i = 0; i < FRAME_LEN; i++)
+    {
+        pow_sum = L_mac(pow_sum, in_buf[i-LOOKAHEAD], in_buf[i-LOOKAHEAD], pOverflow);
+    }
+
+    /*
+      If input power is very low, clear pitch flag of the current frame
+      */
+    if (L_sub(pow_sum, POW_PITCH_THR, pOverflow) < 0)
+    {
+        st->pitch = st->pitch & 0x3fff;
+    }
+
+    /*
+      If input power is very low, clear complex flag of the "current" frame
+      */
+    if (L_sub(pow_sum, POW_COMPLEX_THR, pOverflow) < 0)
+    {
+        st->complex_low = st->complex_low & 0x3fff;
+    }
+
+    /*
+      Run the filter bank which calculates signal levels at each band
+      */
+    filter_bank(st, in_buf, level, pOverflow);
+
+    return (vad_decision(st, level, pow_sum, pOverflow));
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/weight_a.cpp b/media/libstagefright/codecs/amrnb/common/src/weight_a.cpp
new file mode 100644
index 0000000..2e2efc4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/weight_a.cpp
@@ -0,0 +1,196 @@
+/* ------------------------------------------------------------------
+ * 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/weight_a.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put file into template and first pass at optimization.
+
+ Description: Made changes based on comments from the review meeting. Used
+    pointers instead of index addressing in the arrays.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Fixed typecasting issue with TI C compiler.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Modified FOR loop to count down.
+              2. Used address pre-increment instead of address offsets.
+
+ 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.
+
+ Who:                           Date:
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "weight_a.h"
+#include    "typedef.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
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Weight_Ai
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    a = LPC coefficients (Word16)
+    fac = Spectral expansion factors (Word16)
+    a_exp = Spectral expanded LPC coefficients (Word16)
+
+ Outputs:
+    a_exp points to the updated spectral expanded LPC coefficients
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function calculates the spectral expansion for the LP coefficients of
+ order M.
+    a_exp[i] = a[i] * fac[i-1]    ; i=1..M
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ weight_a.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Weight_Ai (
+    Word16 a[],         // (i)     : a[M+1]  LPC coefficients   (M=10)
+    const Word16 fac[], // (i)     : Spectral expansion factors.
+    Word16 a_exp[]      // (o)     : Spectral expanded LPC coefficients
+)
+{
+    Word16 i;
+    a_exp[0] = a[0];
+
+    for (i = 1; i <= M; i++)
+    {
+        a_exp[i] = pv_round (L_mult (a[i], fac[i - 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 Weight_Ai(
+    Word16 a[],         /* (i)   : a[M+1]  LPC coefficients   (M=10)    */
+    const Word16 fac[], /* (i)   : Spectral expansion factors.          */
+    Word16 a_exp[]      /* (o)   : Spectral expanded LPC coefficients   */
+)
+{
+    register Word16 i;
+
+    *(a_exp) = *(a);
+
+    for (i = M; i >= 1; i--)
+    {
+        a_exp += 1;
+        a += 1;
+        fac += 1;
+        *(a_exp) = (Word16)((((Word32) * (a)) * *(fac - 1)
+                             + 0x00004000L) >> 15);
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/common/src/window_tab.cpp b/media/libstagefright/codecs/amrnb/common/src/window_tab.cpp
new file mode 100644
index 0000000..fa5faa6
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/common/src/window_tab.cpp
@@ -0,0 +1,280 @@
+/* ------------------------------------------------------------------
+ * 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/window_tab.c
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed tables from static const to just const.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Who:                       Date:
+ 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             : window.tab
+      Purpose          : Hamming_cos window for LPC analysis.
+
+------------------------------------------------------------------------------
+ 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.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+    /*************************************************************************
+     *
+     * Hamming_cos windows for LPC analysis.
+     *
+     *************************************************************************/
+
+    /* window for non-EFR modesm; uses 40 samples lookahead */
+
+    extern const Word16 window_200_40[L_WINDOW] =
+    {
+        2621,  2623,  2629,  2638,  2651,  2668,  2689,  2713,  2741,  2772,
+        2808,  2847,  2890,  2936,  2986,  3040,  3097,  3158,  3223,  3291,
+        3363,  3438,  3517,  3599,  3685,  3774,  3867,  3963,  4063,  4166,
+        4272,  4382,  4495,  4611,  4731,  4853,  4979,  5108,  5240,  5376,
+        5514,  5655,  5800,  5947,  6097,  6250,  6406,  6565,  6726,  6890,
+        7057,  7227,  7399,  7573,  7750,  7930,  8112,  8296,  8483,  8672,
+        8863,  9057,  9252,  9450,  9650,  9852, 10055, 10261, 10468, 10677,
+        10888, 11101, 11315, 11531, 11748, 11967, 12187, 12409, 12632, 12856,
+        13082, 13308, 13536, 13764, 13994, 14225, 14456, 14688, 14921, 15155,
+        15389, 15624, 15859, 16095, 16331, 16568, 16805, 17042, 17279, 17516,
+        17754, 17991, 18228, 18465, 18702, 18939, 19175, 19411, 19647, 19882,
+        20117, 20350, 20584, 20816, 21048, 21279, 21509, 21738, 21967, 22194,
+        22420, 22644, 22868, 23090, 23311, 23531, 23749, 23965, 24181, 24394,
+        24606, 24816, 25024, 25231, 25435, 25638, 25839, 26037, 26234, 26428,
+        26621, 26811, 26999, 27184, 27368, 27548, 27727, 27903, 28076, 28247,
+        28415, 28581, 28743, 28903, 29061, 29215, 29367, 29515, 29661, 29804,
+        29944, 30081, 30214, 30345, 30472, 30597, 30718, 30836, 30950, 31062,
+        31170, 31274, 31376, 31474, 31568, 31659, 31747, 31831, 31911, 31988,
+        32062, 32132, 32198, 32261, 32320, 32376, 32428, 32476, 32521, 32561,
+        32599, 32632, 32662, 32688, 32711, 32729, 32744, 32755, 32763, 32767,
+        32767, 32741, 32665, 32537, 32359, 32129, 31850, 31521, 31143, 30716,
+        30242, 29720, 29151, 28538, 27879, 27177, 26433, 25647, 24821, 23957,
+        23055, 22117, 21145, 20139, 19102, 18036, 16941, 15820, 14674, 13505,
+        12315, 11106,  9879,  8637,  7381,  6114,  4838,  3554,  2264,   971
+    };
+
+
+    /* window for EFR, first two subframes, no lookahead */
+
+    extern const Word16 window_160_80[L_WINDOW] =
+    {
+        2621, 2624, 2633, 2648, 2668, 2695, 2727, 2765, 2809, 2859,
+        2915, 2976, 3043, 3116, 3194, 3279, 3368, 3464, 3565, 3671,
+        3783, 3900, 4023, 4151, 4285, 4423, 4567, 4716, 4870, 5029,
+        5193, 5362, 5535, 5714, 5897, 6084, 6277, 6473, 6674, 6880,
+        7089, 7303, 7521, 7742, 7968, 8197, 8430, 8667, 8907, 9151,
+        9398, 9648, 9902, 10158, 10417, 10680, 10945, 11212, 11482, 11755,
+        12030, 12307, 12586, 12867, 13150, 13435, 13722, 14010, 14299, 14590,
+        14882, 15175, 15469, 15764, 16060, 16356, 16653, 16950, 17248, 17546,
+        17844, 18141, 18439, 18736, 19033, 19330, 19625, 19920, 20214, 20507,
+        20799, 21090, 21380, 21668, 21954, 22239, 22522, 22803, 23083, 23360,
+        23635, 23907, 24177, 24445, 24710, 24972, 25231, 25488, 25741, 25991,
+        26238, 26482, 26722, 26959, 27192, 27422, 27647, 27869, 28087, 28300,
+        28510, 28715, 28916, 29113, 29305, 29493, 29676, 29854, 30028, 30197,
+        30361, 30519, 30673, 30822, 30966, 31105, 31238, 31366, 31489, 31606,
+        31718, 31825, 31926, 32021, 32111, 32195, 32273, 32346, 32413, 32475,
+        32530, 32580, 32624, 32662, 32695, 32721, 32742, 32756, 32765, 32767,
+        32767, 32756, 32720, 32661, 32578, 32471, 32341, 32188, 32012, 31813,
+        31592, 31349, 31084, 30798, 30492, 30165, 29818, 29453, 29068, 28666,
+        28247, 27810, 27358, 26891, 26408, 25913, 25404, 24883, 24350, 23807,
+        23255, 22693, 22124, 21548, 20965, 20378, 19786, 19191, 18593, 17994,
+        17395, 16796, 16199, 15604, 15012, 14424, 13842, 13265, 12696, 12135,
+        11582, 11039, 10507, 9986, 9477, 8981, 8499, 8031, 7579, 7143,
+        6723, 6321, 5937, 5571, 5225, 4898, 4591, 4305, 4041, 3798,
+        3577, 3378, 3202, 3048, 2918, 2812, 2729, 2669, 2633, 2621
+    };
+
+    /* window for EFR, last two subframes, no lookahead */
+
+    extern const Word16 window_232_8[L_WINDOW] =
+    {
+        2621, 2623, 2627, 2634, 2644, 2656, 2671, 2689, 2710, 2734,
+        2760, 2789, 2821, 2855, 2893, 2933, 2975, 3021, 3069, 3120,
+        3173, 3229, 3288, 3350, 3414, 3481, 3550, 3622, 3697, 3774,
+        3853, 3936, 4021, 4108, 4198, 4290, 4385, 4482, 4582, 4684,
+        4788, 4895, 5004, 5116, 5230, 5346, 5464, 5585, 5708, 5833,
+        5960, 6090, 6221, 6355, 6491, 6629, 6769, 6910, 7054, 7200,
+        7348, 7498, 7649, 7803, 7958, 8115, 8274, 8434, 8597, 8761,
+        8926, 9093, 9262, 9432, 9604, 9778, 9952, 10129, 10306, 10485,
+        10665, 10847, 11030, 11214, 11399, 11586, 11773, 11962, 12152, 12342,
+        12534, 12727, 12920, 13115, 13310, 13506, 13703, 13901, 14099, 14298,
+        14497, 14698, 14898, 15100, 15301, 15504, 15706, 15909, 16112, 16316,
+        16520, 16724, 16928, 17132, 17337, 17541, 17746, 17950, 18155, 18359,
+        18564, 18768, 18972, 19175, 19379, 19582, 19785, 19987, 20189, 20390,
+        20591, 20792, 20992, 21191, 21390, 21588, 21785, 21981, 22177, 22372,
+        22566, 22759, 22951, 23143, 23333, 23522, 23710, 23897, 24083, 24268,
+        24451, 24633, 24814, 24994, 25172, 25349, 25525, 25699, 25871, 26042,
+        26212, 26380, 26546, 26711, 26874, 27035, 27195, 27353, 27509, 27664,
+        27816, 27967, 28115, 28262, 28407, 28550, 28691, 28830, 28967, 29102,
+        29234, 29365, 29493, 29619, 29743, 29865, 29985, 30102, 30217, 30330,
+        30440, 30548, 30654, 30757, 30858, 30956, 31052, 31146, 31237, 31326,
+        31412, 31495, 31576, 31655, 31730, 31804, 31874, 31942, 32008, 32071,
+        32131, 32188, 32243, 32295, 32345, 32392, 32436, 32477, 32516, 32552,
+        32585, 32615, 32643, 32668, 32690, 32709, 32726, 32740, 32751, 32759,
+        32765, 32767, 32767, 32097, 30112, 26895, 22576, 17333, 11380, 4962
+    };
+
+    /*----------------------------------------------------------------------------
+    ; 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/dec/AMRNBDecoder.cpp b/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp
new file mode 100644
index 0000000..fbb6598
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/AMRNBDecoder.cpp
@@ -0,0 +1,187 @@
+/*
+ * 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 "AMRNBDecoder.h"
+
+#include "gsmamr_dec.h"
+
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+static const int32_t kNumSamplesPerFrame = 160;
+static const int32_t kSampleRate = 8000;
+
+AMRNBDecoder::AMRNBDecoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mBufferGroup(NULL),
+      mState(NULL),
+      mAnchorTimeUs(0),
+      mNumSamplesOutput(0),
+      mInputBuffer(NULL) {
+}
+
+AMRNBDecoder::~AMRNBDecoder() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+status_t AMRNBDecoder::start(MetaData *params) {
+    CHECK(!mStarted);
+
+    mBufferGroup = new MediaBufferGroup;
+    mBufferGroup->add_buffer(
+            new MediaBuffer(kNumSamplesPerFrame * sizeof(int16_t)));
+
+    CHECK_EQ(GSMInitDecode(&mState, (Word8 *)"AMRNBDecoder"), 0);
+
+    mSource->start();
+
+    mAnchorTimeUs = 0;
+    mNumSamplesOutput = 0;
+    mStarted = true;
+
+    return OK;
+}
+
+status_t AMRNBDecoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    delete mBufferGroup;
+    mBufferGroup = NULL;
+
+    GSMDecodeFrameExit(&mState);
+
+    mSource->stop();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> AMRNBDecoder::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_RAW);
+    meta->setInt32(kKeyChannelCount, numChannels);
+    meta->setInt32(kKeySampleRate, sampleRate);
+
+    int64_t durationUs;
+    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
+        meta->setInt64(kKeyDuration, durationUs);
+    }
+
+    return meta;
+}
+
+status_t AMRNBDecoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    status_t err;
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        CHECK(seekTimeUs >= 0);
+
+        mNumSamplesOutput = 0;
+
+        if (mInputBuffer) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+    } else {
+        seekTimeUs = -1;
+    }
+
+    if (mInputBuffer == NULL) {
+        err = mSource->read(&mInputBuffer, options);
+
+        if (err != OK) {
+            return err;
+        }
+
+        int64_t timeUs;
+        if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
+            mAnchorTimeUs = timeUs;
+            mNumSamplesOutput = 0;
+        } else {
+            // We must have a new timestamp after seeking.
+            CHECK(seekTimeUs < 0);
+        }
+    }
+
+    MediaBuffer *buffer;
+    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
+
+    const uint8_t *inputPtr =
+        (const uint8_t *)mInputBuffer->data() + mInputBuffer->range_offset();
+
+    size_t numBytesRead =
+        AMRDecode(mState,
+          (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f),
+          (UWord8 *)&inputPtr[1],
+          static_cast<int16_t *>(buffer->data()),
+          MIME_IETF);
+
+    ++numBytesRead;  // Include the frame type header byte.
+
+    buffer->set_range(0, kNumSamplesPerFrame * sizeof(int16_t));
+
+    CHECK(numBytesRead <= mInputBuffer->range_length());
+
+    mInputBuffer->set_range(
+            mInputBuffer->range_offset() + numBytesRead,
+            mInputBuffer->range_length() - numBytesRead);
+
+    if (mInputBuffer->range_length() == 0) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    buffer->meta_data()->setInt64(
+            kKeyTime,
+            mAnchorTimeUs
+                + (mNumSamplesOutput * 1000000) / kSampleRate);
+
+    mNumSamplesOutput += kNumSamplesPerFrame;
+
+    *out = buffer;
+
+    return OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/amrnb/dec/Android.mk b/media/libstagefright/codecs/amrnb/dec/Android.mk
new file mode 100644
index 0000000..a545762
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/Android.mk
@@ -0,0 +1,54 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        AMRNBDecoder.cpp \
+ 	src/a_refl.cpp \
+ 	src/agc.cpp \
+ 	src/amrdecode.cpp \
+ 	src/b_cn_cod.cpp \
+ 	src/bgnscd.cpp \
+ 	src/c_g_aver.cpp \
+ 	src/d1035pf.cpp \
+ 	src/d2_11pf.cpp \
+ 	src/d2_9pf.cpp \
+ 	src/d3_14pf.cpp \
+ 	src/d4_17pf.cpp \
+ 	src/d8_31pf.cpp \
+ 	src/d_gain_c.cpp \
+ 	src/d_gain_p.cpp \
+ 	src/d_plsf.cpp \
+ 	src/d_plsf_3.cpp \
+ 	src/d_plsf_5.cpp \
+ 	src/dec_amr.cpp \
+ 	src/dec_gain.cpp \
+ 	src/dec_input_format_tab.cpp \
+ 	src/dec_lag3.cpp \
+ 	src/dec_lag6.cpp \
+ 	src/dtx_dec.cpp \
+ 	src/ec_gains.cpp \
+ 	src/ex_ctrl.cpp \
+ 	src/if2_to_ets.cpp \
+ 	src/int_lsf.cpp \
+ 	src/lsp_avg.cpp \
+ 	src/ph_disp.cpp \
+ 	src/post_pro.cpp \
+ 	src/preemph.cpp \
+ 	src/pstfilt.cpp \
+ 	src/qgain475_tab.cpp \
+ 	src/sp_dec.cpp \
+ 	src/wmf_to_ets.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= -DOSCL_IMPORT_REF=
+
+LOCAL_MODULE := libstagefright_amrnbdec
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/amrnb/dec/include/pvamrnbdecoder_api.h b/media/libstagefright/codecs/amrnb/dec/include/pvamrnbdecoder_api.h
new file mode 100644
index 0000000..7b94320
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/include/pvamrnbdecoder_api.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.
+****************************************************************************************/
+/*
+ Name: pvamrnbdecoder_api.h
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Who:                                       Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Main header file for the Packet Video AMR Narrow  Band  decoder library. The
+ constants, structures, and functions defined within this file, along with
+ a basic data types header file, is all that is needed to use and communicate
+ with the library. The internal data structures within the library are
+ purposely hidden.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef _PVAMRNBDECODER_API_H
+#define _PVAMRNBDECODER_API_H
+
+#include    "pvgsmamrdecoderinterface.h"
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define MAX_NUM_FRAMES_PER_PACKET 20 /* Max number of frames per packet */
+
+#define MAX_NUM_PACKED_INPUT_BYTES 32 /* Max number of packed input bytes */
+
+#define L_FRAME      160
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* PVMP4AUDIODECODER_API_H */
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp b/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
new file mode 100644
index 0000000..fb7cff3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/a_refl.cpp
@@ -0,0 +1,313 @@
+/* ------------------------------------------------------------------
+ * 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/a_refl.c
+ Functions: a_refl
+
+     Date: 02/05/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removing unneeded include files and the goto statement.
+
+
+ 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:  Using inline functions from basic_op.h .
+               Removing unneeded include files.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "a_refl.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "basic_op.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: AMREncode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    a[] = pointer to directform coefficients of type Word16
+    refl[] = pointer to reflection coefficients of type Word16
+
+ Outputs:
+    pOverflow = 1 if overflow exists in the math operations else zero.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+     File             : a_refl.c
+     Purpose          : Convert from direct form coefficients to
+                        reflection coefficients
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] a_refl.c , 3GPP TS 26.101 version 4.1.0 Release 4, June 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+void A_Refl(
+   Word16 a[],        // i   : Directform coefficients
+   Word16 refl[]      // o   : Reflection coefficients
+)
+{
+   // local variables
+   Word16 i,j;
+   Word16 aState[M];
+   Word16 bState[M];
+   Word16 normShift;
+   Word16 normProd;
+   Word32 L_acc;
+   Word16 scale;
+   Word32 L_temp;
+   Word16 temp;
+   Word16 mult;
+
+   // initialize states
+   for (i = 0; i < M; i++)
+   {
+      aState[i] = a[i];
+   }
+
+   // backward Levinson recursion
+   for (i = M-1; i >= 0; i--)
+   {
+      if (sub(abs_s(aState[i]), 4096) >= 0)
+      {
+         goto ExitRefl;
+      }
+
+      refl[i] = shl(aState[i], 3);
+
+      L_temp = L_mult(refl[i], refl[i]);
+      L_acc = L_sub(MAX_32, L_temp);
+
+      normShift = norm_l(L_acc);
+      scale = sub(15, normShift);
+
+      L_acc = L_shl(L_acc, normShift);
+      normProd = pv_round(L_acc);
+
+      mult = div_s(16384, normProd);
+
+      for (j = 0; j < i; j++)
+      {
+         L_acc = L_deposit_h(aState[j]);
+         L_acc = L_msu(L_acc, refl[i], aState[i-j-1]);
+
+         temp = pv_round(L_acc);
+         L_temp = L_mult(mult, temp);
+         L_temp = L_shr_r(L_temp, scale);
+
+         if (L_sub(L_abs(L_temp), 32767) > 0)
+         {
+            goto ExitRefl;
+         }
+
+         bState[j] = extract_l(L_temp);
+      }
+
+      for (j = 0; j < i; j++)
+      {
+         aState[j] = bState[j];
+      }
+   }
+   return;
+
+ExitRefl:
+   for (i = 0; i < M; i++)
+   {
+      refl[i] = 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 A_Refl(
+    Word16 a[],        /* i   : Directform coefficients */
+    Word16 refl[],     /* o   : Reflection coefficients */
+    Flag   *pOverflow
+)
+{
+    /* local variables */
+    Word16 i;
+    Word16 j;
+    Word16 aState[M];
+    Word16 bState[M];
+    Word16 normShift;
+    Word16 normProd;
+    Word32 L_acc;
+    Word16 scale;
+    Word32 L_temp;
+    Word16 temp;
+    Word16 mult;
+
+    /* initialize states */
+    for (i = 0; i < M; i++)
+    {
+        aState[i] = a[i];
+    }
+
+    /* backward Levinson recursion */
+    for (i = M - 1; i >= 0; i--)
+    {
+        if (abs_s(aState[i]) >= 4096)
+        {
+            for (i = 0; i < M; i++)
+            {
+                refl[i] = 0;
+            }
+            break;
+        }
+
+        refl[i] = shl(aState[i], 3, pOverflow);
+
+        L_temp = L_mult(refl[i], refl[i], pOverflow);
+        L_acc = L_sub(MAX_32, L_temp, pOverflow);
+
+        normShift = norm_l(L_acc);
+        scale = sub(15, normShift, pOverflow);
+
+        L_acc = L_shl(L_acc, normShift, pOverflow);
+        normProd = pv_round(L_acc, pOverflow);
+
+        mult = div_s(16384, normProd);
+
+        for (j = 0; j < i; j++)
+        {
+            L_acc = L_deposit_h(aState[j]);
+            L_acc = L_msu(L_acc, refl[i], aState[i-j-1], pOverflow);
+
+            temp = pv_round(L_acc, pOverflow);
+            L_temp = L_mult(mult, temp, pOverflow);
+            L_temp = L_shr_r(L_temp, scale, pOverflow);
+
+            if (L_abs(L_temp) > 32767)
+            {
+                for (i = 0; i < M; i++)
+                {
+                    refl[i] = 0;
+                }
+                break;
+            }
+
+            bState[j] = extract_l(L_temp);
+        }
+
+        for (j = 0; j < i; j++)
+        {
+            aState[j] = bState[j];
+        }
+    }
+    return;
+}
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/a_refl.h b/media/libstagefright/codecs/amrnb/dec/src/a_refl.h
new file mode 100644
index 0000000..4028e1e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/a_refl.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/a_refl.h
+
+     Date: 08/11/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+    File             : a_refl.h
+    Purpose          : Convert from direct form coefficients to
+                       reflection coefficients
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef A_REFL_H
+#define A_REFL_H
+#define a_refl_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
+    ----------------------------------------------------------------------------*/
+    /*
+     *   FUNCTION:  A_Refl()
+     *   PURPOSE: Convert from direct form coefficients to reflection coefficients
+     *   DESCRIPTION:
+     *       Directform coeffs in Q12 are converted to
+     *       reflection coefficients Q15
+     */
+    void A_Refl(
+        Word16 a[],        /* i   : Directform coefficients */
+        Word16 refl[],     /* o   : Reflection coefficients */
+        Flag   *pOverflow
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _A_REFL_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/agc.cpp b/media/libstagefright/codecs/amrnb/dec/src/agc.cpp
new file mode 100644
index 0000000..4c66d54
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/agc.cpp
@@ -0,0 +1,1066 @@
+/* ------------------------------------------------------------------
+ * 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/agc.c
+ Funtions: energy_old
+           energy_new
+           agc_init
+           agc_reset
+           agc_exit
+           agc
+           agc2
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This set of modules scale the excitation level and output of the speech
+ signals.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "agc.h"
+#include    "cnst.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 VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: energy_old
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    in = input signal (Word16)
+    l_trm = input signal length (Word16)
+    pOverflow = address of overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the energy computation saturates
+
+ Returns:
+    s = return energy of signal (Word32)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Returns the energy of the signal.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word32 energy_old( // o : return energy of signal
+    Word16 in[],          // i : input signal (length l_trm)
+    Word16 l_trm          // i : signal length
+)
+{
+    Word32 s;
+    Word16 i, temp;
+
+    temp = shr (in[0], 2);
+    s = L_mult (temp, temp);
+
+    for (i = 1; i < l_trm; i++)
+    {
+        temp = shr (in[i], 2);
+        s = L_mac (s, temp, temp);
+    }
+
+    return 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]
+
+------------------------------------------------------------------------------
+*/
+
+static Word32 energy_old(       /* o : return energy of signal      */
+    Word16 in[],        /* i : input signal (length l_trm)  */
+    Word16 l_trm,       /* i : signal length                */
+    Flag   *pOverflow   /* overflow: flag to indicate overflow */
+)
+
+{
+    Word32  s = 0;
+    Word16  i;
+    Word16  temp;
+
+    for (i = 0; i < l_trm; i++)
+    {
+        temp = in[i] >> 2;
+        s = L_mac(s, temp, temp, pOverflow);
+    }
+
+    return(s);
+}
+
+/*----------------------------------------------------------------------------*/
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: energy_old__Wrapper
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    in = input signal (Word16)
+    l_trm = input signal length (Word16)
+    pOverflow = address of overflow (Flag)
+ Outputs:
+    pOverflow -> 1 if the energy computation saturates
+
+ Returns:
+    s = return energy of signal (Word32)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function provides external access to the static function energy_old.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ CALL energy_old (  in = in
+            l_trm = l_trm
+            pOverflow = pOverflow )
+   MODIFYING(nothing)
+   RETURNING(energy_old_value = 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]
+
+------------------------------------------------------------------------------
+*/
+
+Word32 energy_old_Wrapper(Word16 in[], Word16 l_trm, Flag *pOverflow)
+{
+    Word32 energy_old_value;
+
+    /*----------------------------------------------------------------------------
+     CALL energy_old (  in = in
+                l_trm = l_trm
+                pOverflow = pOverflow )
+
+      MODIFYING(nothing)
+       RETURNING(energy_old_value = s)
+    ----------------------------------------------------------------------------*/
+    energy_old_value = energy_old(in, l_trm, pOverflow);
+    return(energy_old_value);
+}
+/*--------------------------------------------------------------------------*/
+
+/*
+-----------------------------------------------------------------------------
+ FUNCTION NAME: energy_new
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    in = input signal
+    l_trm = input signal length
+    pOverflow = address of overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the energy computation saturates
+
+ Returns:
+    s = return energy of signal
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Returns the energy of the signal.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+static Word32 energy_new( // o : return energy of signal
+    Word16 in[],          // i : input signal (length l_trm)
+    Word16 l_trm )        // i : signal length
+
+{
+    Word32 s;
+    Word16 i;
+    Flag ov_save;
+
+    ov_save = Overflow;            //save overflow flag in case energy_old
+                                   // must be called
+    s = L_mult(in[0], in[0]);
+    for (i = 1; i < l_trm; i++)
+    {
+        s = L_mac(s, in[i], in[i]);
+    }
+
+    // check for overflow
+    if (L_sub (s, MAX_32) == 0L)
+    {
+        Overflow = ov_save; // restore overflow flag
+        s = energy_old (in, l_trm); // function result
+    }
+    else
+    {
+       s = L_shr(s, 4);
+    }
+
+    return(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]
+
+------------------------------------------------------------------------------
+*/
+
+static Word32 energy_new(       /* o : return energy of signal      */
+    Word16 in[],        /* i : input signal (length l_trm)  */
+    Word16 l_trm,       /* i : signal length                */
+    Flag *pOverflow     /* i : overflow flag                */
+)
+
+{
+    Word32  s = 0;
+    Word16  i;
+    Flag    ov_save;
+
+    ov_save = *(pOverflow);  /* save overflow flag in case energy_old */
+    /* must be called                        */
+
+
+    for (i = 0; i < l_trm; i++)
+    {
+        s = L_mac(s, in[i], in[i], pOverflow);
+    }
+
+    /* check for overflow */
+    if (s != MAX_32)
+    {
+        /* s is a sum of squares, so it won't be negative */
+        s = s >> 4;
+    }
+    else
+    {
+        *(pOverflow) = ov_save;  /* restore overflow flag */
+        s = energy_old(in, l_trm, pOverflow);   /* function result */
+    }
+
+    return (s);
+}
+
+/*--------------------------------------------------------------------------*/
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: energy_new__Wrapper
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    in = input signal (Word16)
+    l_trm = input signal length (Word16)
+    overflow = address of overflow (Flag)
+
+ Outputs:
+    pOverflow -> 1 if the energy computation saturates
+
+ Returns:
+    s = return energy of signal (Word32)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function provides external access to the static function energy_new.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ CALL energy_new (  in = in
+            l_trm = l_trm
+            pOverflow = pOverflow )
+
+   MODIFYING(nothing)
+
+   RETURNING(energy_new_value = 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]
+
+------------------------------------------------------------------------------
+*/
+
+Word32 energy_new_Wrapper(Word16 in[], Word16 l_trm, Flag *pOverflow)
+{
+    Word32 energy_new_value;
+
+    /*----------------------------------------------------------------------------
+     CALL energy_new (  in = in
+                l_trm = l_trm
+                pOverflow = pOverflow )
+
+       MODIFYING(nothing)
+       RETURNING(energy_new_value = s)
+
+    ----------------------------------------------------------------------------*/
+    energy_new_value = energy_new(in, l_trm, pOverflow);
+
+    return(energy_new_value);
+
+}
+
+/*--------------------------------------------------------------------------*/
+
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: agc_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type agcState
+
+ Outputs:
+    Structure pointed to by state is initialized to zeros
+
+ Returns:
+    Returns 0 if memory was successfully initialized,
+        otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Reset of agc (i.e. set state memory to 1.0).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int agc_reset (agcState *state)
+{
+  if (state == (agcState *) NULL)
+  {
+      fprintf(stderr, "agc_reset: invalid parameter\n");
+      return -1;
+  }
+
+  state->past_gain = 4096;   // initial value of past_gain = 1.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 agc_reset(agcState *state)
+{
+    if (state == (agcState *) NULL)
+    {
+        /* fprintf(stderr, "agc_reset: invalid parameter\n"); */
+        return(-1);
+    }
+
+    state->past_gain = 4096;   /* initial value of past_gain = 1.0  */
+
+    return(0);
+}
+
+/*--------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: agc
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to agc state
+    sig_in = pointer to a buffer containing the postfilter input signal
+    sig_out = pointer to a buffer containing the postfilter output signal
+    agc_fac = AGC factor
+    l_trm = subframe size
+    pOverflow = pointer to the overflow flag
+
+ Outputs:
+    st->past_gain = gain
+    buffer pointed to by sig_out contains the new postfilter output signal
+    pOverflow -> 1 if the agc computation saturates
+
+ Returns:
+    return = 0
+
+ Global Variables Used:
+    none.
+
+ Local Variables Needed:
+    none.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Scales the postfilter output on a subframe basis using:
+
+     sig_out[n] = sig_out[n] * gain[n]
+     gain[n] = agc_fac * gain[n-1] + (1 - agc_fac) g_in/g_out
+
+ where: gain[n] = gain at the nth sample given by
+        g_in/g_out = square root of the ratio of energy at
+                     the input and output of the postfilter.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int agc (
+    agcState *st,      // i/o : agc state
+    Word16 *sig_in,    // i   : postfilter input signal  (l_trm)
+    Word16 *sig_out,   // i/o : postfilter output signal (l_trm)
+    Word16 agc_fac,    // i   : AGC factor
+    Word16 l_trm       // i   : subframe size
+)
+{
+    Word16 i, exp;
+    Word16 gain_in, gain_out, g0, gain;
+    Word32 s;
+
+    // calculate gain_out with exponent
+    s = energy_new(sig_out, l_trm); // function result
+
+    if (s == 0)
+    {
+        st->past_gain = 0;
+        return 0;
+    }
+    exp = sub (norm_l (s), 1);
+    gain_out = pv_round (L_shl (s, exp));
+
+    // calculate gain_in with exponent
+    s = energy_new(sig_in, l_trm); // function result
+
+    if (s == 0)
+    {
+        g0 = 0;
+    }
+    else
+    {
+        i = norm_l (s);
+        gain_in = pv_round (L_shl (s, i));
+        exp = sub (exp, i);
+
+         *---------------------------------------------------*
+         *  g0 = (1-agc_fac) * sqrt(gain_in/gain_out);       *
+         *---------------------------------------------------*
+
+        s = L_deposit_l (div_s (gain_out, gain_in));
+        s = L_shl (s, 7);       // s = gain_out / gain_in
+        s = L_shr (s, exp);     // add exponent
+
+        s = Inv_sqrt (s); // function result
+        i = pv_round (L_shl (s, 9));
+
+        // g0 = i * (1-agc_fac)
+        g0 = mult (i, sub (32767, agc_fac));
+    }
+
+    // compute gain[n] = agc_fac * gain[n-1]
+                        + (1-agc_fac) * sqrt(gain_in/gain_out)
+    // sig_out[n] = gain[n] * sig_out[n]
+
+    gain = st->past_gain;
+
+    for (i = 0; i < l_trm; i++)
+    {
+        gain = mult (gain, agc_fac);
+        gain = add (gain, g0);
+        sig_out[i] = extract_h (L_shl (L_mult (sig_out[i], gain), 3));
+    }
+
+    st->past_gain = gain;
+
+    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 agc(
+    agcState *st,      /* i/o : agc state                        */
+    Word16 *sig_in,    /* i   : postfilter input signal  (l_trm) */
+    Word16 *sig_out,   /* i/o : postfilter output signal (l_trm) */
+    Word16 agc_fac,    /* i   : AGC factor                       */
+    Word16 l_trm,      /* i   : subframe size                    */
+    Flag *pOverflow    /* i   : overflow Flag                    */
+
+)
+
+{
+    Word16  i;
+    Word16  exp;
+    Word16  gain_in;
+    Word16  gain_out;
+    Word16  g0;
+    Word16  gain;
+    Word32  s;
+    Word32  L_temp;
+    Word16  temp;
+
+    Word16 *p_sig_out;
+
+    /* calculate gain_out with exponent */
+    s = energy_new(sig_out, l_trm, pOverflow);  /* function result */
+
+    if (s == 0)
+    {
+        st->past_gain = 0;
+        return;
+    }
+    exp = norm_l(s) - 1;
+
+    L_temp = L_shl(s, exp, pOverflow);
+    gain_out = pv_round(L_temp, pOverflow);
+
+    /* calculate gain_in with exponent */
+    s = energy_new(sig_in, l_trm, pOverflow);    /* function result */
+
+    if (s == 0)
+    {
+        g0 = 0;
+    }
+    else
+    {
+        i = norm_l(s);
+
+        /* L_temp = L_shl(s, i, pOverflow); */
+        L_temp = s << i;
+
+        gain_in = pv_round(L_temp, pOverflow);
+
+        exp -= i;
+
+        /*---------------------------------------------------*
+         *  g0 = (1-agc_fac) * sqrt(gain_in/gain_out);       *
+         *---------------------------------------------------*/
+
+        /* s = gain_out / gain_in */
+        temp = div_s(gain_out, gain_in);
+
+        /* s = L_deposit_l (temp); */
+        s = (Word32) temp;
+        s = s << 7;
+        s = L_shr(s, exp, pOverflow);      /* add exponent */
+
+        s = Inv_sqrt(s, pOverflow);    /* function result */
+        L_temp = s << 9;
+
+        i = (Word16)((L_temp + (Word32) 0x00008000L) >> 16);
+
+        /* g0 = i * (1-agc_fac) */
+        temp = 32767 - agc_fac;
+
+        g0 = (Word16)(((Word32) i * temp) >> 15);
+
+    }
+
+    /* compute gain[n] = agc_fac * gain[n-1]
+                        + (1-agc_fac) * sqrt(gain_in/gain_out) */
+    /* sig_out[n] = gain[n] * sig_out[n]                        */
+
+    gain = st->past_gain;
+    p_sig_out = sig_out;
+
+    for (i = 0; i < l_trm; i++)
+    {
+        /* gain = mult (gain, agc_fac, pOverflow); */
+        gain = (Word16)(((Word32) gain * agc_fac) >> 15);
+
+        /* gain = add (gain, g0, pOverflow); */
+        gain += g0;
+
+        /* L_temp = L_mult (sig_out[i], gain, pOverflow); */
+        L_temp = ((Word32)(*(p_sig_out)) * gain) << 1;
+
+        *(p_sig_out++) = (Word16)(L_temp >> 13);
+    }
+
+    st->past_gain = gain;
+
+    return;
+}
+
+/*--------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: agc2
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sig_in = pointer to a buffer containing the postfilter input signal
+    sig_out = pointer to a buffer containing the postfilter output signal
+    l_trm = subframe size
+    pOverflow = pointer to overflow flag
+
+ Outputs:
+    sig_out points to a buffer containing the new scaled output signal.
+    pOverflow -> 1 if the agc computation saturates
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Scales the excitation on a subframe basis.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void agc2 (
+ Word16 *sig_in,        // i   : postfilter input signal
+ Word16 *sig_out,       // i/o : postfilter output signal
+ Word16 l_trm           // i   : subframe size
+)
+{
+    Word16 i, exp;
+    Word16 gain_in, gain_out, g0;
+    Word32 s;
+
+    // calculate gain_out with exponent
+    s = energy_new(sig_out, l_trm); // function result
+
+    if (s == 0)
+    {
+        return;
+    }
+    exp = sub (norm_l (s), 1);
+    gain_out = pv_round (L_shl (s, exp));
+
+    // calculate gain_in with exponent
+    s = energy_new(sig_in, l_trm); // function result
+
+    if (s == 0)
+    {
+        g0 = 0;
+    }
+    else
+    {
+        i = norm_l (s);
+        gain_in = pv_round (L_shl (s, i));
+        exp = sub (exp, i);
+
+         *---------------------------------------------------*
+         *  g0 = sqrt(gain_in/gain_out);                     *
+         *---------------------------------------------------*
+
+        s = L_deposit_l (div_s (gain_out, gain_in));
+        s = L_shl (s, 7);       // s = gain_out / gain_in
+        s = L_shr (s, exp);     // add exponent
+
+        s = Inv_sqrt (s); // function result
+        g0 = pv_round (L_shl (s, 9));
+    }
+
+    // sig_out(n) = gain(n) sig_out(n)
+
+    for (i = 0; i < l_trm; i++)
+    {
+        sig_out[i] = extract_h (L_shl (L_mult (sig_out[i], g0), 3));
+    }
+
+    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 agc2(
+    Word16 *sig_in,        /* i   : postfilter input signal  */
+    Word16 *sig_out,       /* i/o : postfilter output signal */
+    Word16 l_trm,          /* i   : subframe size            */
+    Flag   *pOverflow      /* i   : overflow flag            */
+)
+
+{
+    Word16  i;
+    Word16  exp;
+    Word16  gain_in;
+    Word16  gain_out;
+    Word16  g0;
+    Word32  s;
+    Word32  L_temp;
+    Word16  temp;
+
+    /* calculate gain_out with exponent */
+    s = energy_new(sig_out, l_trm, pOverflow); /* function result */
+
+    if (s == 0)
+    {
+        return;
+    }
+    exp = norm_l(s) - 1;
+    L_temp = L_shl(s, exp, pOverflow);
+    gain_out = pv_round(L_temp, pOverflow);
+
+    /* calculate gain_in with exponent */
+    s = energy_new(sig_in, l_trm, pOverflow); /* function result */
+
+    if (s == 0)
+    {
+        g0 = 0;
+    }
+    else
+    {
+        i = norm_l(s);
+        L_temp = L_shl(s, i, pOverflow);
+        gain_in = pv_round(L_temp, pOverflow);
+        exp -= i;
+
+        /*---------------------------------------------------*
+         *  g0 = sqrt(gain_in/gain_out);                     *
+         *---------------------------------------------------*/
+
+        /* s = gain_out / gain_in */
+        temp = div_s(gain_out, gain_in);
+
+        /* s = L_deposit_l (temp); */
+        s = (Word32)temp;
+
+        if (s > (Word32) 0x00FFFFFFL)
+        {
+            s = MAX_32;
+        }
+        else if (s < (Word32) 0xFF000000L)
+        {
+            s = MIN_32;
+        }
+        else
+        {
+            s = s << 7;
+        }
+        s = L_shr(s, exp, pOverflow);      /* add exponent */
+
+        s = Inv_sqrt(s, pOverflow);    /* function result */
+
+        if (s > (Word32) 0x003FFFFFL)
+        {
+            L_temp = MAX_32;
+        }
+        else if (s < (Word32) 0xFFC00000L)
+        {
+            L_temp = MIN_32;
+        }
+        else
+        {
+            L_temp = s << 9;
+        }
+        g0 = pv_round(L_temp, pOverflow);
+    }
+
+    /* sig_out(n) = gain(n) sig_out(n) */
+
+    for (i = l_trm - 1; i >= 0; i--)
+    {
+        L_temp = L_mult(sig_out[i], g0, pOverflow);
+        if (L_temp > (Word32) 0x0FFFFFFFL)
+        {
+            sig_out[i] = MAX_16;
+        }
+        else if (L_temp < (Word32) 0xF0000000L)
+        {
+            sig_out[i] = MIN_16;
+        }
+        else
+        {
+            sig_out[i] = (Word16)(L_temp >> 13);
+        }
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/agc.h b/media/libstagefright/codecs/amrnb/dec/src/agc.h
new file mode 100644
index 0000000..b6e3249
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/agc.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/src/include/agc.h
+
+     Date: 12/07/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed unneeded sections of the standard template.
+              Updated function prototype for agc() and agc2() to match new
+              interface
+
+ Description: Changed paramter name from "overflow" to "pOverflow" for
+              functions agc() and agc2()
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : agc.h
+      Purpose          : Scales the postfilter output on a subframe basis
+                       : by automatic control of the subframe gain.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _AGC_H_
+#define _AGC_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
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 past_gain;
+    } agcState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function    : agc_reset
+    ;  Purpose     : Reset of agc (i.e. set state memory to 1.0)
+    ;  Returns     : 0 on success
+    ;
+    ----------------------------------------------------------------------------*/
+    Word16 agc_reset(agcState *st);
+
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function    : agc
+    ;  Purpose     : Scales the postfilter output on a subframe basis
+    ;  Description : sig_out[n] = sig_out[n] * gain[n];
+    ;                where gain[n] is the gain at the nth sample given by
+    ;                gain[n] = agc_fac * gain[n-1] + (1 - agc_fac) g_in/g_out
+    ;                g_in/g_out is the square root of the ratio of energy at
+    ;                the input and output of the postfilter.
+    ;
+    ----------------------------------------------------------------------------*/
+    void agc(
+        agcState *st,      /* i/o : agc state                         */
+        Word16 *sig_in,    /* i   : postfilter input signal, (l_trm)  */
+        Word16 *sig_out,   /* i/o : postfilter output signal, (l_trm) */
+        Word16 agc_fac,    /* i   : AGC factor                        */
+        Word16 l_trm,      /* i   : subframe size                     */
+        Flag *pOverflow    /* i   : overflow flag                     */
+    );
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:  agc2
+    ;  Purpose:   Scales the excitation on a subframe basis
+    ;
+    ----------------------------------------------------------------------------*/
+    void agc2(
+        Word16 *sig_in,    /* i   : postfilter input signal   */
+        Word16 *sig_out,   /* i/o : postfilter output signal  */
+        Word16 l_trm,      /* i   : subframe size             */
+        Flag *pOverflow    /* i   : overflow flag             */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _AGC_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/amrdecode.cpp b/media/libstagefright/codecs/amrnb/dec/src/amrdecode.cpp
new file mode 100644
index 0000000..873d7af
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/amrdecode.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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+ Pathname: ./audio/gsm-amr/c/src/amrdecode.c
+
+     Date: 05/23/2001
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:       AMRDecode now doesn't call getbits() or put_header_in().
+                    It also now obtains a new bit_offset value from a constant
+                    rather than from the returned value of getbits().
+
+ Description:       AMRDecode now returns byte_offset rather than bit_offset,
+                    so the program can access the next frame that is byte
+                    aligned rather than packed without padding.
+
+ Description:       The structure types Speech_Decode_FrameState are now
+                    passed into amrdecode( ) using void pointers, so that
+                    higher level functions don't need to know anything about
+                    this structure type.
+
+ Description: Changed input argument list. Added code to handle incoming DTX
+              frames, and added call to wmf_to_ets function prior to calling
+              GSMFrameDecode.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Changed all references to bit_offset to byte_offset.
+
+ Description: Added input_type to the function interface and modified code
+              to check type of conversion that needs to be made.
+
+ Description: Modified pseudo-code to include IF2 and ETS input formats.
+              Removed byte_offset from input list. Renamed speech_bits
+              to speech_bits_ptr.
+
+ Description: Added dec_input_format_tab.h in Include section. Modified
+              pseudo-code to use correct table names. Renamed input_type to
+              input_format and speech_bits to speech_bits_ptr.
+
+ Description: Removed *prev_mode_ptr in the input argument list.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Removed dec_input_format_tab.h from Include section.
+              2. Changed type definition of raw_pcm_buffer in the I/O
+                 definition section.
+
+ Description: Renamed WmfBytesPerFrame to WmfDecBytesPerFrame, and
+              If2BytesPerFrame to If2DecBytesPerFrame.
+
+ Description: Modified code so that the ETS testvectors could be fed directly
+              to this function.
+
+ Description: Changed '&' to '&&' in the setting of rx_type and mode for
+              AMR_SID < frame_type < NO_DATA case.
+
+ Description: Added code comments and made some code optimizations per Phase
+              2/3 review comments.
+
+ Description: Added conditional compile around the call to GSMFrameDecode to
+              allow amrdecode.c to be used in the ETS reference console.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "amrdecode.h"
+#include "cnst.h"
+#include "typedef.h"
+#include "frame.h"
+#include "sp_dec.h"
+#include "wmf_to_ets.h"
+#include "if2_to_ets.h"
+#include "frame_type_3gpp.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: AMRDecode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state_data      = pointer to a structure (type void)
+
+    frame_type      = 3GPP frame type (enum Frame_Type_3GPP)
+
+    speech_bits_ptr = pointer to the beginning of the raw encoded speech bits
+                      for the current frame to be decoded (unsigned char)
+
+    raw_pcm_buffer  = pointer to the output pcm outputs array (Word16)
+
+    input_format    = input format used; valid values are AMR_WMF, AMR_IF2,
+                      and AMR_ETS (Word16)
+
+ Outputs:
+    raw_pcm_buffer contains the newly decoded linear PCM speech samples
+    state_data->prev_mode contains the new mode
+
+ Returns:
+    byte_offset     = address offset of the next frame to be processed or
+                      error condition flag (-1) (int)
+
+ Global Variables Used:
+    WmfDecBytesPerFrame = table containing the number of core AMR data bytes
+                          used by each codec mode for WMF input format (const
+                          int)
+
+    If2DecBytesPerFrame = table containing the number of core AMR data bytes
+                          used by each codec mode for IF2 input format (const
+                          int)
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is the top level entry function to the GSM AMR Decoder library.
+
+ First, it checks the input format type (input_format) to determine the type
+ of de-formattting that needs to be done. If input_format is AMR_WMF, the input
+ data is in WMF (aka, non-IF2) format and the function wmf_to_ets will be
+ called to convert to the ETS format (1 bit/word, where 1 word = 16 bits),
+ and byte_offset will be updated according to the contents of WmfDecBytesPerFrame
+ table.
+
+ If input_format is AMR_IF2, the input data is in IF2 format [1] and the
+ function if2_to_ets will be called to convert to the ETS format, and
+ byte_offset will be updated according to the contents of If2DecBytesPerFrame
+ table.
+
+ The codec mode and receive frame type is initialized based on the incoming
+ frame_type.
+
+ If input_format is AMR_ETS, the input data is in the ETS format. The receive
+ frame type is set to the value in the first location of the buffer pointed to
+ by speech_bits_ptr. Then, the encoded speech parameters in the buffer pointed
+ to by speech_bits is copied to dec_ets_input_bfr and the type will be changed
+ from unsigned char to Word16. Lastly, if the receive frame type is not
+ RX_NO_DATA, the mode is obtained from the buffer pointed to by
+ speech_bits_ptr, offset by MAX_SERIAL_SIZE+1, otherwise, the mode is set to
+ the previous mode (found the in state_data->prev_mode).
+
+ If input_format is an unsupported format, byte_offset will be set to -1, to
+ indicate an error condition has occurred, and the function will exit.
+
+ If there are no errors, GSMFrameDecode is called to decode a 20 ms frame. It
+ puts the decoded linear PCM samples in the buffer pointed to by
+ raw_pcm_buffer. Then, the prev_mode field of the structure pointed to by
+ state_data is updated to the current mode.
+
+ This function returns the new byte_offset value to indicate the address
+ offset of the next speech frame to be decoded.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] "AMR Speech Codec Frame Structure", 3GPP TS 26.101 version 4.1.0
+     Release 4, June 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: AMRSID_RXTYPE_BIT_OFFSET = 35
+       AMRSID_RXMODE_BIT_OFFSET = 36
+       NUM_AMRSID_RXMODE_BITS = 3
+
+
+ // Set up Decoder state structure pointer
+ Speech_Decode_FrameState *decoder_state
+            = (Speech_Decode_FrameState *) state_data
+
+ // Determine type of de-formatting
+
+ // Decode WMF or IF2 frames
+ IF ((input_format == AMR_RX_WMF) | (input_format == AMR_RX_IF2))
+ THEN
+     IF (input_format == AMR_RX_WMF)
+     THEN
+         // Convert incoming packetized raw WMF data to ETS format
+         CALL wmf_to_ets(frame_type = frame_type
+                         input_ptr = speech_bits_ptr
+                         output_ptr = &dec_ets_input_bfr)
+           MODIFYING(nothing)
+           RETURNING(nothing)
+
+         // Address offset of the start of next frame
+         byte_offset = WmfDecBytesPerFrame[frame_type]
+
+     ELSEIF (input_format == AMR_RX_IF2)
+     THEN
+         // Convert incoming packetized raw IF2 data to ETS format
+         CALL if2_to_ets(frame_type = frame_type
+                         input_ptr = speech_bits_ptr
+                         output_ptr = &dec_ets_input_bfr)
+           MODIFYING(nothing)
+           RETURNING(nothing)
+
+         // Address offset of the start of next frame
+         byte_offset = If2DecBytesPerFrame[frame_type]
+
+     ENDIF
+
+       // Determine AMR codec mode and AMR RX frame type
+     IF (frame_type <= AMR_122)
+     THEN
+         mode = (enum Mode) frame_type;
+         rx_type = RX_SPEECH_GOOD;
+
+     ELSEIF (frame_type == AMR_SID)
+     THEN
+         // Clear mode store prior to reading mode info from input buffer
+         mode = 0
+
+         FOR i = 0 TO NUM_AMRSID_RXMODE_BITS-1
+
+             mode |= (dec_ets_input_bfr[AMRSID_RXMODE_BIT_OFFSET+i] << i)
+
+         ENDFOR
+
+         IF (dec_ets_input_bfr[AMRSID_RXTYPE_BIT_OFFSET] == 0)
+         THEN
+             rx_type = RX_SID_FIRST
+
+         ELSE
+             rx_type = RX_SID_UPDATE
+
+         ENDIF
+
+     ELSEIF ((frame_type > AMR_SID) && (frame_type < NO_DATA))
+     THEN
+         // Use previous mode
+         mode = decoder_state->prev_mode
+
+         // Unsupported SID frames
+         rx_type = RX_SPEECH_BAD;
+
+     ELSE
+         // Use previous mode
+         mode = decoder_state->prev_mode
+
+         // No data received
+         rx_type = RX_NO_DATA;
+
+     ENDIF
+
+ // Decode ETS frames
+ ELSEIF (input_format == AMR_RX_ETS)
+ THEN
+     // Change type of pointer to incoming raw ETS data
+     ets_word_ptr = (Word16 *) speech_bits_ptr
+
+     // Get RX frame type
+     rx_type = (enum RXFrameType) *ets_word_ptr
+     ets_word_ptr = ets_word_ptr + 1
+
+     // Copy incoming raw ETS data to dec_ets_input_bfr
+     FOR i = 0 TO MAX_SERIAL_SIZE-1
+
+         dec_ets_input_bfr[i] = *ets_word_ptr
+         ets_word_ptr = ets_word_ptr + 1
+
+     ENDFOR
+
+     // Get codec mode
+     IF (rx_type != RX_NO_DATA)
+     THEN
+         mode = (enum Mode) *ets_word_ptr
+
+     ELSE
+         //Use previous mode if no received data
+         mode = decoder_state->prev_mode
+
+     ENDIF
+
+     // Set up byte_offset
+     byte_offset = 2*(MAX_SERIAL_SIZE+2)
+
+ ELSE
+     // Invalid format, return error code
+     byte_offset = -1
+
+ ENDIF
+
+ // Proceed with decoding frame, if there are no errors
+ IF (byte_offset != -1)
+ THEN
+     // Decode a 20 ms frame
+     CALL GSMFrameDecode( st = decoder_state
+                          mode = mode
+                          serial = dec_ets_input_bfr,
+                          frame_type = rx_type,
+                          synth = (Word16 *)raw_pcm_buffer);
+       MODIFYING (nothing)
+       RETURNING (Nothing)
+
+     // Save mode for next frame
+     decoder_state->prev_mode = mode
+
+ ENDIF
+
+ RETURN (byte_offset)
+
+------------------------------------------------------------------------------
+ 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 AMRDecode(
+    void                      *state_data,
+    enum Frame_Type_3GPP      frame_type,
+    UWord8                    *speech_bits_ptr,
+    Word16                    *raw_pcm_buffer,
+    bitstream_format          input_format
+)
+{
+    Word16 *ets_word_ptr;
+    enum Mode mode = (enum Mode)MR475;
+    int modeStore;
+    int tempInt;
+    enum RXFrameType rx_type = RX_NO_DATA;
+    Word16 dec_ets_input_bfr[MAX_SERIAL_SIZE];
+    Word16 i;
+    Word16 byte_offset = -1;
+
+    /* Type cast state_data to Speech_Decode_FrameState rather than passing
+     * that structure type to this function so the structure make up can't
+     * be viewed from higher level functions than this.
+     */
+    Speech_Decode_FrameState *decoder_state
+    = (Speech_Decode_FrameState *) state_data;
+
+    /* Determine type of de-formatting */
+    /* WMF or IF2 frames */
+    if ((input_format == MIME_IETF) | (input_format == IF2))
+    {
+        if (input_format == MIME_IETF)
+        {
+            /* Convert incoming packetized raw WMF data to ETS format */
+            wmf_to_ets(frame_type, speech_bits_ptr, dec_ets_input_bfr);
+
+            /* Address offset of the start of next frame */
+            byte_offset = WmfDecBytesPerFrame[frame_type];
+        }
+        else   /* else has to be input_format  IF2 */
+        {
+            /* Convert incoming packetized raw IF2 data to ETS format */
+            if2_to_ets(frame_type, speech_bits_ptr, dec_ets_input_bfr);
+
+            /* Address offset of the start of next frame */
+            byte_offset = If2DecBytesPerFrame[frame_type];
+        }
+
+        /* At this point, input data is in ETS format     */
+        /* Determine AMR codec mode and AMR RX frame type */
+        if (frame_type <= AMR_122)
+        {
+            mode = (enum Mode) frame_type;
+            rx_type = RX_SPEECH_GOOD;
+        }
+        else if (frame_type == AMR_SID)
+        {
+            /* Clear mode store prior to reading mode info from input buffer */
+            modeStore = 0;
+
+            for (i = 0; i < NUM_AMRSID_RXMODE_BITS; i++)
+            {
+                tempInt = dec_ets_input_bfr[AMRSID_RXMODE_BIT_OFFSET+i] << i;
+                modeStore |= tempInt;
+            }
+            mode = (enum Mode) modeStore;
+
+            /* Get RX frame type */
+            if (dec_ets_input_bfr[AMRSID_RXTYPE_BIT_OFFSET] == 0)
+            {
+                rx_type = RX_SID_FIRST;
+            }
+            else
+            {
+                rx_type = RX_SID_UPDATE;
+            }
+        }
+        else if (frame_type < AMR_NO_DATA)
+        {
+            /* Invalid frame_type, return error code */
+            byte_offset = -1;   /*  !!! */
+        }
+        else
+        {
+            mode = decoder_state->prev_mode;
+
+            /*
+             * RX_NO_DATA, generate exponential decay from latest valid frame for the first 6 frames
+             * after that, create silent frames
+             */
+            rx_type = RX_NO_DATA;
+
+        }
+
+    }
+
+    /* ETS frames */
+    else if (input_format == ETS)
+    {
+        /* Change type of pointer to incoming raw ETS data */
+        ets_word_ptr = (Word16 *) speech_bits_ptr;
+
+        /* Get RX frame type */
+        rx_type = (enum RXFrameType) * ets_word_ptr;
+        ets_word_ptr++;
+
+        /* Copy incoming raw ETS data to dec_ets_input_bfr */
+        for (i = 0; i < MAX_SERIAL_SIZE; i++)
+        {
+            dec_ets_input_bfr[i] = *ets_word_ptr;
+            ets_word_ptr++;
+        }
+
+        /* Get codec mode */
+        if (rx_type != RX_NO_DATA)
+        {
+            /* Get mode from input bitstream */
+            mode = (enum Mode) * ets_word_ptr;
+        }
+        else
+        {
+            /* Use previous mode if no received data */
+            mode = decoder_state->prev_mode;
+        }
+
+        /* Set up byte_offset */
+        byte_offset = 2 * (MAX_SERIAL_SIZE + 2);
+    }
+    else
+    {
+        /* Invalid input format, return error code */
+        byte_offset = -1;
+    }
+
+    /* Proceed with decoding frame, if there are no errors */
+    if (byte_offset != -1)
+    {
+        /* Decode a 20 ms frame */
+
+#ifndef CONSOLE_DECODER_REF
+        /* Use PV version of sp_dec.c */
+        GSMFrameDecode(decoder_state, mode, dec_ets_input_bfr, rx_type,
+                       raw_pcm_buffer);
+
+#else
+        /* Use ETS version of sp_dec.c */
+        Speech_Decode_Frame(decoder_state, mode, dec_ets_input_bfr, rx_type,
+                            raw_pcm_buffer);
+
+#endif
+
+        /* Save mode for next frame */
+        decoder_state->prev_mode = mode;
+    }
+
+    return (byte_offset);
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/amrdecode.h b/media/libstagefright/codecs/amrnb/dec/src/amrdecode.h
new file mode 100644
index 0000000..db951b9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/amrdecode.h
@@ -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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./gsm-amr/c/include/amrdecode.h
+
+     Date: 05/23/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Added BytesUsed table so that the code can allow for padding
+              at the end of each frame.
+
+ Description: Removed function prototypes for getbits, putbits,
+              put_frame_header_in, and get_frame_header_off. Removed
+              basicop_malloc.h and replaced it with typedef.h in the include
+              section. Fixed table entries for various SID modes. Removed
+              #defines because they are not used by AMRDecode function.
+              Removed tables not used by AMRDecode function.
+
+ Description: The data type Speech_Decode_FrameState is now being passed into
+              this function as a void pointer rather than a structure of type
+              Speech_Decode_FrameState.
+
+ Description: The variable decoder_state was renamed to state_data.
+
+ Description: Updated function prototype and header template.
+
+ Description: Added mode.h and frame_type_3gpp.h to include section, and
+              removed sp_dec.h.
+
+ Description: Removed definition of Changed BytesThisFrame[] table. Added
+              extern declaration for BytesThisFrame[] table.
+
+ Description: Added #define for WMF and IF2. Updated function prototype.
+
+ Description: Moved input format #defines and BytesThisFrame table to
+              dec_input_format_tab.h and dec_input_format_tab.c, respectively.
+              Updated function prototype.
+
+ Description: Updated function prototype of AMRDecode due to the removal of
+              *prev_mode_ptr. Added extern of If2BytesPerFrame
+
+ Description: Added #defines for WMF, IF2, and ETS input formats.
+
+ Description: Changed WmfBytesPerFrame to WmfDecBytesPerFrame, and
+              If2BytesPerFrame to If2DecBytesPerFrame.
+
+ Description: Renamed #defines for input format types to make it unique to the
+              decoder.
+
+ 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 norm_s function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ARMDECODE_H
+#define ARMDECODE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "typedef.h"
+#include    "mode.h"
+#include    "frame_type_3gpp.h"
+#include    "pvamrnbdecoder_api.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define NUM_AMRSID_RXMODE_BITS   3
+#define AMRSID_RXMODE_BIT_OFFSET 36
+#define AMRSID_RXTYPE_BIT_OFFSET 35
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern const Word16 WmfDecBytesPerFrame[];
+    extern const Word16 If2DecBytesPerFrame[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 AMRDecode(
+        void *state_data,
+        enum Frame_Type_3GPP  frame_type,
+        UWord8 *speech_bits_ptr,
+        Word16 *raw_pcm_buffer,
+        bitstream_format input_format
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _AMRDECODE_H_ */
diff --git a/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.cpp b/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.cpp
new file mode 100644
index 0000000..e62e483
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.cpp
@@ -0,0 +1,516 @@
+/* ------------------------------------------------------------------
+ * 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/b_cn_cod.c
+ Functions: pseudonoise
+            build_CN_code
+            build_CN_param
+
+     Date: 09/28/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Cleaned up code. Passing in a pointer to
+              overflow flag for build_CN_code() and build_CN_param() functions.
+              Removed unnecessary header files.
+ Description: Make chnages per formal review. Fix error introduced during
+              optimization in pseudonoise().
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This module contains functions for comfort noise(CN) generation.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "b_cn_cod.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.]
+----------------------------------------------------------------------------*/
+#define  NB_PULSE 10        /* number of random pulses in DTX operation   */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; [List function prototypes here]
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; [Variable declaration - defined here and used outside this module]
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: pseudonoise
+------------------------------------------------------------------------------
+ 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
+
+ Generate a random integer value to use in comfort noise generation. The
+ algorithm uses polynomial x^31 + x^3 + 1. Length of the PN sequence
+ is 2^31 - 1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ b_cn_cod.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 pseudonoise (
+    Word32 *shift_reg, // i/o : Old CN generator shift register state
+    Word16 no_bits     // i   : Number of bits
+)
+{
+   Word16 noise_bits, Sn, i;
+
+   noise_bits = 0;
+   for (i = 0; i < no_bits; i++)
+   {
+      // State n == 31
+      if ((*shift_reg & 0x00000001L) != 0)
+      {
+         Sn = 1;
+      }
+      else
+      {
+         Sn = 0;
+      }
+
+      // State n == 3
+      if ((*shift_reg & 0x10000000L) != 0)
+      {
+         Sn = Sn ^ 1;
+      }
+      else
+      {
+         Sn = Sn ^ 0;
+      }
+
+      noise_bits = shl (noise_bits, 1);
+      noise_bits = noise_bits | (extract_l (*shift_reg) & 1);
+
+      *shift_reg = L_shr (*shift_reg, 1);
+      if (Sn & 1)
+      {
+         *shift_reg = *shift_reg | 0x40000000L;
+      }
+   }
+   return noise_bits;
+}
+
+------------------------------------------------------------------------------
+ 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 pseudonoise(
+    Word32 *pShift_reg,     /* i/o : Old CN generator shift register state */
+    Word16 no_bits          /* i   : Number of bits                        */
+)
+{
+    Word16 noise_bits;
+    Word16 Sn;
+    Word16 i;
+    Word16 temp;
+
+    noise_bits = 0;
+
+    for (i = 0; i < no_bits; i++)
+    {
+        /* State n == 31 */
+        if ((*pShift_reg & 0x00000001L) != 0)
+        {
+            Sn = 1;
+        }
+        else
+        {
+            Sn = 0;
+        }
+
+        /* State n == 3 */
+        if ((*pShift_reg & 0x10000000L) != 0)
+        {
+            Sn ^= 1;
+        }
+        else
+        {
+            Sn ^= 0;
+        }
+
+        noise_bits <<= 1;
+
+        temp = (Word16)((*pShift_reg) & 1);
+        noise_bits |= temp;
+
+        *pShift_reg >>= 1;
+        if (Sn & 1)
+        {
+            *pShift_reg |= 0x40000000L;
+        }
+    }
+    return noise_bits;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: build_CN_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pSeed = pointer to the Old CN generator shift register state (Word32)
+    cod[] = array to hold the generated CN fixed code vector (Word16)
+    pOverflow = pointer to overflow flag (Flag)
+
+ Outputs:
+    cod[] = generated CN fixed code vector (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 computes the comfort noise fixed codebook excitation. The gains
+of the pulses are always +/-1.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ b_cn_cod.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void build_CN_code (
+    Word32 *seed,         // i/o : Old CN generator shift register state
+    Word16 cod[]          // o   : Generated CN fixed codebook vector
+)
+{
+   Word16 i, j, k;
+
+   for (i = 0; i < L_SUBFR; i++)
+   {
+      cod[i] = 0;
+   }
+
+// The reference ETSI code uses a global flag for Overflow. However in the
+// actual implementation a pointer to the overflow flag is passed into the
+// function so that it can be passed into the basic math functions L_mult()
+// and add()
+
+   for (k = 0; k < NB_PULSE; k++)
+   {
+      i = pseudonoise (seed, 2);      // generate pulse position
+      i = shr (extract_l (L_mult (i, 10)), 1);
+      i = add (i, k);
+
+      j = pseudonoise (seed, 1);      // generate sign
+
+      if (j > 0)
+      {
+         cod[i] = 4096;
+      }
+      else
+      {
+         cod[i] = -4096;
+      }
+   }
+
+   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 build_CN_code(
+    Word32 *pSeed,          /* i/o : Old CN generator shift register state  */
+    Word16 cod[],           /* o   : Generated CN fixed codebook vector     */
+    Flag   *pOverflow       /* i/o : Overflow flag                          */
+)
+{
+    Word16 i, j, k;
+    Word16 temp;
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        cod[i] = 0;
+    }
+
+    for (k = 0; k < NB_PULSE; k++)
+    {
+        i = pseudonoise(pSeed, 2);       /* generate pulse position */
+
+        temp = (Word16)(L_mult(i, 10, pOverflow));
+        i = temp >> 1;
+        i = add(i, k, pOverflow);
+
+        j = pseudonoise(pSeed, 1);       /* generate sign */
+
+        if (j > 0)
+        {
+            cod[i] = 4096;
+        }
+        else
+        {
+            cod[i] = -4096;
+        }
+    }
+
+    return;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: build_CN_param
+------------------------------------------------------------------------------
+ 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 randomizes the speech parameters, so that they do not produce
+tonal artifacts if used by ECU.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ b_cn_cod.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+void build_CN_param (
+    Word16 *seed,             // i/o : Old CN generator shift register state
+    const Word16 n_param,           // i  : number of params
+    const Word16 param_size_table[],// i : size of params
+    Word16 parm[]                   // o : CN Generated params
+    )
+{
+   Word16 i;
+   const Word16 *p;
+
+// The reference ETSI code uses a global flag for Overflow. However in the
+// actual implementation a pointer to the overflow flag is passed into the
+// function so that it can be passed into the basic math functions L_add()
+// and L_mult()
+
+   *seed = extract_l(L_add(L_shr(L_mult(*seed, 31821), 1), 13849L));
+
+   p = &window_200_40[*seed & 0x7F];
+   for(i=0; i< n_param;i++){
+     parm[i] = *p++ & ~(0xFFFF<<param_size_table[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]
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void build_CN_param(
+    Word16 *pSeed,          /* i/o : Old CN generator shift register state  */
+    const Word16 n_param,           /* i  : number of params                */
+    const Word16 param_size_table[],/* i : size of params                   */
+    Word16 parm[],                  /* o : CN Generated params              */
+    Flag  *pOverflow                /* i/o : Overflow Flag                  */
+)
+
+{
+    Word16 i;
+    const Word16 *pTemp;
+    Word32 L_temp;
+    Word16 temp;
+
+    L_temp = L_mult(*pSeed, 31821, pOverflow);
+    L_temp >>= 1;
+
+    *pSeed = (Word16)(L_add(L_temp, 13849L, pOverflow));
+
+    pTemp = &window_200_40[*pSeed & 0x7F];
+
+    for (i = 0; i < n_param; i++)
+    {
+        temp = ~(0xFFFF << param_size_table[i]);
+        parm[i] = *pTemp++ & temp;
+    }
+}
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.h b/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.h
new file mode 100644
index 0000000..743237c
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/b_cn_cod.h
@@ -0,0 +1,171 @@
+/* ------------------------------------------------------------------
+ * 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/add.h
+
+
+
+
+     Date: 08/11/2000
+
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description: Created separate header file for add function.
+
+ Description: Changed function prototype; pointer to  overflow flag is passed
+              in as a parameter.
+
+ Description: Updated copyright section.
+              Changed "overflow" to "pOverflow" in the function prototype.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the comfort noise(CN) generator functions
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef B_CN_COD_H
+#define B_CN_COD_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
+    ----------------------------------------------------------------------------*/
+    extern Word16 window_200_40[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+
+    ; FUNCTION NAME: pseudonoise
+    ;
+    ; PURPOSE: Generate a random integer value to use in comfort noise
+    ;          generation. The algorithm uses polynomial x^31 + x^3 + 1
+    ;          (length of PN sequence is 2^31 - 1).
+    ;
+    ----------------------------------------------------------------------------*/
+
+    Word16 pseudonoise(
+        Word32 *pShift_reg,     /* i/o : Old CN generator shift register state */
+        Word16 no_bits          /* i   : Number of bits                        */
+    );
+
+    /*----------------------------------------------------------------------------
+
+    ; FUNCTION NAME: build_CN_code
+    ;
+    ; PURPOSE: Compute the comfort noise fixed codebook excitation. The
+    ;          gains of the pulses are always +/-1.
+    ;
+    ----------------------------------------------------------------------------*/
+
+    void build_CN_code(
+        Word32 *pSeed,          /* i/o : Old CN generator shift register state  */
+        Word16 cod[],           /* o   : Generated CN fixed codebook vector     */
+        Flag   *pOverflow       /* i/o : Overflow flag                          */
+    );
+
+    /*----------------------------------------------------------------------------
+
+    ; FUNCTION NAME: build_CN_param
+    ;
+    ; PURPOSE: Randomize the speech parameters. So that they
+    ;          do not produce tonal artifacts if used by ECU.
+    ;
+    ----------------------------------------------------------------------------*/
+
+    void build_CN_param(
+        Word16 *pSeed,          /* i/o : Old CN generator shift register state  */
+        const Word16 n_param,               /* i  : number of params            */
+        const Word16 param_size_table[],    /* i : size of params               */
+        Word16 parm[],                  /* o : CN Generated params              */
+        Flag  *pOverflow                /* i/o : Overflow Flag                  */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _B_CN_COD_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/bgnscd.cpp b/media/libstagefright/codecs/amrnb/dec/src/bgnscd.cpp
new file mode 100644
index 0000000..e732007
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/bgnscd.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/bgnscd.c
+ Functions:
+           Bgn_scd_reset
+           Bgn_scd
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ Background noise source characteristic detector (SCD)
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include    "bgnscd.h"
+#include    "typedef.h"
+#include    "basic_op.h"
+#include    "cnst.h"
+#include    "copy.h"
+#include    "gmed_n.h"
+#include    "sqrt_l.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define TRUE  1
+#define FALSE 0
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Bgn_scd_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = points to memory of type Bgn_scdState.
+
+ Outputs:
+    The memory of type Bgn_scdState pointed to by state is set to all
+        zeros.
+
+ Returns:
+    Returns 0 if memory was successfully initialized,
+        otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Resets state memory.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ bgnscd.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Bgn_scd_reset (Bgn_scdState *state)
+{
+   if (state == (Bgn_scdState *) NULL){
+      fprintf(stderr, "Bgn_scd_reset: invalid parameter\n");
+      return -1;
+   }
+
+   // Static vectors to zero
+   Set_zero (state->frameEnergyHist, L_ENERGYHIST);
+
+   // Initialize hangover handling
+   state->bgHangover = 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  Bgn_scd_reset(Bgn_scdState *state)
+{
+    if (state == (Bgn_scdState *) NULL)
+    {
+        /* fprintf(stderr, "Bgn_scd_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    /* Static vectors to zero */
+    memset(state->frameEnergyHist, 0, L_ENERGYHIST*sizeof(Word16));
+
+    /* Initialize hangover handling */
+    state->bgHangover = 0;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Bgn_scd
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to state variables of type Bgn_scdState
+    ltpGainHist[] = LTP gain history (Word16)
+    speech[] = synthesis speech frame (Word16)
+    voicedHangover = pointer to # of frames after last voiced frame (Word16)
+    pOverflow      = pointer to overflow indicator (Flag)
+
+ Outputs:
+    st = function updates the state variables of type Bgn_scdState
+        pointed to by st.
+    voicedHangover = function updates the # of frames after last voiced
+        frame pointed to by voicedHangover.
+    pOverflow = 1 if the basic math function L_add() results in saturation.
+                  else pOverflow is zero.
+
+ Returns:
+    inbgNoise = flag if background noise is present (Word16)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Characterize synthesis speech and detect background noise.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ bgnscd.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Bgn_scd (Bgn_scdState *st,      // i : State variables for bgn SCD
+                Word16 ltpGainHist[],  // i : LTP gain history
+                Word16 speech[],       // o : synthesis speech frame
+                Word16 *voicedHangover // o : # of frames after last
+                                              voiced frame
+                )
+{
+   Word16 i;
+   Word16 prevVoiced, inbgNoise;
+   Word16 temp;
+   Word16 ltpLimit, frameEnergyMin;
+   Word16 currEnergy, noiseFloor, maxEnergy, maxEnergyLastPart;
+   Word32 s;
+
+   // Update the inBackgroundNoise flag (valid for use in next frame if BFI)
+   // it now works as a energy detector floating on top
+   // not as good as a VAD.
+
+   currEnergy = 0;
+   s = (Word32) 0;
+
+   for (i = 0; i < L_FRAME; i++)
+   {
+       s = L_mac (s, speech[i], speech[i]);
+   }
+
+   s = L_shl(s, 2);
+
+   currEnergy = extract_h (s);
+
+   frameEnergyMin = 32767;
+
+   for (i = 0; i < L_ENERGYHIST; i++)
+   {
+      if (sub(st->frameEnergyHist[i], frameEnergyMin) < 0)
+         frameEnergyMin = st->frameEnergyHist[i];
+   }
+
+   noiseFloor = shl (frameEnergyMin, 4); // Frame Energy Margin of 16
+
+   maxEnergy = st->frameEnergyHist[0];
+   for (i = 1; i < L_ENERGYHIST-4; i++)
+   {
+      if ( sub (maxEnergy, st->frameEnergyHist[i]) < 0)
+      {
+         maxEnergy = st->frameEnergyHist[i];
+      }
+   }
+
+   maxEnergyLastPart = st->frameEnergyHist[2*L_ENERGYHIST/3];
+   for (i = 2*L_ENERGYHIST/3+1; i < L_ENERGYHIST; i++)
+   {
+      if ( sub (maxEnergyLastPart, st->frameEnergyHist[i] ) < 0)
+      {
+         maxEnergyLastPart = st->frameEnergyHist[i];
+      }
+   }
+
+   inbgNoise = 0;        // false
+
+   // Do not consider silence as noise
+   // Do not consider continuous high volume as noise
+   // Or if the current noise level is very low
+   // Mark as noise if under current noise limit
+   // OR if the maximum energy is below the upper limit
+
+   if ( (sub(maxEnergy, LOWERNOISELIMIT) > 0) &&
+        (sub(currEnergy, FRAMEENERGYLIMIT) < 0) &&
+        (sub(currEnergy, LOWERNOISELIMIT) > 0) &&
+        ( (sub(currEnergy, noiseFloor) < 0) ||
+          (sub(maxEnergyLastPart, UPPERNOISELIMIT) < 0)))
+   {
+      if (sub(add(st->bgHangover, 1), 30) > 0)
+      {
+         st->bgHangover = 30;
+      } else
+      {
+         st->bgHangover = add(st->bgHangover, 1);
+      }
+   }
+   else
+   {
+      st->bgHangover = 0;
+   }
+
+   // make final decision about frame state , act somewhat cautiosly
+   if (sub(st->bgHangover,1) > 0)
+      inbgNoise = 1;       // true
+
+   for (i = 0; i < L_ENERGYHIST-1; i++)
+   {
+      st->frameEnergyHist[i] = st->frameEnergyHist[i+1];
+   }
+   st->frameEnergyHist[L_ENERGYHIST-1] = currEnergy;
+
+   // prepare for voicing decision; tighten the threshold after some
+      time in noise
+   ltpLimit = 13926;             // 0.85  Q14
+   if (sub(st->bgHangover, 8) > 0)
+   {
+      ltpLimit = 15565;          // 0.95  Q14
+   }
+   if (sub(st->bgHangover, 15) > 0)
+   {
+      ltpLimit = 16383;          // 1.00  Q14
+   }
+
+   // weak sort of voicing indication.
+   prevVoiced = 0;        // false
+
+   if (sub(gmed_n(&ltpGainHist[4], 5), ltpLimit) > 0)
+   {
+      prevVoiced = 1;     // true
+   }
+   if (sub(st->bgHangover, 20) > 0) {
+      if (sub(gmed_n(ltpGainHist, 9), ltpLimit) > 0)
+      {
+         prevVoiced = 1;  // true
+      }
+      else
+      {
+         prevVoiced = 0;  // false
+      }
+   }
+
+   if (prevVoiced)
+   {
+      *voicedHangover = 0;
+   }
+   else
+   {
+      temp = add(*voicedHangover, 1);
+      if (sub(temp, 10) > 0)
+      {
+         *voicedHangover = 10;
+      }
+      else
+      {
+         *voicedHangover = temp;
+      }
+   }
+
+   return inbgNoise;
+}
+
+------------------------------------------------------------------------------
+ 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  Bgn_scd(Bgn_scdState *st,       /* i : State variables for bgn SCD  */
+                Word16 ltpGainHist[],  /* i : LTP gain history             */
+                Word16 speech[],       /* o : synthesis speech frame       */
+                Word16 *voicedHangover,/* o : # of frames after last
+                                               voiced frame                 */
+                Flag   *pOverflow
+               )
+{
+    Word16  i;
+    Word16  prevVoiced, inbgNoise;
+    Word16  temp;
+    Word16  ltpLimit, frameEnergyMin;
+    Word16  currEnergy, noiseFloor, maxEnergy, maxEnergyLastPart;
+    Word32  s, L_temp;
+
+
+    /* Update the inBackgroundNoise flag (valid for use in next frame if BFI)   */
+    /* it now works as a energy detector floating on top                        */
+    /* not as good as a VAD.                                                    */
+
+    s = (Word32) 0;
+
+    for (i = L_FRAME - 1; i >= 0; i--)
+    {
+        L_temp = ((Word32) speech[i]) * speech[i];
+        if (L_temp != (Word32) 0x40000000L)
+        {
+            L_temp = L_temp << 1;
+        }
+        else
+        {
+            L_temp = MAX_32;
+        }
+        s = L_add(s, L_temp, pOverflow);
+    }
+
+    /* s is a sum of squares, so don't need to check for neg overflow */
+    if (s > (Word32)0x1fffffffL)
+    {
+        currEnergy = MAX_16;
+    }
+    else
+    {
+        currEnergy = (Word16)(s >> 14);
+    }
+
+    frameEnergyMin = 32767;
+    for (i = L_ENERGYHIST - 1; i >= 0; i--)
+    {
+        if (st->frameEnergyHist[i] < frameEnergyMin)
+        {
+            frameEnergyMin = st->frameEnergyHist[i];
+        }
+    }
+
+    /* Frame Energy Margin of 16 */
+    L_temp = (Word32)frameEnergyMin << 4;
+    if (L_temp != (Word32)((Word16) L_temp))
+    {
+        if (L_temp > 0)
+        {
+            noiseFloor = MAX_16;
+        }
+        else
+        {
+            noiseFloor = MIN_16;
+        }
+    }
+    else
+    {
+        noiseFloor = (Word16)(L_temp);
+    }
+
+    maxEnergy = st->frameEnergyHist[0];
+    for (i = L_ENERGYHIST - 5; i >= 1; i--)
+    {
+        if (maxEnergy < st->frameEnergyHist[i])
+        {
+            maxEnergy = st->frameEnergyHist[i];
+        }
+    }
+
+    maxEnergyLastPart = st->frameEnergyHist[2*L_ENERGYHIST/3];
+    for (i = 2 * L_ENERGYHIST / 3 + 1; i < L_ENERGYHIST; i++)
+    {
+        if (maxEnergyLastPart < st->frameEnergyHist[i])
+        {
+            maxEnergyLastPart = st->frameEnergyHist[i];
+        }
+    }
+
+    /* Do not consider silence as noise */
+    /* Do not consider continuous high volume as noise */
+    /* Or if the current noise level is very low */
+    /* Mark as noise if under current noise limit */
+    /* OR if the maximum energy is below the upper limit */
+
+    if ((maxEnergy > LOWERNOISELIMIT) &&
+            (currEnergy < FRAMEENERGYLIMIT) &&
+            (currEnergy > LOWERNOISELIMIT) &&
+            ((currEnergy < noiseFloor) ||
+             (maxEnergyLastPart < UPPERNOISELIMIT)))
+    {
+        if ((st->bgHangover + 1) > 30)
+        {
+            st->bgHangover = 30;
+        }
+        else
+        {
+            st->bgHangover += 1;
+        }
+    }
+    else
+    {
+        st->bgHangover = 0;
+    }
+
+    /* make final decision about frame state , act somewhat cautiosly */
+
+    if (st->bgHangover > 1)
+    {
+        inbgNoise = TRUE;
+    }
+    else
+    {
+        inbgNoise = FALSE;
+    }
+
+    for (i = 0; i < L_ENERGYHIST - 1; i++)
+    {
+        st->frameEnergyHist[i] = st->frameEnergyHist[i+1];
+    }
+    st->frameEnergyHist[L_ENERGYHIST-1] = currEnergy;
+
+    /* prepare for voicing decision; tighten the threshold after some
+       time in noise */
+
+    if (st->bgHangover > 15)
+    {
+        ltpLimit = 16383;       /* 1.00  Q14 */
+    }
+    else if (st->bgHangover > 8)
+    {
+        ltpLimit = 15565;       /* 0.95  Q14 */
+    }
+    else
+    {
+        ltpLimit = 13926;       /* 0.85  Q14 */
+    }
+
+    /* weak sort of voicing indication. */
+    prevVoiced = FALSE;
+
+    if (gmed_n(&ltpGainHist[4], 5) > ltpLimit)
+    {
+        prevVoiced = TRUE;
+    }
+
+    if (st->bgHangover > 20)
+    {
+        if (gmed_n(ltpGainHist, 9) > ltpLimit)
+        {
+            prevVoiced = TRUE;
+        }
+        else
+        {
+            prevVoiced = FALSE;
+        }
+    }
+
+
+    if (prevVoiced)
+    {
+        *voicedHangover = 0;
+    }
+    else
+    {
+        temp = *voicedHangover + 1;
+
+        if (temp > 10)
+        {
+            *voicedHangover = 10;
+        }
+        else
+        {
+            *voicedHangover = temp;
+        }
+    }
+
+    return(inbgNoise);
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/bgnscd.h b/media/libstagefright/codecs/amrnb/dec/src/bgnscd.h
new file mode 100644
index 0000000..41349d9
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/bgnscd.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/src/include/bgnscd.h
+
+     Date: 12/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : bgnscd.h
+      Purpose          : Background noise source charateristic detector (SCD)
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _BGNSCD_H_
+#define _BGNSCD_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.]
+    ----------------------------------------------------------------------------*/
+#define L_ENERGYHIST 60
+#define INV_L_FRAME 102
+
+
+    /* 2*(160*x)^2 / 65536  where x is FLP values 150,5 and 50 */
+#define FRAMEENERGYLIMIT  17578         /* 150 */
+#define LOWERNOISELIMIT      20         /*   5 */
+#define UPPERNOISELIMIT    1953         /*  50 */
+
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        /* history vector of past synthesis speech energy */
+        Word16 frameEnergyHist[L_ENERGYHIST];
+
+        /* state flags */
+        Word16 bgHangover; /* counter; number of frames after last speech frame */
+
+    } Bgn_scdState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+     *  Function    : Bgn_scd_init
+     *  Purpose     : Allocates initializes state memory
+     *  Description : Stores pointer to filter status struct in *st. This
+     *                pointer has to be passed to Bgn_scd in each call.
+     *  Returns     : 0 on success
+     */
+    Word16 Bgn_scd_init(Bgn_scdState **st);
+
+    /*
+     *  Function    : Bgn_scd_reset
+     *  Purpose     : Resets state memory
+     *  Returns     : 0 on success
+     */
+    Word16 Bgn_scd_reset(Bgn_scdState *st);
+
+    /*
+     *  Function    : Bgn_scd_exit
+     *  Purpose     : The memory used for state memory is freed
+     *  Description : Stores NULL in *s
+     *  Returns     : void
+     */
+    void Bgn_scd_exit(Bgn_scdState **st);
+
+    /*
+     *  Function    : Bgn_scd
+     *  Purpose     : Charaterice synthesis speech and detect background noise
+     *  Returns     : background noise decision; 0 = bgn, 1 = no bgn
+     */
+    Word16 Bgn_scd(Bgn_scdState *st,       /* i : State variables for bgn SCD         */
+                   Word16 ltpGainHist[],  /* i : LTP gain history                    */
+                   Word16 speech[],       /* o : synthesis speech frame              */
+                   Word16 *voicedHangover,/* o : # of frames after last voiced frame */
+                   Flag   *pOverflow
+                  );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _BGNSCD_H_ */
diff --git a/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.cpp b/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.cpp
new file mode 100644
index 0000000..91d3982
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.cpp
@@ -0,0 +1,648 @@
+/* ------------------------------------------------------------------
+ * 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/c_g_aver.c
+ Functions:
+            Cb_gain_average_reset
+            Cb_gain_average
+
+     Date: 03/28/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made some changes to the comments to match the comments from
+    other modules.
+
+ Description: Made changes based on comments from the review meeting.
+
+ 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. Defined one local variable per line.
+
+ Description: Removed the functions Cb_gain_average_init and
+ Cb_gain_average_exit.  The Cb_gain_average related structure is no longer
+ dynamically allocated.
+
+ Description: Passing in pOverflow to comply with changes needed for EPOC
+              Updated the include files for the module.
+
+ Description: Changed round 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:
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains functions that reset and perform
+ codebook gain calculations.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include    "c_g_aver.h"
+#include    "typedef.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 VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Cb_gain_average_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type Cb_gain_averageState
+
+ Outputs:
+    Structure pointed to by state is initialized to zeros
+
+ Returns:
+    Returns 0 if memory was successfully initialized,
+        otherwise returns -1.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Resets state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c_g_aver.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Cb_gain_average_reset (Cb_gain_averageState *state)
+{
+   if (state == (Cb_gain_averageState *) NULL){
+      fprintf(stderr, "Cb_gain_average_reset: invalid parameter\n");
+      return -1;
+   }
+
+   // Static vectors to zero
+   Set_zero (state->cbGainHistory, L_CBGAINHIST);
+
+   // Initialize hangover handling
+   state->hangVar = 0;
+   state->hangCount= 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  Cb_gain_average_reset(Cb_gain_averageState *state)
+{
+    if (state == (Cb_gain_averageState *) NULL)
+    {
+        /* fprint(stderr, "Cb_gain_average_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    /* Static vectors to zero */
+    memset(state->cbGainHistory, 0, L_CBGAINHIST*sizeof(Word16));
+
+    /* Initialize hangover handling */
+    state->hangVar = 0;
+    state->hangCount = 0;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Cb_gain_average
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structure of type Cb_gain_averageState
+    mode = AMR mode (enum Mode)
+    gain_code = CB gain (Word16)
+    lsp = the LSP for the current frame (Word16)
+    lspAver = the average of LSP for 8 frames (Word16)
+    bfi = bad frame indication flag (Word16)
+    prev_bf = previous bad frame indication flag (Word16)
+    pdfi = potential degraded bad frame ind flag (Word16)
+    prev_pdf = prev pot. degraded bad frame ind flag (Word16)
+    inBackgroundNoise = background noise decision (Word16)
+    voicedHangover = # of frames after last voiced frame (Word16)
+    pOverflow = address of overflow (Flag)
+
+ Returns:
+    cbGainMix = codebook gain (Word16)
+
+ Outputs:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ The mix cb gains for MR475, MR515, MR59, MR67, MR102; gain_code other modes
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ c_g_aver.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+Word16 Cb_gain_average (
+   Cb_gain_averageState *st, // i/o : State variables for CB gain avergeing
+   enum Mode mode,           // i   : AMR mode
+   Word16 gain_code,         // i   : CB gain                              Q1
+   Word16 lsp[],             // i   : The LSP for the current frame       Q15
+   Word16 lspAver[],         // i   : The average of LSP for 8 frames     Q15
+   Word16 bfi,               // i   : bad frame indication flag
+   Word16 prev_bf,           // i   : previous bad frame indication flag
+   Word16 pdfi,              // i   : potential degraded bad frame ind flag
+   Word16 prev_pdf,          // i   : prev pot. degraded bad frame ind flag
+   Word16 inBackgroundNoise, // i   : background noise decision
+   Word16 voicedHangover     // i   : # of frames after last voiced frame
+   )
+{
+   //---------------------------------------------------------*
+    * Compute mixed cb gain, used to make cb gain more        *
+    * smooth in background noise for modes 5.15, 5.9 and 6.7  *
+    * states that needs to be updated by all                  *
+    *---------------------------------------------------------
+   Word16 i;
+   Word16 cbGainMix, diff, tmp_diff, bgMix, cbGainMean;
+   Word32 L_sum;
+   Word16 tmp[M], tmp1, tmp2, shift1, shift2, shift;
+
+   // set correct cbGainMix for MR74, MR795, MR122
+   cbGainMix = gain_code;
+
+    *-------------------------------------------------------*
+    *   Store list of CB gain needed in the CB gain         *
+    *   averaging                                           *
+    *-------------------------------------------------------*
+   for (i = 0; i < (L_CBGAINHIST-1); i++)
+   {
+      st->cbGainHistory[i] = st->cbGainHistory[i+1];
+   }
+   st->cbGainHistory[L_CBGAINHIST-1] = gain_code;
+
+   // compute lsp difference
+   for (i = 0; i < M; i++) {
+      tmp1 = abs_s(sub(lspAver[i], lsp[i]));  // Q15
+      shift1 = sub(norm_s(tmp1), 1);          // Qn
+      tmp1 = shl(tmp1, shift1);               // Q15+Qn
+      shift2 = norm_s(lspAver[i]);            // Qm
+      tmp2 = shl(lspAver[i], shift2);         // Q15+Qm
+      tmp[i] = div_s(tmp1, tmp2);             // Q15+(Q15+Qn)-(Q15+Qm)
+      shift = sub(add(2, shift1), shift2);
+      if (shift >= 0)
+      {
+         tmp[i] = shr(tmp[i], shift); // Q15+Qn-Qm-Qx=Q13
+      }
+      else
+      {
+         tmp[i] = shl(tmp[i], negate(shift)); // Q15+Qn-Qm-Qx=Q13
+      }
+   }
+
+   diff = tmp[0];
+   for (i = 1; i < M; i++) {
+      diff = add(diff, tmp[i]);       // Q13
+   }
+
+   // Compute hangover
+   if (sub(diff, 5325) > 0)  // 0.65 in Q11
+   {
+      st->hangVar = add(st->hangVar, 1);
+   }
+   else
+   {
+      st->hangVar = 0;
+   }
+
+   if (sub(st->hangVar, 10) > 0)
+   {
+      st->hangCount = 0;  // Speech period, reset hangover variable
+   }
+
+   // Compute mix constant (bgMix)
+   bgMix = 8192;    // 1 in Q13
+   if ((sub(mode, MR67) <= 0) || (sub(mode, MR102) == 0))
+      // MR475, MR515, MR59, MR67, MR102
+   {
+      // if errors and presumed noise make smoothing probability stronger
+      if (((((pdfi != 0) && (prev_pdf != 0)) || (bfi != 0) || (prev_bf != 0)) &&
+          (sub(voicedHangover, 1) > 0) && (inBackgroundNoise != 0) &&
+          ((sub(mode, MR475) == 0) ||
+           (sub(mode, MR515) == 0) ||
+           (sub(mode, MR59) == 0)) ))
+      {
+         // bgMix = min(0.25, max(0.0, diff-0.55)) / 0.25;
+         tmp_diff = sub(diff, 4506);   // 0.55 in Q13
+
+         // max(0.0, diff-0.55)
+         if (tmp_diff > 0)
+         {
+            tmp1 = tmp_diff;
+         }
+         else
+         {
+            tmp1 = 0;
+         }
+
+         // min(0.25, tmp1)
+         if (sub(2048, tmp1) < 0)
+         {
+            bgMix = 8192;
+         }
+         else
+         {
+            bgMix = shl(tmp1, 2);
+         }
+      }
+      else
+      {
+         // bgMix = min(0.25, max(0.0, diff-0.40)) / 0.25;
+         tmp_diff = sub(diff, 3277); // 0.4 in Q13
+
+         // max(0.0, diff-0.40)
+         if (tmp_diff > 0)
+         {
+            tmp1 = tmp_diff;
+         }
+         else
+         {
+            tmp1 = 0;
+         }
+
+         // min(0.25, tmp1)
+         if (sub(2048, tmp1) < 0)
+         {
+            bgMix = 8192;
+         }
+         else
+         {
+            bgMix = shl(tmp1, 2);
+         }
+      }
+
+      if ((sub(st->hangCount, 40) < 0) || (sub(diff, 5325) > 0)) // 0.65 in Q13
+      {
+         bgMix = 8192;  // disable mix if too short time since
+      }
+
+      // Smoothen the cb gain trajectory
+      // smoothing depends on mix constant bgMix
+      L_sum = L_mult(6554, st->cbGainHistory[2]); // 0.2 in Q15; L_sum in Q17
+      for (i = 3; i < L_CBGAINHIST; i++)
+      {
+         L_sum = L_mac(L_sum, 6554, st->cbGainHistory[i]);
+      }
+      cbGainMean = pv_round(L_sum);                      // Q1
+
+      // more smoothing in error and bg noise (NB no DFI used  here)
+      if (((bfi != 0) || (prev_bf != 0)) && (inBackgroundNoise != 0) &&
+          ((sub(mode, MR475) == 0) ||
+           (sub(mode, MR515) == 0) ||
+           (sub(mode, MR59) == 0)) )
+      {
+         L_sum = L_mult(4681, st->cbGainHistory[0]); // 0.143 in Q15; L_sum in Q17
+         for (i = 1; i < L_CBGAINHIST; i++)
+         {
+            L_sum = L_mac(L_sum, 4681, st->cbGainHistory[i]);
+         }
+         cbGainMean = pv_round(L_sum);                   // Q1
+      }
+
+      // cbGainMix = bgMix*cbGainMix + (1-bgMix)*cbGainMean;
+      L_sum = L_mult(bgMix, cbGainMix);               // L_sum in Q15
+      L_sum = L_mac(L_sum, 8192, cbGainMean);
+      L_sum = L_msu(L_sum, bgMix, cbGainMean);
+      cbGainMix = pv_round(L_shl(L_sum, 2));             // Q1
+   }
+
+   st->hangCount = add(st->hangCount, 1);
+   return cbGainMix;
+}
+
+------------------------------------------------------------------------------
+ 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 Cb_gain_average(
+    Cb_gain_averageState *st, /* i/o : State variables for CB gain averaging */
+    enum Mode mode,           /* i   : AMR mode                              */
+    Word16 gain_code,         /* i   : CB gain                            Q1 */
+    Word16 lsp[],             /* i   : The LSP for the current frame     Q15 */
+    Word16 lspAver[],         /* i   : The average of LSP for 8 frames   Q15 */
+    Word16 bfi,               /* i   : bad frame indication flag             */
+    Word16 prev_bf,           /* i   : previous bad frame indication flag    */
+    Word16 pdfi,              /* i   : potential degraded bad frame ind flag */
+    Word16 prev_pdf,          /* i   : prev pot. degraded bad frame ind flag */
+    Word16 inBackgroundNoise, /* i   : background noise decision             */
+    Word16 voicedHangover,    /* i   : # of frames after last voiced frame   */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+    Word16 cbGainMix;
+    Word16 diff;
+    Word16 tmp_diff;
+    Word16 bgMix;
+    Word16 cbGainMean;
+    Word32 L_sum;
+    Word16 tmp[M];
+    Word16 tmp1;
+    Word16 tmp2;
+    Word16 shift1;
+    Word16 shift2;
+    Word16 shift;
+
+    /*---------------------------------------------------------*
+     * Compute mixed cb gain, used to make cb gain more        *
+     * smooth in background noise for modes 5.15, 5.9 and 6.7  *
+     * states that needs to be updated by all                  *
+     *---------------------------------------------------------*/
+
+    /* set correct cbGainMix for MR74, MR795, MR122 */
+    cbGainMix = gain_code;
+
+    /*-------------------------------------------------------*
+     *   Store list of CB gain needed in the CB gain         *
+     *   averaging                                           *
+     *-------------------------------------------------------*/
+    for (i = 0; i < (L_CBGAINHIST - 1); i++)
+    {
+        st->cbGainHistory[i] = st->cbGainHistory[i+1];
+    }
+    st->cbGainHistory[L_CBGAINHIST-1] = gain_code;
+
+    diff = 0;
+
+    /* compute lsp difference */
+    for (i = 0; i < M; i++)
+    {
+        tmp1 = abs_s(sub(*(lspAver + i), *(lsp + i), pOverflow));
+        /* Q15      */
+        shift1 = sub(norm_s(tmp1), 1, pOverflow);       /* Qn       */
+        tmp1 = shl(tmp1, shift1, pOverflow);            /* Q15+Qn   */
+        shift2 = norm_s(*(lspAver + i));                /* Qm       */
+        tmp2 = shl(*(lspAver + i), shift2, pOverflow);  /* Q15+Qm   */
+        tmp[i] = div_s(tmp1, tmp2);        /* Q15+(Q15+Qn)-(Q15+Qm) */
+
+        shift = 2 + shift1 - shift2;
+
+        if (shift >= 0)
+        {
+            *(tmp + i) = shr(*(tmp + i), shift, pOverflow);
+            /* Q15+Qn-Qm-Qx=Q13 */
+        }
+        else
+        {
+            *(tmp + i) = shl(*(tmp + i), negate(shift), pOverflow);
+            /* Q15+Qn-Qm-Qx=Q13 */
+        }
+
+        diff = add(diff, *(tmp + i), pOverflow);           /* Q13 */
+    }
+
+    /* Compute hangover */
+
+    if (diff > 5325)                /* 0.65 in Q11 */
+    {
+        st->hangVar += 1;
+    }
+    else
+    {
+        st->hangVar = 0;
+    }
+
+
+    if (st->hangVar > 10)
+    {
+        /* Speech period, reset hangover variable */
+        st->hangCount = 0;
+    }
+
+    /* Compute mix constant (bgMix) */
+    bgMix = 8192;    /* 1 in Q13 */
+
+    if ((mode <= MR67) || (mode == MR102))
+        /* MR475, MR515, MR59, MR67, MR102 */
+    {
+        /* if errors and presumed noise make smoothing probability stronger */
+
+        if (((((pdfi != 0) && (prev_pdf != 0)) || (bfi != 0) ||
+                (prev_bf != 0))
+                && (voicedHangover > 1)
+                && (inBackgroundNoise != 0)
+                && ((mode == MR475) || (mode == MR515) ||
+                    (mode == MR59))))
+        {
+            /* bgMix = min(0.25, max(0.0, diff-0.55)) / 0.25; */
+            tmp_diff = sub(diff, 4506, pOverflow);   /* 0.55 in Q13 */
+        }
+        else
+        {
+            /* bgMix = min(0.25, max(0.0, diff-0.40)) / 0.25; */
+            tmp_diff = sub(diff, 3277, pOverflow); /* 0.4 in Q13 */
+        }
+
+        /* max(0.0, diff-0.55)  or  */
+        /* max(0.0, diff-0.40) */
+        if (tmp_diff > 0)
+        {
+            tmp1 = tmp_diff;
+        }
+        else
+        {
+            tmp1 = 0;
+        }
+
+        /* min(0.25, tmp1) */
+        if (2048 < tmp1)
+        {
+            bgMix = 8192;
+        }
+        else
+        {
+            bgMix = shl(tmp1, 2, pOverflow);
+        }
+
+        if ((st->hangCount < 40) || (diff > 5325)) /* 0.65 in Q13 */
+        {
+            /* disable mix if too short time since */
+            bgMix = 8192;
+        }
+
+        /* Smoothen the cb gain trajectory  */
+        /* smoothing depends on mix constant bgMix */
+        L_sum = L_mult(6554, st->cbGainHistory[2], pOverflow);
+        /* 0.2 in Q15; L_sum in Q17 */
+
+        for (i = 3; i < L_CBGAINHIST; i++)
+        {
+            L_sum = L_mac(L_sum, 6554, st->cbGainHistory[i], pOverflow);
+        }
+        cbGainMean = pv_round(L_sum, pOverflow);               /* Q1 */
+
+        /* more smoothing in error and bg noise (NB no DFI used here) */
+
+        if (((bfi != 0) || (prev_bf != 0)) && (inBackgroundNoise != 0)
+                && ((mode == MR475) || (mode == MR515)
+                    || (mode == MR59)))
+        {
+            /* 0.143 in Q15; L_sum in Q17    */
+            L_sum = L_mult(4681, st->cbGainHistory[0], pOverflow);
+            for (i = 1; i < L_CBGAINHIST; i++)
+            {
+                L_sum =
+                    L_mac(L_sum, 4681, st->cbGainHistory[i], pOverflow);
+            }
+            cbGainMean = pv_round(L_sum, pOverflow);              /* Q1 */
+        }
+
+        /* cbGainMix = bgMix*cbGainMix + (1-bgMix)*cbGainMean; */
+        /* L_sum in Q15 */
+        L_sum = L_mult(bgMix, cbGainMix, pOverflow);
+        L_sum = L_mac(L_sum, 8192, cbGainMean, pOverflow);
+        L_sum = L_msu(L_sum, bgMix, cbGainMean, pOverflow);
+        cbGainMix = pv_round(L_shl(L_sum, 2, pOverflow), pOverflow);  /* Q1 */
+    }
+
+    st->hangCount += 1;
+
+    return (cbGainMix);
+}
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.h b/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.h
new file mode 100644
index 0000000..0b53753
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/c_g_aver.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/src/include/c_g_aver.h
+
+     Date: 12/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : c_g_aver.h
+      Purpose          : Background noise source charateristic detector (SCD)
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _C_G_AVER_H_
+#define _C_G_AVER_H_
+
+/*----------------------------------------------------------------------------
+; 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.]
+    ----------------------------------------------------------------------------*/
+#define L_CBGAINHIST 7
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; [Declare variables used in this module but defined elsewhere]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        /* history vector of past synthesis speech energy */
+        Word16 cbGainHistory[L_CBGAINHIST];
+
+        /* state flags */
+        Word16 hangVar;       /* counter; */
+        Word16 hangCount;     /* counter; */
+
+    } Cb_gain_averageState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    /*
+     *  Function    : Cb_gain_average_init
+     *  Purpose     : Allocates initializes state memory
+     *  Description : Stores pointer to filter status struct in *st. This
+     *                pointer has to be passed to Cb_gain_average in each call.
+     *  Returns     : 0 on success
+     */
+    Word16 Cb_gain_average_init(Cb_gain_averageState **st);
+
+    /*
+     *  Function    : Cb_gain_average_reset
+     *  Purpose     : Resets state memory
+     *  Returns     : 0 on success
+     */
+    Word16 Cb_gain_average_reset(Cb_gain_averageState *st);
+
+    /*
+     *  Function    : Cb_gain_average_exit
+     *  Purpose     : The memory used for state memory is freed
+     *  Description : Stores NULL in *s
+     *  Returns     : void
+     */
+    void Cb_gain_average_exit(Cb_gain_averageState **st);
+
+    /*
+     *  Function    : Cb_gain_average
+     *  Purpose     : Charaterice synthesis speech and detect background noise
+     *  Returns     : background noise decision; 0 = bgn, 1 = no bgn
+     */
+    Word16 Cb_gain_average(
+        Cb_gain_averageState *st, /* i/o : State variables for CB gain avergeing   */
+        enum Mode mode,           /* i   : AMR mode                                */
+        Word16 gain_code,         /* i   : CB gain                              Q1 */
+        Word16 lsp[],             /* i   : The LSP for the current frame       Q15 */
+        Word16 lspAver[],         /* i   : The average of LSP for 8 frames     Q15 */
+        Word16 bfi,               /* i   : bad frame indication flag               */
+        Word16 prev_bf,           /* i   : previous bad frame indication flag      */
+        Word16 pdfi,              /* i   : potential degraded bad frame ind flag   */
+        Word16 prev_pdf,          /* i   : prev pot. degraded bad frame ind flag   */
+        Word16 inBackgroundNoise, /* i   : background noise decision               */
+        Word16 voicedHangover,    /* i   : # of frames after last voiced frame     */
+        Flag   *pOverflow
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _C_G_AVER_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d1035pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d1035pf.cpp
new file mode 100644
index 0000000..899daba
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d1035pf.cpp
@@ -0,0 +1,263 @@
+/* ------------------------------------------------------------------
+ * 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/d1035pf.c
+
+     Date: 04/14/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.
+
+ Description: Synchronized file with UTMS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Removed inclusion of "gray.tab".
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "d1035pf.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.
+----------------------------------------------------------------------------*/
+#define NB_PULSE  10            /* number of pulses  */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dec_10i40_35bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    index = buffer containing index of 10 pulses; each element is
+        represented by sign+position
+    cod = buffer of algebraic (fixed) codebook excitation
+
+ Outputs:
+    cod buffer contains the new algebraic codebook excitation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    dgray = gray decoding table
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function builds the innovative codevector from the received index of
+ algebraic codebook. See c1035pf.c for more details about the algebraic
+ codebook structure.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d1035pf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void dec_10i40_35bits (
+    Word16 index[],    // (i)     : index of 10 pulses (sign+position)
+    Word16 cod[]       // (o)     : algebraic (fixed) codebook excitation
+)
+{
+    Word16 i, j, pos1, pos2, sign, tmp;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        cod[i] = 0;
+    }
+
+    // decode the positions and signs of pulses and build the codeword
+
+    for (j = 0; j < NB_TRACK; j++)
+    {
+        // compute index i
+
+        tmp = index[j];
+        i = tmp & 7;
+        i = dgray[i];
+
+        i = extract_l (L_shr (L_mult (i, 5), 1));
+        pos1 = add (i, j); // position of pulse "j"
+
+        i = shr (tmp, 3) & 1;
+        if (i == 0)
+        {
+            sign = 4096; // +1.0
+        }
+        else
+        {
+            sign = -4096; // -1.0
+        }
+
+        cod[pos1] = sign;
+
+        // compute index i
+
+        i = index[add (j, 5)] & 7;
+        i = dgray[i];
+        i = extract_l (L_shr (L_mult (i, 5), 1));
+
+        pos2 = add (i, j);      // position of pulse "j+5"
+
+        if (sub (pos2, pos1) < 0)
+        {
+            sign = negate (sign);
+        }
+        cod[pos2] = add (cod[pos2], sign);
+    }
+
+    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 dec_10i40_35bits(
+    Word16 index[],    /* (i)     : index of 10 pulses (sign+position)       */
+    Word16 cod[]       /* (o)     : algebraic (fixed) codebook excitation    */
+)
+{
+    register Word16 i, j, pos1, pos2;
+    Word16 sign, tmp;
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        *(cod + i) = 0;
+    }
+
+    /* decode the positions and signs of pulses and build the codeword */
+
+    for (j = 0; j < NB_TRACK; j++)
+    {
+        /* compute index i */
+
+        tmp = *(index + j);
+        i = tmp & 7;
+        i = *(dgray + i);
+
+        i = (Word16)(i * 5);
+        pos1 = i + j; /* position of pulse "j" */
+
+        i = (tmp >> 3) & 1;
+
+        if (i == 0)
+        {
+            sign = 4096;                                 /* +1.0 */
+        }
+        else
+        {
+            sign = -4096;                                /* -1.0 */
+        }
+
+        *(cod + pos1) = sign;
+
+        /* compute index i */
+
+        i = *(index + j + 5) & 7;
+        i = *(dgray + i);
+        i = (Word16)(i * 5);
+
+        pos2 = i + j;      /* position of pulse "j+5" */
+
+
+        if (pos2 < pos1)
+        {
+            sign = negate(sign);
+        }
+        *(cod + pos2) += sign;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d1035pf.h b/media/libstagefright/codecs/amrnb/dec/src/d1035pf.h
new file mode 100644
index 0000000..51f1f42
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d1035pf.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/include/d1035pf.h
+
+     Date: 09/28/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Added extern declaration for dgray[] defined
+              in gray_tbl.c
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains the prototype declaration for dec_10i40_35bits function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef D1035PF_H
+#define D1035PF_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 Word16 dgray[];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void dec_10i40_35bits(
+        Word16 index[],    /* (i)   : index of 10 pulses (sign+position)        */
+        Word16 cod[]       /* (o)   : algebraic (fixed) codebook excitation     */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _D1035PF_H_ */
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.cpp
new file mode 100644
index 0000000..e1e544f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.cpp
@@ -0,0 +1,224 @@
+/* ------------------------------------------------------------------
+ * 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/d2_11pf.c
+ Functions:
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to place file in the correct template format. Eliminated
+ use of special functions to perform simple mathematical operations.
+
+ Description: Per review comments...
+ (1) Removed include of "count.h" and "basic_op.h"
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "d2_11pf.h"
+#include "typedef.h"
+#include "cnst.h"
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decode_2i40_11bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sign  -- Word16 -- signs of 2 pulses.
+    index -- Word16 -- Positions of the 2 pulses.
+
+ Outputs:
+    cod[] -- array of type Word16 -- algebraic (fixed) codebook excitation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d2_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]
+
+------------------------------------------------------------------------------
+*/
+
+void decode_2i40_11bits(
+    Word16 sign,   /* i : signs of 2 pulses.                       */
+    Word16 index,  /* i : Positions of the 2 pulses.               */
+    Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+)
+
+{
+    Word16 i;
+    Word16 j;
+
+    Word16 pos[NB_PULSE];
+
+    /* Decode the positions */
+
+    j = index & 0x1;
+
+    index >>= 1;
+
+    i = index & 0x7;
+
+    pos[0] = i * 5 + j * 2 + 1;
+
+
+
+
+    index >>= 3;
+
+    j = index & 0x3;
+
+    index >>= 2;
+
+    i = index & 0x7;
+
+    if (j == 3)
+    {
+        pos[1] = i * 5 + 4;
+    }
+    else
+    {
+        pos[1] = i * 5 + j;
+    }
+
+
+
+
+    /* decode the signs  and build the codeword */
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        cod[i] = 0;
+    }
+
+    for (j = 0; j < NB_PULSE; j++)
+    {
+        i = sign & 1;
+
+        /* This line is equivalent to...
+         *
+         *
+         *  if (i == 1)
+         *  {
+         *      cod[pos[j]] = 8191;
+         *  }
+         *  if (i == 0)
+         *  {
+         *      cod[pos[j]] = -8192;
+         *  }
+         */
+
+        cod[pos[j]] = i * 16383 - 8192;
+
+        sign >>= 1;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.h b/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.h
new file mode 100644
index 0000000..aaf2e08
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d2_11pf.h
@@ -0,0 +1,93 @@
+/* ------------------------------------------------------------------
+ * 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             : d2_11pf.h
+*      Purpose          : Algebraic codebook decoder
+*
+********************************************************************************
+*/
+#ifndef d2_11pf_h
+#define d2_11pf_h "$Id $"
+
+/*
+********************************************************************************
+*                         INCLUDE FILES
+********************************************************************************
+*/
+#include "typedef.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*
+    ********************************************************************************
+    *                         LOCAL VARIABLES AND TABLES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DEFINITION OF DATA TYPES
+    ********************************************************************************
+    */
+
+    /*
+    ********************************************************************************
+    *                         DECLARATION OF PROTOTYPES
+    ********************************************************************************
+    */
+    /*************************************************************************
+     *
+     *  FUNCTION:  decode_2i40_11bits (decod_ACELP())
+     *
+     *  PURPOSE:   Algebraic codebook decoder for 2 pulses coded with 11 bits
+     *
+     *************************************************************************/
+
+    void decode_2i40_11bits(
+        Word16 sign,   /* i : signs of 2 pulses.                       */
+        Word16 index,  /* i : Positions of the 2 pulses.               */
+        Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.cpp
new file mode 100644
index 0000000..2c36706
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.cpp
@@ -0,0 +1,248 @@
+/* ------------------------------------------------------------------
+ * 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/d2_9pf.c
+ Functions: decode_2i40_9bits
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to place file in the correct template format. Eliminated
+ use of special functions to perform simple mathematical operations, where
+ possible.  Added the parameter pOverflow for the basic math operations.
+
+ Description: Per review comments...
+ (1) Removed include of basic_op.h, replaced with shl.h
+ (2) Added pOverflow to the output section of the template
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+ FUNCTION:  decode_2i40_9bits (decod_ACELP())
+
+ PURPOSE:   Algebraic codebook decoder. For details about the encoding see
+            c2_9pf.c
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "d2_9pf.h"
+#include "typedef.h"
+#include "basic_op.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 NB_PULSE  2
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    extern const Word16 startPos[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decode_2i40_11bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sign  -- Word16 -- signs of 2 pulses.
+    index -- Word16 -- Positions of the 2 pulses.
+
+ Outputs:
+    cod[] -- array of type Word16 -- algebraic (fixed) codebook excitation
+    pOverflow = pointer to overflow flag
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d2_9pf.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 decode_2i40_9bits(
+    Word16 subNr,  /* i : subframe number                          */
+    Word16 sign,   /* i : signs of 2 pulses.                       */
+    Word16 index,  /* i : Positions of the 2 pulses.               */
+    Word16 cod[],  /* o : algebraic (fixed) codebook excitation    */
+    Flag  *pOverflow  /* o : Flag set when overflow occurs         */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 k;
+
+    Word16 pos[NB_PULSE];
+
+    /* Decode the positions */
+    /* table bit  is the MSB */
+
+    j = (Word16)(index & 64);
+
+    j >>= 3;
+
+    i = index & 7;
+
+    k =
+        shl(
+            subNr,
+            1,
+            pOverflow);
+
+    k += j;
+
+    /* pos0 =i*5+startPos[j*8+subNr*2] */
+    pos[0] = i * 5 + startPos[k++];
+
+
+    index >>= 3;
+
+    i = index & 7;
+
+    /* pos1 =i*5+startPos[j*8+subNr*2 + 1] */
+    pos[1] = i * 5 + startPos[k];
+
+
+    /* decode the signs  and build the codeword */
+
+    for (i = L_SUBFR - 1; i >= 0; i--)
+    {
+        cod[i] = 0;
+    }
+
+    for (j = 0; j < NB_PULSE; j++)
+    {
+        i = sign & 0x1;
+
+        /* This line is equivalent to...
+         *
+         *
+         *  if (i == 1)
+         *  {
+         *      cod[pos[j]] = 8191;
+         *  }
+         *  if (i == 0)
+         *  {
+         *      cod[pos[j]] = -8192;
+         *  }
+         */
+
+        cod[pos[j]] = i * 16383 - 8192;
+
+        sign >>= 1;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.h b/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.h
new file mode 100644
index 0000000..38076d8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d2_9pf.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/d2_9pf.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: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the d2_9pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef d2_9pf_h
+#define d2_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
+    ----------------------------------------------------------------------------*/
+
+    void decode_2i40_9bits(
+        Word16 subNr,       /* i : subframe number                          */
+        Word16 sign,        /* i : signs of 2 pulses.                       */
+        Word16 index,       /* i : Positions of the 2 pulses.               */
+        Word16 cod[],       /* o : algebraic (fixed) codebook excitation    */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs            */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _d2_9PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.cpp
new file mode 100644
index 0000000..d1912cf
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.cpp
@@ -0,0 +1,233 @@
+/* ------------------------------------------------------------------
+ * 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/d3_14pf.c
+ Functions: decode_3i40_14bits
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to place file in the correct template format. Eliminated
+ use of special functions to perform simple mathematical operations.
+
+ Description: Per review comments...
+ (1) Removed include of "count.h" and "basic_op.h"
+ (2) Updated the pathname to indicate the correct file.  (Line 39)
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+ FUNCTION:  decode_3i40_14bits (decod_ACELP())
+
+ PURPOSE:   Algebraic codebook decoder. For details about the encoding see
+            c3_14pf.c
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "d3_14pf.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NB_PULSE 3           /* number of pulses  */
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decode_3i40_14bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sign  -- Word16 -- signs of 3 pulses.
+    index -- Word16 -- Positions of the 3 pulses.
+
+ Outputs:
+    cod[] -- array of type Word16 -- algebraic (fixed) codebook excitation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d2_9pf.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 decode_3i40_14bits(
+    Word16 sign,   /* i : signs of 3 pulses.                       */
+    Word16 index,  /* i : Positions of the 3 pulses.               */
+    Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+)
+{
+    Word16 i;
+    Word16 j;
+
+    Word16 pos[NB_PULSE];
+
+    /* Decode the positions */
+
+    i = index & 0x7;
+
+    pos[0] = i * 5;
+
+
+
+
+
+    index >>= 3;
+
+    j = index & 0x1;
+
+    index >>= 1;
+
+    i = index & 0x7;
+
+    pos[1] = i * 5 + j * 2 + 1;
+
+
+
+
+
+    index >>= 3;
+
+    j = index & 0x1;
+
+    index >>= 1;
+
+    i = index & 0x7;
+
+    pos[2] = i * 5 + j * 2 + 2;
+
+
+    /* decode the signs  and build the codeword */
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        cod[i] = 0;
+    }
+
+    for (j = 0; j < NB_PULSE; j++)
+    {
+        i = sign & 1;
+
+        /* This line is equivalent to...
+         *
+         *
+         *  if (i == 1)
+         *  {
+         *      cod[pos[j]] = 8191;
+         *  }
+         *  if (i == 0)
+         *  {
+         *      cod[pos[j]] = -8192;
+         *  }
+         */
+
+        cod[pos[j]] = i * 16383 - 8192;
+
+        sign >>= 1;
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.h b/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.h
new file mode 100644
index 0000000..1e2e0cd
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d3_14pf.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/d2_9pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the d3_14pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef d3_14pf_h
+#define d3_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
+    ----------------------------------------------------------------------------*/
+    void decode_3i40_14bits(
+        Word16 sign,   /* i : signs of 3 pulses.                       */
+        Word16 index,  /* i : Positions of the 3 pulses.               */
+        Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _d3_14PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.cpp
new file mode 100644
index 0000000..ece82c0
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.cpp
@@ -0,0 +1,271 @@
+/* ------------------------------------------------------------------
+ * 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/d4_17pf.c
+ Functions: decode_4i40_17bits
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Modified to place file in the correct template format. Eliminated
+ use of special functions to perform simple mathematical operations.
+
+ Description: An incorrect comment in the original source lead me to implement
+ the calculation of pos[2] incorrectly.  The correct formula is pos2 =i*5+2,
+ not pos2 = i*5 + 1.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+
+ FUNCTION:  decode_4i40_17bits (decod_ACELP())
+
+ PURPOSE:   Algebraic codebook decoder. For details about the encoding see
+            c4_17pf.c
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "d4_17pf.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           /* number of pulses  */
+
+
+    /*----------------------------------------------------------------------------
+    ; 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 dgray[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decode_4i40_17bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    sign  -- Word16 -- signs of 3 pulses.
+    index -- Word16 -- Positions of the 3 pulses.
+
+ Outputs:
+    cod[] -- array of type Word16 -- algebraic (fixed) codebook excitation
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d4_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]
+
+------------------------------------------------------------------------------
+*/
+
+void decode_4i40_17bits(
+    Word16 sign,   /* i : signs of 4 pulses.                       */
+    Word16 index,  /* i : Positions of the 4 pulses.               */
+    Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+)
+{
+    Word16 i;
+    Word16 j;
+
+    Word16 pos[NB_PULSE];
+
+    /* Index is a 13-bit value.  3 bits each correspond to the
+     * positions 0-2, with 4 bits allocated for position 3.
+     *
+     *
+     * [][][][] [][][] [][][] [][][]
+     *    |       |      |     |
+     *    |       |      |     |
+     *   pos3    pos2   pos1  pos0
+     */
+
+    /* Decode the positions */
+
+    i = index & 0x7;
+
+    i = dgray[i];
+
+    pos[0] = i * 5; /* pos0 =i*5 */
+
+
+    index >>= 3;
+
+    i = index & 0x7;
+
+    i = dgray[i];
+
+    pos[1] = i * 5 + 1;  /* pos1 =i*5+1 */
+
+
+
+    index >>= 3;
+
+    i = index & 0x7;
+
+    i = dgray[i];
+
+    pos[2] = i * 5 + 2; /* pos2 =i*5+2 */
+
+
+
+
+
+    index >>= 3;
+
+    j = index & 0x1;
+
+    index >>= 1;
+
+    i = index & 0x7;
+
+    i = dgray[i];
+
+    pos[3] = i * 5 + 3 + j; /* pos3 =i*5+3+j */
+
+
+    /* decode the signs  and build the codeword */
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        cod[i] = 0;
+    }
+
+    for (j = 0; j < NB_PULSE; j++)
+    {
+        i = sign & 0x1;
+
+        /* This line is equivalent to...
+         *
+         *
+         *  if (i == 1)
+         *  {
+         *      cod[pos[j]] = 8191;
+         *  }
+         *  if (i == 0)
+         *  {
+         *      cod[pos[j]] = -8192;
+         *  }
+         */
+
+        cod[pos[j]] = i * 16383 - 8192;
+
+        sign >>= 1;
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.h b/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.h
new file mode 100644
index 0000000..5dc43f3
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d4_17pf.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/d4_17pf.h
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Placed header file in the proper template format.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the d4_17pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef d4_17pf_h
+#define d4_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
+    ----------------------------------------------------------------------------*/
+
+    void decode_4i40_17bits(
+        Word16 sign,   /* i : signs of 4 pulses.                       */
+        Word16 index,  /* i : Positions of the 4 pulses.               */
+        Word16 cod[]   /* o : algebraic (fixed) codebook excitation    */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _d4_17PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.cpp
new file mode 100644
index 0000000..917c47f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.cpp
@@ -0,0 +1,626 @@
+/* ------------------------------------------------------------------
+ * 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/d8_31pf.c
+ Functions:
+
+
+     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: Per review comments...
+ (1) Removed include of "count.h" and "basic_op.h"
+ (2) Added includes of mult.h, shl.h, shr.h, add.h, sub.h, negate.h,
+     L_mult.h, and L_shr.h
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "d8_31pf.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.
+----------------------------------------------------------------------------*/
+#define NB_PULSE  8           /* number of pulses  */
+
+/* define values/representation for output codevector and sign */
+#define POS_CODE  8191
+#define NEG_CODE  8191
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decompress10
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+   MSBs -- Word16 -- MSB part of the index
+   LSBs -- Word16 -- LSB part of the index
+   index1 -- Word16 -- index for first pos in pos_index[]
+   index2 -- Word16 -- index for second pos in pos_index[]
+   index3 -- Word16 -- index for third pos in pos_index[]
+
+ Outputs:
+   pos_indx[] -- array of type Word16 -- position of 3 pulses (decompressed)
+
+   pOverflow  Flag set when overflow occurs, pointer of type Flag *
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d8_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 void decompress10(
+    Word16 MSBs,        /* i : MSB part of the index                 */
+    Word16 LSBs,        /* i : LSB part of the index                 */
+    Word16 index1,      /* i : index for first pos in pos_index[]    */
+    Word16 index2,      /* i : index for second pos in pos_index[]   */
+    Word16 index3,      /* i : index for third pos in pos_index[]    */
+    Word16 pos_indx[],  /* o : position of 3 pulses (decompressed)   */
+    Flag  *pOverflow)   /* o : Flag set when overflow occurs         */
+{
+    Word16 ia;
+    Word16 ib;
+    Word16 ic;
+    Word32 tempWord32;
+
+    /*
+      pos_indx[index1] = ((MSBs-25*(MSBs/25))%5)*2 + (LSBs-4*(LSBs/4))%2;
+      pos_indx[index2] = ((MSBs-25*(MSBs/25))/5)*2 + (LSBs-4*(LSBs/4))/2;
+      pos_indx[index3] = (MSBs/25)*2 + LSBs/4;
+    */
+
+    if (MSBs > 124)
+    {
+        MSBs = 124;
+    }
+
+    ia =
+        mult(
+            MSBs,
+            1311,
+            pOverflow);
+
+    tempWord32 =
+        L_mult(
+            ia,
+            25,
+            pOverflow);
+
+
+    ia = (Word16)(MSBs - (tempWord32 >> 1));
+    ib =
+        mult(
+            ia,
+            6554,
+            pOverflow);
+
+    tempWord32 =
+        L_mult(
+            ib,
+            5,
+            pOverflow);
+
+    ib = ia - (Word16)(tempWord32 >> 1);
+
+    ib =
+        shl(
+            ib,
+            1,
+            pOverflow);
+
+
+    ic = LSBs - ((LSBs >> 2) << 2);
+
+
+    pos_indx[index1] = ib + (ic & 1);
+
+
+    ib =
+        mult(
+            ia,
+            6554,
+            pOverflow);
+
+    ib =
+        shl(
+            ib,
+            1,
+            pOverflow);
+
+
+    pos_indx[index2] = ib + (ic >> 1);
+
+
+    ib = LSBs >> 2;
+
+    ic =
+        mult(
+            MSBs,
+            1311,
+            pOverflow);
+
+    ic =
+        shl(
+            ic,
+            1,
+            pOverflow);
+
+    pos_indx[index3] =
+        add(
+            ib,
+            ic,
+            pOverflow);
+
+    return;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: decompress_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    indx[] -- array of type Word16 -- position and sign of
+                                      8 pulses (compressed)
+
+ Outputs:
+    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 type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    PURPOSE: decompression 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
+
+ d8_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 void decompress_code(
+    Word16 indx[],      /* i : position and sign of 8 pulses (compressed) */
+    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 ia;
+    Word16 ib;
+    Word16 MSBs;
+    Word16 LSBs;
+    Word16 MSBs0_24;
+    Word32 tempWord32;
+
+    for (i = 0; i < NB_TRACK_MR102; i++)
+    {
+        sign_indx[i] = indx[i];
+    }
+
+    /*
+      First index: 10x10x10 -> 2x5x2x5x2x5-> 125x2x2x2 -> 7+1x3 bits
+      MSBs = indx[NB_TRACK]/8;
+      LSBs = indx[NB_TRACK]%8;
+      */
+    MSBs = indx[NB_TRACK_MR102] >> 3;
+
+    LSBs = indx[NB_TRACK_MR102] & 0x7;
+
+    decompress10(
+        MSBs,
+        LSBs,
+        0,
+        4,
+        1,
+        pos_indx,
+        pOverflow);
+
+    /*
+      Second index: 10x10x10 -> 2x5x2x5x2x5-> 125x2x2x2 -> 7+1x3 bits
+      MSBs = indx[NB_TRACK+1]/8;
+      LSBs = indx[NB_TRACK+1]%8;
+      */
+    MSBs = indx[NB_TRACK_MR102+1] >> 3;
+
+    LSBs = indx[NB_TRACK_MR102+1] & 0x7;
+
+    decompress10(
+        MSBs,
+        LSBs,
+        2,
+        6,
+        5,
+        pos_indx,
+        pOverflow);
+
+    /*
+      Third index: 10x10 -> 2x5x2x5-> 25x2x2 -> 5+1x2 bits
+      MSBs = indx[NB_TRACK+2]/4;
+      LSBs = indx[NB_TRACK+2]%4;
+      MSBs0_24 = (MSBs*25+12)/32;
+      if ((MSBs0_24/5)%2==1)
+         pos_indx[3] = (4-(MSBs0_24%5))*2 + LSBs%2;
+      else
+         pos_indx[3] = (MSBs0_24%5)*2 + LSBs%2;
+      pos_indx[7] = (MSBs0_24/5)*2 + LSBs/2;
+      */
+
+    MSBs = indx[NB_TRACK_MR102+2] >> 2;
+
+    LSBs = indx[NB_TRACK_MR102+2] & 0x3;
+
+    tempWord32 =
+        L_mult(
+            MSBs,
+            25,
+            pOverflow);
+
+    ia =
+        (Word16)
+        L_shr(
+            tempWord32,
+            1,
+            pOverflow);
+
+    ia += 12;
+
+    MSBs0_24 = ia >> 5;
+
+
+    ia =
+        mult(
+            MSBs0_24,
+            6554,
+            pOverflow);
+
+    ia &= 1;
+
+
+    ib =
+        mult(
+            MSBs0_24,
+            6554,
+            pOverflow);
+
+    tempWord32 =
+        L_mult(
+            ib,
+            5,
+            pOverflow);
+
+
+    ib = MSBs0_24 - (Word16)(tempWord32 >> 1);
+
+    if (ia == 1)
+    {
+        ib = 4 - ib;
+
+    }
+
+
+    ib =
+        shl(
+            ib,
+            1,
+            pOverflow);
+
+    ia = LSBs & 0x1;
+
+    pos_indx[3] =
+        add(
+            ib,
+            ia,
+            pOverflow);
+
+    ia =
+        mult(
+            MSBs0_24,
+            6554,
+            pOverflow);
+
+    ia =
+        shl(
+            ia,
+            1,
+            pOverflow);
+
+    pos_indx[7] = ia + (LSBs >> 1);
+
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dec_8i40_31bits
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    index   array of type Word16 --  index of 8 pulses (sign+position)
+
+ Outputs:
+    cod     array of type Word16 --  algebraic (fixed) codebook excitation
+    pOverflow pointer to type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Builds the innovative codevector from the received
+           index of algebraic codebook.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d8_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 dec_8i40_31bits(
+    Word16 index[],    /* i : index of 8 pulses (sign+position)         */
+    Word16 cod[],      /* o : algebraic (fixed) codebook excitation     */
+    Flag  *pOverflow   /* o : Flag set when overflow occurs             */
+)
+{
+    Word16 i;
+    Word16 j;
+    Word16 pos1;
+    Word16 pos2;
+    Word16 sign;
+
+    Word16 linear_signs[NB_TRACK_MR102];
+    Word16 linear_codewords[NB_PULSE];
+
+    for (i = 0; i < L_CODE; i++)
+    {
+        cod[i] = 0;
+    }
+
+    decompress_code(
+        index,
+        linear_signs,
+        linear_codewords,
+        pOverflow);
+
+    /* decode the positions and signs of pulses and build the codeword */
+    for (j = 0; j < NB_TRACK_MR102; j++)    /* NB_TRACK_MR102 = 4 */
+    {
+        /* position of pulse "j" */
+
+        pos1 = (linear_codewords[j] << 2) + j;
+
+
+        if (linear_signs[j] == 0)
+        {
+            sign = POS_CODE; /* +1.0 */
+        }
+        else
+        {
+            sign = -NEG_CODE; /* -1.0 */
+        }
+
+        if (pos1 < L_SUBFR)
+        {
+            cod[pos1] = sign;    /* avoid buffer overflow */
+        }
+
+        /* compute index i */
+        /* position of pulse "j+4" */
+
+        pos2 = (linear_codewords[j + 4] << 2) + j;
+
+
+        if (pos2 < pos1)
+        {
+            sign = negate(sign);
+        }
+
+        if (pos2 < L_SUBFR)
+        {
+            cod[pos2] += sign;     /* avoid buffer overflow */
+        }
+
+
+    } /* for (j = 0; j < NB_TRACK_MR102; j++) */
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.h b/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.h
new file mode 100644
index 0000000..162685f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d8_31pf.h
@@ -0,0 +1,120 @@
+/* ------------------------------------------------------------------
+ * 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/d2_9pf.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: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the d8_31pf.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef d8_31pf_h
+#define d8_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 dec_8i40_31bits(
+        Word16 index[],     /* i : index of 8 pulses (sign+position)         */
+        Word16 cod[],       /* o : algebraic (fixed) codebook excitation     */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs             */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _d8_31PF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_gain_c.cpp b/media/libstagefright/codecs/amrnb/dec/src/d_gain_c.cpp
new file mode 100644
index 0000000..b6c62f8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d_gain_c.cpp
@@ -0,0 +1,254 @@
+/* ------------------------------------------------------------------
+ * 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/d_gain_c.c
+ Functions: d_gain_c
+
+     Date: 01/29/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated include files and intput/output section. Changed .tab
+              files to .c files.
+
+ 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:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pred_state  = pointer to sturcture type gc_predState. MA predictor state
+    mode        = AMR mode (MR795 or MR122) of type enum Mode
+    index       = received quantization index of type Word16
+    code[]      = pointer to innovation codevector of type Word16
+    pOverflow= pointer to value indicating existence of overflow (Flag)
+
+ Outputs:
+    pred_state  = pointer to sturcture type gc_predState. MA predictor state
+    gain_code   = pointer to decoded innovation gain of type Word16
+    pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Function    : d_gain_code
+  Purpose     : Decode the fixed codebook gain using the received index.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_gain_c.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 "d_gain_c.h"
+#include "typedef.h"
+#include "mode.h"
+
+#include "oper_32b.h"
+#include "cnst.h"
+#include "log2.h"
+#include "pow2.h"
+#include "gc_pred.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.
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    extern const Word16 qua_gain_code[];
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void d_gain_code(
+    gc_predState *pred_state, /* i/o : MA predictor state               */
+    enum Mode mode,           /* i   : AMR mode (MR795 or MR122)        */
+    Word16 index,             /* i   : received quantization index      */
+    Word16 code[],            /* i   : innovation codevector            */
+    Word16 *gain_code,        /* o   : decoded innovation gain          */
+    Flag   *pOverflow
+)
+{
+    Word16 gcode0, exp, frac;
+    const Word16 *p;
+    Word16 qua_ener_MR122, qua_ener;
+    Word16 exp_inn_en;
+    Word16 frac_inn_en;
+    Word32 L_tmp;
+    Word16 tbl_tmp;
+    Word16 temp;
+    /*-------------- Decode codebook gain ---------------*/
+
+    /*-------------------------------------------------------------------*
+     *  predict codebook gain                                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~                                            *
+     *  gc0     = Pow2(int(d)+frac(d))                                   *
+     *          = 2^exp + 2^frac                                         *
+     *                                                                   *
+     *-------------------------------------------------------------------*/
+
+    gc_pred(pred_state, mode, code, &exp, &frac,
+            &exp_inn_en, &frac_inn_en, pOverflow);
+
+    index &= 31;                    /* index < 32, to avoid buffer overflow */
+    tbl_tmp = index + (index << 1);
+
+    p = &qua_gain_code[tbl_tmp];
+
+    /* Different scalings between MR122 and the other modes */
+    temp = sub((Word16)mode, (Word16)MR122, pOverflow);
+    if (temp == 0)
+    {
+        gcode0 = (Word16)(Pow2(exp, frac, pOverflow));    /* predicted gain */
+        gcode0 = shl(gcode0, 4, pOverflow);
+        *gain_code = shl(mult(gcode0, *p++, pOverflow), 1, pOverflow);
+    }
+    else
+    {
+        gcode0 = (Word16)(Pow2(14, frac, pOverflow));
+        L_tmp = L_mult(*p++, gcode0, pOverflow);
+        L_tmp = L_shr(L_tmp, sub(9, exp, pOverflow), pOverflow);
+        *gain_code = extract_h(L_tmp);          /* Q1 */
+    }
+
+    /*-------------------------------------------------------------------*
+     *  update table of past quantized energies                          *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                          *
+     *-------------------------------------------------------------------*/
+    qua_ener_MR122 = *p++;
+    qua_ener = *p++;
+    gc_pred_update(pred_state, qua_ener_MR122, qua_ener);
+
+    return;
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp b/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp
new file mode 100644
index 0000000..99446db
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d_gain_p.cpp
@@ -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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/c/src/d_gain_p.c
+ Functions: d_gain_p
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Removed extra includes
+ (2) Replaced function calls to basic math operations with ANSI C standard
+     mathemtical operations.
+ (3) Placed code in the proper software template.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    mode  -- enumerated type -- AMR mode
+    index -- Word16          -- index of quantization
+ Outputs:
+    None
+
+ Returns:
+    Word16 gain -- (Q14)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Function    : d_gain_pitch
+ Purpose     : Decodes the pitch gain using the received index.
+               output is in Q14
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_gain_p.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 "d_gain_p.h"
+#include "typedef.h"
+#include "mode.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
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    extern const Word16 qua_gain_pitch[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+Word16 d_gain_pitch(       /* return value: gain (Q14)                */
+    enum Mode mode,        /* i   : AMR mode                          */
+    Word16 index           /* i   : index of quantization             */
+)
+{
+    Word16 gain;
+
+    gain = qua_gain_pitch[index];
+
+    if (mode == MR122)
+    {
+        /* clear 2 LSBits */
+        gain &= 0xFFFC;
+    }
+
+    return gain;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf.cpp b/media/libstagefright/codecs/amrnb/dec/src/d_plsf.cpp
new file mode 100644
index 0000000..138193f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d_plsf.cpp
@@ -0,0 +1,207 @@
+/* ------------------------------------------------------------------
+ * 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/d_plsf.c
+ Functions:
+
+
+     Date: 04/14/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed the functions d_plsf_init and d_plsf_exit.
+ The d_plsf related structure is no longer dynamically allocated.
+
+ Description: Removed q_plsf_5.tab from Include section and added
+              q_plsf_5_tbl.h to Include section. Changed "mean_lsf"
+              to "mean_lsf_5" in D_plsf_reset().
+
+ 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
+
+ common part (reset) of LSF decoder
+ module (rest in d_plsf_3.c and d_plsf_5.c)
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "basic_op.h"
+#include "cnst.h"
+#include "copy.h"
+#include "d_plsf.h"
+#include "q_plsf_5_tbl.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: D_plsf_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to structure of type D_plsf_reset
+
+ Outputs:
+    fields of the structure pointed to by state is initialized to zero
+
+ Returns:
+    return_value = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Resets state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_plsf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int D_plsf_reset (D_plsfState *state)
+{
+  Word16 i;
+
+  if (state == (D_plsfState *) NULL){
+      // fprintf(stderr, "D_plsf_reset: invalid parameter\n");
+      return -1;
+  }
+
+  for (i = 0; i < M; i++){
+      state->past_r_q[i] = 0;             // Past quantized prediction error
+  }
+
+  // Past dequantized lsfs
+  Copy(mean_lsf, &state->past_lsf_q[0], M);
+
+  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 D_plsf_reset(D_plsfState *state)
+{
+    Word16 i;
+
+    if (state == (D_plsfState *) NULL)
+    {
+        /* fprintf(stderr, "D_plsf_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    for (i = 0; i < M; i++)
+    {
+        state->past_r_q[i] = 0;             /* Past quantized prediction error */
+    }
+
+    /* Past dequantized lsfs */
+    Copy(mean_lsf_5, &state->past_lsf_q[0], M);
+
+    return 0;
+
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf_3.cpp b/media/libstagefright/codecs/amrnb/dec/src/d_plsf_3.cpp
new file mode 100644
index 0000000..7b31d04
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d_plsf_3.cpp
@@ -0,0 +1,496 @@
+/* ------------------------------------------------------------------
+ * 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/d_plsf_3.c
+ Functions: D_plsf_3
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- Pointer to type struct D_plsfState
+    mode -- enum Mode -- coder mode
+    bfi -- Word16 -- bad frame indicator (set to 1 if a bad frame is received)
+    indice -- Pointer to type Word16 -- quantization indices of
+                                        3 submatrices, Q0
+
+ Outputs:
+    st -- Pointer to type struct D_plsfState
+    lsp1_q -- Pointer to type Word16 -- quantized 1st LSP vector Q15
+    pOverflow -- Pointer to type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE: Decodes the LSP parameters using the received quantization
+          indices.1st order MA prediction and split by 3 vector
+          quantization (split-VQ)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_plsf_3.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 "d_plsf.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+#include "copy.h"
+#include "q_plsf_3_tbl.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define ALPHA     29491     /* ALPHA    ->  0.9                            */
+#define ONE_ALPHA 3277      /* ONE_ALPHA-> (1.0-ALPHA)                     */
+
+
+/*----------------------------------------------------------------------------
+; 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 D_plsf_3(
+    D_plsfState *st,   /* i/o: State struct                               */
+    enum Mode mode,    /* i  : coder mode                                 */
+    Word16 bfi,        /* i  : bad frame indicator (set to 1 if a         */
+    /*      bad frame is received)                     */
+    Word16 * indice,   /* i  : quantization indices of 3 submatrices, Q0  */
+    Word16 * lsp1_q,   /* o  : quantized 1st LSP vector,              Q15 */
+    Flag  *pOverflow   /* o : Flag set when overflow occurs               */
+)
+{
+    Word16 i;
+    Word16 temp;
+    Word16 index;
+
+    Word16 lsf1_r[M];
+    Word16 lsf1_q[M];
+
+    if (bfi != 0)   /* if bad frame */
+    {
+        /* use the past LSFs slightly shifted towards their mean */
+
+        for (i = 0; i < M; i++)
+        {
+            /* lsfi_q[i] = ALPHA*past_lsf_q[i] + ONE_ALPHA*mean_lsf[i]; */
+            temp =
+                mult(
+                    st->past_lsf_q[i],
+                    ALPHA,
+                    pOverflow);
+
+            index =
+                mult(
+                    mean_lsf_3[i],
+                    ONE_ALPHA,
+                    pOverflow);
+
+            lsf1_q[i] =
+                add(
+                    index,
+                    temp,
+                    pOverflow);
+        }
+
+        /* estimate past quantized residual to be used in next frame */
+        if (mode != MRDTX)
+        {
+            for (i = 0; i < M; i++)
+            {
+                /* temp  = mean_lsf[i] +  past_r2_q[i] * PRED_FAC; */
+
+                temp =
+                    mult(
+                        st->past_r_q[i],
+                        pred_fac_3[i],
+                        pOverflow);
+
+                temp =
+                    add(
+                        mean_lsf_3[i],
+                        temp,
+                        pOverflow);
+
+                st->past_r_q[i] =
+                    sub(
+                        lsf1_q[i],
+                        temp,
+                        pOverflow);
+            }
+
+        } /* if (mode == MRDTX) */
+        else
+        {
+            for (i = 0; i < M; i++)
+            {
+                /* temp  = mean_lsf[i] +  past_r2_q[i]; */
+
+                temp =
+                    add(
+                        mean_lsf_3[i],
+                        st->past_r_q[i],
+                        pOverflow);
+
+                st->past_r_q[i] =
+                    sub(
+                        lsf1_q[i],
+                        temp,
+                        pOverflow);
+            }
+        }
+
+    } /* if (bfi != 0) */
+
+    else  /* if good LSFs received */
+    {
+
+        Word16 index_limit_1 = 0;
+        Word16 index_limit_2 = (DICO2_SIZE - 1) * 3;
+        Word16 index_limit_3 = 0;
+
+        const Word16 *p_cb1;
+        const Word16 *p_cb2;
+        const Word16 *p_cb3;
+        const Word16 *p_dico;
+
+
+        p_cb2 = dico2_lsf_3;    /* size DICO2_SIZE*3 */
+
+        if ((mode == MR475) || (mode == MR515))
+        {   /* MR475, MR515 */
+            p_cb1 = dico1_lsf_3;    /* size DICO1_SIZE*3 */
+            p_cb3 = mr515_3_lsf;    /* size MR515_3_SIZE*4 */
+
+            index_limit_1 = (DICO1_SIZE - 1) * 3;
+            index_limit_3 = (MR515_3_SIZE - 1) * 4;
+
+        }
+        else if (mode == MR795)
+        {   /* MR795 */
+            p_cb1 = mr795_1_lsf;    /* size MR795_1_SIZE*3 */
+            p_cb3 = dico3_lsf_3;    /* size DICO3_SIZE*4 */
+
+            index_limit_1 = (MR795_1_SIZE - 1) * 3;
+            index_limit_3 = (DICO3_SIZE - 1) * 4;
+
+        }
+        else
+        {   /* MR59, MR67, MR74, MR102, MRDTX */
+            p_cb1 = dico1_lsf_3;    /* size DICO1_SIZE*3 */
+            p_cb3 = dico3_lsf_3;    /* size DICO3_SIZE*4 */
+
+            index_limit_1 = (DICO1_SIZE - 1) * 3;
+            index_limit_3 = (DICO3_SIZE - 1) * 4;
+
+        }
+
+        /* decode prediction residuals from 3 received indices */
+
+        index = *indice++;
+
+        /* temp = 3*index; */
+        temp = index + (index << 1);
+
+        if (temp > index_limit_1)
+        {
+            temp = index_limit_1;  /* avoid buffer overrun */
+        }
+
+        p_dico = &p_cb1[temp];
+
+        lsf1_r[0] = *p_dico++;
+        lsf1_r[1] = *p_dico++;
+        lsf1_r[2] = *p_dico++;
+
+        index = *indice++;
+
+        if (mode == MR475 || mode == MR515)
+        {   /* MR475, MR515 only using every second entry */
+            index <<= 1;
+        }
+
+        /* temp = 3*index */
+        temp = index + (index << 1);
+
+        if (temp > index_limit_2)
+        {
+            temp = index_limit_2;  /* avoid buffer overrun */
+        }
+
+        p_dico = &p_cb2[temp];
+
+        lsf1_r[3] = *p_dico++;
+        lsf1_r[4] = *p_dico++;
+        lsf1_r[5] = *p_dico++;
+
+        index = *indice++;
+
+        temp = index << 2;
+
+        if (temp > index_limit_3)
+        {
+            temp = index_limit_3;  /* avoid buffer overrun */
+        }
+
+
+        p_dico = &p_cb3[temp];
+
+        lsf1_r[6] = *p_dico++;
+        lsf1_r[7] = *p_dico++;
+        lsf1_r[8] = *p_dico++;
+        lsf1_r[9] = *p_dico++;
+
+        /* Compute quantized LSFs and update the past quantized residual */
+
+        if (mode != MRDTX)
+        {
+            for (i = 0; i < M; i++)
+            {
+                temp =
+                    mult(
+                        st->past_r_q[i],
+                        pred_fac_3[i],
+                        pOverflow);
+
+                temp =
+                    add(
+                        mean_lsf_3[i],
+                        temp,
+                        pOverflow);
+
+                lsf1_q[i] =
+                    add(
+                        lsf1_r[i],
+                        temp,
+                        pOverflow);
+
+                st->past_r_q[i] = lsf1_r[i];
+            }
+        }
+        else
+        {
+            for (i = 0; i < M; i++)
+            {
+                temp =
+                    add(
+                        mean_lsf_3[i],
+                        st->past_r_q[i],
+                        pOverflow);
+
+                lsf1_q[i] =
+                    add(
+                        lsf1_r[i],
+                        temp,
+                        pOverflow);
+
+                st->past_r_q[i] = lsf1_r[i];
+            }
+        }
+
+    }
+
+    /* verification that LSFs has minimum distance of LSF_GAP Hz */
+
+    Reorder_lsf(
+        lsf1_q,
+        LSF_GAP,
+        M,
+        pOverflow);
+
+    Copy(
+        lsf1_q,
+        st->past_lsf_q,
+        M);
+
+    /*  convert LSFs to the cosine domain */
+
+    Lsf_lsp(
+        lsf1_q,
+        lsp1_q,
+        M,
+        pOverflow);
+
+    return;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Init_D_plsf_3
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type D_plsfState
+    index = Word16, past_rq_init[] index [0, 7]
+
+ Outputs:
+    st = pointer to a structure of type D_plsfState
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes the D_plsfState structure.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_plsf_3.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 Init_D_plsf_3(
+    D_plsfState *st,      /* i/o: State struct                */
+    Word16       index    /* i  : past_rq_init[] index [0, 7] */)
+{
+    Copy(
+        &past_rq_init[index * M],
+        st->past_r_q,
+        M);
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/d_plsf_5.cpp b/media/libstagefright/codecs/amrnb/dec/src/d_plsf_5.cpp
new file mode 100644
index 0000000..08b690d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/d_plsf_5.cpp
@@ -0,0 +1,539 @@
+/* ------------------------------------------------------------------
+ * 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/d_plsf_5.c
+
+     Date: 04/24/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Made changes based on review meeting.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Updated to accept new parameter, Flag *pOverflow.
+
+ Description:
+ (1) Removed "count.h" and "basic_op.h" and replaced with individual include
+     files (add.h, sub.h, etc.)
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Added #ifdef __cplusplus around extern'ed table.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "d_plsf.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+#include "cnst.h"
+#include "copy.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here. Include conditional
+    ; compile variables also.
+    ----------------------------------------------------------------------------*/
+    /* ALPHA    ->  0.95       */
+    /* ONE_ALPHA-> (1.0-ALPHA) */
+#define ALPHA     31128
+#define ONE_ALPHA 1639
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    /* These tables are defined in q_plsf_5_tbl.c */
+    extern const Word16 mean_lsf_5[];
+    extern const Word16 dico1_lsf_5[];
+    extern const Word16 dico2_lsf_5[];
+    extern const Word16 dico3_lsf_5[];
+    extern const Word16 dico4_lsf_5[];
+    extern const Word16 dico5_lsf_5[];
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: D_plsf_5
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type D_plsfState
+    bfi = bad frame indicator; set to 1 if a bad frame is received (Word16)
+    indice = pointer to quantization indices of 5 submatrices (Word16)
+    lsp1_q = pointer to the quantized 1st LSP vector (Word16)
+    lsp2_q = pointer to the quantized 2nd LSP vector (Word16)
+
+ Outputs:
+    lsp1_q points to the updated quantized 1st LSP vector
+    lsp2_q points to the updated quantized 2nd LSP vector
+    Flag  *pOverflow  -- Flag set when overflow occurs.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function decodes the 2 sets of LSP parameters in a frame using the
+ received quantization indices.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ d_plsf_5.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int D_plsf_5 (
+    D_plsfState *st,    // i/o: State variables
+    Word16 bfi,         // i  : bad frame indicator (set to 1 if a bad
+                                frame is received)
+    Word16 *indice,     // i  : quantization indices of 5 submatrices, Q0
+    Word16 *lsp1_q,     // o  : quantized 1st LSP vector (M),          Q15
+    Word16 *lsp2_q      // o  : quantized 2nd LSP vector (M),          Q15
+)
+{
+    Word16 i;
+    const Word16 *p_dico;
+    Word16 temp, sign;
+    Word16 lsf1_r[M], lsf2_r[M];
+    Word16 lsf1_q[M], lsf2_q[M];
+
+    if (bfi != 0)                               // if bad frame
+    {
+        // use the past LSFs slightly shifted towards their mean
+
+        for (i = 0; i < M; i++)
+        {
+            // lsfi_q[i] = ALPHA*st->past_lsf_q[i] + ONE_ALPHA*mean_lsf[i];
+
+            lsf1_q[i] = add (mult (st->past_lsf_q[i], ALPHA),
+                             mult (mean_lsf[i], ONE_ALPHA));
+
+            lsf2_q[i] = lsf1_q[i];
+        }
+
+        // estimate past quantized residual to be used in next frame
+
+        for (i = 0; i < M; i++)
+        {
+            // temp  = mean_lsf[i] +  st->past_r_q[i] * LSP_PRED_FAC_MR122;
+
+            temp = add (mean_lsf[i], mult (st->past_r_q[i],
+                                           LSP_PRED_FAC_MR122));
+
+            st->past_r_q[i] = sub (lsf2_q[i], temp);
+        }
+    }
+    else
+        // if good LSFs received
+    {
+        // decode prediction residuals from 5 received indices
+
+        p_dico = &dico1_lsf[shl (indice[0], 2)];
+        lsf1_r[0] = *p_dico++;
+        lsf1_r[1] = *p_dico++;
+        lsf2_r[0] = *p_dico++;
+        lsf2_r[1] = *p_dico++;
+
+        p_dico = &dico2_lsf[shl (indice[1], 2)];
+        lsf1_r[2] = *p_dico++;
+        lsf1_r[3] = *p_dico++;
+        lsf2_r[2] = *p_dico++;
+        lsf2_r[3] = *p_dico++;
+
+        sign = indice[2] & 1;
+        i = shr (indice[2], 1);
+        p_dico = &dico3_lsf[shl (i, 2)];
+
+        if (sign == 0)
+        {
+            lsf1_r[4] = *p_dico++;
+            lsf1_r[5] = *p_dico++;
+            lsf2_r[4] = *p_dico++;
+            lsf2_r[5] = *p_dico++;
+        }
+        else
+        {
+            lsf1_r[4] = negate (*p_dico++);
+            lsf1_r[5] = negate (*p_dico++);
+            lsf2_r[4] = negate (*p_dico++);
+            lsf2_r[5] = negate (*p_dico++);
+        }
+
+        p_dico = &dico4_lsf[shl (indice[3], 2)];
+        lsf1_r[6] = *p_dico++;
+        lsf1_r[7] = *p_dico++;
+        lsf2_r[6] = *p_dico++;
+        lsf2_r[7] = *p_dico++;
+
+        p_dico = &dico5_lsf[shl (indice[4], 2)];
+        lsf1_r[8] = *p_dico++;
+        lsf1_r[9] = *p_dico++;
+        lsf2_r[8] = *p_dico++;
+        lsf2_r[9] = *p_dico++;
+
+        // Compute quantized LSFs and update the past quantized residual
+        for (i = 0; i < M; i++)
+        {
+            temp = add (mean_lsf[i], mult (st->past_r_q[i],
+                                           LSP_PRED_FAC_MR122));
+            lsf1_q[i] = add (lsf1_r[i], temp);
+            lsf2_q[i] = add (lsf2_r[i], temp);
+            st->past_r_q[i] = lsf2_r[i];
+        }
+    }
+
+    // verification that LSFs have minimum distance of LSF_GAP Hz
+
+    Reorder_lsf (lsf1_q, LSF_GAP, M);
+    Reorder_lsf (lsf2_q, LSF_GAP, M);
+
+    Copy (lsf2_q, st->past_lsf_q, M);
+
+    //  convert LSFs to the cosine domain
+
+    Lsf_lsp (lsf1_q, lsp1_q, M);
+    Lsf_lsp (lsf2_q, lsp2_q, M);
+
+    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 D_plsf_5(
+    D_plsfState *st,    /* i/o: State variables                             */
+    Word16 bfi,         /* i  : bad frame indicator (set to 1 if a bad
+                                frame is received)                          */
+    Word16 *indice,     /* i  : quantization indices of 5 submatrices, Q0   */
+    Word16 *lsp1_q,     /* o  : quantized 1st LSP vector (M),          Q15  */
+    Word16 *lsp2_q,     /* o  : quantized 2nd LSP vector (M),          Q15  */
+    Flag  *pOverflow    /* o : Flag set when overflow occurs                */
+)
+{
+    register Word16 i;
+    Word16 temp;
+    Word16 sign;
+
+    const Word16 *p_dico;
+
+    Word16 lsf1_r[M];
+    Word16 lsf2_r[M];
+    Word16 lsf1_q[M];
+    Word16 lsf2_q[M];
+
+    if (bfi != 0)                               /* if bad frame */
+    {
+        /* use the past LSFs slightly shifted towards their mean */
+
+        for (i = 0; i < M; i++)
+        {
+            /*
+             *  lsfi_q[i] = ALPHA*st->past_lsf_q[i] +
+             *  ONE_ALPHA*mean_lsf[i];
+             */
+
+            temp =
+                mult(
+                    st->past_lsf_q[i],
+                    ALPHA,
+                    pOverflow);
+
+            sign =
+                mult(
+                    *(mean_lsf_5 + i),
+                    ONE_ALPHA,
+                    pOverflow);
+
+            *(lsf1_q + i) =
+                add(
+                    sign,
+                    temp,
+                    pOverflow);
+
+            *(lsf2_q + i) = *(lsf1_q + i);
+
+            /*
+             * estimate past quantized residual to be used in
+             * next frame
+             */
+
+            /*
+             * temp  = mean_lsf[i] +
+             * st->past_r_q[i] * LSP_PRED_FAC_MR122;
+             */
+
+            temp =
+                mult(
+                    st->past_r_q[i],
+                    LSP_PRED_FAC_MR122,
+                    pOverflow);
+
+            temp =
+                add(
+                    *(mean_lsf_5 + i),
+                    temp,
+                    pOverflow);
+
+            st->past_r_q[i] =
+                sub(
+                    *(lsf2_q + i),
+                    temp,
+                    pOverflow);
+        }
+    }
+    else
+        /* if good LSFs received */
+    {
+        /* decode prediction residuals from 5 received indices */
+
+        temp =
+            shl(
+                *(indice),
+                2,
+                pOverflow);
+
+        p_dico = &dico1_lsf_5[temp];
+
+        *(lsf1_r + 0) = *p_dico++;
+        *(lsf1_r + 1) = *p_dico++;
+        *(lsf2_r + 0) = *p_dico++;
+        *(lsf2_r + 1) = *p_dico++;
+
+        temp =
+            shl(
+                *(indice + 1),
+                2,
+                pOverflow);
+
+        p_dico = &dico2_lsf_5[temp];
+
+        *(lsf1_r + 2) = *p_dico++;
+        *(lsf1_r + 3) = *p_dico++;
+        *(lsf2_r + 2) = *p_dico++;
+        *(lsf2_r + 3) = *p_dico++;
+
+        sign = *(indice + 2) & 1;
+
+        if (*(indice + 2) < 0)
+        {
+            i = ~(~(*(indice + 2)) >> 1);
+        }
+        else
+        {
+            i = *(indice + 2) >> 1;
+        }
+
+        temp =
+            shl(
+                i,
+                2,
+                pOverflow);
+
+        p_dico = &dico3_lsf_5[temp];
+
+        if (sign == 0)
+        {
+            *(lsf1_r + 4) = *p_dico++;
+            *(lsf1_r + 5) = *p_dico++;
+            *(lsf2_r + 4) = *p_dico++;
+            *(lsf2_r + 5) = *p_dico++;
+        }
+        else
+        {
+            *(lsf1_r + 4) = negate(*p_dico++);
+            *(lsf1_r + 5) = negate(*p_dico++);
+            *(lsf2_r + 4) = negate(*p_dico++);
+            *(lsf2_r + 5) = negate(*p_dico++);
+        }
+
+        temp =
+            shl(
+                *(indice + 3),
+                2,
+                pOverflow);
+
+        p_dico = &dico4_lsf_5[temp];
+
+        *(lsf1_r + 6) = *p_dico++;
+        *(lsf1_r + 7) = *p_dico++;
+        *(lsf2_r + 6) = *p_dico++;
+        *(lsf2_r + 7) = *p_dico++;
+
+        temp =
+            shl(
+                *(indice + 4),
+                2,
+                pOverflow);
+
+        p_dico = &dico5_lsf_5[temp];
+
+        *(lsf1_r + 8) = *p_dico++;
+        *(lsf1_r + 9) = *p_dico++;
+        *(lsf2_r + 8) = *p_dico++;
+        *(lsf2_r + 9) = *p_dico++;
+
+        /* Compute quantized LSFs and update the past quantized
+        residual */
+        for (i = 0; i < M; i++)
+        {
+            temp =
+                mult(
+                    st->past_r_q[i],
+                    LSP_PRED_FAC_MR122,
+                    pOverflow);
+
+            temp =
+                add(
+                    *(mean_lsf_5 + i),
+                    temp,
+                    pOverflow);
+
+            *(lsf1_q + i) =
+                add(
+                    *(lsf1_r + i),
+                    temp,
+                    pOverflow);
+
+            *(lsf2_q + i) =
+                add(
+                    *(lsf2_r + i),
+                    temp,
+                    pOverflow);
+
+            st->past_r_q[i] = *(lsf2_r + i);
+        }
+    }
+
+    /* verification that LSFs have minimum distance of LSF_GAP Hz */
+
+    Reorder_lsf(
+        lsf1_q,
+        LSF_GAP,
+        M,
+        pOverflow);
+
+    Reorder_lsf(
+        lsf2_q,
+        LSF_GAP,
+        M,
+        pOverflow);
+
+    Copy(
+        lsf2_q,
+        st->past_lsf_q,
+        M);
+
+    /*  convert LSFs to the cosine domain */
+
+    Lsf_lsp(
+        lsf1_q,
+        lsp1_q,
+        M,
+        pOverflow);
+
+    Lsf_lsp(
+        lsf2_q,
+        lsp2_q,
+        M,
+        pOverflow);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_amr.cpp b/media/libstagefright/codecs/amrnb/dec/src/dec_amr.cpp
new file mode 100644
index 0000000..9190aea
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_amr.cpp
@@ -0,0 +1,2374 @@
+/* ------------------------------------------------------------------
+ * 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/dec_amr.c
+ Funtions: Decoder_amr_init
+           Decoder_amr_reset
+           Decoder_amr
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the function used to decode one speech frame using a given
+ codec mode. The functions used to initialize, reset, and exit are also
+ included in this file.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "dec_amr.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "copy.h"
+#include "set_zero.h"
+#include "syn_filt.h"
+#include "d_plsf.h"
+#include "agc.h"
+#include "int_lpc.h"
+#include "dec_gain.h"
+#include "dec_lag3.h"
+#include "dec_lag6.h"
+#include "d2_9pf.h"
+#include "d2_11pf.h"
+#include "d3_14pf.h"
+#include "d4_17pf.h"
+#include "d8_31pf.h"
+#include "d1035pf.h"
+#include "pred_lt.h"
+#include "d_gain_p.h"
+#include "d_gain_c.h"
+#include "dec_gain.h"
+#include "ec_gains.h"
+#include "ph_disp.h"
+#include "c_g_aver.h"
+#include "int_lsf.h"
+#include "lsp_lsf.h"
+#include "lsp_avg.h"
+#include "bgnscd.h"
+#include "ex_ctrl.h"
+#include "sqrt_l.h"
+#include "frame.h"
+#include "bitno_tab.h"
+#include "b_cn_cod.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: Decoder_amr_init
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a pointer to structures of type Decoder_amrState
+
+ Outputs:
+    structure pointed to by the pointer which is pointed to by state is
+      initialized to each field's initial values
+
+    state pointer points to the address of the memory allocated by
+      Decoder_amr_init function
+
+ Returns:
+    return_value = 0, if the initialization was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function allocates and initializes state memory used by the Decoder_amr
+ function. It stores the pointer to the filter status structure in state. This
+ pointer has to be passed to Decoder_amr in each call. The function returns
+ 0, if initialization was successful and -1, otherwise.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Decoder_amr_init (Decoder_amrState **state)
+{
+  Decoder_amrState* s;
+  Word16 i;
+
+  if (state == (Decoder_amrState **) NULL){
+      fprintf(stderr, "Decoder_amr_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (Decoder_amrState *) malloc(sizeof(Decoder_amrState))) == NULL){
+      fprintf(stderr, "Decoder_amr_init: can not malloc state structure\n");
+      return -1;
+  }
+
+  s->T0_lagBuff = 40;
+  s->inBackgroundNoise = 0;
+  s->voicedHangover = 0;
+  for (i = 0; i < 9; i++)
+     s->ltpGainHistory[i] = 0;
+
+  s->lsfState = NULL;
+  s->ec_gain_p_st = NULL;
+  s->ec_gain_c_st = NULL;
+  s->pred_state = NULL;
+  s->ph_disp_st = NULL;
+  s->dtxDecoderState = NULL;
+
+  if (D_plsf_init(&s->lsfState) ||
+      ec_gain_pitch_init(&s->ec_gain_p_st) ||
+      ec_gain_code_init(&s->ec_gain_c_st) ||
+      gc_pred_init(&s->pred_state) ||
+      Cb_gain_average_init(&s->Cb_gain_averState) ||
+      lsp_avg_init(&s->lsp_avg_st) ||
+      Bgn_scd_init(&s->background_state) ||
+      ph_disp_init(&s->ph_disp_st) ||
+      dtx_dec_init(&s->dtxDecoderState)) {
+      Decoder_amr_exit(&s);
+      return -1;
+  }
+
+  Decoder_amr_reset(s, (enum Mode)0);
+  *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 Decoder_amr_init(Decoder_amrState *s)
+{
+    Word16 i;
+
+    if (s == (Decoder_amrState *) NULL)
+    {
+        /* fprint(stderr, "Decoder_amr_init: invalid parameter\n");  */
+        return(-1);
+    }
+
+    s->T0_lagBuff = 40;
+    s->inBackgroundNoise = 0;
+    s->voicedHangover = 0;
+
+    /* Initialize overflow Flag */
+
+    s->overflow = 0;
+
+    for (i = 0; i < LTP_GAIN_HISTORY_LEN; i++)
+    {
+        s->ltpGainHistory[i] = 0;
+    }
+
+    D_plsf_reset(&s->lsfState);
+    ec_gain_pitch_reset(&s->ec_gain_p_st);
+    ec_gain_code_reset(&s->ec_gain_c_st);
+    Cb_gain_average_reset(&s->Cb_gain_averState);
+    lsp_avg_reset(&s->lsp_avg_st);
+    Bgn_scd_reset(&s->background_state);
+    ph_disp_reset(&s->ph_disp_st);
+    dtx_dec_reset(&s->dtxDecoderState);
+    gc_pred_reset(&s->pred_state);
+
+    Decoder_amr_reset(s, MR475);
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Decoder_amr_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type Decoder_amrState
+    mode = codec mode (enum Mode)
+
+ Outputs:
+    structure pointed to by state is initialized to its reset value
+
+ Returns:
+    return_value = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets the state memory used by the Decoder_amr function. It
+ returns a 0, if reset was successful and -1, otherwise.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Decoder_amr_reset (Decoder_amrState *state, enum Mode mode)
+{
+  Word16 i;
+
+  if (state == (Decoder_amrState *) NULL){
+      fprintf(stderr, "Decoder_amr_reset: invalid parameter\n");
+      return -1;
+  }
+
+  // Initialize static pointer
+  state->exc = state->old_exc + PIT_MAX + L_INTERPOL;
+
+  // Static vectors to zero
+  Set_zero (state->old_exc, PIT_MAX + L_INTERPOL);
+
+  if (mode != MRDTX)
+     Set_zero (state->mem_syn, M);
+
+  // initialize pitch sharpening
+  state->sharp = SHARPMIN;
+  state->old_T0 = 40;
+
+  // Initialize state->lsp_old []
+
+  if (mode != MRDTX) {
+      Copy(lsp_init_data, &state->lsp_old[0], M);
+  }
+
+  // Initialize memories of bad frame handling
+  state->prev_bf = 0;
+  state->prev_pdf = 0;
+  state->state = 0;
+
+  state->T0_lagBuff = 40;
+  state->inBackgroundNoise = 0;
+  state->voicedHangover = 0;
+  if (mode != MRDTX) {
+      for (i=0;i<9;i++)
+          state->excEnergyHist[i] = 0;
+  }
+
+  for (i = 0; i < 9; i++)
+     state->ltpGainHistory[i] = 0;
+
+  Cb_gain_average_reset(state->Cb_gain_averState);
+  if (mode != MRDTX)
+     lsp_avg_reset(state->lsp_avg_st);
+  D_plsf_reset(state->lsfState);
+  ec_gain_pitch_reset(state->ec_gain_p_st);
+  ec_gain_code_reset(state->ec_gain_c_st);
+
+  if (mode != MRDTX)
+     gc_pred_reset(state->pred_state);
+
+  Bgn_scd_reset(state->background_state);
+  state->nodataSeed = 21845;
+  ph_disp_reset(state->ph_disp_st);
+  if (mode != MRDTX)
+     dtx_dec_reset(state->dtxDecoderState);
+
+  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 Decoder_amr_reset(Decoder_amrState *state, enum Mode mode)
+{
+    Word16 i;
+
+    if (state == (Decoder_amrState *) NULL)
+    {
+        /* fprint(stderr, "Decoder_amr_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    /* Initialize static pointer */
+    state->exc = state->old_exc + PIT_MAX + L_INTERPOL;
+
+    /* Static vectors to zero */
+    memset(state->old_exc, 0, sizeof(Word16)*(PIT_MAX + L_INTERPOL));
+
+    if (mode != MRDTX)
+    {
+        memset(state->mem_syn, 0, sizeof(Word16)*M);
+    }
+    /* initialize pitch sharpening */
+    state->sharp = SHARPMIN;
+    state->old_T0 = 40;
+
+    /* Initialize overflow Flag */
+
+    state->overflow = 0;
+
+    /* Initialize state->lsp_old [] */
+
+    if (mode != MRDTX)
+    {
+        state->lsp_old[0] = 30000;
+        state->lsp_old[1] = 26000;
+        state->lsp_old[2] = 21000;
+        state->lsp_old[3] = 15000;
+        state->lsp_old[4] = 8000;
+        state->lsp_old[5] = 0;
+        state->lsp_old[6] = -8000;
+        state->lsp_old[7] = -15000;
+        state->lsp_old[8] = -21000;
+        state->lsp_old[9] = -26000;
+    }
+
+    /* Initialize memories of bad frame handling */
+    state->prev_bf = 0;
+    state->prev_pdf = 0;
+    state->state = 0;
+
+    state->T0_lagBuff = 40;
+    state->inBackgroundNoise = 0;
+    state->voicedHangover = 0;
+    if (mode != MRDTX)
+    {
+        for (i = 0; i < EXC_ENERGY_HIST_LEN; i++)
+        {
+            state->excEnergyHist[i] = 0;
+        }
+    }
+
+    for (i = 0; i < LTP_GAIN_HISTORY_LEN; i++)
+    {
+        state->ltpGainHistory[i] = 0;
+    }
+
+    Cb_gain_average_reset(&(state->Cb_gain_averState));
+    if (mode != MRDTX)
+    {
+        lsp_avg_reset(&(state->lsp_avg_st));
+    }
+    D_plsf_reset(&(state->lsfState));
+    ec_gain_pitch_reset(&(state->ec_gain_p_st));
+    ec_gain_code_reset(&(state->ec_gain_c_st));
+
+    if (mode != MRDTX)
+    {
+        gc_pred_reset(&(state->pred_state));
+    }
+
+    Bgn_scd_reset(&(state->background_state));
+    state->nodataSeed = 21845;
+    ph_disp_reset(&(state->ph_disp_st));
+    if (mode != MRDTX)
+    {
+        dtx_dec_reset(&(state->dtxDecoderState));
+    }
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Decoder_amr
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type Decoder_amrState
+    mode = codec mode (enum Mode)
+    parm = buffer of synthesis parameters (Word16)
+    frame_type = received frame type (enum RXFrameType)
+    synth = buffer containing synthetic speech (Word16)
+    A_t = buffer containing decoded LP filter in 4 subframes (Word16)
+
+ Outputs:
+    structure pointed to by st contains the newly calculated decoder
+      parameters
+    synth buffer contains the decoded speech samples
+    A_t buffer contains the decoded LP filter parameters
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the decoding of one speech frame for a given codec
+ mode.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dec_amr.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Decoder_amr (
+    Decoder_amrState *st,      // i/o : State variables
+    enum Mode mode,            // i   : AMR mode
+    Word16 parm[],             // i   : vector of synthesis parameters
+                                        (PRM_SIZE)
+    enum RXFrameType frame_type, // i   : received frame type
+    Word16 synth[],            // o   : synthesis speech (L_FRAME)
+    Word16 A_t[]               // o   : decoded LP filter in 4 subframes
+                                        (AZ_SIZE)
+)
+{
+    // LPC coefficients
+
+    Word16 *Az;                // Pointer on A_t
+
+    // LSPs
+
+    Word16 lsp_new[M];
+    Word16 lsp_mid[M];
+
+    // LSFs
+
+    Word16 prev_lsf[M];
+    Word16 lsf_i[M];
+
+    // Algebraic codevector
+
+    Word16 code[L_SUBFR];
+
+    // excitation
+
+    Word16 excp[L_SUBFR];
+    Word16 exc_enhanced[L_SUBFR];
+
+    // Scalars
+
+    Word16 i, i_subfr;
+    Word16 T0, T0_frac, index, index_mr475 = 0;
+    Word16 gain_pit, gain_code, gain_code_mix, pit_sharp, pit_flag, pitch_fac;
+    Word16 t0_min, t0_max;
+    Word16 delta_frc_low, delta_frc_range;
+    Word16 tmp_shift;
+    Word16 temp;
+    Word32 L_temp;
+    Word16 flag4;
+    Word16 carefulFlag;
+    Word16 excEnergy;
+    Word16 subfrNr;
+    Word16 evenSubfr = 0;
+
+    Word16 bfi = 0;   // bad frame indication flag
+    Word16 pdfi = 0;  // potential degraded bad frame flag
+
+    enum DTXStateType newDTXState;  // SPEECH , DTX, DTX_MUTE
+
+    // find the new  DTX state  SPEECH OR DTX
+    newDTXState = rx_dtx_handler(st->dtxDecoderState, frame_type);
+
+    // DTX actions
+    if (sub(newDTXState, SPEECH) != 0 )
+    {
+       Decoder_amr_reset (st, MRDTX);
+
+       dtx_dec(st->dtxDecoderState,
+               st->mem_syn,
+               st->lsfState,
+               st->pred_state,
+               st->Cb_gain_averState,
+               newDTXState,
+               mode,
+               parm, synth, A_t);
+       // update average lsp
+
+       Lsf_lsp(st->lsfState->past_lsf_q, st->lsp_old, M);
+       lsp_avg(st->lsp_avg_st, st->lsfState->past_lsf_q);
+       goto the_end;
+    }
+
+    // SPEECH action state machine
+    if ((sub(frame_type, RX_SPEECH_BAD) == 0) ||
+        (sub(frame_type, RX_NO_DATA) == 0) ||
+        (sub(frame_type, RX_ONSET) == 0))
+    {
+       bfi = 1;
+       if ((sub(frame_type, RX_NO_DATA) == 0) ||
+           (sub(frame_type, RX_ONSET) == 0))
+       {
+      build_CN_param(&st->nodataSeed,
+             prmno[mode],
+             bitno[mode],
+             parm);
+       }
+    }
+    else if (sub(frame_type, RX_SPEECH_DEGRADED) == 0)
+    {
+       pdfi = 1;
+    }
+
+    if (bfi != 0)
+    {
+        st->state = add (st->state, 1);
+    }
+    else if (sub (st->state, 6) == 0)
+
+    {
+        st->state = 5;
+    }
+    else
+    {
+        st->state = 0;
+    }
+
+    if (sub (st->state, 6) > 0)
+    {
+        st->state = 6;
+    }
+
+    // If this frame is the first speech frame after CNI period,
+    // set the BFH state machine to an appropriate state depending
+    // on whether there was DTX muting before start of speech or not
+    // If there was DTX muting, the first speech frame is muted.
+    // If there was no DTX muting, the first speech frame is not
+    // muted. The BFH state machine starts from state 5, however, to
+    // keep the audible noise resulting from a SID frame which is
+    // erroneously interpreted as a good speech frame as small as
+    // possible (the decoder output in this case is quickly muted)
+
+    if (sub(st->dtxDecoderState->dtxGlobalState, DTX) == 0)
+    {
+       st->state = 5;
+       st->prev_bf = 0;
+    }
+    else if (sub(st->dtxDecoderState->dtxGlobalState, DTX_MUTE) == 0)
+    {
+       st->state = 5;
+       st->prev_bf = 1;
+    }
+
+    // save old LSFs for CB gain smoothing
+    Copy (st->lsfState->past_lsf_q, prev_lsf, M);
+
+    // decode LSF parameters and generate interpolated lpc coefficients
+       for the 4 subframes
+    if (sub (mode, MR122) != 0)
+    {
+       D_plsf_3(st->lsfState, mode, bfi, parm, lsp_new);
+
+       // Advance synthesis parameters pointer
+       parm += 3;
+
+       Int_lpc_1to3(st->lsp_old, lsp_new, A_t);
+    }
+    else
+    {
+       D_plsf_5 (st->lsfState, bfi, parm, lsp_mid, lsp_new);
+
+       // Advance synthesis parameters pointer
+       parm += 5;
+
+       Int_lpc_1and3 (st->lsp_old, lsp_mid, lsp_new, A_t);
+    }
+
+    // update the LSPs for the next frame
+    for (i = 0; i < M; i++)
+    {
+       st->lsp_old[i] = lsp_new[i];
+    }
+
+    *------------------------------------------------------------------------*
+    *          Loop for every subframe in the analysis frame                 *
+    *------------------------------------------------------------------------*
+    * The subframe size is L_SUBFR and the loop is repeated L_FRAME/L_SUBFR  *
+    *  times                                                                 *
+    *     - decode the pitch delay                                           *
+    *     - decode algebraic code                                            *
+    *     - decode pitch and codebook gains                                  *
+    *     - find the excitation and compute synthesis speech                 *
+    *------------------------------------------------------------------------*
+
+    // pointer to interpolated LPC parameters
+    Az = A_t;
+
+    evenSubfr = 0;
+    subfrNr = -1;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+       subfrNr = add(subfrNr, 1);
+       evenSubfr = sub(1, evenSubfr);
+
+       // flag for first and 3th subframe
+       pit_flag = i_subfr;
+
+       if (sub (i_subfr, L_FRAME_BY2) == 0)
+       {
+          if (sub(mode, MR475) != 0 && sub(mode, MR515) != 0)
+          {
+             pit_flag = 0;
+          }
+       }
+
+       // pitch index
+       index = *parm++;
+
+        *-------------------------------------------------------*
+        * - decode pitch lag and find adaptive codebook vector. *
+        *-------------------------------------------------------*
+
+       if (sub(mode, MR122) != 0)
+       {
+          // flag4 indicates encoding with 4 bit resolution;
+          // this is needed for mode MR475, MR515, MR59 and MR67
+
+          flag4 = 0;
+          if ((sub (mode, MR475) == 0) ||
+              (sub (mode, MR515) == 0) ||
+              (sub (mode, MR59) == 0) ||
+              (sub (mode, MR67) == 0) ) {
+             flag4 = 1;
+          }
+
+           *-------------------------------------------------------*
+           * - get ranges for the t0_min and t0_max                *
+           * - only needed in delta decoding                       *
+           *-------------------------------------------------------*
+
+          delta_frc_low = 5;
+          delta_frc_range = 9;
+
+          if ( sub(mode, MR795) == 0 )
+          {
+             delta_frc_low = 10;
+             delta_frc_range = 19;
+          }
+
+          t0_min = sub(st->old_T0, delta_frc_low);
+          if (sub(t0_min, PIT_MIN) < 0)
+          {
+             t0_min = PIT_MIN;
+          }
+          t0_max = add(t0_min, delta_frc_range);
+          if (sub(t0_max, PIT_MAX) > 0)
+          {
+             t0_max = PIT_MAX;
+             t0_min = sub(t0_max, delta_frc_range);
+          }
+
+          Dec_lag3 (index, t0_min, t0_max, pit_flag, st->old_T0,
+                    &T0, &T0_frac, flag4);
+
+          st->T0_lagBuff = T0;
+
+          if (bfi != 0)
+          {
+             if (sub (st->old_T0, PIT_MAX) < 0)
+             {                                      // Graceful pitch
+                st->old_T0 = add(st->old_T0, 1);    // degradation
+             }
+             T0 = st->old_T0;
+             T0_frac = 0;
+
+             if ( st->inBackgroundNoise != 0 &&
+                  sub(st->voicedHangover, 4) > 0 &&
+                  ((sub(mode, MR475) == 0 ) ||
+                   (sub(mode, MR515) == 0 ) ||
+                   (sub(mode, MR59) == 0) )
+                  )
+             {
+                T0 = st->T0_lagBuff;
+             }
+          }
+
+          Pred_lt_3or6 (st->exc, T0, T0_frac, L_SUBFR, 1);
+       }
+       else
+       {
+          Dec_lag6 (index, PIT_MIN_MR122,
+                    PIT_MAX, pit_flag, &T0, &T0_frac);
+
+          if ( bfi == 0 && (pit_flag == 0 || sub (index, 61) < 0))
+          {
+          }
+          else
+          {
+             st->T0_lagBuff = T0;
+             T0 = st->old_T0;
+             T0_frac = 0;
+          }
+
+          Pred_lt_3or6 (st->exc, T0, T0_frac, L_SUBFR, 0);
+       }
+
+        *-------------------------------------------------------*
+        * - (MR122 only: Decode pitch gain.)                    *
+        * - Decode innovative codebook.                         *
+        * - set pitch sharpening factor                         *
+        *-------------------------------------------------------*
+
+        if (sub (mode, MR475) == 0 || sub (mode, MR515) == 0)
+        {   // MR475, MR515
+           index = *parm++;        // index of position
+           i = *parm++;            // signs
+
+           decode_2i40_9bits (subfrNr, i, index, code);
+
+           pit_sharp = shl (st->sharp, 1);
+        }
+        else if (sub (mode, MR59) == 0)
+        {   // MR59
+           index = *parm++;        // index of position
+           i = *parm++;            // signs
+
+           decode_2i40_11bits (i, index, code);
+
+           pit_sharp = shl (st->sharp, 1);
+        }
+        else if (sub (mode, MR67) == 0)
+        {   // MR67
+           index = *parm++;        // index of position
+           i = *parm++;            // signs
+
+           decode_3i40_14bits (i, index, code);
+
+           pit_sharp = shl (st->sharp, 1);
+        }
+        else if (sub (mode, MR795) <= 0)
+        {   // MR74, MR795
+           index = *parm++;        // index of position
+           i = *parm++;            // signs
+
+           decode_4i40_17bits (i, index, code);
+
+           pit_sharp = shl (st->sharp, 1);
+        }
+        else if (sub (mode, MR102) == 0)
+        {  // MR102
+           dec_8i40_31bits (parm, code);
+           parm += 7;
+
+           pit_sharp = shl (st->sharp, 1);
+        }
+        else
+        {  // MR122
+           index = *parm++;
+           if (bfi != 0)
+           {
+              ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
+           }
+           else
+           {
+              gain_pit = d_gain_pitch (mode, index);
+           }
+           ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
+                                 &gain_pit);
+
+           dec_10i40_35bits (parm, code);
+           parm += 10;
+
+           // pit_sharp = gain_pit;
+           // if (pit_sharp > 1.0) pit_sharp = 1.0;
+
+           pit_sharp = shl (gain_pit, 1);
+        }
+
+         *-------------------------------------------------------*
+         * - Add the pitch contribution to code[].               *
+         *-------------------------------------------------------*
+        for (i = T0; i < L_SUBFR; i++)
+        {
+           temp = mult (code[i - T0], pit_sharp);
+           code[i] = add (code[i], temp);
+        }
+
+         *------------------------------------------------------------*
+         * - Decode codebook gain (MR122) or both pitch               *
+         *   gain and codebook gain (all others)                      *
+         * - Update pitch sharpening "sharp" with quantized gain_pit  *
+         *------------------------------------------------------------*
+
+        if (sub (mode, MR475) == 0)
+        {
+           // read and decode pitch and code gain
+           if (evenSubfr != 0)
+           {
+              index_mr475 = *parm++; // index of gain(s)
+           }
+
+           if (bfi == 0)
+           {
+              Dec_gain(st->pred_state, mode, index_mr475, code,
+                       evenSubfr, &gain_pit, &gain_code);
+           }
+           else
+           {
+              ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
+              ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
+                            &gain_code);
+           }
+           ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
+                                 &gain_pit);
+           ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
+                                &gain_code);
+
+           pit_sharp = gain_pit;
+           if (sub (pit_sharp, SHARPMAX) > 0)
+           {
+               pit_sharp = SHARPMAX;
+           }
+
+        }
+        else if ((sub (mode, MR74) <= 0) ||
+                 (sub (mode, MR102) == 0))
+        {
+            // read and decode pitch and code gain
+            index = *parm++; // index of gain(s)
+
+            if (bfi == 0)
+            {
+               Dec_gain(st->pred_state, mode, index, code,
+                        evenSubfr, &gain_pit, &gain_code);
+            }
+            else
+            {
+               ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
+               ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
+                             &gain_code);
+            }
+            ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
+                                  &gain_pit);
+            ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
+                                 &gain_code);
+
+            pit_sharp = gain_pit;
+            if (sub (pit_sharp, SHARPMAX) > 0)
+            {
+               pit_sharp = SHARPMAX;
+            }
+
+            if (sub (mode, MR102) == 0)
+            {
+               if (sub (st->old_T0, add(L_SUBFR, 5)) > 0)
+               {
+                  pit_sharp = shr(pit_sharp, 2);
+               }
+            }
+        }
+        else
+        {
+           // read and decode pitch gain
+           index = *parm++; // index of gain(s)
+
+           if (sub (mode, MR795) == 0)
+           {
+              // decode pitch gain
+              if (bfi != 0)
+              {
+                 ec_gain_pitch (st->ec_gain_p_st, st->state, &gain_pit);
+              }
+              else
+              {
+                 gain_pit = d_gain_pitch (mode, index);
+              }
+              ec_gain_pitch_update (st->ec_gain_p_st, bfi, st->prev_bf,
+                                    &gain_pit);
+
+              // read and decode code gain
+              index = *parm++;
+              if (bfi == 0)
+              {
+                 d_gain_code (st->pred_state, mode, index, code, &gain_code);
+              }
+              else
+              {
+                 ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
+                               &gain_code);
+              }
+              ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
+                                   &gain_code);
+
+              pit_sharp = gain_pit;
+              if (sub (pit_sharp, SHARPMAX) > 0)
+              {
+                 pit_sharp = SHARPMAX;
+              }
+           }
+           else
+           { // MR122
+              if (bfi == 0)
+              {
+                 d_gain_code (st->pred_state, mode, index, code, &gain_code);
+              }
+              else
+              {
+                 ec_gain_code (st->ec_gain_c_st, st->pred_state, st->state,
+                               &gain_code);
+              }
+              ec_gain_code_update (st->ec_gain_c_st, bfi, st->prev_bf,
+                                   &gain_code);
+
+              pit_sharp = gain_pit;
+           }
+        }
+
+        // store pitch sharpening for next subframe
+        // (for modes which use the previous pitch gain for
+        // pitch sharpening in the search phase)
+        // do not update sharpening in even subframes for MR475
+        if (sub(mode, MR475) != 0 || evenSubfr == 0)
+        {
+            st->sharp = gain_pit;
+            if (sub (st->sharp, SHARPMAX) > 0)
+            {
+                st->sharp = SHARPMAX;
+            }
+        }
+
+        pit_sharp = shl (pit_sharp, 1);
+        if (sub (pit_sharp, 16384) > 0)
+        {
+           for (i = 0; i < L_SUBFR; i++)
+            {
+               temp = mult (st->exc[i], pit_sharp);
+               L_temp = L_mult (temp, gain_pit);
+               if (sub(mode, MR122)==0)
+               {
+                  L_temp = L_shr (L_temp, 1);
+               }
+               excp[i] = pv_round (L_temp);
+            }
+        }
+
+         *-------------------------------------------------------*
+         * - Store list of LTP gains needed in the source        *
+         *   characteristic detector (SCD)                       *
+         *-------------------------------------------------------*
+        if ( bfi == 0 )
+        {
+           for (i = 0; i < 8; i++)
+           {
+              st->ltpGainHistory[i] = st->ltpGainHistory[i+1];
+           }
+           st->ltpGainHistory[8] = gain_pit;
+        }
+
+         *-------------------------------------------------------*
+         * - Limit gain_pit if in background noise and BFI       *
+         *   for MR475, MR515, MR59                              *
+         *-------------------------------------------------------*
+
+        if ( (st->prev_bf != 0 || bfi != 0) && st->inBackgroundNoise != 0 &&
+             ((sub(mode, MR475) == 0) ||
+              (sub(mode, MR515) == 0) ||
+              (sub(mode, MR59) == 0))
+             )
+        {
+           if ( sub (gain_pit, 12288) > 0)    // if (gain_pit > 0.75) in Q14
+              gain_pit = add( shr( sub(gain_pit, 12288), 1 ), 12288 );
+              // gain_pit = (gain_pit-0.75)/2.0 + 0.75;
+
+           if ( sub (gain_pit, 14745) > 0)    // if (gain_pit > 0.90) in Q14
+           {
+              gain_pit = 14745;
+           }
+        }
+
+         *-------------------------------------------------------*
+         *  Calculate CB mixed gain                              *
+         *-------------------------------------------------------*
+        Int_lsf(prev_lsf, st->lsfState->past_lsf_q, i_subfr, lsf_i);
+        gain_code_mix = Cb_gain_average(
+            st->Cb_gain_averState, mode, gain_code,
+            lsf_i, st->lsp_avg_st->lsp_meanSave, bfi,
+            st->prev_bf, pdfi, st->prev_pdf,
+            st->inBackgroundNoise, st->voicedHangover);
+
+        // make sure that MR74, MR795, MR122 have original code_gain
+        if ((sub(mode, MR67) > 0) && (sub(mode, MR102) != 0) )
+           // MR74, MR795, MR122
+        {
+           gain_code_mix = gain_code;
+        }
+
+         *-------------------------------------------------------*
+         * - Find the total excitation.                          *
+         * - Find synthesis speech corresponding to st->exc[].   *
+         *-------------------------------------------------------*
+        if (sub(mode, MR102) <= 0) // MR475, MR515, MR59, MR67, MR74, MR795, MR102
+        {
+           pitch_fac = gain_pit;
+           tmp_shift = 1;
+        }
+        else       // MR122
+        {
+           pitch_fac = shr (gain_pit, 1);
+           tmp_shift = 2;
+        }
+
+        // copy unscaled LTP excitation to exc_enhanced (used in phase
+         * dispersion below) and compute total excitation for LTP feedback
+
+        for (i = 0; i < L_SUBFR; i++)
+        {
+           exc_enhanced[i] = st->exc[i];
+
+           // st->exc[i] = gain_pit*st->exc[i] + gain_code*code[i];
+           L_temp = L_mult (st->exc[i], pitch_fac);
+                                                      // 12.2: Q0 * Q13
+                                                      //  7.4: Q0 * Q14
+           L_temp = L_mac (L_temp, code[i], gain_code);
+                                                      // 12.2: Q12 * Q1
+                                                      //  7.4: Q13 * Q1
+           L_temp = L_shl (L_temp, tmp_shift);                   // Q16
+           st->exc[i] = pv_round (L_temp);
+        }
+
+         *-------------------------------------------------------*
+         * - Adaptive phase dispersion                           *
+         *-------------------------------------------------------*
+        ph_disp_release(st->ph_disp_st); // free phase dispersion adaption
+
+        if ( ((sub(mode, MR475) == 0) ||
+              (sub(mode, MR515) == 0) ||
+              (sub(mode, MR59) == 0))   &&
+             sub(st->voicedHangover, 3) > 0 &&
+             st->inBackgroundNoise != 0 &&
+             bfi != 0 )
+        {
+           ph_disp_lock(st->ph_disp_st); // Always Use full Phase Disp.
+        }                                // if error in bg noise
+
+        // apply phase dispersion to innovation (if enabled) and
+           compute total excitation for synthesis part
+        ph_disp(st->ph_disp_st, mode,
+                exc_enhanced, gain_code_mix, gain_pit, code,
+                pitch_fac, tmp_shift);
+
+         *-------------------------------------------------------*
+         * - The Excitation control module are active during BFI.*
+         * - Conceal drops in signal energy if in bg noise.      *
+         *-------------------------------------------------------*
+
+        L_temp = 0;
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            L_temp = L_mac (L_temp, exc_enhanced[i], exc_enhanced[i] );
+        }
+
+        L_temp = L_shr (L_temp, 1);     // excEnergy = sqrt(L_temp) in Q0
+        L_temp = sqrt_l_exp(L_temp, &temp); // function result
+        L_temp = L_shr(L_temp, add( shr(temp, 1), 15));
+        L_temp = L_shr(L_temp, 2);       // To cope with 16-bit and
+        excEnergy = extract_l(L_temp);   // scaling in ex_ctrl()
+
+        if ( ((sub (mode, MR475) == 0) ||
+              (sub (mode, MR515) == 0) ||
+              (sub (mode, MR59) == 0))  &&
+             sub(st->voicedHangover, 5) > 0 &&
+             st->inBackgroundNoise != 0 &&
+             sub(st->state, 4) < 0 &&
+             ( (pdfi != 0 && st->prev_pdf != 0) ||
+                bfi != 0 ||
+                st->prev_bf != 0) )
+        {
+           carefulFlag = 0;
+           if ( pdfi != 0 && bfi == 0 )
+           {
+              carefulFlag = 1;
+           }
+
+           Ex_ctrl(exc_enhanced,
+                   excEnergy,
+                   st->excEnergyHist,
+                   st->voicedHangover,
+                   st->prev_bf,
+                   carefulFlag);
+        }
+
+        if ( st->inBackgroundNoise != 0 &&
+             ( bfi != 0 || st->prev_bf != 0 ) &&
+             sub(st->state, 4) < 0 )
+        {
+           ; // do nothing!
+        }
+        else
+        {
+           // Update energy history for all modes
+           for (i = 0; i < 8; i++)
+           {
+              st->excEnergyHist[i] = st->excEnergyHist[i+1];
+           }
+           st->excEnergyHist[8] = excEnergy;
+        }
+         *-------------------------------------------------------*
+         * Excitation control module end.                        *
+         *-------------------------------------------------------*
+
+        if (sub (pit_sharp, 16384) > 0)
+        {
+           for (i = 0; i < L_SUBFR; i++)
+           {
+              excp[i] = add (excp[i], exc_enhanced[i]);
+           }
+           agc2 (exc_enhanced, excp, L_SUBFR);
+           Overflow = 0;
+           Syn_filt (Az, excp, &synth[i_subfr], L_SUBFR,
+                     st->mem_syn, 0);
+        }
+        else
+        {
+           Overflow = 0;
+           Syn_filt (Az, exc_enhanced, &synth[i_subfr], L_SUBFR,
+                     st->mem_syn, 0);
+        }
+
+        if (Overflow != 0)    // Test for overflow
+        {
+           for (i = 0; i < PIT_MAX + L_INTERPOL + L_SUBFR; i++)
+           {
+              st->old_exc[i] = shr(st->old_exc[i], 2);
+           }
+           for (i = 0; i < L_SUBFR; i++)
+           {
+              exc_enhanced[i] = shr(exc_enhanced[i], 2);
+           }
+           Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR, st->mem_syn, 1);
+        }
+        else
+        {
+           Copy(&synth[i_subfr+L_SUBFR-M], st->mem_syn, M);
+        }
+
+         *--------------------------------------------------*
+         * Update signal for next frame.                    *
+         * -> shift to the left by L_SUBFR  st->exc[]       *
+         *--------------------------------------------------*
+
+        Copy (&st->old_exc[L_SUBFR], &st->old_exc[0], PIT_MAX + L_INTERPOL);
+
+        // interpolated LPC parameters for next subframe
+        Az += MP1;
+
+        // store T0 for next subframe
+        st->old_T0 = T0;
+    }
+
+     *-------------------------------------------------------*
+     * Call the Source Characteristic Detector which updates *
+     * st->inBackgroundNoise and st->voicedHangover.         *
+     *-------------------------------------------------------*
+
+    st->inBackgroundNoise = Bgn_scd(st->background_state,
+                                    &(st->ltpGainHistory[0]),
+                                    &(synth[0]),
+                                    &(st->voicedHangover) );
+
+    dtx_dec_activity_update(st->dtxDecoderState,
+                            st->lsfState->past_lsf_q,
+                            synth);
+
+    // store bfi for next subframe
+    st->prev_bf = bfi;
+    st->prev_pdf = pdfi;
+
+     *--------------------------------------------------*
+     * Calculate the LSF averages on the eight          *
+     * previous frames                                  *
+     *--------------------------------------------------*
+
+    lsp_avg(st->lsp_avg_st, st->lsfState->past_lsf_q);
+
+the_end:
+    st->dtxDecoderState->dtxGlobalState = newDTXState;
+
+    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 Decoder_amr(
+    Decoder_amrState *st,      /* i/o : State variables                   */
+    enum Mode mode,            /* i   : AMR mode                          */
+    Word16 parm[],             /* i   : vector of synthesis parameters
+                                        (PRM_SIZE)                        */
+    enum RXFrameType frame_type, /* i   : received frame type             */
+    Word16 synth[],            /* o   : synthesis speech (L_FRAME)        */
+    Word16 A_t[]               /* o   : decoded LP filter in 4 subframes
+                                        (AZ_SIZE)                         */
+)
+{
+    /* LPC coefficients */
+
+    Word16 *Az;                /* Pointer on A_t */
+
+    /* LSPs */
+
+    Word16 lsp_new[M];
+    Word16 lsp_mid[M];
+
+    /* LSFs */
+
+    Word16 prev_lsf[M];
+    Word16 lsf_i[M];
+
+    /* Algebraic codevector */
+
+    Word16 code[L_SUBFR];
+
+    /* excitation */
+
+    Word16 excp[L_SUBFR];
+    Word16 exc_enhanced[L_SUBFR];
+
+    /* Scalars */
+
+    Word16 i;
+    Word16 i_subfr;
+    Word16 T0;
+    Word16 T0_frac;
+    Word16 index;
+    Word16 index_mr475 = 0;
+    Word16 gain_pit;
+    Word16 gain_code;
+    Word16 gain_code_mix;
+    Word16 pit_sharp;
+    Word16 pit_flag;
+    Word16 pitch_fac;
+    Word16 t0_min;
+    Word16 t0_max;
+    Word16 delta_frc_low;
+    Word16 delta_frc_range;
+    Word16 tmp_shift;
+    Word16 temp;
+    Word32 L_temp;
+    Word16 flag4;
+    Word16 carefulFlag;
+    Word16 excEnergy;
+    Word16 subfrNr;
+    Word16 evenSubfr = 0;
+
+    Word16 bfi = 0;   /* bad frame indication flag                          */
+    Word16 pdfi = 0;  /* potential degraded bad frame flag                  */
+
+    enum DTXStateType newDTXState;  /* SPEECH , DTX, DTX_MUTE */
+    Flag   *pOverflow = &(st->overflow);     /* Overflow flag            */
+
+
+    /* find the new  DTX state  SPEECH OR DTX */
+    newDTXState = rx_dtx_handler(&(st->dtxDecoderState), frame_type, pOverflow);
+
+    /* DTX actions */
+
+    if (newDTXState != SPEECH)
+    {
+        Decoder_amr_reset(st, MRDTX);
+
+        dtx_dec(&(st->dtxDecoderState),
+                st->mem_syn,
+                &(st->lsfState),
+                &(st->pred_state),
+                &(st->Cb_gain_averState),
+                newDTXState,
+                mode,
+                parm, synth, A_t, pOverflow);
+
+        /* update average lsp */
+        Lsf_lsp(
+            st->lsfState.past_lsf_q,
+            st->lsp_old,
+            M,
+            pOverflow);
+
+        lsp_avg(
+            &(st->lsp_avg_st),
+            st->lsfState.past_lsf_q,
+            pOverflow);
+
+        goto the_end;
+    }
+
+    /* SPEECH action state machine  */
+    if ((frame_type == RX_SPEECH_BAD) || (frame_type == RX_NO_DATA) ||
+            (frame_type == RX_ONSET))
+    {
+        bfi = 1;
+
+        if ((frame_type == RX_NO_DATA) || (frame_type == RX_ONSET))
+        {
+            build_CN_param(&st->nodataSeed,
+                           prmno[mode],
+                           bitno[mode],
+                           parm,
+                           pOverflow);
+        }
+    }
+    else if (frame_type == RX_SPEECH_DEGRADED)
+    {
+        pdfi = 1;
+    }
+
+    if (bfi != 0)
+    {
+        st->state += 1;
+    }
+    else if (st->state == 6)
+
+    {
+        st->state = 5;
+    }
+    else
+    {
+        st->state = 0;
+    }
+
+
+    if (st->state > 6)
+    {
+        st->state = 6;
+    }
+
+    /* If this frame is the first speech frame after CNI period,     */
+    /* set the BFH state machine to an appropriate state depending   */
+    /* on whether there was DTX muting before start of speech or not */
+    /* If there was DTX muting, the first speech frame is muted.     */
+    /* If there was no DTX muting, the first speech frame is not     */
+    /* muted. The BFH state machine starts from state 5, however, to */
+    /* keep the audible noise resulting from a SID frame which is    */
+    /* erroneously interpreted as a good speech frame as small as    */
+    /* possible (the decoder output in this case is quickly muted)   */
+
+    if (st->dtxDecoderState.dtxGlobalState == DTX)
+    {
+        st->state = 5;
+        st->prev_bf = 0;
+    }
+    else if (st->dtxDecoderState.dtxGlobalState == DTX_MUTE)
+    {
+        st->state = 5;
+        st->prev_bf = 1;
+    }
+
+    /* save old LSFs for CB gain smoothing */
+    Copy(st->lsfState.past_lsf_q, prev_lsf, M);
+
+    /* decode LSF parameters and generate interpolated lpc coefficients
+       for the 4 subframes */
+
+    if (mode != MR122)
+    {
+        D_plsf_3(
+            &(st->lsfState),
+            mode,
+            bfi,
+            parm,
+            lsp_new,
+            pOverflow);
+
+        /* Advance synthesis parameters pointer */
+        parm += 3;
+
+        Int_lpc_1to3(
+            st->lsp_old,
+            lsp_new,
+            A_t,
+            pOverflow);
+    }
+    else
+    {
+        D_plsf_5(
+            &(st->lsfState),
+            bfi,
+            parm,
+            lsp_mid,
+            lsp_new,
+            pOverflow);
+
+        /* Advance synthesis parameters pointer */
+        parm += 5;
+
+        Int_lpc_1and3(
+            st->lsp_old,
+            lsp_mid,
+            lsp_new,
+            A_t,
+            pOverflow);
+    }
+
+    /* update the LSPs for the next frame */
+    for (i = 0; i < M; i++)
+    {
+        st->lsp_old[i] = lsp_new[i];
+    }
+
+    /*------------------------------------------------------------------------*
+     *          Loop for every subframe in the analysis frame                 *
+     *------------------------------------------------------------------------*
+     * The subframe size is L_SUBFR and the loop is repeated L_FRAME/L_SUBFR  *
+     *  times                                                                 *
+     *     - decode the pitch delay                                           *
+     *     - decode algebraic code                                            *
+     *     - decode pitch and codebook gains                                  *
+     *     - find the excitation and compute synthesis speech                 *
+     *------------------------------------------------------------------------*/
+
+    /* pointer to interpolated LPC parameters */
+    Az = A_t;
+
+    evenSubfr = 0;
+    subfrNr = -1;
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        subfrNr += 1;
+        evenSubfr = 1 - evenSubfr;
+
+        /* flag for first and 3th subframe */
+        pit_flag = i_subfr;
+
+
+        if (i_subfr == L_FRAME_BY2)
+        {
+            if ((mode != MR475) && (mode != MR515))
+            {
+                pit_flag = 0;
+            }
+        }
+
+        /* pitch index */
+        index = *parm++;
+
+        /*-------------------------------------------------------*
+        * - decode pitch lag and find adaptive codebook vector. *
+        *-------------------------------------------------------*/
+
+        if (mode != MR122)
+        {
+            /* flag4 indicates encoding with 4 bit resolution;     */
+            /* this is needed for mode MR475, MR515, MR59 and MR67 */
+
+            flag4 = 0;
+
+            if ((mode == MR475) || (mode == MR515) || (mode == MR59) ||
+                    (mode == MR67))
+            {
+                flag4 = 1;
+            }
+
+            /*-------------------------------------------------------*
+            * - get ranges for the t0_min and t0_max                *
+            * - only needed in delta decoding                       *
+            *-------------------------------------------------------*/
+
+            delta_frc_low = 5;
+            delta_frc_range = 9;
+
+            if (mode == MR795)
+            {
+                delta_frc_low = 10;
+                delta_frc_range = 19;
+            }
+
+            t0_min = sub(st->old_T0, delta_frc_low, pOverflow);
+
+            if (t0_min < PIT_MIN)
+            {
+                t0_min = PIT_MIN;
+            }
+            t0_max = add(t0_min, delta_frc_range, pOverflow);
+
+            if (t0_max > PIT_MAX)
+            {
+                t0_max = PIT_MAX;
+                t0_min = t0_max - delta_frc_range;
+            }
+
+            Dec_lag3(index, t0_min, t0_max, pit_flag, st->old_T0,
+                     &T0, &T0_frac, flag4, pOverflow);
+
+            st->T0_lagBuff = T0;
+
+            if (bfi != 0)
+            {
+                if (st->old_T0 < PIT_MAX)
+                {                               /* Graceful pitch */
+                    st->old_T0 += 1;            /* degradation    */
+                }
+                T0 = st->old_T0;
+                T0_frac = 0;
+
+                if ((st->inBackgroundNoise != 0) && (st->voicedHangover > 4) &&
+                        ((mode == MR475) || (mode == MR515) || (mode == MR59)))
+                {
+                    T0 = st->T0_lagBuff;
+                }
+            }
+
+            Pred_lt_3or6(st->exc, T0, T0_frac, L_SUBFR, 1, pOverflow);
+        }
+        else
+        {
+            Dec_lag6(index, PIT_MIN_MR122,
+                     PIT_MAX, pit_flag, &T0, &T0_frac, pOverflow);
+
+
+            if (!(bfi == 0 && (pit_flag == 0 || index < 61)))
+            {
+                st->T0_lagBuff = T0;
+                T0 = st->old_T0;
+                T0_frac = 0;
+            }
+
+            Pred_lt_3or6(st->exc, T0, T0_frac, L_SUBFR, 0, pOverflow);
+        }
+
+        /*-------------------------------------------------------*
+         * - (MR122 only: Decode pitch gain.)                    *
+         * - Decode innovative codebook.                         *
+         * - set pitch sharpening factor                         *
+         *-------------------------------------------------------*/
+        if ((mode == MR475) || (mode == MR515))
+        {   /* MR475, MR515 */
+            index = *parm++;        /* index of position */
+            i = *parm++;            /* signs             */
+
+            decode_2i40_9bits(subfrNr, i, index, code, pOverflow);
+
+            L_temp = (Word32)st->sharp << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        else if (mode == MR59)
+        {   /* MR59 */
+            index = *parm++;        /* index of position */
+            i = *parm++;            /* signs             */
+
+            decode_2i40_11bits(i, index, code);
+
+            L_temp = (Word32)st->sharp << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        else if (mode == MR67)
+        {   /* MR67 */
+            index = *parm++;        /* index of position */
+            i = *parm++;            /* signs             */
+
+            decode_3i40_14bits(i, index, code);
+
+            L_temp = (Word32)st->sharp << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        else if (mode <= MR795)
+        {   /* MR74, MR795 */
+            index = *parm++;        /* index of position */
+            i = *parm++;            /* signs             */
+
+            decode_4i40_17bits(i, index, code);
+
+            L_temp = (Word32)st->sharp << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        else if (mode == MR102)
+        {  /* MR102 */
+            dec_8i40_31bits(parm, code, pOverflow);
+            parm += 7;
+
+            L_temp = (Word32)st->sharp << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (st->sharp > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        else
+        {  /* MR122 */
+            index = *parm++;
+
+            if (bfi != 0)
+            {
+                ec_gain_pitch(
+                    &(st->ec_gain_p_st),
+                    st->state,
+                    &gain_pit,
+                    pOverflow);
+            }
+            else
+            {
+                gain_pit = d_gain_pitch(mode, index);
+            }
+            ec_gain_pitch_update(
+                &(st->ec_gain_p_st),
+                bfi,
+                st->prev_bf,
+                &gain_pit,
+                pOverflow);
+
+
+            dec_10i40_35bits(parm, code);
+            parm += 10;
+
+            /* pit_sharp = gain_pit;                   */
+            /* if (pit_sharp > 1.0) pit_sharp = 1.0;   */
+
+            L_temp = (Word32)gain_pit << 1;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                pit_sharp = (gain_pit > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                pit_sharp = (Word16) L_temp;
+            }
+        }
+        /*-------------------------------------------------------*
+         * - Add the pitch contribution to code[].               *
+         *-------------------------------------------------------*/
+        for (i = T0; i < L_SUBFR; i++)
+        {
+            temp = mult(*(code + i - T0), pit_sharp, pOverflow);
+            *(code + i) = add(*(code + i), temp, pOverflow);
+
+        }
+
+        /*------------------------------------------------------------*
+         * - Decode codebook gain (MR122) or both pitch               *
+         *   gain and codebook gain (all others)                      *
+         * - Update pitch sharpening "sharp" with quantized gain_pit  *
+         *------------------------------------------------------------*/
+        if (mode == MR475)
+        {
+            /* read and decode pitch and code gain */
+
+            if (evenSubfr != 0)
+            {
+                index_mr475 = *parm++;         /* index of gain(s) */
+            }
+
+            if (bfi == 0)
+            {
+                Dec_gain(
+                    &(st->pred_state),
+                    mode,
+                    index_mr475,
+                    code,
+                    evenSubfr,
+                    &gain_pit,
+                    &gain_code,
+                    pOverflow);
+            }
+            else
+            {
+                ec_gain_pitch(
+                    &(st->ec_gain_p_st),
+                    st->state,
+                    &gain_pit,
+                    pOverflow);
+
+                ec_gain_code(
+                    &(st->ec_gain_c_st),
+                    &(st->pred_state),
+                    st->state,
+                    &gain_code,
+                    pOverflow);
+            }
+            ec_gain_pitch_update(
+                &st->ec_gain_p_st,
+                bfi,
+                st->prev_bf,
+                &gain_pit,
+                pOverflow);
+
+            ec_gain_code_update(
+                &st->ec_gain_c_st,
+                bfi,
+                st->prev_bf,
+                &gain_code,
+                pOverflow);
+
+            pit_sharp = gain_pit;
+
+            if (pit_sharp > SHARPMAX)
+            {
+                pit_sharp = SHARPMAX;
+            }
+
+        }
+        else if ((mode <= MR74) || (mode == MR102))
+        {
+            /* read and decode pitch and code gain */
+            index = *parm++;                 /* index of gain(s) */
+
+            if (bfi == 0)
+            {
+                Dec_gain(
+                    &(st->pred_state),
+                    mode,
+                    index,
+                    code,
+                    evenSubfr,
+                    &gain_pit,
+                    &gain_code,
+                    pOverflow);
+            }
+            else
+            {
+                ec_gain_pitch(
+                    &(st->ec_gain_p_st),
+                    st->state,
+                    &gain_pit,
+                    pOverflow);
+
+                ec_gain_code(
+                    &(st->ec_gain_c_st),
+                    &(st->pred_state),
+                    st->state,
+                    &gain_code,
+                    pOverflow);
+            }
+
+            ec_gain_pitch_update(
+                &(st->ec_gain_p_st),
+                bfi,
+                st->prev_bf,
+                &gain_pit,
+                pOverflow);
+
+            ec_gain_code_update(
+                &(st->ec_gain_c_st),
+                bfi,
+                st->prev_bf,
+                &gain_code,
+                pOverflow);
+
+            pit_sharp = gain_pit;
+
+            if (pit_sharp > SHARPMAX)
+            {
+                pit_sharp = SHARPMAX;
+            }
+
+            if (mode == MR102)
+            {
+                if (st->old_T0 > (L_SUBFR + 5))
+                {
+                    if (pit_sharp < 0)
+                    {
+                        pit_sharp = ~((~pit_sharp) >> 2);
+                    }
+                    else
+                    {
+                        pit_sharp = pit_sharp >> 2;
+                    }
+                }
+            }
+        }
+        else
+        {
+            /* read and decode pitch gain */
+            index = *parm++;                 /* index of gain(s) */
+
+            if (mode == MR795)
+            {
+                /* decode pitch gain */
+                if (bfi != 0)
+                {
+                    ec_gain_pitch(
+                        &(st->ec_gain_p_st),
+                        st->state,
+                        &gain_pit,
+                        pOverflow);
+                }
+                else
+                {
+                    gain_pit = d_gain_pitch(mode, index);
+                }
+                ec_gain_pitch_update(
+                    &(st->ec_gain_p_st),
+                    bfi,
+                    st->prev_bf,
+                    &gain_pit,
+                    pOverflow);
+
+                /* read and decode code gain */
+                index = *parm++;
+
+                if (bfi == 0)
+                {
+                    d_gain_code(
+                        &(st->pred_state),
+                        mode,
+                        index,
+                        code,
+                        &gain_code,
+                        pOverflow);
+                }
+                else
+                {
+                    ec_gain_code(
+                        &(st->ec_gain_c_st),
+                        &(st->pred_state),
+                        st->state,
+                        &gain_code,
+                        pOverflow);
+                }
+
+                ec_gain_code_update(
+                    &(st->ec_gain_c_st),
+                    bfi,
+                    st->prev_bf,
+                    &gain_code,
+                    pOverflow);
+
+                pit_sharp = gain_pit;
+
+                if (pit_sharp > SHARPMAX)
+                {
+                    pit_sharp = SHARPMAX;
+                }
+            }
+            else
+            { /* MR122 */
+
+                if (bfi == 0)
+                {
+                    d_gain_code(
+                        &(st->pred_state),
+                        mode,
+                        index,
+                        code,
+                        &gain_code,
+                        pOverflow);
+                }
+                else
+                {
+                    ec_gain_code(
+                        &(st->ec_gain_c_st),
+                        &(st->pred_state),
+                        st->state,
+                        &gain_code,
+                        pOverflow);
+                }
+
+                ec_gain_code_update(
+                    &(st->ec_gain_c_st),
+                    bfi,
+                    st->prev_bf,
+                    &gain_code,
+                    pOverflow);
+
+                pit_sharp = gain_pit;
+            }
+        }
+
+        /* store pitch sharpening for next subframe             */
+        /* (for modes which use the previous pitch gain for     */
+        /* pitch sharpening in the search phase)                */
+        /* do not update sharpening in even subframes for MR475 */
+        if ((mode != MR475) || (evenSubfr == 0))
+        {
+            st->sharp = gain_pit;
+
+            if (st->sharp > SHARPMAX)
+            {
+                st->sharp = SHARPMAX;
+            }
+        }
+
+        pit_sharp = shl(pit_sharp, 1, pOverflow);
+
+        if (pit_sharp > 16384)
+        {
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                temp = mult(st->exc[i], pit_sharp, pOverflow);
+                L_temp = L_mult(temp, gain_pit, pOverflow);
+
+                if (mode == MR122)
+                {
+                    if (L_temp < 0)
+                    {
+                        L_temp = ~((~L_temp) >> 1);
+                    }
+                    else
+                    {
+                        L_temp = L_temp >> 1;
+                    }
+                }
+                *(excp + i) = pv_round(L_temp, pOverflow);
+            }
+        }
+
+        /*-------------------------------------------------------*
+         * - Store list of LTP gains needed in the source        *
+         *   characteristic detector (SCD)                       *
+         *-------------------------------------------------------*/
+
+        if (bfi == 0)
+        {
+            for (i = 0; i < 8; i++)
+            {
+                st->ltpGainHistory[i] = st->ltpGainHistory[i+1];
+            }
+            st->ltpGainHistory[8] = gain_pit;
+        }
+
+        /*-------------------------------------------------------*
+        * - Limit gain_pit if in background noise and BFI       *
+        *   for MR475, MR515, MR59                              *
+        *-------------------------------------------------------*/
+
+
+        if ((st->prev_bf != 0 || bfi != 0) && st->inBackgroundNoise != 0 &&
+                ((mode == MR475) || (mode == MR515) || (mode == MR59)))
+        {
+
+            if (gain_pit > 12288)    /* if (gain_pit > 0.75) in Q14*/
+            {
+                gain_pit = ((gain_pit - 12288) >> 1) + 12288;
+                /* gain_pit = (gain_pit-0.75)/2.0 + 0.75; */
+            }
+
+            if (gain_pit > 14745)    /* if (gain_pit > 0.90) in Q14*/
+            {
+                gain_pit = 14745;
+            }
+        }
+
+        /*-------------------------------------------------------*
+         *  Calculate CB mixed gain                              *
+         *-------------------------------------------------------*/
+        Int_lsf(
+            prev_lsf,
+            st->lsfState.past_lsf_q,
+            i_subfr,
+            lsf_i,
+            pOverflow);
+
+        gain_code_mix =
+            Cb_gain_average(
+                &(st->Cb_gain_averState),
+                mode,
+                gain_code,
+                lsf_i,
+                st->lsp_avg_st.lsp_meanSave,
+                bfi,
+                st->prev_bf,
+                pdfi,
+                st->prev_pdf,
+                st->inBackgroundNoise,
+                st->voicedHangover,
+                pOverflow);
+
+        /* make sure that MR74, MR795, MR122 have original code_gain*/
+        if ((mode > MR67) && (mode != MR102))
+            /* MR74, MR795, MR122 */
+        {
+            gain_code_mix = gain_code;
+        }
+
+        /*-------------------------------------------------------*
+         * - Find the total excitation.                          *
+         * - Find synthesis speech corresponding to st->exc[].   *
+         *-------------------------------------------------------*/
+        if (mode <= MR102) /* MR475, MR515, MR59, MR67, MR74, MR795, MR102*/
+        {
+            pitch_fac = gain_pit;
+            tmp_shift = 1;
+        }
+        else       /* MR122 */
+        {
+            if (gain_pit < 0)
+            {
+                pitch_fac = ~((~gain_pit) >> 1);
+            }
+            else
+            {
+                pitch_fac = gain_pit >> 1;
+            }
+            tmp_shift = 2;
+        }
+
+        /* copy unscaled LTP excitation to exc_enhanced (used in phase
+         * dispersion below) and compute total excitation for LTP feedback
+         */
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            exc_enhanced[i] = st->exc[i];
+
+            /* st->exc[i] = gain_pit*st->exc[i] + gain_code*code[i]; */
+            L_temp = L_mult(st->exc[i], pitch_fac, pOverflow);
+            /* 12.2: Q0 * Q13 */
+            /*  7.4: Q0 * Q14 */
+            L_temp = L_mac(L_temp, code[i], gain_code, pOverflow);
+            /* 12.2: Q12 * Q1 */
+            /*  7.4: Q13 * Q1 */
+            L_temp = L_shl(L_temp, tmp_shift, pOverflow);     /* Q16 */
+            st->exc[i] = pv_round(L_temp, pOverflow);
+        }
+
+        /*-------------------------------------------------------*
+         * - Adaptive phase dispersion                           *
+         *-------------------------------------------------------*/
+        ph_disp_release(&(st->ph_disp_st)); /* free phase dispersion adaption */
+
+
+        if (((mode == MR475) || (mode == MR515) || (mode == MR59)) &&
+                (st->voicedHangover > 3) && (st->inBackgroundNoise != 0) &&
+                (bfi != 0))
+        {
+            ph_disp_lock(&(st->ph_disp_st)); /* Always Use full Phase Disp. */
+        }                                 /* if error in bg noise       */
+
+        /* apply phase dispersion to innovation (if enabled) and
+           compute total excitation for synthesis part           */
+        ph_disp(
+            &(st->ph_disp_st),
+            mode,
+            exc_enhanced,
+            gain_code_mix,
+            gain_pit,
+            code,
+            pitch_fac,
+            tmp_shift,
+            pOverflow);
+
+        /*-------------------------------------------------------*
+         * - The Excitation control module are active during BFI.*
+         * - Conceal drops in signal energy if in bg noise.      *
+         *-------------------------------------------------------*/
+        L_temp = 0;
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            L_temp = L_mac(L_temp, *(exc_enhanced + i), *(exc_enhanced + i), pOverflow);
+        }
+
+        /* excEnergy = sqrt(L_temp) in Q0 */
+        if (L_temp < 0)
+        {
+            L_temp = ~((~L_temp) >> 1);
+        }
+        else
+        {
+            L_temp = L_temp >> 1;
+        }
+
+        L_temp = sqrt_l_exp(L_temp, &temp, pOverflow);
+        /* To cope with 16-bit and scaling in ex_ctrl() */
+        L_temp = L_shr(L_temp, (Word16)((temp >> 1) + 15), pOverflow);
+        if (L_temp < 0)
+        {
+            excEnergy = (Word16)(~((~L_temp) >> 2));
+        }
+        else
+        {
+            excEnergy = (Word16)(L_temp >> 2);
+        }
+
+        if (((mode == MR475) || (mode == MR515) || (mode == MR59))  &&
+                (st->voicedHangover > 5) && (st->inBackgroundNoise != 0) &&
+                (st->state < 4) &&
+                ((pdfi != 0 && st->prev_pdf != 0) || bfi != 0 || st->prev_bf != 0))
+        {
+            carefulFlag = 0;
+
+            if (pdfi != 0 && bfi == 0)
+            {
+                carefulFlag = 1;
+            }
+
+            Ex_ctrl(exc_enhanced,
+                    excEnergy,
+                    st->excEnergyHist,
+                    st->voicedHangover,
+                    st->prev_bf,
+                    carefulFlag, pOverflow);
+        }
+
+        if (!((st->inBackgroundNoise != 0) && (bfi != 0 || st->prev_bf != 0) &&
+                (st->state < 4)))
+        {
+            /* Update energy history for all modes */
+            for (i = 0; i < 8; i++)
+            {
+                st->excEnergyHist[i] = st->excEnergyHist[i+1];
+            }
+            st->excEnergyHist[8] = excEnergy;
+        }
+        /*-------------------------------------------------------*
+         * Excitation control module end.                        *
+         *-------------------------------------------------------*/
+        if (pit_sharp > 16384)
+        {
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                *(excp + i) = add(*(excp + i), *(exc_enhanced + i), pOverflow);
+
+            }
+            agc2(exc_enhanced, excp, L_SUBFR, pOverflow);
+            *pOverflow = 0;
+            Syn_filt(Az, excp, &synth[i_subfr], L_SUBFR,
+                     st->mem_syn, 0);
+        }
+        else
+        {
+            *pOverflow = 0;
+            Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR,
+                     st->mem_syn, 0);
+        }
+
+        if (*pOverflow != 0)    /* Test for overflow */
+        {
+            for (i = PIT_MAX + L_INTERPOL + L_SUBFR - 1; i >= 0; i--)
+            {
+                if (st->old_exc[i] < 0)
+                {
+                    st->old_exc[i] = ~((~st->old_exc[i]) >> 2);
+                }
+                else
+                {
+                    st->old_exc[i] = st->old_exc[i] >> 2;
+                }
+
+            }
+
+            for (i = L_SUBFR - 1; i >= 0; i--)
+            {
+                if (*(exc_enhanced + i) < 0)
+                {
+                    *(exc_enhanced + i) = ~((~(*(exc_enhanced + i))) >> 2);
+                }
+                else
+                {
+                    *(exc_enhanced + i) = *(exc_enhanced + i) >> 2;
+                }
+            }
+            Syn_filt(Az, exc_enhanced, &synth[i_subfr], L_SUBFR, st->mem_syn, 1);
+        }
+        else
+        {
+            Copy(&synth[i_subfr+L_SUBFR-M], st->mem_syn, M);
+        }
+
+        /*--------------------------------------------------*
+         * Update signal for next frame.                    *
+         * -> shift to the left by L_SUBFR  st->exc[]       *
+         *--------------------------------------------------*/
+
+        Copy(&st->old_exc[L_SUBFR], &st->old_exc[0], PIT_MAX + L_INTERPOL);
+
+        /* interpolated LPC parameters for next subframe */
+        Az += MP1;
+
+        /* store T0 for next subframe */
+        st->old_T0 = T0;
+    }
+
+    /*-------------------------------------------------------*
+     * Call the Source Characteristic Detector which updates *
+     * st->inBackgroundNoise and st->voicedHangover.         *
+     *-------------------------------------------------------*/
+
+    st->inBackgroundNoise =
+        Bgn_scd(
+            &(st->background_state),
+            &(st->ltpGainHistory[0]),
+            &(synth[0]),
+            &(st->voicedHangover),
+            pOverflow);
+
+    dtx_dec_activity_update(
+        &(st->dtxDecoderState),
+        st->lsfState.past_lsf_q,
+        synth,
+        pOverflow);
+
+    /* store bfi for next subframe */
+    st->prev_bf = bfi;
+    st->prev_pdf = pdfi;
+
+    /*--------------------------------------------------*
+     * Calculate the LSF averages on the eight          *
+     * previous frames                                  *
+     *--------------------------------------------------*/
+    lsp_avg(
+        &(st->lsp_avg_st),
+        st->lsfState.past_lsf_q,
+        pOverflow);
+
+the_end:
+    st->dtxDecoderState.dtxGlobalState = newDTXState;
+
+//    return(0);
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_amr.h b/media/libstagefright/codecs/amrnb/dec/src/dec_amr.h
new file mode 100644
index 0000000..b04137d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_amr.h
@@ -0,0 +1,206 @@
+/* ------------------------------------------------------------------
+ * 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_amr.h
+
+     Date: 02/06/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Update function prototype for Decoder_amr(). Include overflow
+              flag in Decode_amrState structure
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+     File             : dec_amr.h
+     Purpose          : Speech decoder routine.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DEC_AMR_H
+#define DEC_AMR_H "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "cnst.h"
+#include "mode.h"
+#include "dtx_dec.h"
+#include "d_plsf.h"
+#include "gc_pred.h"
+#include "ec_gains.h"
+#include "ph_disp.h"
+#include "c_g_aver.h"
+#include "bgnscd.h"
+#include "lsp_avg.h"
+#include "frame.h"
+
+/*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+#define EXC_ENERGY_HIST_LEN  9
+#define LTP_GAIN_HISTORY_LEN 9
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct Decoder_amrState
+    {
+        /* Excitation vector */
+        Word16 old_exc[L_SUBFR + PIT_MAX + L_INTERPOL];
+        Word16 *exc;
+
+        /* Lsp (Line spectral pairs) */
+        /* Word16 lsp[M]; */      /* Used by CN codec */
+        Word16 lsp_old[M];
+
+        /* Filter's memory */
+        Word16 mem_syn[M];
+
+        /* pitch sharpening */
+        Word16 sharp;
+        Word16 old_T0;
+
+        /* Memories for bad frame handling */
+        Word16 prev_bf;
+        Word16 prev_pdf;
+        Word16 state;
+        Word16 excEnergyHist[EXC_ENERGY_HIST_LEN];
+
+        /* Variable holding received ltpLag, used in background noise and BFI */
+        Word16 T0_lagBuff;
+
+        /* Variables for the source characteristic detector (SCD) */
+        Word16 inBackgroundNoise;
+        Word16 voicedHangover;
+        Word16 ltpGainHistory[LTP_GAIN_HISTORY_LEN];
+
+        Bgn_scdState background_state;
+        Word16 nodataSeed;
+
+        Cb_gain_averageState Cb_gain_averState;
+        lsp_avgState lsp_avg_st;
+
+        D_plsfState lsfState;
+        ec_gain_pitchState ec_gain_p_st;
+        ec_gain_codeState ec_gain_c_st;
+        gc_predState pred_state;
+        ph_dispState ph_disp_st;
+        dtx_decState dtxDecoderState;
+        Flag overflow;
+    } Decoder_amrState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+    /*
+     *  Function    : Decoder_amr_init
+     *  Purpose     : Allocates initializes state memory
+     *  Description : Stores pointer to filter status struct in *st. This
+     *                pointer has to be passed to Decoder_amr in each call.
+     *  Returns     : 0 on success
+     */
+    Word16 Decoder_amr_init(Decoder_amrState *st);
+
+    /*
+     *  Function    : Decoder_amr_reset
+     *  Purpose     : Resets state memory
+     *  Returns     : 0 on success
+     */
+    Word16 Decoder_amr_reset(Decoder_amrState *st, enum Mode mode);
+
+    /*
+     *  Function    : Decoder_amr
+     *  Purpose     : Speech decoder routine.
+     *  Returns     : 0
+     */
+    void Decoder_amr(
+        Decoder_amrState *st,  /* i/o : State variables                       */
+        enum Mode mode,        /* i   : AMR mode                              */
+        Word16 parm[],         /* i   : vector of synthesis parameters
+                                    (PRM_SIZE)                            */
+        enum RXFrameType frame_type, /* i   : received frame type               */
+        Word16 synth[],        /* o   : synthesis speech (L_FRAME)            */
+        Word16 A_t[]           /* o   : decoded LP filter in 4 subframes
+                                    (AZ_SIZE)                             */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* DEC_AMR_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_gain.cpp b/media/libstagefright/codecs/amrnb/dec/src/dec_gain.cpp
new file mode 100644
index 0000000..ceab48d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_gain.cpp
@@ -0,0 +1,305 @@
+/* ------------------------------------------------------------------
+ * 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/dec_gain.c
+ Funtions: dec_gain
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updating include file lists, and other things as per review
+              comments.
+
+ Description: Added fixes to the code as per review comments. Removed nested
+              function calls and declared temp2 as a variable.
+
+ Description: A Word32 was being stored improperly in a Word16.
+
+ Description: Removed qua_gain.tab and qgain475.tab from Include section and
+              added qua_gain_tbl.h and qgain475_tab.h to Include section.
+
+ Description: Changed round 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:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "dec_gain.h"
+#include "typedef.h"
+#include "mode.h"
+#include "cnst.h"
+#include "pow2.h"
+#include "log2.h"
+#include "gc_pred.h"
+#include "basic_op.h"
+#include "qua_gain_tbl.h"
+#include "qgain475_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: dec_gain
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    pred_state = pointer to MA predictor state of type gc_predState
+    index = AMR mode of type enum Mode
+    code[] = pointer to innovative vector of type Word16
+    evenSubfr = Flag for even subframes of type Word16
+    pOverflow = pointer to overflow flag
+
+
+ Outputs:
+    pred_state = pointer to MA predictor state of type gc_predState
+    gain_pit = pointer to pitch gain of type Word16
+    gain_cod = pointer to code gain of type Word16
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      File             : dec_gain.c
+      Purpose          : Decode the pitch and codebook gains
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ agc.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 Dec_gain(
+    gc_predState *pred_state, /* i/o: MA predictor state           */
+    enum Mode mode,           /* i  : AMR mode                     */
+    Word16 index,             /* i  : index of quantization.       */
+    Word16 code[],            /* i  : Innovative vector.           */
+    Word16 evenSubfr,         /* i  : Flag for even subframes      */
+    Word16 * gain_pit,        /* o  : Pitch gain.                  */
+    Word16 * gain_cod,        /* o  : Code gain.                   */
+    Flag   * pOverflow
+)
+{
+    const Word16 *p;
+    Word16 frac;
+    Word16 gcode0;
+    Word16 exp;
+    Word16 qua_ener;
+    Word16 qua_ener_MR122;
+    Word16 g_code;
+    Word32 L_tmp;
+    Word16 temp1;
+    Word16 temp2;
+
+    /* Read the quantized gains (table depends on mode) */
+    index = shl(index, 2, pOverflow);
+
+    if (mode == MR102 || mode == MR74 || mode == MR67)
+    {
+        p = &table_gain_highrates[index];
+
+        *gain_pit = *p++;
+        g_code = *p++;
+        qua_ener_MR122 = *p++;
+        qua_ener = *p;
+    }
+    else
+    {
+        if (mode == MR475)
+        {
+            index += (1 ^ evenSubfr) << 1; /* evenSubfr is 0 or 1 */
+
+            if (index > (MR475_VQ_SIZE*4 - 2))
+            {
+                index = (MR475_VQ_SIZE * 4 - 2); /* avoid possible buffer overflow */
+            }
+
+            p = &table_gain_MR475[index];
+
+            *gain_pit = *p++;
+            g_code = *p++;
+
+            /*---------------------------------------------------------*
+             *  calculate predictor update values (not stored in 4.75  *
+             *  quantizer table to save space):                        *
+             *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  *
+             *                                                         *
+             *   qua_ener       = log2(g)                              *
+             *   qua_ener_MR122 = 20*log10(g)                          *
+             *---------------------------------------------------------*/
+
+            /* Log2(x Q12) = log2(x) + 12 */
+            temp1 = (Word16) L_deposit_l(g_code);
+            Log2(temp1, &exp, &frac, pOverflow);
+            exp = sub(exp, 12, pOverflow);
+
+            temp1 = shr_r(frac, 5, pOverflow);
+            temp2 = shl(exp, 10, pOverflow);
+            qua_ener_MR122 = add(temp1, temp2, pOverflow);
+
+            /* 24660 Q12 ~= 6.0206 = 20*log10(2) */
+            L_tmp = Mpy_32_16(exp, frac, 24660, pOverflow);
+            L_tmp = L_shl(L_tmp, 13, pOverflow);
+            qua_ener = pv_round(L_tmp, pOverflow);
+            /* Q12 * Q0 = Q13 -> Q10 */
+        }
+        else
+        {
+            p = &table_gain_lowrates[index];
+
+            *gain_pit = *p++;
+            g_code = *p++;
+            qua_ener_MR122 = *p++;
+            qua_ener = *p;
+        }
+    }
+
+    /*-------------------------------------------------------------------*
+     *  predict codebook gain                                            *
+     *  ~~~~~~~~~~~~~~~~~~~~~                                            *
+     *  gc0     = Pow2(int(d)+frac(d))                                   *
+     *          = 2^exp + 2^frac                                         *
+     *                                                                   *
+     *  gcode0 (Q14) = 2^14*2^frac = gc0 * 2^(14-exp)                    *
+     *-------------------------------------------------------------------*/
+
+    gc_pred(pred_state, mode, code, &exp, &frac, NULL, NULL, pOverflow);
+
+    gcode0 = (Word16) Pow2(14, frac, pOverflow);
+
+    /*------------------------------------------------------------------*
+     *  read quantized gains, update table of past quantized energies   *
+     *  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   *
+     *  st->past_qua_en(Q10) = 20 * Log10(g_fac) / constant             *
+     *                       = Log2(g_fac)                              *
+     *                       = qua_ener                                 *
+     *                                           constant = 20*Log10(2) *
+     *------------------------------------------------------------------*/
+
+    L_tmp = L_mult(g_code, gcode0, pOverflow);
+    temp1 = sub(10, exp, pOverflow);
+    L_tmp = L_shr(L_tmp, temp1, pOverflow);
+    *gain_cod = extract_h(L_tmp);
+
+    /* update table of past quantized energies */
+
+    gc_pred_update(pred_state, qua_ener_MR122, qua_ener);
+
+    return;
+}
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_gain.h b/media/libstagefright/codecs/amrnb/dec/src/dec_gain.h
new file mode 100644
index 0000000..b9c6a8d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_gain.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/src/include/dec_gain.h
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : dec_gain.h
+      Purpose          : Decode the pitch and codebook gains
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _DEC_GAIN_H_
+#define _DEC_GAIN_H_
+#define dec_gain_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.]
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; 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:  Dec_gain()
+     *   PURPOSE: Decode the pitch and codebook gains
+     */
+    void Dec_gain(
+        gc_predState *pred_state, /* i/o: MA predictor state           */
+        enum Mode mode,           /* i  : AMR mode                     */
+        Word16 index,             /* i  : index of quantization.       */
+        Word16 code[],            /* i  : Innovative vector.           */
+        Word16 evenSubfr,         /* i  : Flag for even subframes      */
+        Word16 * gain_pit,        /* o  : Pitch gain.                  */
+        Word16 * gain_cod,        /* o  : Code gain.                   */
+        Flag   * pOverflow
+    );
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _DEC_GAIN_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_input_format_tab.cpp b/media/libstagefright/codecs/amrnb/dec/src/dec_input_format_tab.cpp
new file mode 100644
index 0000000..a59f5fa
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_input_format_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/dec_input_format_tab.c
+
+     Date: 03/01/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Renamed BytesThisFrame to WmfBytesPerFrame, changed its type
+              from 'const short' to 'const int'. Added If2BytesPerFrame
+              table for IF2 input format. Updated copyright year and I/O
+              definition sections, and added reference document for IF2.
+
+ Description: Renamed WmfBytesPerFrame to WmfDecBytesPerFrame, and
+              If2BytesPerFrame to If2DecBytesPerFrame.
+
+ 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 input 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
+    ----------------------------------------------------------------------------*/
+    /* Table containing the number of core AMR data bytes for                */
+    /* each codec mode for WMF input format(number excludes frame type byte) */
+    extern const Word16 WmfDecBytesPerFrame[16] =
+    {
+        12, /* 4.75 */
+        13, /* 5.15 */
+        15, /* 5.90 */
+        17, /* 6.70 */
+        19, /* 7.40 */
+        20, /* 7.95 */
+        26, /* 10.2 */
+        31, /* 12.2 */
+        5, /* GsmAmr comfort noise */
+        6, /* Gsm-Efr comfort noise */
+        5, /* IS-641 comfort noise */
+        5, /* Pdc-Efr comfort noise */
+        0, /* future use */
+        0, /* future use */
+        0, /* future use */
+        0 /* No transmission */
+    };
+
+    /* Table containing the number of core AMR data bytes for   */
+    /* each codec mode for IF2 input format.                    */
+    extern const Word16 If2DecBytesPerFrame[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/dec/src/dec_lag3.cpp b/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.cpp
new file mode 100644
index 0000000..70baaba
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.cpp
@@ -0,0 +1,407 @@
+/* ------------------------------------------------------------------
+ * 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/dec_lag3.c
+ Functions: Dec_lag3
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Updated to accept new parameter, Flag *pOverflow.
+ (2) Placed file in the proper PV Software template.
+
+ Description:
+ (1) Removed "count.h" and "basic_op.h" and replaced with individual include
+     files (add.h, sub.h, etc.)
+
+ 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 "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    index   -- Word16 -- received pitch index
+    t0_min  -- Word16 -- minimum of search range
+    t0_max  -- Word16 -- maximum of search range
+    i_subfr -- Word16 -- subframe flag
+    T0_prev -- Word16 -- integer pitch delay of last subframe
+                         used in 2nd and 4th subframes
+    flag4   -- Word16 -- flag for encoding with 4 bits
+
+ Outputs:
+
+    T0 -- Pointer to type Word16 -- integer part of pitch lag
+    T0_frac -- Pointer to type Word16 -- fractional part of pitch lag
+    pOverflow -- Pointer to type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+
+              )
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Decoding of fractional pitch lag with 1/3 resolution.
+           Extract the integer and fraction parts of the pitch lag from
+           the received adaptive codebook index.
+
+  See "Enc_lag3.c" for more details about the encoding procedure.
+
+  The fractional lag in 1st and 3rd subframes is encoded with 8 bits
+  while that in 2nd and 4th subframes is relatively encoded with 4, 5
+  and 6 bits depending on the mode.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dec_lag3.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 "dec_lag3.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 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 Dec_lag3(Word16 index,     /* i : received pitch index                 */
+              Word16 t0_min,    /* i : minimum of search range              */
+              Word16 t0_max,    /* i : maximum of search range              */
+              Word16 i_subfr,   /* i : subframe flag                        */
+              Word16 T0_prev,   /* i : integer pitch delay of last subframe
+                                       used in 2nd and 4th subframes        */
+              Word16 * T0,      /* o : integer part of pitch lag            */
+              Word16 * T0_frac, /* o : fractional part of pitch lag         */
+              Word16 flag4,     /* i : flag for encoding with 4 bits        */
+              Flag  *pOverflow  /* o : Flag set when overflow occurs        */
+             )
+{
+    Word16 i;
+    Word16 tmp_lag;
+
+    if (i_subfr == 0)    /* if 1st or 3rd subframe */
+    {
+
+        if (index < 197)
+        {
+
+            tmp_lag = index + 2;
+
+            tmp_lag =
+                mult(
+                    tmp_lag,
+                    10923,
+                    pOverflow);
+
+            i =
+                add(
+                    tmp_lag,
+                    19,
+                    pOverflow);
+
+            *T0 = i;
+
+            /* i = 3 * (*T0) */
+
+            i = add(i, i, pOverflow);
+            i = add(i, *T0, pOverflow);
+
+            tmp_lag =
+                sub(
+                    index,
+                    i,
+                    pOverflow);
+
+            *T0_frac =
+                add(
+                    tmp_lag,
+                    58,
+                    pOverflow);
+        }
+        else
+        {
+            *T0 = index - 112;
+
+            *T0_frac = 0;
+        }
+
+    }
+    else
+    {  /* 2nd or 4th subframe */
+
+        if (flag4 == 0)
+        {
+
+            /* 'normal' decoding: either with 5 or 6 bit resolution */
+
+            i =
+                add(
+                    index,
+                    2,
+                    pOverflow);
+
+            i =
+                mult(
+                    i,
+                    10923,
+                    pOverflow);
+
+            i =
+                sub(
+                    i,
+                    1,
+                    pOverflow);
+
+            *T0 =
+                add(
+                    i,
+                    t0_min,
+                    pOverflow);
+
+            /* i = 3* (*T0) */
+            i = add(add(i, i, pOverflow), i, pOverflow);
+
+            tmp_lag =
+                sub(
+                    index,
+                    2,
+                    pOverflow);
+
+            *T0_frac =
+                sub(
+                    tmp_lag,
+                    i,
+                    pOverflow);
+        }
+        else
+        {
+
+            /* decoding with 4 bit resolution */
+
+            tmp_lag = T0_prev;
+
+            i =
+                sub(
+                    tmp_lag,
+                    t0_min,
+                    pOverflow);
+
+            if (i > 5)
+            {
+                tmp_lag =
+                    add(
+                        t0_min,
+                        5,
+                        pOverflow);
+            }
+
+            i =
+                sub(
+                    t0_max,
+                    tmp_lag,
+                    pOverflow);
+
+            if (i > 4)
+            {
+                tmp_lag =
+                    sub(
+                        t0_max,
+                        4,
+                        pOverflow);
+            }
+
+            if (index < 4)
+            {
+                i =
+                    sub(
+                        tmp_lag,
+                        5,
+                        pOverflow);
+
+                *T0 =
+                    add(
+                        i,
+                        index,
+                        pOverflow);
+
+                *T0_frac = 0;
+            }
+            else
+            {
+                /* 4 >= index < 12 */
+                if (index < 12)
+                {
+                    i = index - 5;
+
+                    i = mult(
+                            i,
+                            10923,
+                            pOverflow);
+
+                    i--;
+
+                    *T0 = add(
+                              i,
+                              tmp_lag,
+                              pOverflow);
+
+                    i = add(
+                            add(
+                                i,
+                                i,
+                                pOverflow),
+                            i,
+                            pOverflow);
+
+                    tmp_lag = index - 9;
+
+                    *T0_frac =
+                        sub(
+                            tmp_lag,
+                            i,
+                            pOverflow);
+                }
+                else
+                {
+                    i = index - 12;
+
+                    i =
+                        add(
+                            i,
+                            tmp_lag,
+                            pOverflow);
+
+                    *T0 =
+                        add(
+                            i,
+                            1,
+                            pOverflow);
+
+                    *T0_frac = 0;
+                }
+            }
+
+        } /* end if (decoding with 4 bit resolution) */
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.h b/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.h
new file mode 100644
index 0000000..e758b92
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_lag3.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/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: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the dec_lag3.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef dec_lag3_h
+#define dec_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
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void Dec_lag3(Word16 index,     /* i : received pitch index                 */
+    Word16 T0_min,    /* i : minimum of search range              */
+    Word16 T0_max,    /* i : maximum of search range              */
+    Word16 i_subfr,   /* i : subframe flag                        */
+    Word16 T0_prev,   /* i : integer pitch delay of last subframe
+                                       used in 2nd and 4th subframes        */
+    Word16 * T0,      /* o : integer part of pitch lag            */
+    Word16 * T0_frac, /* o : fractional part of pitch lag         */
+    Word16 flag4,     /* i : flag for encoding with 4 bits        */
+    Flag   * pOverflow  /* o : Flag set when overflow occurs      */
+                 );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _DEC_LAG_3_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.cpp b/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.cpp
new file mode 100644
index 0000000..7dc7a8d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.cpp
@@ -0,0 +1,337 @@
+/* ------------------------------------------------------------------
+ * 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/dec_lag6.c
+ Functions: Dec_lag6
+
+     Date: 01/31/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+ (1) Updated to accept new parameter, Flag *pOverflow.
+ (2) Placed file in the proper PV Software template.
+
+ Description:
+ (1) Removed "count.h" and "basic_op.h" and replaced with individual include
+     files (add.h, sub.h, etc.)
+
+ 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 "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+ ------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    index   -- Word16 -- received pitch index
+    pit_min  -- Word16 -- minimum pitch lag
+    pit_max  -- Word16 -- maximum pitch lag
+    i_subfr -- Word16 -- subframe flag
+    T0 -- Pointer to type Word16 -- integer part of pitch lag
+
+ Outputs:
+
+    T0 -- Pointer to type Word16 -- integer part of pitch lag
+    T0_frac -- Pointer to type Word16 -- fractional part of pitch lag
+    pOverflow -- Pointer to type Flag -- Flag set when overflow occurs
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ PURPOSE:  Decoding of fractional pitch lag with 1/6 resolution.
+           Extract the integer and fraction parts of the pitch lag from
+           the received adaptive codebook index.
+
+  See "Enc_lag6.c" for more details about the encoding procedure.
+
+  The fractional lag in 1st and 3rd subframes is encoded with 9 bits
+  while that in 2nd and 4th subframes is relatively encoded with 6 bits.
+  Note that in relative encoding 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. In this case, the pitch lag from
+  previous subframe (actually from previous frame) is used.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dec_lag6.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 "dec_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 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 Dec_lag6(
+    Word16 index,      /* input : received pitch index           */
+    Word16 pit_min,    /* input : minimum pitch lag              */
+    Word16 pit_max,    /* input : maximum pitch lag              */
+    Word16 i_subfr,    /* input : subframe flag                  */
+    Word16 *T0,        /* in/out: integer part of pitch lag      */
+    Word16 *T0_frac,   /* output: fractional part of pitch lag   */
+    Flag   *pOverflow  /* o : Flag set when overflow occurs      */
+)
+{
+    Word16 i;
+    Word16 T0_min;
+    Word16 T0_max;
+    Word16 k;
+    Word16 w;
+
+    if (i_subfr == 0)          /* if 1st or 3rd subframe */
+    {
+        if (index < 463)
+        {
+            /* T0 = (index+5)/6 + 17 */
+            i = index + 5;
+            i =
+                mult(
+                    i,
+                    5462,
+                    pOverflow);
+
+            i =
+                add(
+                    i,
+                    17,
+                    pOverflow);
+
+            *T0 = i;
+
+            /* i = 3* (*T0) */
+
+            i = add(i, i, pOverflow);
+            i = add(i, *T0, pOverflow);
+
+            /* *T0_frac = index - T0*6 + 105 */
+
+            i =
+                add(
+                    i,
+                    i,
+                    pOverflow);
+
+            i =
+                sub(
+                    index,
+                    i,
+                    pOverflow);
+
+            *T0_frac =
+                add(
+                    i,
+                    105,
+                    pOverflow);
+        }
+        else
+        {
+            *T0 =
+                sub(
+                    index,
+                    368,
+                    pOverflow);
+
+            *T0_frac = 0;
+        }
+    }
+    else       /* second or fourth subframe */
+    {
+        /* find T0_min and T0_max for 2nd (or 4th) subframe */
+
+        T0_min =
+            sub(
+                *T0,
+                5,
+                pOverflow);
+
+        if (T0_min < pit_min)
+        {
+            T0_min = pit_min;
+        }
+
+        T0_max =
+            add(
+                T0_min,
+                9,
+                pOverflow);
+
+        if (T0_max > pit_max)
+        {
+            T0_max = pit_max;
+
+            T0_min =
+                sub(
+                    T0_max,
+                    9,
+                    pOverflow);
+        }
+
+        /* i = (index+5)/6 - 1 */
+        i =
+            add(
+                index,
+                5,
+                pOverflow);
+
+        i =
+            mult(
+                i,
+                5462,
+                pOverflow);
+
+        i =
+            sub(
+                i,
+                1,
+                pOverflow);
+
+        *T0 =
+            add(
+                i,
+                T0_min,
+                pOverflow);
+
+        /* i = 3* (*T0) */
+
+        w = add(i, i, pOverflow);
+        i = add(i, w, pOverflow);
+
+        i =
+            add(
+                i,
+                i,
+                pOverflow);
+
+        k =
+            sub(
+                index,
+                3,
+                pOverflow);
+
+        *T0_frac =
+            sub(
+                k,
+                i,
+                pOverflow);
+    }
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.h b/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.h
new file mode 100644
index 0000000..7322bc8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dec_lag6.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/dec_lag6.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: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file contains all the constant definitions and prototype definitions
+ needed by the dec_lag6.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef dec_lag6_h
+#define dec_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
+    ----------------------------------------------------------------------------*/
+    void Dec_lag6(
+        Word16 index,      /* input : received pitch index           */
+        Word16 pit_min,    /* input : minimum pitch lag              */
+        Word16 pit_max,    /* input : maximum pitch lag              */
+        Word16 i_subfr,    /* input : subframe flag                  */
+        Word16 *T0,        /* in/out: integer part of pitch lag      */
+        Word16 *T0_frac,   /* output: fractional part of pitch lag   */
+        Flag   * pOverflow  /* o : Flag set when overflow occurs     */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _DEC_LAG_6_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.cpp b/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.cpp
new file mode 100644
index 0000000..9d04373
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.cpp
@@ -0,0 +1,1956 @@
+/* ------------------------------------------------------------------
+ * 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_dec.c
+ Functions:
+           dtx_dec_reset
+           dtx_dec
+           dtx_dec_activity_update
+           rx_dtx_handler
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ These modules decode the comfort noise when in DTX.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "dtx_dec.h"
+#include "typedef.h"
+#include "basic_op.h"
+#include "copy.h"
+#include "set_zero.h"
+#include "mode.h"
+#include "log2.h"
+#include "lsp_az.h"
+#include "pow2.h"
+#include "a_refl.h"
+#include "b_cn_cod.h"
+#include "syn_filt.h"
+#include "lsp_lsf.h"
+#include "reorder.h"
+#include "lsp_tab.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define PN_INITIAL_SEED 0x70816958L   /* Pseudo noise generator seed value  */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/***************************************************
+ * Scaling factors for the lsp variability operation *
+ ***************************************************/
+static const Word16 lsf_hist_mean_scale[M] =
+{
+    20000,
+    20000,
+    20000,
+    20000,
+    20000,
+    18000,
+    16384,
+    8192,
+    0,
+    0
+};
+
+/*************************************************
+ * level adjustment for different modes Q11      *
+ *************************************************/
+static const Word16 dtx_log_en_adjust[9] =
+{
+    -1023, /* MR475 */
+    -878, /* MR515 */
+    -732, /* MR59  */
+    -586, /* MR67  */
+    -440, /* MR74  */
+    -294, /* MR795 */
+    -148, /* MR102 */
+    0, /* MR122 */
+    0, /* MRDTX */
+};
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_dec_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type dtx_decState
+
+ Outputs:
+    Structure pointed to by st is initialized to a set of initial values.
+
+ Returns:
+    return_value = 0 if memory was successfully initialized,
+        otherwise returns -1 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Reset of state memory for dtx_dec.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.3.0, December 12, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_dec_reset (dtx_decState *st)
+{
+   int i;
+
+   if (st == (dtx_decState *) NULL){
+      fprintf(stderr, "dtx_dec_reset: invalid parameter\n");
+      return -1;
+   }
+
+   st->since_last_sid = 0;
+   st->true_sid_period_inv = (1 << 13);
+
+   st->log_en = 3500;
+   st->old_log_en = 3500;
+   // low level noise for better performance in  DTX handover cases
+
+   st->L_pn_seed_rx = PN_INITIAL_SEED;
+
+   // Initialize state->lsp [] and state->lsp_old []
+   Copy(lsp_init_data, &st->lsp[0], M);
+   Copy(lsp_init_data, &st->lsp_old[0], M);
+
+   st->lsf_hist_ptr = 0;
+   st->log_pg_mean = 0;
+   st->log_en_hist_ptr = 0;
+
+   // initialize decoder lsf history
+   Copy(mean_lsf, &st->lsf_hist[0], M);
+
+   for (i = 1; i < DTX_HIST_SIZE; i++)
+   {
+      Copy(&st->lsf_hist[0], &st->lsf_hist[M*i], M);
+   }
+   Set_zero(st->lsf_hist_mean, M*DTX_HIST_SIZE);
+
+   // initialize decoder log frame energy
+   for (i = 0; i < DTX_HIST_SIZE; i++)
+   {
+      st->log_en_hist[i] = st->log_en;
+   }
+
+   st->log_en_adjust = 0;
+
+   st->dtxHangoverCount = DTX_HANG_CONST;
+   st->decAnaElapsedCount = 32767;
+
+   st->sid_frame = 0;
+   st->valid_data = 0;
+   st->dtxHangoverAdded = 0;
+
+   st->dtxGlobalState = DTX;
+   st->data_updated = 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 dtx_dec_reset(dtx_decState *st)
+{
+    Word16 i;
+
+    if (st == (dtx_decState *) NULL)
+    {
+        /* fprint(stderr, "dtx_dec_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    st->since_last_sid = 0;
+    st->true_sid_period_inv = (1 << 13);
+
+    st->log_en = 3500;
+    st->old_log_en = 3500;
+    /* low level noise for better performance in  DTX handover cases*/
+
+    st->L_pn_seed_rx = PN_INITIAL_SEED;
+
+    /* Initialize state->lsp [] */
+    st->lsp[0] = 30000;
+    st->lsp[1] = 26000;
+    st->lsp[2] = 21000;
+    st->lsp[3] = 15000;
+    st->lsp[4] = 8000;
+    st->lsp[5] = 0;
+    st->lsp[6] = -8000;
+    st->lsp[7] = -15000;
+    st->lsp[8] = -21000;
+    st->lsp[9] = -26000;
+
+    /* Initialize state->lsp_old [] */
+    st->lsp_old[0] = 30000;
+    st->lsp_old[1] = 26000;
+    st->lsp_old[2] = 21000;
+    st->lsp_old[3] = 15000;
+    st->lsp_old[4] = 8000;
+    st->lsp_old[5] = 0;
+    st->lsp_old[6] = -8000;
+    st->lsp_old[7] = -15000;
+    st->lsp_old[8] = -21000;
+    st->lsp_old[9] = -26000;
+
+    st->lsf_hist_ptr = 0;
+    st->log_pg_mean = 0;
+    st->log_en_hist_ptr = 0;
+
+    /* initialize decoder lsf history */
+    st->lsf_hist[0] =  1384;
+    st->lsf_hist[1] =  2077;
+    st->lsf_hist[2] =  3420;
+    st->lsf_hist[3] =  5108;
+    st->lsf_hist[4] =  6742;
+    st->lsf_hist[5] =  8122;
+    st->lsf_hist[6] =  9863;
+    st->lsf_hist[7] = 11092;
+    st->lsf_hist[8] = 12714;
+    st->lsf_hist[9] = 13701;
+
+    for (i = 1; i < DTX_HIST_SIZE; i++)
+    {
+        Copy(&st->lsf_hist[0], &st->lsf_hist[M*i], M);
+    }
+    memset(st->lsf_hist_mean, 0, sizeof(Word16)*M*DTX_HIST_SIZE);
+
+    /* initialize decoder log frame energy */
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        st->log_en_hist[i] = st->log_en;
+    }
+
+    st->log_en_adjust = 0;
+
+    st->dtxHangoverCount = DTX_HANG_CONST;
+    st->decAnaElapsedCount = 32767;
+
+    st->sid_frame = 0;
+    st->valid_data = 0;
+    st->dtxHangoverAdded = 0;
+
+    st->dtxGlobalState = DTX;
+    st->data_updated = 0;
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_dec
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type dtx_decState
+    mem_syn = AMR decoder state
+    lsfState = decoder lsf states
+    predState = prediction states
+    averState = CB gain average states
+    new_state = new DTX state
+    mode = AMR mode
+    parm = Vector of synthesis parameters
+
+ Outputs:
+    st points to an updated structure of type dtx_decState
+    mem_syn = AMR decoder state
+    lsfState = decoder lsf states
+    predState = prediction states
+    averState = CB gain average states
+    synth = synthesised speech
+    A_t = decoded LP filter in 4 subframes
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Decode comfort noise when in DTX.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.3.0, December 12, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int dtx_dec(
+   dtx_decState *st,                // i/o : State struct
+   Word16 mem_syn[],                // i/o : AMR decoder state
+   D_plsfState* lsfState,           // i/o : decoder lsf states
+   gc_predState* predState,         // i/o : prediction states
+   Cb_gain_averageState* averState, // i/o : CB gain average states
+   enum DTXStateType new_state,     // i   : new DTX state
+   enum Mode mode,                  // i   : AMR mode
+   Word16 parm[],                   // i   : Vector of synthesis parameters
+   Word16 synth[],                  // o   : synthesised speech
+   Word16 A_t[]                     // o   : decoded LP filter in 4 subframes
+   )
+{
+   Word16 log_en_index;
+   Word16 i, j;
+   Word16 int_fac;
+   Word32 L_log_en_int;
+   Word16 lsp_int[M];
+   Word16 log_en_int_e;
+   Word16 log_en_int_m;
+   Word16 level;
+   Word16 acoeff[M + 1];
+   Word16 refl[M];
+   Word16 pred_err;
+   Word16 ex[L_SUBFR];
+   Word16 ma_pred_init;
+   Word16 log_pg_e, log_pg_m;
+   Word16 log_pg;
+   Flag negative;
+   Word16 lsf_mean;
+   Word32 L_lsf_mean;
+   Word16 lsf_variab_index;
+   Word16 lsf_variab_factor;
+   Word16 lsf_int[M];
+   Word16 lsf_int_variab[M];
+   Word16 lsp_int_variab[M];
+   Word16 acoeff_variab[M + 1];
+
+   Word16 lsf[M];
+   Word32 L_lsf[M];
+   Word16 ptr;
+   Word16 tmp_int_length;
+
+
+    // This function is called if synthesis state is not SPEECH
+    // the globally passed  inputs to this function are
+    // st->sid_frame
+    // st->valid_data
+    // st->dtxHangoverAdded
+    // new_state  (SPEECH, DTX, DTX_MUTE)
+
+   if ((st->dtxHangoverAdded != 0) &&
+       (st->sid_frame != 0))
+   {
+      // sid_first after dtx hangover period
+      // or sid_upd after dtxhangover
+
+      // set log_en_adjust to correct value
+      st->log_en_adjust = dtx_log_en_adjust[mode];
+
+      ptr = add(st->lsf_hist_ptr, M);
+      if (sub(ptr, 80) == 0)
+      {
+         ptr = 0;
+      }
+      Copy( &st->lsf_hist[st->lsf_hist_ptr],&st->lsf_hist[ptr],M);
+
+      ptr = add(st->log_en_hist_ptr,1);
+      if (sub(ptr, DTX_HIST_SIZE) == 0)
+      {
+         ptr = 0;
+      }
+      st->log_en_hist[ptr] = st->log_en_hist[st->log_en_hist_ptr]; // Q11
+
+      // compute mean log energy and lsp
+      // from decoded signal (SID_FIRST)
+      st->log_en = 0;
+      for (i = 0; i < M; i++)
+      {
+         L_lsf[i] = 0;
+      }
+
+      // average energy and lsp
+      for (i = 0; i < DTX_HIST_SIZE; i++)
+      {
+         st->log_en = add(st->log_en,
+                          shr(st->log_en_hist[i],3));
+         for (j = 0; j < M; j++)
+         {
+            L_lsf[j] = L_add(L_lsf[j],
+                             L_deposit_l(st->lsf_hist[i * M + j]));
+         }
+      }
+
+      for (j = 0; j < M; j++)
+      {
+         lsf[j] = extract_l(L_shr(L_lsf[j],3)); // divide by 8
+      }
+
+      Lsf_lsp(lsf, st->lsp, M);
+
+      // make log_en speech coder mode independent
+      // added again later before synthesis
+      st->log_en = sub(st->log_en, st->log_en_adjust);
+
+      // compute lsf variability vector
+      Copy(st->lsf_hist, st->lsf_hist_mean, 80);
+
+      for (i = 0; i < M; i++)
+      {
+         L_lsf_mean = 0;
+         // compute mean lsf
+         for (j = 0; j < 8; j++)
+         {
+            L_lsf_mean = L_add(L_lsf_mean,
+                               L_deposit_l(st->lsf_hist_mean[i+j*M]));
+         }
+
+         lsf_mean = extract_l(L_shr(L_lsf_mean, 3));
+          // subtract mean and limit to within reasonable limits
+          // moreover the upper lsf's are attenuated
+         for (j = 0; j < 8; j++)
+         {
+            // subtract mean
+            st->lsf_hist_mean[i+j*M] =
+               sub(st->lsf_hist_mean[i+j*M], lsf_mean);
+
+            // attenuate deviation from mean, especially for upper lsf's
+            st->lsf_hist_mean[i+j*M] =
+               mult(st->lsf_hist_mean[i+j*M], lsf_hist_mean_scale[i]);
+
+            // limit the deviation
+            if (st->lsf_hist_mean[i+j*M] < 0)
+            {
+               negative = 1;
+            }
+            else
+            {
+               negative = 0;
+            }
+            st->lsf_hist_mean[i+j*M] = abs_s(st->lsf_hist_mean[i+j*M]);
+
+            // apply soft limit
+            if (sub(st->lsf_hist_mean[i+j*M], 655) > 0)
+            {
+               st->lsf_hist_mean[i+j*M] =
+                  add(655, shr(sub(st->lsf_hist_mean[i+j*M], 655), 2));
+            }
+
+            // apply hard limit
+            if (sub(st->lsf_hist_mean[i+j*M], 1310) > 0)
+            {
+               st->lsf_hist_mean[i+j*M] = 1310;
+            }
+            if (negative != 0)
+            {
+               st->lsf_hist_mean[i+j*M] = -st->lsf_hist_mean[i+j*M];
+            }
+
+         }
+      }
+   }
+
+   if (st->sid_frame != 0 )
+   {
+      // Set old SID parameters, always shift
+      // even if there is no new valid_data
+      Copy(st->lsp, st->lsp_old, M);
+      st->old_log_en = st->log_en;
+
+      if (st->valid_data != 0 )  // new data available (no CRC)
+      {
+         // Compute interpolation factor, since the division only works
+         // for values of since_last_sid < 32 we have to limit the
+         // interpolation to 32 frames
+         tmp_int_length = st->since_last_sid;
+         st->since_last_sid = 0;
+
+         if (sub(tmp_int_length, 32) > 0)
+         {
+            tmp_int_length = 32;
+         }
+         if (sub(tmp_int_length, 2) >= 0)
+         {
+            st->true_sid_period_inv = div_s(1 << 10, shl(tmp_int_length, 10));
+         }
+         else
+         {
+            st->true_sid_period_inv = 1 << 14; // 0.5 it Q15
+         }
+
+         Init_D_plsf_3(lsfState, parm[0]);  // temporay initialization
+         D_plsf_3(lsfState, MRDTX, 0, &parm[1], st->lsp);
+         Set_zero(lsfState->past_r_q, M);   // reset for next speech frame
+
+         log_en_index = parm[4];
+         // Q11 and divide by 4
+         st->log_en = shl(log_en_index, (11 - 2));
+
+         // Subtract 2.5 in Q11
+         st->log_en = sub(st->log_en, (2560 * 2));
+
+         // Index 0 is reserved for silence
+         if (log_en_index == 0)
+         {
+            st->log_en = MIN_16;
+         }
+
+         // no interpolation at startup after coder reset
+         // or when SID_UPD has been received right after SPEECH
+         if ((st->data_updated == 0) ||
+             (sub(st->dtxGlobalState, SPEECH) == 0)
+             )
+         {
+            Copy(st->lsp, st->lsp_old, M);
+            st->old_log_en = st->log_en;
+         }
+      } // endif valid_data
+
+      // initialize gain predictor memory of other modes
+      ma_pred_init = sub(shr(st->log_en,1), 9000);
+      if (ma_pred_init > 0)
+      {
+         ma_pred_init = 0;
+      }
+      if (sub(ma_pred_init, -14436) < 0)
+      {
+         ma_pred_init = -14436;
+      }
+
+      predState->past_qua_en[0] = ma_pred_init;
+      predState->past_qua_en[1] = ma_pred_init;
+      predState->past_qua_en[2] = ma_pred_init;
+      predState->past_qua_en[3] = ma_pred_init;
+
+      // past_qua_en for other modes than MR122
+      ma_pred_init = mult(5443, ma_pred_init);
+      // scale down by factor 20*log10(2) in Q15
+      predState->past_qua_en_MR122[0] = ma_pred_init;
+      predState->past_qua_en_MR122[1] = ma_pred_init;
+      predState->past_qua_en_MR122[2] = ma_pred_init;
+      predState->past_qua_en_MR122[3] = ma_pred_init;
+   } // endif sid_frame
+
+   // CN generation
+   // recompute level adjustment factor Q11
+   // st->log_en_adjust = 0.9*st->log_en_adjust +
+   //                     0.1*dtx_log_en_adjust[mode]);
+   st->log_en_adjust = add(mult(st->log_en_adjust, 29491),
+                           shr(mult(shl(dtx_log_en_adjust[mode],5),3277),5));
+
+   // Interpolate SID info
+   int_fac = shl(add(1,st->since_last_sid), 10); // Q10
+   int_fac = mult(int_fac, st->true_sid_period_inv); // Q10 * Q15 -> Q10
+
+   // Maximize to 1.0 in Q10
+   if (sub(int_fac, 1024) > 0)
+   {
+      int_fac = 1024;
+   }
+   int_fac = shl(int_fac, 4); // Q10 -> Q14
+
+   L_log_en_int = L_mult(int_fac, st->log_en); // Q14 * Q11->Q26
+   for(i = 0; i < M; i++)
+   {
+      lsp_int[i] = mult(int_fac, st->lsp[i]);// Q14 * Q15 -> Q14
+   }
+
+   int_fac = sub(16384, int_fac); // 1-k in Q14
+
+   // (Q14 * Q11 -> Q26) + Q26 -> Q26
+   L_log_en_int = L_mac(L_log_en_int, int_fac, st->old_log_en);
+   for(i = 0; i < M; i++)
+   {
+      // Q14 + (Q14 * Q15 -> Q14) -> Q14
+      lsp_int[i] = add(lsp_int[i], mult(int_fac, st->lsp_old[i]));
+      lsp_int[i] = shl(lsp_int[i], 1); // Q14 -> Q15
+   }
+
+   // compute the amount of lsf variability
+   lsf_variab_factor = sub(st->log_pg_mean,2457); // -0.6 in Q12
+   // *0.3 Q12*Q15 -> Q12
+   lsf_variab_factor = sub(4096, mult(lsf_variab_factor, 9830));
+
+   // limit to values between 0..1 in Q12
+   if (sub(lsf_variab_factor, 4096) > 0)
+   {
+      lsf_variab_factor = 4096;
+   }
+   if (lsf_variab_factor < 0)
+   {
+      lsf_variab_factor = 0;
+   }
+   lsf_variab_factor = shl(lsf_variab_factor, 3); // -> Q15
+
+   // get index of vector to do variability with
+   lsf_variab_index = pseudonoise(&st->L_pn_seed_rx, 3);
+
+   // convert to lsf
+   Lsp_lsf(lsp_int, lsf_int, M);
+
+   // apply lsf variability
+   Copy(lsf_int, lsf_int_variab, M);
+   for(i = 0; i < M; i++)
+   {
+      lsf_int_variab[i] = add(lsf_int_variab[i],
+                              mult(lsf_variab_factor,
+                                   st->lsf_hist_mean[i+lsf_variab_index*M]));
+   }
+
+   // make sure that LSP's are ordered
+   Reorder_lsf(lsf_int, LSF_GAP, M);
+   Reorder_lsf(lsf_int_variab, LSF_GAP, M);
+
+   // copy lsf to speech decoders lsf state
+   Copy(lsf_int, lsfState->past_lsf_q, M);
+
+   // convert to lsp
+   Lsf_lsp(lsf_int, lsp_int, M);
+   Lsf_lsp(lsf_int_variab, lsp_int_variab, M);
+
+   // Compute acoeffs Q12 acoeff is used for level
+   // normalization and postfilter, acoeff_variab is
+   // used for synthesis filter
+   // by doing this we make sure that the level
+   // in high frequenncies does not jump up and down
+
+   Lsp_Az(lsp_int, acoeff);
+   Lsp_Az(lsp_int_variab, acoeff_variab);
+
+   // For use in postfilter
+   Copy(acoeff, &A_t[0],           M + 1);
+   Copy(acoeff, &A_t[M + 1],       M + 1);
+   Copy(acoeff, &A_t[2 * (M + 1)], M + 1);
+   Copy(acoeff, &A_t[3 * (M + 1)], M + 1);
+
+   // Compute reflection coefficients Q15
+   A_Refl(&acoeff[1], refl);
+
+   // Compute prediction error in Q15
+   pred_err = MAX_16; // 0.99997 in Q15
+   for (i = 0; i < M; i++)
+   {
+      pred_err = mult(pred_err, sub(MAX_16, mult(refl[i], refl[i])));
+   }
+
+   // compute logarithm of prediction gain
+   Log2(L_deposit_l(pred_err), &log_pg_e, &log_pg_m);
+
+   // convert exponent and mantissa to Word16 Q12
+   log_pg = shl(sub(log_pg_e,15), 12);  // Q12
+   log_pg = shr(sub(0,add(log_pg, shr(log_pg_m, 15-12))), 1);
+   st->log_pg_mean = add(mult(29491,st->log_pg_mean),
+                         mult(3277, log_pg));
+
+   // Compute interpolated log energy
+   L_log_en_int = L_shr(L_log_en_int, 10); // Q26 -> Q16
+
+   // Add 4 in Q16
+   L_log_en_int = L_add(L_log_en_int, 4 * 65536L);
+
+   // subtract prediction gain
+   L_log_en_int = L_sub(L_log_en_int, L_shl(L_deposit_l(log_pg), 4));
+
+   // adjust level to speech coder mode
+   L_log_en_int = L_add(L_log_en_int,
+                        L_shl(L_deposit_l(st->log_en_adjust), 5));
+
+   log_en_int_e = extract_h(L_log_en_int);
+   log_en_int_m = extract_l(L_shr(L_sub(L_log_en_int,
+                                        L_deposit_h(log_en_int_e)), 1));
+   level = extract_l(Pow2(log_en_int_e, log_en_int_m)); // Q4
+
+   for (i = 0; i < 4; i++)
+   {
+      // Compute innovation vector
+      build_CN_code(&st->L_pn_seed_rx, ex);
+      for (j = 0; j < L_SUBFR; j++)
+      {
+         ex[j] = mult(level, ex[j]);
+      }
+      // Synthesize
+      Syn_filt(acoeff_variab, ex, &synth[i * L_SUBFR], L_SUBFR,
+               mem_syn, 1);
+
+   } // next i
+
+   // reset codebook averaging variables
+   averState->hangVar = 20;
+   averState->hangCount = 0;
+
+   if (sub(new_state, DTX_MUTE) == 0)
+   {
+      // mute comfort noise as it has been quite a long time since
+       * last SID update  was performed
+
+      tmp_int_length = st->since_last_sid;
+      if (sub(tmp_int_length, 32) > 0)
+      {
+         tmp_int_length = 32;
+      }
+
+      // safety guard against division by zero
+      if(tmp_int_length <= 0) {
+         tmp_int_length = 8;
+      }
+
+      st->true_sid_period_inv = div_s(1 << 10, shl(tmp_int_length, 10));
+
+      st->since_last_sid = 0;
+      Copy(st->lsp, st->lsp_old, M);
+      st->old_log_en = st->log_en;
+      // subtract 1/8 in Q11 i.e -6/8 dB
+      st->log_en = sub(st->log_en, 256);
+   }
+
+   // reset interpolation length timer
+   // if data has been updated.
+   if ((st->sid_frame != 0) &&
+       ((st->valid_data != 0) ||
+        ((st->valid_data == 0) &&  (st->dtxHangoverAdded) != 0)))
+   {
+      st->since_last_sid =  0;
+      st->data_updated = 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]
+
+------------------------------------------------------------------------------
+*/
+
+void dtx_dec(
+    dtx_decState *st,                /* i/o : State struct                    */
+    Word16 mem_syn[],                /* i/o : AMR decoder state               */
+    D_plsfState* lsfState,           /* i/o : decoder lsf states              */
+    gc_predState* predState,         /* i/o : prediction states               */
+    Cb_gain_averageState* averState, /* i/o : CB gain average states          */
+    enum DTXStateType new_state,     /* i   : new DTX state                   */
+    enum Mode mode,                  /* i   : AMR mode                        */
+    Word16 parm[],                   /* i   : Vector of synthesis parameters  */
+    Word16 synth[],                  /* o   : synthesised speech              */
+    Word16 A_t[],                    /* o   : decoded LP filter in 4 subframes*/
+    Flag   *pOverflow
+)
+{
+    Word16 log_en_index;
+    Word16 i;
+    Word16 j;
+    Word16 int_fac;
+    Word32 L_log_en_int;
+    Word16 lsp_int[M];
+    Word16 log_en_int_e;
+    Word16 log_en_int_m;
+    Word16 level;
+    Word16 acoeff[M + 1];
+    Word16 refl[M];
+    Word16 pred_err;
+    Word16 ex[L_SUBFR];
+    Word16 ma_pred_init;
+    Word16 log_pg_e;
+    Word16 log_pg_m;
+    Word16 log_pg;
+    Flag negative;
+    Word16 lsf_mean;
+    Word32 L_lsf_mean;
+    Word16 lsf_variab_index;
+    Word16 lsf_variab_factor;
+    Word16 lsf_int[M];
+    Word16 lsf_int_variab[M];
+    Word16 lsp_int_variab[M];
+    Word16 acoeff_variab[M + 1];
+
+    Word16 lsf[M];
+    Word32 L_lsf[M];
+    Word16 ptr;
+    Word16 tmp_int_length;
+
+    Word32 L_temp;
+    Word16 temp;
+
+    /*  This function is called if synthesis state is not SPEECH
+     *  the globally passed  inputs to this function are
+     * st->sid_frame
+     * st->valid_data
+     * st->dtxHangoverAdded
+     * new_state  (SPEECH, DTX, DTX_MUTE)
+     */
+
+    if ((st->dtxHangoverAdded != 0) &&
+            (st->sid_frame != 0))
+    {
+        /* sid_first after dtx hangover period */
+        /* or sid_upd after dtxhangover        */
+
+        /* set log_en_adjust to correct value */
+        st->log_en_adjust = dtx_log_en_adjust[mode];
+
+        ptr = st->lsf_hist_ptr + M;
+
+        if (ptr == 80)
+        {
+            ptr = 0;
+        }
+        Copy(&st->lsf_hist[st->lsf_hist_ptr], &st->lsf_hist[ptr], M);
+
+        ptr = st->log_en_hist_ptr + 1;
+
+        if (ptr == DTX_HIST_SIZE)
+        {
+            ptr = 0;
+        }
+
+        st->log_en_hist[ptr] = st->log_en_hist[st->log_en_hist_ptr]; /* Q11 */
+
+        /* compute mean log energy and lsp *
+         * from decoded signal (SID_FIRST) */
+        st->log_en = 0;
+        for (i = M - 1; i >= 0; i--)
+        {
+            L_lsf[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]) >> 3);
+            }
+            else
+            {
+                temp = st->log_en_hist[i] >> 3;
+            }
+            st->log_en = add(st->log_en, temp, pOverflow);
+            for (j = M - 1; j >= 0; j--)
+            {
+                L_lsf[j] = L_add(L_lsf[j],
+                                 L_deposit_l(st->lsf_hist[i * M + j]), pOverflow);
+            }
+        }
+
+        for (j = M - 1; j >= 0; j--)
+        {
+            if (L_lsf[j] < 0)
+            {
+                lsf[j] = (Word16)(~((~L_lsf[j]) >> 3));
+            }
+            else
+            {
+                lsf[j] = (Word16)(L_lsf[j] >> 3);
+            }
+        }
+
+        Lsf_lsp(lsf, st->lsp, M, pOverflow);
+
+        /* make log_en speech coder mode independent */
+        /* added again later before synthesis        */
+        st->log_en = sub(st->log_en, st->log_en_adjust, pOverflow);
+
+        /* compute lsf variability vector */
+        Copy(st->lsf_hist, st->lsf_hist_mean, 80);
+
+        for (i = M - 1; i >= 0; i--)
+        {
+            L_lsf_mean = 0;
+            /* compute mean lsf */
+            for (j = 8 - 1; j >= 0; j--)
+            {
+                L_lsf_mean = L_add(L_lsf_mean,
+                                   L_deposit_l(st->lsf_hist_mean[i+j*M]), pOverflow);
+            }
+
+            if (L_lsf_mean < 0)
+            {
+                lsf_mean = (Word16)(~((~L_lsf_mean) >> 3));
+            }
+            else
+            {
+                lsf_mean = (Word16)(L_lsf_mean >> 3);
+            }
+            /* subtract mean and limit to within reasonable limits  *
+            * moreover the upper lsf's are attenuated              */
+            for (j = 8 - 1; j >= 0; j--)
+            {
+                /* subtract mean */
+                st->lsf_hist_mean[i+j*M] =
+                    sub(st->lsf_hist_mean[i+j*M], lsf_mean, pOverflow);
+
+                /* attenuate deviation from mean, especially for upper lsf's */
+                st->lsf_hist_mean[i+j*M] =
+                    mult(st->lsf_hist_mean[i+j*M], lsf_hist_mean_scale[i], pOverflow);
+
+                /* limit the deviation */
+                if (st->lsf_hist_mean[i+j*M] < 0)
+                {
+                    negative = 1;
+                }
+                else
+                {
+                    negative = 0;
+                }
+                st->lsf_hist_mean[i+j*M] = abs_s(st->lsf_hist_mean[i+j*M]);
+
+                /* apply soft limit */
+                if (st->lsf_hist_mean[i+j*M] > 655)
+                {
+                    st->lsf_hist_mean[i+j*M] = 655 + ((st->lsf_hist_mean[i+j*M]
+                                                       - 655) >> 2);
+                }
+
+                /* apply hard limit */
+                if (st->lsf_hist_mean[i+j*M] > 1310)
+                {
+                    st->lsf_hist_mean[i+j*M] = 1310;
+                }
+
+                if (negative != 0)
+                {
+                    st->lsf_hist_mean[i+j*M] = -st->lsf_hist_mean[i+j*M];
+                }
+            }
+        }
+    }
+
+
+    if (st->sid_frame != 0)
+    {
+        /* Set old SID parameters, always shift */
+        /* even if there is no new valid_data   */
+        Copy(st->lsp, st->lsp_old, M);
+        st->old_log_en = st->log_en;
+
+        if (st->valid_data != 0)   /* new data available (no CRC) */
+        {
+            /* Compute interpolation factor, since the division only works *
+             * for values of since_last_sid < 32 we have to limit the      *
+             * interpolation to 32 frames                                  */
+            tmp_int_length = st->since_last_sid;
+            st->since_last_sid = 0;
+
+            if (tmp_int_length >= 32)
+            {
+                tmp_int_length = 32;
+            }
+
+            L_temp = ((Word32) tmp_int_length) << 10;
+            if (L_temp != (Word32)((Word16) L_temp))
+            {
+                *pOverflow = 1;
+                L_temp = (Word32)((tmp_int_length > 0) ? MAX_16 : MIN_16);
+            }
+            temp = (Word16) L_temp;
+
+            if (tmp_int_length >= 2)
+            {
+                st->true_sid_period_inv = div_s(1 << 10, temp);
+            }
+            else
+            {
+                st->true_sid_period_inv = 1 << 14; /* 0.5 it Q15 */
+            }
+
+            Init_D_plsf_3(lsfState, parm[0]);
+            D_plsf_3(lsfState, MRDTX, 0, &parm[1], st->lsp, pOverflow);
+            Set_zero(lsfState->past_r_q, M);   /* reset for next speech frame */
+
+            log_en_index = parm[4];
+            /* Q11 and divide by 4 */
+            if ((log_en_index > 63) || (log_en_index < -64))
+            {
+                st->log_en = (log_en_index > 0) ? MAX_16 : MIN_16;
+            }
+            else
+            {
+                st->log_en = (log_en_index) << (11 - 2);
+            }
+
+            /* Subtract 2.5 in Q11 */
+            st->log_en = sub(st->log_en, (2560 * 2), pOverflow);
+
+            /* Index 0 is reserved for silence */
+            if (log_en_index == 0)
+            {
+                st->log_en = MIN_16;
+            }
+
+            /* no interpolation at startup after coder reset        */
+            /* or when SID_UPD has been received right after SPEECH */
+
+            if ((st->data_updated == 0) ||
+                    (st->dtxGlobalState == SPEECH))
+            {
+                Copy(st->lsp, st->lsp_old, M);
+                st->old_log_en = st->log_en;
+            }
+        } /* endif valid_data */
+
+        /* initialize gain predictor memory of other modes */
+        if (st->log_en < 0)
+        {
+            temp = ~((~st->log_en) >> 1);
+        }
+        else
+        {
+            temp = st->log_en >> 1;
+        }
+        ma_pred_init = sub(temp, 9000, pOverflow);
+
+        if (ma_pred_init > 0)
+        {
+            ma_pred_init = 0;
+        }
+        else if (ma_pred_init < -14436)
+        {
+            ma_pred_init = -14436;
+        }
+
+        predState->past_qua_en[0] = ma_pred_init;
+        predState->past_qua_en[1] = ma_pred_init;
+        predState->past_qua_en[2] = ma_pred_init;
+        predState->past_qua_en[3] = ma_pred_init;
+
+        /* past_qua_en for other modes than MR122 */
+        ma_pred_init = mult(5443, ma_pred_init, pOverflow);
+        /* scale down by factor 20*log10(2) in Q15 */
+        predState->past_qua_en_MR122[0] = ma_pred_init;
+        predState->past_qua_en_MR122[1] = ma_pred_init;
+        predState->past_qua_en_MR122[2] = ma_pred_init;
+        predState->past_qua_en_MR122[3] = ma_pred_init;
+    } /* endif sid_frame */
+
+    /* CN generation */
+    /* recompute level adjustment factor Q11             *
+     * st->log_en_adjust = 0.9*st->log_en_adjust +       *
+     *                     0.1*dtx_log_en_adjust[mode]); */
+    if (dtx_log_en_adjust[mode] > 1023)
+    {
+        temp = MAX_16;
+    }
+    else if (dtx_log_en_adjust[mode] < -1024)
+    {
+        temp = MIN_16;
+    }
+    else
+    {
+        temp = mult((Word16)((Word32)dtx_log_en_adjust[mode] << 5), 3277, pOverflow);
+    }
+
+    if (temp < 0)
+    {
+        temp = ~((~temp) >> 5);
+    }
+    else
+    {
+        temp >>= 5;
+    }
+    st->log_en_adjust = add(mult(st->log_en_adjust, 29491, pOverflow), temp, pOverflow);
+
+    /* Interpolate SID info */
+    int_fac = shl(add(1, st->since_last_sid, pOverflow), 10, pOverflow); /* Q10 */
+    int_fac = mult(int_fac, st->true_sid_period_inv, pOverflow); /* Q10 * Q15 -> Q10 */
+
+    /* Maximize to 1.0 in Q10 */
+    if (int_fac > 1024)
+    {
+        int_fac = 16384;
+    }
+    else if (int_fac < -2048)
+    {
+        int_fac = MIN_16;
+    }
+    else
+    {
+        int_fac <<= 4;      /* Q10 -> Q14 */
+    }
+
+    L_log_en_int = L_mult(int_fac, st->log_en, pOverflow); /* Q14 * Q11->Q26 */
+    for (i = M - 1; i >= 0; i--)
+    {
+        lsp_int[i] = mult(int_fac, st->lsp[i], pOverflow);/* Q14 * Q15 -> Q14 */
+    }
+
+    int_fac = sub(16384, int_fac, pOverflow); /* 1-k in Q14 */
+
+    /* (Q14 * Q11 -> Q26) + Q26 -> Q26 */
+    L_log_en_int = L_mac(L_log_en_int, int_fac, st->old_log_en, pOverflow);
+    for (i = M - 1; i >= 0; i--)
+    {
+        /* Q14 + (Q14 * Q15 -> Q14) -> Q14 */
+        lsp_int[i] = add(lsp_int[i], mult(int_fac, st->lsp_old[i], pOverflow), pOverflow);
+
+        L_temp = ((Word32) lsp_int[i]) << 1;    /* Q14 -> Q15 */
+        if (L_temp != (Word32)((Word16) L_temp))
+        {
+            *pOverflow = 1;
+            L_temp = (Word32)((lsp_int[i] > 0) ? MAX_16 : MIN_16);
+        }
+        lsp_int[i] = (Word16) L_temp;
+    }
+
+    /* compute the amount of lsf variability */
+    lsf_variab_factor = sub(st->log_pg_mean, 2457, pOverflow); /* -0.6 in Q12 */
+    /* *0.3 Q12*Q15 -> Q12 */
+    lsf_variab_factor = sub(4096, mult(lsf_variab_factor, 9830, pOverflow), pOverflow);
+
+    /* limit to values between 0..1 in Q12 */
+    if (lsf_variab_factor > 4095)
+    {
+        lsf_variab_factor = MAX_16;
+    }
+    else if (lsf_variab_factor < 0)
+    {
+        lsf_variab_factor = 0;
+    }
+    else
+    {
+        lsf_variab_factor <<= 3; /* -> Q15 */
+    }
+
+    /* get index of vector to do variability with */
+    lsf_variab_index = pseudonoise(&st->L_pn_seed_rx, 3);
+
+    /* convert to lsf */
+    Lsp_lsf(lsp_int, lsf_int, M, pOverflow);
+
+    /* apply lsf variability */
+    Copy(lsf_int, lsf_int_variab, M);
+    for (i = M - 1; i >= 0; i--)
+    {
+        lsf_int_variab[i] = add(lsf_int_variab[i],
+                                mult(lsf_variab_factor,
+                                     st->lsf_hist_mean[i+lsf_variab_index*M], pOverflow)
+                                , pOverflow);
+    }
+
+    /* make sure that LSP's are ordered */
+    Reorder_lsf(lsf_int, LSF_GAP, M, pOverflow);
+    Reorder_lsf(lsf_int_variab, LSF_GAP, M, pOverflow);
+
+    /* copy lsf to speech decoders lsf state */
+    Copy(lsf_int, lsfState->past_lsf_q, M);
+
+    /* convert to lsp */
+    Lsf_lsp(lsf_int, lsp_int, M, pOverflow);
+    Lsf_lsp(lsf_int_variab, lsp_int_variab, M, pOverflow);
+
+    /* Compute acoeffs Q12 acoeff is used for level    *
+     * normalization and postfilter, acoeff_variab is  *
+     * used for synthesis filter                       *
+     * by doing this we make sure that the level       *
+     * in high frequenncies does not jump up and down  */
+
+    Lsp_Az(lsp_int, acoeff, pOverflow);
+    Lsp_Az(lsp_int_variab, acoeff_variab, pOverflow);
+
+    /* For use in postfilter */
+    Copy(acoeff, &A_t[0],           M + 1);
+    Copy(acoeff, &A_t[M + 1],       M + 1);
+    Copy(acoeff, &A_t[2 *(M + 1)], M + 1);
+    Copy(acoeff, &A_t[3 *(M + 1)], M + 1);
+
+    /* Compute reflection coefficients Q15 */
+    A_Refl(&acoeff[1], refl, pOverflow);
+
+    /* Compute prediction error in Q15 */
+    pred_err = MAX_16; /* 0.99997 in Q15 */
+    for (i = 0; i < M; i++)
+    {
+        L_temp = (((Word32) refl[i]) * refl[i]) >> 15;
+        if (L_temp <= 0x00007fffL)
+        {
+            temp = MAX_16 - (Word16) L_temp;
+        }
+        else
+        {
+            *pOverflow = 1;
+            temp = 0;
+        }
+        pred_err = mult(pred_err, temp, pOverflow);
+    }
+
+    /* compute logarithm of prediction gain */
+    Log2(L_deposit_l(pred_err), &log_pg_e, &log_pg_m, pOverflow);
+
+    /* convert exponent and mantissa to Word16 Q12 */
+    log_pg = shl(sub(log_pg_e, 15, pOverflow), 12, pOverflow); /* Q12 */
+    log_pg = shr(sub(0, add(log_pg, shr(log_pg_m, 15 - 12, pOverflow),
+                            pOverflow), pOverflow), 1, pOverflow);
+    st->log_pg_mean = add(mult(29491, st->log_pg_mean, pOverflow),
+                          mult(3277, log_pg, pOverflow), pOverflow);
+
+    /* Compute interpolated log energy */
+    L_log_en_int = L_shr(L_log_en_int, 10, pOverflow); /* Q26 -> Q16 */
+
+    /* Add 4 in Q16 */
+    L_log_en_int = L_add(L_log_en_int, 4 * 65536L, pOverflow);
+
+    /* subtract prediction gain */
+    L_log_en_int = L_sub(L_log_en_int, L_shl(L_deposit_l(log_pg), 4, pOverflow), pOverflow);
+
+    /* adjust level to speech coder mode */
+    L_log_en_int = L_add(L_log_en_int,
+                         L_shl(L_deposit_l(st->log_en_adjust), 5, pOverflow), pOverflow);
+
+    log_en_int_e = (Word16)(L_log_en_int >> 16);
+
+    log_en_int_m = (Word16)(L_shr(L_sub(L_log_en_int,
+                                        L_deposit_h(log_en_int_e), pOverflow), 1, pOverflow));
+    level = (Word16)(Pow2(log_en_int_e, log_en_int_m, pOverflow));  /* Q4 */
+
+    for (i = 0; i < 4; i++)
+    {
+        /* Compute innovation vector */
+        build_CN_code(&st->L_pn_seed_rx, ex, pOverflow);
+        for (j = L_SUBFR - 1; j >= 0; j--)
+        {
+            ex[j] = mult(level, ex[j], pOverflow);
+        }
+        /* Synthesize */
+        Syn_filt(acoeff_variab, ex, &synth[i * L_SUBFR], L_SUBFR,
+                 mem_syn, 1);
+
+    } /* next i */
+
+    /* reset codebook averaging variables */
+    averState->hangVar = 20;
+    averState->hangCount = 0;
+
+    if (new_state == DTX_MUTE)
+    {
+        /* mute comfort noise as it has been quite a long time since
+         * last SID update  was performed                            */
+
+        tmp_int_length = st->since_last_sid;
+
+        if (tmp_int_length > 32)
+        {
+            tmp_int_length = 32;
+        }
+        else if (tmp_int_length <= 0)
+        {
+            /* safety guard against division by zero */
+            tmp_int_length = 8;
+        }
+
+        L_temp = ((Word32) tmp_int_length) << 10;
+        if (L_temp != (Word32)((Word16) L_temp))
+        {
+            *pOverflow = 1;
+            L_temp = (Word32)((tmp_int_length > 0) ? MAX_16 : MIN_16);
+        }
+        temp = (Word16) L_temp;
+
+        st->true_sid_period_inv = div_s(1 << 10, temp);
+
+        st->since_last_sid = 0;
+        Copy(st->lsp, st->lsp_old, M);
+        st->old_log_en = st->log_en;
+        /* subtract 1/8 in Q11 i.e -6/8 dB */
+        st->log_en = sub(st->log_en, 256, pOverflow);
+    }
+
+    /* reset interpolation length timer
+     * if data has been updated.        */
+    if ((st->sid_frame != 0) &&
+            ((st->valid_data != 0) ||
+             ((st->valid_data == 0) && (st->dtxHangoverAdded) != 0)))
+    {
+        st->since_last_sid =  0;
+        st->data_updated = 1;
+    }
+
+    return;
+}
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: dtx_dec_activity_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type dtx_decState
+    lsf =
+        frame =
+
+ Outputs:
+    st points to an updated structure of type dtx_decState
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function updates the DTX parameters.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.3.0, December 12, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void dtx_dec_activity_update(dtx_decState *st,
+                             Word16 lsf[],
+                             Word16 frame[])
+{
+   Word16 i;
+
+   Word32 L_frame_en;
+   Word16 log_en_e, log_en_m, log_en;
+
+   // update lsp history
+   st->lsf_hist_ptr = add(st->lsf_hist_ptr,M);
+   if (sub(st->lsf_hist_ptr, 80) == 0)
+   {
+      st->lsf_hist_ptr = 0;
+   }
+   Copy(lsf, &st->lsf_hist[st->lsf_hist_ptr], 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, frame[i], frame[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, 7497+1024);
+
+   // insert into log energy buffer, no division by two as  *
+    * log_en in decoder is Q11
+   st->log_en_hist_ptr = add(st->log_en_hist_ptr, 1);
+   if (sub(st->log_en_hist_ptr, DTX_HIST_SIZE) == 0)
+   {
+      st->log_en_hist_ptr = 0;
+   }
+   st->log_en_hist[st->log_en_hist_ptr] = log_en; // Q11
+}
+
+------------------------------------------------------------------------------
+ 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_dec_activity_update(dtx_decState *st,
+                             Word16 lsf[],
+                             Word16 frame[],
+                             Flag   *pOverflow)
+{
+    Word16 i;
+
+    Word32 L_frame_en;
+    Word32 L_temp;
+    Word16 log_en_e;
+    Word16 log_en_m;
+    Word16 log_en;
+
+    /* update lsp history */
+    st->lsf_hist_ptr += M;
+
+    if (st->lsf_hist_ptr == 80)
+    {
+        st->lsf_hist_ptr = 0;
+    }
+    Copy(lsf, &st->lsf_hist[st->lsf_hist_ptr], M);
+
+    /* compute log energy based on frame energy */
+    L_frame_en = 0;     /* Q0 */
+    for (i = L_FRAME - 1; i >= 0; i--)
+    {
+        L_temp = ((Word32) frame[i]) * frame[i];
+        if (L_temp != (Word32) 0x40000000L)
+        {
+            L_temp = L_temp << 1;
+        }
+        else
+        {
+            L_temp = MAX_32;
+        }
+        L_frame_en = L_add(L_frame_en, L_temp, pOverflow);
+    }
+    Log2(L_frame_en, &log_en_e, &log_en_m, pOverflow);
+
+    /* convert exponent and mantissa to Word16 Q10 */
+    L_temp = ((Word32) log_en_e) << 10;
+
+    if (L_temp != (Word32)((Word16) L_temp))
+    {
+        *pOverflow = 1;
+        L_temp = (Word32)((log_en_e > 0) ? MAX_16 : MIN_16);
+    }
+    log_en_e = (Word16) L_temp;
+
+    if (log_en_m < 0)
+    {
+        log_en_m = ~((~log_en_m) >> 5);
+    }
+    else
+    {
+        log_en_m >>= 5;
+    }
+    log_en = add(log_en_e, log_en_m, pOverflow);
+
+    /* divide with L_FRAME i.e subtract with log2(L_FRAME) = 7.32193 */
+    log_en = sub(log_en, 7497 + 1024, pOverflow);
+
+    /* insert into log energy buffer, no division by two as  *
+    * log_en in decoder is Q11                              */
+    st->log_en_hist_ptr += 1;
+
+    if (st->log_en_hist_ptr == DTX_HIST_SIZE)
+    {
+        st->log_en_hist_ptr = 0;
+    }
+    st->log_en_hist[st->log_en_hist_ptr] = log_en; /* Q11 */
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: rx_dtx_handler
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type dtx_decState
+    frame_type = RX frame type
+
+ Returns:
+    newState = variable of type DTXStateType
+
+ Outputs:
+    st points to an updated structure of type dtx_decState
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function determines the new state of the decoder based on the frame_type
+ and sets up the decoder parameters according to newState.
+
+ Table of new SPD synthesis states
+
+                           |     previous SPD_synthesis_state
+     Incoming              |
+     frame_type            | SPEECH       | DTX           | DTX_MUTE
+     ---------------------------------------------------------------
+     RX_SPEECH_GOOD ,      |              |               |
+     RX_SPEECH_PR_DEGRADED | SPEECH       | SPEECH        | SPEECH
+     ----------------------------------------------------------------
+     RX_SPEECH_PR_BAD,     |              |               |
+     RX_SPEECH_BAD,        | SPEECH       | DTX           | DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_FIRST,         | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_UPDATE,        | DTX          | DTX           | DTX
+     ----------------------------------------------------------------
+     RX_SID_BAD,           | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_NO_DATA            | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
+                           |(class2 garb.)|               |
+     ----------------------------------------------------------------
+     RX_ONSET              | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
+                           |(class2 garb.)|               |
+     ----------------------------------------------------------------
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ dtx_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.3.0, December 12, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+enum DTXStateType rx_dtx_handler(
+                      dtx_decState *st,           // i/o : State struct
+                      enum RXFrameType frame_type // i   : Frame type
+                      )
+{
+   enum DTXStateType newState;
+   enum DTXStateType encState;
+
+   // DTX if SID frame or previously in DTX{_MUTE} and (NO_RX OR BAD_SPEECH)
+   if ((sub(frame_type, RX_SID_FIRST) == 0)   ||
+       (sub(frame_type, RX_SID_UPDATE) == 0)  ||
+       (sub(frame_type, RX_SID_BAD) == 0)     ||
+       (((sub(st->dtxGlobalState, DTX) == 0) ||
+         (sub(st->dtxGlobalState, DTX_MUTE) == 0)) &&
+        ((sub(frame_type, RX_NO_DATA) == 0) ||
+         (sub(frame_type, RX_SPEECH_BAD) == 0) ||
+         (sub(frame_type, RX_ONSET) == 0))))
+   {
+      newState = DTX;
+
+      // stay in mute for these input types
+      if ((sub(st->dtxGlobalState, DTX_MUTE) == 0) &&
+          ((sub(frame_type, RX_SID_BAD) == 0) ||
+           (sub(frame_type, RX_SID_FIRST) ==  0) ||
+           (sub(frame_type, RX_ONSET) ==  0) ||
+           (sub(frame_type, RX_NO_DATA) == 0)))
+      {
+         newState = DTX_MUTE;
+      }
+
+      // evaluate if noise parameters are too old
+      // since_last_sid is reset when CN parameters have been updated
+      st->since_last_sid = add(st->since_last_sid, 1);
+
+      // no update of sid parameters in DTX for a long while
+      // Due to the delayed update of  st->since_last_sid counter
+      // SID_UPDATE frames need to be handled separately to avoid
+      // entering DTX_MUTE for late SID_UPDATE frames
+      if((sub(frame_type, RX_SID_UPDATE) != 0) &&
+         (sub(st->since_last_sid, DTX_MAX_EMPTY_THRESH) > 0))
+      {
+         newState = DTX_MUTE;
+      }
+   }
+   else
+   {
+      newState = SPEECH;
+      st->since_last_sid = 0;
+   }
+
+    // reset the decAnaElapsed Counter when receiving CNI data the first
+    // time, to robustify counter missmatch after handover
+    // this might delay the bwd CNI analysis in the new decoder slightly.
+
+   if ((st->data_updated == 0) &&
+       (sub(frame_type, RX_SID_UPDATE) == 0))
+   {
+      st->decAnaElapsedCount = 0;
+   }
+
+   // update the SPE-SPD DTX hangover synchronization
+   // to know when SPE has added dtx hangover
+   st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1);
+   st->dtxHangoverAdded = 0;
+
+   if ((sub(frame_type, RX_SID_FIRST) == 0)  ||
+       (sub(frame_type, RX_SID_UPDATE) == 0) ||
+       (sub(frame_type, RX_SID_BAD) == 0)    ||
+       (sub(frame_type, RX_ONSET) == 0)      ||
+       (sub(frame_type, RX_NO_DATA) == 0))
+   {
+      encState = DTX;
+
+      // In frame errors simulations RX_NO_DATA may occasionally mean that
+      // a speech packet was probably sent by the encoder,
+      // the assumed _encoder_ state should be SPEECH in such cases.
+      if((sub(frame_type, RX_NO_DATA) == 0) &&
+         (sub(newState, SPEECH) == 0))
+      {
+         encState = SPEECH;
+      }
+
+      // Note on RX_ONSET operation differing from RX_NO_DATA operation:
+      // If a  RX_ONSET is received in the decoder (by "accident")
+      // it is still most likely that the encoder  state
+      // for the "ONSET frame" was DTX.
+
+   }
+   else
+   {
+      encState = SPEECH;
+   }
+
+   if (sub(encState, SPEECH) == 0)
+   {
+      st->dtxHangoverCount = DTX_HANG_CONST;
+   }
+   else
+   {
+      if (sub(st->decAnaElapsedCount, DTX_ELAPSED_FRAMES_THRESH) > 0)
+      {
+         st->dtxHangoverAdded = 1;
+         st->decAnaElapsedCount = 0;
+         st->dtxHangoverCount = 0;
+      }
+      else if (st->dtxHangoverCount == 0)
+      {
+         st->decAnaElapsedCount = 0;
+      }
+      else
+      {
+         st->dtxHangoverCount = sub(st->dtxHangoverCount, 1);
+      }
+   }
+
+   if (sub(newState, SPEECH) != 0)
+   {
+      // DTX or DTX_MUTE
+      // CN data is not in a first SID, first SIDs are marked as SID_BAD
+      //  but will do backwards analysis if a hangover period has been added
+      // according to the state machine above
+
+      st->sid_frame = 0;
+      st->valid_data = 0;
+
+      if (sub(frame_type, RX_SID_FIRST) == 0)
+      {
+         st->sid_frame = 1;
+      }
+      else if (sub(frame_type, RX_SID_UPDATE) == 0)
+      {
+         st->sid_frame = 1;
+         st->valid_data = 1;
+      }
+      else if (sub(frame_type, RX_SID_BAD) == 0)
+      {
+         st->sid_frame = 1;
+         st->dtxHangoverAdded = 0; // use old data
+      }
+   }
+
+   return newState;
+   // newState is used by both SPEECH AND DTX synthesis routines
+}
+
+------------------------------------------------------------------------------
+ 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]
+
+------------------------------------------------------------------------------
+*/
+
+enum DTXStateType rx_dtx_handler(
+    dtx_decState *st,           /* i/o : State struct     */
+    enum RXFrameType frame_type,/* i   : Frame type       */
+    Flag *pOverflow)
+{
+    enum DTXStateType newState;
+    enum DTXStateType encState;
+
+
+    /* DTX if SID frame or previously in DTX{_MUTE} and (NO_RX OR BAD_SPEECH) */
+
+    if ((frame_type == RX_SID_FIRST)   ||
+            (frame_type == RX_SID_UPDATE)  ||
+            (frame_type == RX_SID_BAD)     ||
+            (((st->dtxGlobalState == DTX) || (st->dtxGlobalState == DTX_MUTE)) &&
+             ((frame_type == RX_NO_DATA) || (frame_type == RX_SPEECH_BAD) ||
+              (frame_type == RX_ONSET))))
+    {
+        newState = DTX;
+
+        /* stay in mute for these input types */
+
+        if ((st->dtxGlobalState == DTX_MUTE) &&
+                ((frame_type == RX_SID_BAD) ||
+                 (frame_type == RX_SID_FIRST) ||
+                 (frame_type == RX_ONSET) ||
+                 (frame_type == RX_NO_DATA)))
+        {
+            newState = DTX_MUTE;
+        }
+
+        /* evaluate if noise parameters are too old                     */
+        /* since_last_sid is reset when CN parameters have been updated */
+        st->since_last_sid = add(st->since_last_sid, 1, pOverflow);
+
+        /* no update of sid parameters in DTX for a long while      */
+        /* Due to the delayed update of  st->since_last_sid counter */
+        /* SID_UPDATE frames need to be handled separately to avoid */
+        /* entering DTX_MUTE for late SID_UPDATE frames             */
+        if ((frame_type != RX_SID_UPDATE) &&
+                (st->since_last_sid > DTX_MAX_EMPTY_THRESH))
+        {
+            newState = DTX_MUTE;
+        }
+    }
+    else
+    {
+        newState = SPEECH;
+        st->since_last_sid = 0;
+    }
+
+    /*
+    reset the decAnaElapsed Counter when receiving CNI data the first
+    time, to robustify counter missmatch after handover
+    this might delay the bwd CNI analysis in the new decoder slightly.
+    */
+
+    if ((st->data_updated == 0) &&
+            (frame_type == RX_SID_UPDATE))
+    {
+        st->decAnaElapsedCount = 0;
+    }
+
+    /* update the SPE-SPD DTX hangover synchronization */
+    /* to know when SPE has added dtx hangover         */
+    st->decAnaElapsedCount = add(st->decAnaElapsedCount, 1, pOverflow);
+    st->dtxHangoverAdded = 0;
+
+    if ((frame_type == RX_SID_FIRST)  ||
+            (frame_type == RX_SID_UPDATE) ||
+            (frame_type == RX_SID_BAD)    ||
+            (frame_type == RX_ONSET) ||
+            (frame_type == RX_NO_DATA))
+    {
+        encState = DTX;
+
+        /*
+         In frame errors simulations RX_NO_DATA may occasionally mean that
+         a speech packet was probably sent by the encoder,
+         the assumed _encoder_ state should be SPEECH in such cases.
+        */
+        if ((frame_type == RX_NO_DATA) &&
+                (newState == SPEECH))
+        {
+            encState = SPEECH;
+        }
+
+        /*
+         Note on RX_ONSET operation differing from RX_NO_DATA operation:
+         If a  RX_ONSET is received in the decoder (by "accident")
+         it is still most likely that the encoder  state
+         for the "ONSET frame" was DTX.
+        */
+    }
+    else
+    {
+        encState = SPEECH;
+    }
+
+
+    if (encState == SPEECH)
+    {
+        st->dtxHangoverCount = DTX_HANG_CONST;
+    }
+    else
+    {
+
+        if (st->decAnaElapsedCount > DTX_ELAPSED_FRAMES_THRESH)
+        {
+            st->dtxHangoverAdded = 1;
+            st->decAnaElapsedCount = 0;
+            st->dtxHangoverCount = 0;
+        }
+        else if (st->dtxHangoverCount == 0)
+        {
+            st->decAnaElapsedCount = 0;
+        }
+        else
+        {
+            st->dtxHangoverCount -= 1;
+        }
+    }
+
+    if (newState != SPEECH)
+    {
+        /* DTX or DTX_MUTE
+         * CN data is not in a first SID, first SIDs are marked as SID_BAD
+         *  but will do backwards analysis if a hangover period has been added
+         *  according to the state machine above
+        */
+
+        st->sid_frame = 0;
+        st->valid_data = 0;
+
+        if (frame_type == RX_SID_FIRST)
+        {
+            st->sid_frame = 1;
+        }
+        else if (frame_type == RX_SID_UPDATE)
+        {
+            st->sid_frame = 1;
+            st->valid_data = 1;
+        }
+        else if (frame_type == RX_SID_BAD)
+        {
+            st->sid_frame = 1;
+            st->dtxHangoverAdded = 0; /* use old data */
+        }
+    }
+
+    /* newState is used by both SPEECH AND DTX synthesis routines */
+    return(newState);
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.h b/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.h
new file mode 100644
index 0000000..2b5a614
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/dtx_dec.h
@@ -0,0 +1,191 @@
+/* ------------------------------------------------------------------
+ * 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/dtx_dec.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             : dtx_dec.h
+    Purpose          : Decode comfort noice when in DTX
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef DTX_DEC_H
+#define DTX_DEC_H
+#define dtx_dec_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "d_plsf.h"
+#include "gc_pred.h"
+#include "c_g_aver.h"
+#include "frame.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
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    enum DTXStateType {SPEECH = 0, DTX, DTX_MUTE};
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 since_last_sid;
+        Word16 true_sid_period_inv;
+        Word16 log_en;
+        Word16 old_log_en;
+        Word32 L_pn_seed_rx;
+        Word16 lsp[M];
+        Word16 lsp_old[M];
+
+        Word16 lsf_hist[M*DTX_HIST_SIZE];
+        Word16 lsf_hist_ptr;
+        Word16 lsf_hist_mean[M*DTX_HIST_SIZE];
+        Word16 log_pg_mean;
+        Word16 log_en_hist[DTX_HIST_SIZE];
+        Word16 log_en_hist_ptr;
+
+        Word16 log_en_adjust;
+
+        Word16 dtxHangoverCount;
+        Word16 decAnaElapsedCount;
+
+        Word16 sid_frame;
+        Word16 valid_data;
+        Word16 dtxHangoverAdded;
+
+        enum DTXStateType dtxGlobalState;     /* contains previous state */
+        /* updated in main decoder */
+
+        Word16 data_updated;      /* marker to know if CNI data is ever renewed */
+
+    } dtx_decState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*
+     *  Function    : dtx_dec_reset
+     *  Purpose     : Resets state memory
+     *  Returns     : 0 on success
+     */
+    Word16 dtx_dec_reset(dtx_decState *st);
+
+    /*
+     *  Function    : dtx_dec
+     *  Purpose     :
+     *  Description :
+     */
+    void dtx_dec(
+        dtx_decState *st,                /* i/o : State struct                    */
+        Word16 mem_syn[],                /* i/o : AMR decoder state               */
+        D_plsfState* lsfState,           /* i/o : decoder lsf states              */
+        gc_predState* predState,         /* i/o : prediction states               */
+        Cb_gain_averageState* averState, /* i/o : CB gain average states          */
+        enum DTXStateType new_state,     /* i   : new DTX state                   */
+        enum Mode mode,                  /* i   : AMR mode                        */
+        Word16 parm[],                   /* i   : Vector of synthesis parameters  */
+        Word16 synth[],                  /* o   : synthesised speech              */
+        Word16 A_t[],                    /* o   : decoded LP filter in 4 subframes*/
+        Flag   *pOverflow
+    );
+
+    void dtx_dec_activity_update(dtx_decState *st,
+                                 Word16 lsf[],
+                                 Word16 frame[],
+                                 Flag   *pOverflow);
+
+    /*
+     *  Function    : rx_dtx_handler
+     *  Purpose     : reads the frame type and checks history
+     *  Description : to decide what kind of DTX/CNI action to perform
+     */
+    enum DTXStateType rx_dtx_handler(dtx_decState *st,           /* i/o : State struct */
+                                     enum RXFrameType frame_type,/* i   : Frame type   */
+                                     Flag *pOverflow);
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* DEC_AMR_H_ */
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ec_gains.cpp b/media/libstagefright/codecs/amrnb/dec/src/ec_gains.cpp
new file mode 100644
index 0000000..e73db62
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ec_gains.cpp
@@ -0,0 +1,842 @@
+/* ------------------------------------------------------------------
+ * 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/ec_gain.c
+ Funtions:
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed the functions ec_gain_code_init, ec_gain_pitch_init,
+ ech_gain_code_exit, and ec_gain_pitch_exit.
+
+ The ec_gains related structures are no longer dynamically allocated.
+
+ Description: Updated include files and input/output sections.
+
+ 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
+
+ These modules execute the code book gains for error concealment. This module
+ contains the init, reset, exit, and "main" functions in this process.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "ec_gains.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "gmed_n.h"
+#include "gc_pred.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.
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; LOCAL VARIABLE DEFINITIONS
+    ; Variable declaration - defined here and used outside this module
+    ----------------------------------------------------------------------------*/
+
+    extern const Word16 qua_gain_pitch[];
+    extern const Word16 qua_gain_code[];
+
+
+    /*--------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_code_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  state = pointer to a pointer to a structure containing code state data of
+          stucture type ec_gain_codeState
+
+ Outputs:
+    None.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function resets the state data for the ec_gain module.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ None
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ec_gain_code_reset (ec_gain_codeState *state)
+{
+  Word16 i;
+
+  if (state == (ec_gain_codeState *) NULL){
+      // fprintf(stderr, "ec_gain_code_reset: invalid parameter\n");
+      return -1;
+  }
+
+  for ( i = 0; i < 5; i++)
+      state->gbuf[i] = 1;
+  state->past_gain_code = 0;
+  state->prev_gc = 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 ec_gain_code_reset(ec_gain_codeState *state)
+{
+    Word16 i;
+
+    if (state == (ec_gain_codeState *) NULL)
+    {
+        /* fprintf(stderr, "ec_gain_code_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    for (i = 0; i < 5; i++)
+        state->gbuf[i] = 1;
+    state->past_gain_code = 0;
+    state->prev_gc = 1;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_code
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  st = pointer to a pointer to a structure containing code state data of
+       stucture type ec_gain_codeState
+  pred_state = pointer to MA predictor state of type gc_predState
+  state  = state of the state machine of type Word16
+  gain_code = pointer to decoded innovation gain of type Word16
+  pOverflow = pointer to overflow indicator of type Flag
+
+ Outputs:
+  st = pointer to a pointer to a structure containing code state data of
+       stucture type ec_gain_codeState
+  pred_state = pointer to MA predictor state of type gc_predState
+  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 does error concealment using the codebook. Call this function
+only in BFI (instead of normal gain decoding function).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ec_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    static const Word16 cdown[7] =
+    {
+        32767, 32112, 32112, 32112,
+        32112, 32112, 22937
+    };
+
+    Word16 tmp;
+    Word16 qua_ener_MR122;
+    Word16 qua_ener;
+
+    // calculate median of last five gain values
+    tmp = gmed_n (st->gbuf,5);
+
+    // new gain = minimum(median, past_gain) * cdown[state]
+    if (sub (tmp, st->past_gain_code) > 0)
+    {
+        tmp = st->past_gain_code;
+    }
+    tmp = mult (tmp, cdown[state]);
+    *gain_code = tmp;
+
+    // update table of past quantized energies with average of
+    // current values
+
+    gc_pred_average_limited(pred_state, &qua_ener_MR122, &qua_ener);
+    gc_pred_update(pred_state, 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 ec_gain_code(
+    ec_gain_codeState *st,    /* i/o : State struct                     */
+    gc_predState *pred_state, /* i/o : MA predictor state               */
+    Word16 state,             /* i   : state of the state machine       */
+    Word16 *gain_code,        /* o   : decoded innovation gain          */
+    Flag   *pOverflow
+)
+{
+    static const Word16 cdown[7] =
+    {
+        32767, 32112, 32112, 32112,
+        32112, 32112, 22937
+    };
+
+    Word16 tmp;
+    Word16 qua_ener_MR122;
+    Word16 qua_ener;
+
+    /* calculate median of last five gain values */
+    tmp = gmed_n(st->gbuf, 5);
+
+    /* new gain = minimum(median, past_gain) * cdown[state] */
+    if (sub(tmp, st->past_gain_code, pOverflow) > 0)
+    {
+        tmp = st->past_gain_code;
+    }
+    tmp = mult(tmp, cdown[state], pOverflow);
+    *gain_code = tmp;
+
+    /* update table of past quantized energies with average of
+     * current values
+     */
+    gc_pred_average_limited(pred_state, &qua_ener_MR122, &qua_ener, pOverflow);
+    gc_pred_update(pred_state, qua_ener_MR122, qua_ener);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_code_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  st = pointer to a pointer to a structure containing code state data of
+       stucture type ec_gain_codeState
+  bfi = a flag that indicates if the frame is bad of type Word16
+  prev_bf = a flag that indicates if the previous frame was bad of type Word16
+  gain_code = pointer to decoded innovation gain of type Word16
+  pOverflow = pointer to overflow indicator of type Flag
+
+ Outputs:
+  st = pointer to a pointer to a structure containing code state data of
+       stucture type ec_gain_codeState
+  gain_code = pointer to decoded innovation gain of type Word16
+  pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Purpose     : update the codebook gain concealment state;
+                limit gain_code if the previous frame was bad
+                Call this function always after decoding (or concealing)
+                the gain
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ec_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    Word16 i;
+
+    // limit gain_code by previous good gain if previous frame was bad
+    if (bfi == 0)
+    {
+        if (prev_bf != 0)
+        {
+            if (sub (*gain_code, st->prev_gc) > 0)
+            {
+                *gain_code = st->prev_gc;
+            }
+        }
+        st->prev_gc = *gain_code;
+    }
+
+    // update EC states: previous gain, gain buffer
+    st->past_gain_code = *gain_code;
+
+    for (i = 1; i < 5; i++)
+    {
+        st->gbuf[i - 1] = st->gbuf[i];
+    }
+    st->gbuf[4] = *gain_code;
+
+    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 ec_gain_code_update(
+    ec_gain_codeState *st,    /* i/o : State struct                     */
+    Word16 bfi,               /* i   : flag: frame is bad               */
+    Word16 prev_bf,           /* i   : flag: previous frame was bad     */
+    Word16 *gain_code,        /* i/o : decoded innovation gain          */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+
+    /* limit gain_code by previous good gain if previous frame was bad */
+    if (bfi == 0)
+    {
+        if (prev_bf != 0)
+        {
+            if (sub(*gain_code, st->prev_gc, pOverflow) > 0)
+            {
+                *gain_code = st->prev_gc;
+            }
+        }
+        st->prev_gc = *gain_code;
+    }
+
+    /* update EC states: previous gain, gain buffer */
+    st->past_gain_code = *gain_code;
+
+    for (i = 1; i < 5; i++)
+    {
+        st->gbuf[i - 1] = st->gbuf[i];
+    }
+    st->gbuf[4] = *gain_code;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_pitch
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  st = pointer to a pointer to a structure containing code
+       state data of stucture type ec_gain_pitchState
+  state = state of the state machine of type Word16
+  pOverflow = pointer to overflow indicator of type Flag
+
+  Outputs:
+  state = pointer to a pointer to a structure containing code
+          state data of stucture type ec_gain_pitchState
+  gain_pitch = pointer to pitch gain (Q14) of type Word16
+  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 conceals the error using code gain implementation in this
+ function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ec_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+    static const Word16 pdown[7] =
+    {
+        32767, 32112, 32112, 26214,
+        9830, 6553, 6553
+    };
+
+    Word16 tmp;
+
+    // calculate median of last five gains
+    tmp = gmed_n (st->pbuf, 5);
+
+    // new gain = minimum(median, past_gain) * pdown[state]
+    if (sub (tmp, st->past_gain_pit) > 0)
+    {
+        tmp = st->past_gain_pit;
+    }
+    *gain_pitch = mult (tmp, pdown[state]);
+
+
+------------------------------------------------------------------------------
+ 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 ec_gain_pitch(
+    ec_gain_pitchState *st, /* i/o : state variables                   */
+    Word16 state,           /* i   : state of the state machine        */
+    Word16 *gain_pitch,     /* o   : pitch gain (Q14)                  */
+    Flag   *pOverflow
+)
+{
+    static const Word16 pdown[7] =
+    {
+        32767, 32112, 32112, 26214,
+        9830, 6553, 6553
+    };
+
+    Word16 tmp;
+
+    /* calculate median of last five gains */
+    tmp = gmed_n(st->pbuf, 5);
+
+    /* new gain = minimum(median, past_gain) * pdown[state] */
+    if (sub(tmp, st->past_gain_pit, pOverflow) > 0)
+    {
+        tmp = st->past_gain_pit;
+    }
+    *gain_pitch = mult(tmp, pdown[state], pOverflow);
+}
+
+/****************************************************************************/
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_pitch_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  state = state of the state machine of type Word16
+  pOverflow = pointer to overflow indicator of type Flag
+
+  Outputs:
+  state = pointer to a pointer to a structure containing code
+          state data of stucture type ec_gain_pitchState
+  pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Function:   ec_gain_pitch_reset
+ Purpose:    Resets state memory
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ec_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ec_gain_pitch_reset (ec_gain_pitchState *state)
+{
+  Word16 i;
+
+  if (state == (ec_gain_pitchState *) NULL){
+      // fprintf(stderr, "ec_gain_pitch_reset: invalid parameter\n");
+      return -1;
+  }
+
+  for(i = 0; i < 5; i++)
+      state->pbuf[i] = 1640;
+  state->past_gain_pit = 0;
+  state->prev_gp = 16384;
+
+  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 ec_gain_pitch_reset(ec_gain_pitchState *state)
+{
+    Word16 i;
+
+    if (state == (ec_gain_pitchState *) NULL)
+    {
+        /* fprintf(stderr, "ec_gain_pitch_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    for (i = 0; i < 5; i++)
+        state->pbuf[i] = 1640;
+    state->past_gain_pit = 0;
+    state->prev_gp = 16384;
+
+    return 0;
+}
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ec_gain_pitch_update
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+  st = pointer to a pointer to a structure containing code
+       state data of stucture type ec_gain_pitchState
+  bfi = flag indicating the frame is bad of type Word16
+  prev_bf = flag indicating the previous frame was bad of type Word16
+  gain_pitch = pointer to pitch gain of type Word16
+  pOverflow = pointer to overflow indicator of type Flag
+
+  Outputs:
+  state = pointer to a pointer to a structure containing code
+          state data of stucture type ec_gain_pitchState
+  gain_pitch = pointer to pitch gain of type Word16
+  pOverflow = 1 if there is an overflow else it is zero.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+  Purpose     : update the pitch gain concealment state;
+                limit gain_pitch if the previous frame was bad
+                Call this function always after decoding (or concealing)
+                the gain
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ec_gain.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    Word16 i;
+
+    if (bfi == 0)
+    {
+        if (prev_bf != 0)
+        {
+            if (sub (*gain_pitch, st->prev_gp) > 0)
+            {
+                *gain_pitch = st->prev_gp;
+            }
+        }
+        st->prev_gp = *gain_pitch;
+    }
+
+    st->past_gain_pit = *gain_pitch;
+
+    if (sub (st->past_gain_pit, 16384) > 0)  // if (st->past_gain_pit > 1.0)
+    {
+        st->past_gain_pit = 16384;
+    }
+    for (i = 1; i < 5; i++)
+    {
+        st->pbuf[i - 1] = st->pbuf[i];
+    }
+    st->pbuf[4] = st->past_gain_pit;
+
+
+------------------------------------------------------------------------------
+ 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 ec_gain_pitch_update(
+    ec_gain_pitchState *st, /* i/o : state variables                   */
+    Word16 bfi,             /* i   : flag: frame is bad                */
+    Word16 prev_bf,         /* i   : flag: previous frame was bad      */
+    Word16 *gain_pitch,     /* i/o : pitch gain                        */
+    Flag   *pOverflow
+)
+{
+    Word16 i;
+
+    if (bfi == 0)
+    {
+        if (prev_bf != 0)
+        {
+            if (sub(*gain_pitch, st->prev_gp, pOverflow) > 0)
+            {
+                *gain_pitch = st->prev_gp;
+            }
+        }
+        st->prev_gp = *gain_pitch;
+    }
+
+    st->past_gain_pit = *gain_pitch;
+
+    if (sub(st->past_gain_pit, 16384, pOverflow) > 0)
+        /* if (st->past_gain_pit > 1.0) */
+    {
+        st->past_gain_pit = 16384;
+    }
+    for (i = 1; i < 5; i++)
+    {
+        st->pbuf[i - 1] = st->pbuf[i];
+    }
+    st->pbuf[4] = st->past_gain_pit;
+}
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ec_gains.h b/media/libstagefright/codecs/amrnb/dec/src/ec_gains.h
new file mode 100644
index 0000000..e05a0af
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ec_gains.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/ec_gains.h
+
+     Date: 01/28/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+      File             : ec_gains.c
+      Purpose:         : Error concealment for pitch and codebook gains
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _EC_GAINS_H_
+#define _EC_GAINS_H_
+#define ec_gains_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.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
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 pbuf[5];
+        Word16 past_gain_pit;
+        Word16 prev_gp;
+    } ec_gain_pitchState;
+
+    typedef struct
+    {
+        Word16 gbuf[5];
+        Word16 past_gain_code;
+        Word16 prev_gc;
+    } ec_gain_codeState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    /*
+     *  Function    : ec_gain_code_reset
+     *  Purpose     : Resets state memory
+     *
+     */
+    Word16 ec_gain_code_reset(
+        ec_gain_codeState *state
+    );
+
+
+    /*
+     *  Function    : ec_gain_code
+     *  Purpose     : conceal the codebook gain
+     *                Call this function only in BFI (instead of normal gain
+     *                decoding function)
+     */
+    void ec_gain_code(
+        ec_gain_codeState *st,    /* i/o : State struct                     */
+        gc_predState *pred_state, /* i/o : MA predictor state               */
+        Word16 state,             /* i   : state of the state machine       */
+        Word16 *gain_code,        /* o   : decoded innovation gain          */
+        Flag   *pOverflow
+    );
+
+    /*
+     *  Function    : ec_gain_code_update
+     *  Purpose     : update the codebook gain concealment state;
+     *                limit gain_code if the previous frame was bad
+     *                Call this function always after decoding (or concealing)
+     *                the gain
+     */
+    void ec_gain_code_update(
+        ec_gain_codeState *st,    /* i/o : State struct                     */
+        Word16 bfi,               /* i   : flag: frame is bad               */
+        Word16 prev_bf,           /* i   : flag: previous frame was bad     */
+        Word16 *gain_code,        /* i/o : decoded innovation gain          */
+        Flag   *pOverflow
+    );
+
+
+    /*
+     *  Function:   ec_gain_pitch_reset
+     *  Purpose:    Resets state memory
+     */
+    Word16 ec_gain_pitch_reset(
+        ec_gain_pitchState *state
+    );
+
+    /*
+     *  Function    : ec_gain_pitch_exit
+     *  Purpose     : The memory used for state memory is freed
+     */
+    void ec_gain_pitch_exit(
+        ec_gain_pitchState **state
+    );
+
+    /*
+     *  Function    : ec_gain_pitch
+     *  Purpose     : conceal the pitch gain
+     *                Call this function only in BFI (instead of normal gain
+     *                decoding function)
+     */
+    void ec_gain_pitch(
+        ec_gain_pitchState *st, /* i/o : state variables                   */
+        Word16 state,           /* i   : state of the state machine        */
+        Word16 *gain_pitch,     /* o   : pitch gain (Q14)                  */
+        Flag   *pOverflow
+    );
+
+    /*
+     *  Function    : ec_gain_pitch_update
+     *  Purpose     : update the pitch gain concealment state;
+     *                limit gain_pitch if the previous frame was bad
+     *                Call this function always after decoding (or concealing)
+     *                the gain
+     */
+    void ec_gain_pitch_update(
+        ec_gain_pitchState *st, /* i/o : state variables                   */
+        Word16 bfi,             /* i   : flag: frame is bad                */
+        Word16 prev_bf,         /* i   : flag: previous frame was bad      */
+        Word16 *gain_pitch,     /* i/o : pitch gain                        */
+        Flag   *pOverflow
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _EC_GAINS_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.cpp b/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.cpp
new file mode 100644
index 0000000..f18054b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.cpp
@@ -0,0 +1,219 @@
+/* ------------------------------------------------------------------
+ * 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/ex_ctrl.c
+ Funtions: ex_ctrl
+
+     Date: 02/08/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "ex_ctrl.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "copy.h"
+#include "set_zero.h"
+#include "gmed_n.h"
+#include "sqrt_l.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: ex_ctrl
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+ excitation = pointer to current subframe excitation of type Word16
+ excEnergy = Exc. Energy, sqrt(totEx*totEx) of type Word16
+ exEnergyHist = pointer to history of subframe energies of type Word16
+ voicedHangover = # of fr. after last voiced fr  of type Word16
+ carefulFlag = restrict dynamic in scaling of type Word16
+ pOverflow = pointer to overflow indicator
+
+ Outputs:
+ pOverflow = 1 if overflow exists in the math functions called by this function.
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Function    : Ex_ctrl
+ Purpose     : Charaterice synthesis speech and detect background noise
+ Returns     : background noise decision; 0 = no bgn, 1 = bgn
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ex_ctrl.c, 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]
+
+------------------------------------------------------------------------------
+*/
+Word16 Ex_ctrl(Word16 excitation[],    /*i/o: Current subframe excitation   */
+               Word16 excEnergy,      /* i : Exc. Energy, sqrt(totEx*totEx)*/
+               Word16 exEnergyHist[], /* i : History of subframe energies  */
+               Word16 voicedHangover, /* i : # of fr. after last voiced fr.*/
+               Word16 prevBFI,        /* i : Set i previous BFI            */
+               Word16 carefulFlag,    /* i : Restrict dymamic in scaling   */
+               Flag   *pOverflow
+              )
+{
+    Word16 i, exp;
+    Word16 testEnergy, scaleFactor, avgEnergy, prevEnergy;
+    Word32 t0;
+
+    /* get target level */
+    avgEnergy = gmed_n(exEnergyHist, 9);
+
+    prevEnergy = shr(add(exEnergyHist[7], exEnergyHist[8], pOverflow) , 1, pOverflow);
+
+    if (exEnergyHist[8] < prevEnergy)
+    {
+        prevEnergy = exEnergyHist[8];
+    }
+
+    /* upscaling to avoid too rapid energy rises  for some cases */
+    if ((excEnergy < avgEnergy) && (excEnergy > 5))
+    {
+        testEnergy = shl(prevEnergy, 2, pOverflow);  /* testEnergy = 4*prevEnergy; */
+
+        if ((voicedHangover < 7) || prevBFI != 0)
+        {
+            /* testEnergy = 3*prevEnergy */
+            testEnergy = sub(testEnergy, prevEnergy, pOverflow);
+        }
+
+        if (avgEnergy > testEnergy)
+        {
+            avgEnergy = testEnergy;
+        }
+
+        /* scaleFactor=avgEnergy/excEnergy in Q0 (const 29 below)*/
+        exp = norm_s(excEnergy);
+        excEnergy = shl(excEnergy, exp, pOverflow);
+        excEnergy = div_s((Word16) 16383, excEnergy);
+        t0 = L_mult(avgEnergy, excEnergy, pOverflow);
+        t0 = L_shr(t0, sub(20, exp, pOverflow), pOverflow);
+        /* const=30 for t0 in Q0, 20 for Q10 */
+        if (t0 > 32767)
+        {
+            t0 = 32767; /* saturate  */
+        }
+        scaleFactor = extract_l(t0);
+
+        /* test if scaleFactor > 3.0 */
+        if (carefulFlag != 0 && (scaleFactor > 3072))
+        {
+            scaleFactor = 3072;
+        }
+
+        /* scale the excitation by scaleFactor */
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            t0 = L_mult(scaleFactor, excitation[i], pOverflow);
+            t0 = L_shr(t0, 11, pOverflow);
+            excitation[i] = extract_l(t0);
+        }
+    }
+
+    return 0;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.h b/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.h
new file mode 100644
index 0000000..11c632e
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ex_ctrl.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/ex_ctrl.h
+
+     Date: 02/08/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+     File             : ex_ctrl.h
+     Purpose          : Excitation Control module in background noise
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef ex_ctrl_h
+#define ex_ctrl_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.
+    ----------------------------------------------------------------------------*/
+#define L_ENERGYHIST 60
+    /*----------------------------------------------------------------------------
+    ; 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    : Ex_ctrl
+     *  Purpose     : Charaterice synthesis speech and detect background noise
+     *  Returns     : background noise decision; 0 = bgn, 1 = no bgn
+     */
+    Word16 Ex_ctrl(Word16 excitation[],    /*i/o: Current subframe excitation   */
+    Word16 excEnergy,      /* i : Exc. Energy, sqrt(totEx*totEx)*/
+    Word16 exEnergyHist[], /* i : History of subframe energies  */
+    Word16 voicedHangover, /* i : # of fr. after last voiced fr.*/
+    Word16 prevBFI,        /* i : Set i previous BFI            */
+    Word16 carefulFlag,    /* i : Restrict dymamic in scaling   */
+    Flag   *pOverflow
+                  );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _ex_ctrl_h_ */
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/gsmamr_dec.h b/media/libstagefright/codecs/amrnb/dec/src/gsmamr_dec.h
new file mode 100644
index 0000000..673a94a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/gsmamr_dec.h
@@ -0,0 +1,187 @@
+/* ------------------------------------------------------------------
+ * 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_dec.h
+
+     Date: 09/10/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Adding comments and removing some tables as per review comments.
+
+ Description: Replace enum Mode with enum Frame_Type_3GPP and updated function
+              prototype of AMRDecode().
+
+ Description: Added back the enum Mode type definition, removed RXFrameType
+              type definition, and updated AMRDecode and GSMInitDecode function
+              prototypes.
+
+ Description: Added #defines for WMF and IF2. Updated AMRDecode function
+              prototype.
+
+ Description: Removed enum Mode type definition and updated AMRDecode function
+              prototype.
+
+ Description: Renamed WMF and IF2 to AMR_WMF and AMR_IF2, respectively. Added
+              #define for AMR_ETS format.
+
+ Description: Rename input format defines to make it unique to the decoder.
+
+ Description: Added comment to describe L_FRAME.
+
+ Description: Moved _cplusplus #ifdef after Include section.
+
+ Description: Included file "typedefs.h" to avoid re-declaring similar typedef
+              this for OSCL-ed compatibility
+
+ Description: Included file "gsm_amr_typedefs.h" and eliminated re-definition
+              of types UWord8, Word8, Word16
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This header contains all the necessary information needed to allow the gsm amr
+ decoder library to be used properly upon release.
+
+------------------------------------------------------------------------------
+*/
+#ifndef _GSMAMR_DEC_H_
+#define _GSMAMR_DEC_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "gsm_amr_typedefs.h"
+#include "pvamrnbdecoder_api.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
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    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
+    ----------------------------------------------------------------------------*/
+    /*
+     * This function allocates memory for filter structure and initializes state
+     * memory used by the GSM AMR decoder. This function returns zero. It will
+     * return negative one if there is an error.
+     */
+    Word16 GSMInitDecode(void **state_data,
+                         Word8 *id);
+
+    /*
+     * AMRDecode steps into the part of the library that decodes the raw data
+     * speech bits for the decoding process. It returns the address offset of
+     * the next frame to be decoded.
+     */
+    Word16 AMRDecode(
+        void                      *state_data,
+        enum Frame_Type_3GPP      frame_type,
+        UWord8                    *speech_bits_ptr,
+        Word16                    *raw_pcm_buffer,
+        Word16                    input_format
+    );
+
+    /*
+     * This function resets the state memory used by the GSM AMR decoder. This
+     * function returns zero. It will return negative one if there is an error.
+     */
+    Word16 Speech_Decode_Frame_reset(void *state_data);
+
+    /*
+     * This function frees up the memory used for the state memory of the
+     * GSM AMR decoder.
+     */
+    void GSMDecodeFrameExit(void **state_data);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _GSMAMR_DEC_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.cpp b/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.cpp
new file mode 100644
index 0000000..733c8b8
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.cpp
@@ -0,0 +1,196 @@
+/* ------------------------------------------------------------------
+ * 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/if2_to_ets.c
+ Funtions: if2_to_ets
+
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "frame_type_3gpp.h"
+#include "if2_to_ets.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: if2_to_ets
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    frame_type_3gpp = decoder speech bit rate (enum Frame_Type_3GPP)
+    if2_input_ptr   = pointer to input encoded speech bits in IF2 format (Word8)
+    ets_output_ptr  = pointer to output encoded speech bits in ETS format (Word16)
+
+ Outputs:
+    ets_output_ptr  = pointer to encoded speech bits in the ETS format (Word16)
+
+ 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 IF2 to ETS. 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. ETS format has the encoded speech
+ bits each separate with only one bit stored in each word.
+
+------------------------------------------------------------------------------
+ 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 if2_to_ets(
+    enum Frame_Type_3GPP frame_type_3gpp,
+    UWord8   *if2_input_ptr,
+    Word16   *ets_output_ptr)
+{
+
+    Word16 i;
+    Word16 j;
+    Word16 x = 0;
+
+    /*
+     * The following section of code accesses bits in the IF2 method of
+     * bit ordering. Each bit is given its own location in the buffer pointed
+     * to by ets_output_ptr. The bits (for modes less than AMR_SID) are
+     * reordered using the tables in bitreorder.c before the data is stored
+     * into the buffer pointed to by ets_output_ptr.
+     */
+
+    if (frame_type_3gpp < AMR_SID)
+    {
+        for (j = 4; j < 8; j++)
+        {
+            ets_output_ptr[reorderBits[frame_type_3gpp][x++]] =
+                (if2_input_ptr[0] >> j) & 0x01;
+        }
+        for (i = 1; i < numCompressedBytes[frame_type_3gpp]; i++)
+        {
+            for (j = 0; j < 8; j++)
+            {
+                if (x >= numOfBits[frame_type_3gpp])
+                {
+                    break;
+                }
+                ets_output_ptr[reorderBits[frame_type_3gpp][x++]] =
+                    (if2_input_ptr[i] >> j) & 0x01;
+            }
+        }
+    }
+    else
+    {
+        for (j = 4; j < 8; j++)
+        {
+            ets_output_ptr[x++] =
+                (if2_input_ptr[0] >> j) & 0x01;
+        }
+        for (i = 1; i < numCompressedBytes[frame_type_3gpp]; i++)
+        {
+            for (j = 0; j < 8; j++)
+            {
+                ets_output_ptr[x++] =
+                    (if2_input_ptr[i] >> j) & 0x01;
+            }
+        }
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.h b/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.h
new file mode 100644
index 0000000..490565d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/if2_to_ets.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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+
+
+ Pathname: ./audio/gsm-amr/include/src/if2_to_ets.h
+
+     Date: 01/22/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changed mode to frame_type_3gpp
+
+ 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 if2_to_ets function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef IF2_TO_ETS_H
+#define IF2_TO_ETS_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 if2_to_ets(enum Frame_Type_3GPP frame_type_3gpp,
+    UWord8   *if2_input_ptr,
+    Word16   *ets_output_ptr);
+
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrnb/dec/src/int_lsf.cpp b/media/libstagefright/codecs/amrnb/dec/src/int_lsf.cpp
new file mode 100644
index 0000000..c5aefe4
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/int_lsf.cpp
@@ -0,0 +1,315 @@
+/* ------------------------------------------------------------------
+ * 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/int_lsf.c
+
+     Date: 04/20/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Put file into template and first pass at optimization.
+
+ Description: Made changes based on comments from the review meeting. Used
+    pointers instead of index addressing in the arrays.
+
+ Description: Added type definition to the input/output section. Fixed tabs.
+              Deleted pseudo-code.
+
+ Description: Synchronized file with UMTS versin 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. Made some cosmetic changes in the Pseudo-code section.
+
+ Description: Changed to pass in overflow flag pointer to the add() routine.
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "int_lsf.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 STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Int_lsf
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    lsf_old = LSF vector at the 4th SF of past frame (Word16)
+    lsf_new = LSF vector at the 4th SF of present frame (Word16)
+    i_subfr = Current subframe (equal to 0,40,80 or 120) (Word16)
+    lsf_out = interpolated LSF parameters for current subframe (Word16)
+
+ Outputs:
+    lsf_out   = new interpolated LSF parameters for current subframe
+    pOverflow = pointer of type Flag * to overflow indicator.
+
+ Returns:
+    None.
+
+ Global Variables Used:
+    None.
+
+ Local Variables Needed:
+    None.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function interpolates the LSFs for selected subframe.
+ The 20 ms speech frame is divided into 4 subframes. The LSFs are
+ interpolated at the 1st, 2nd and 3rd subframe and only forwarded
+ at the 4th subframe.
+
+                      |------|------|------|------|
+                         sf1    sf2    sf3    sf4
+                   F0                          F1
+
+                 sf1:   3/4 F0 + 1/4 F1         sf3:   1/4 F0 + 3/4 F1
+                 sf2:   1/2 F0 + 1/2 F1         sf4:       F1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ int_lsf.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void Int_lsf(
+    Word16 lsf_old[], // i : LSF vector at the 4th SF of past frame
+    Word16 lsf_new[], // i : LSF vector at the 4th SF of present frame
+    Word16 i_subfr,   // i : Pointer to current sf (equal to 0,40,80 or 120)
+    Word16 lsf_out[]  // o : interpolated LSF parameters for current sf
+)
+{
+    Word16 i;
+
+    if ( i_subfr == 0 )
+    {
+       for (i = 0; i < M; i++) {
+          lsf_out[i] = add(sub(lsf_old[i], shr(lsf_old[i], 2)),
+                           shr(lsf_new[i], 2));
+       }
+    }
+    else if ( sub(i_subfr, 40) == 0 )
+    {
+       for (i = 0; i < M; i++) {
+          lsf_out[i] = add(shr(lsf_old[i],1), shr(lsf_new[i], 1) );
+       }
+    }
+    else if ( sub(i_subfr, 80) == 0 )
+    {
+       for (i = 0; i < M; i++) {
+          lsf_out[i] = add(shr(lsf_old[i], 2),
+                           sub(lsf_new[i], shr(lsf_new[i], 2)));
+       }
+    }
+    else if ( sub(i_subfr, 120) == 0 )
+    {
+       for (i = 0; i < M; i++) {
+          lsf_out[i] = lsf_new[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]
+
+------------------------------------------------------------------------------
+*/
+
+void Int_lsf(
+    Word16 lsf_old[], /* i : LSF vector at the 4th SF of past frame         */
+    Word16 lsf_new[], /* i : LSF vector at the 4th SF of present frame      */
+    Word16 i_subfr,   /* i : Current sf (equal to 0,40,80 or 120)           */
+    Word16 lsf_out[], /* o : interpolated LSF parameters for current sf     */
+    Flag  *pOverflow  /* o : flag set if overflow occurs                    */
+)
+{
+    register Word16 i;
+    register Word16 temp1;
+    register Word16 temp2;
+
+    if (i_subfr == 0)
+    {
+        for (i = M - 1; i >= 0; i--)
+        {
+            if (*(lsf_old + i) < 0)
+            {
+                temp1 = ~(~(*(lsf_old + i)) >> 2);
+            }
+            else
+            {
+                temp1 = *(lsf_old + i) >> 2;
+            }
+            if (*(lsf_new + i) < 0)
+            {
+                temp2 = ~(~(*(lsf_new + i)) >> 2);
+            }
+            else
+            {
+                temp2 = *(lsf_new + i) >> 2;
+            }
+            *(lsf_out + i) = add((Word16)(*(lsf_old + i) - temp1),
+                                 (Word16)temp2,
+                                 pOverflow);
+        }
+    }
+
+    else if (i_subfr == 40)
+    {
+        for (i = M - 1; i >= 0; i--)
+        {
+            if (*(lsf_old + i) < 0)
+            {
+                temp1 = ~(~(*(lsf_old + i)) >> 1);
+            }
+            else
+            {
+                temp1 = *(lsf_old + i) >> 1;
+            }
+            if (*(lsf_new + i) < 0)
+            {
+                temp2 = ~(~(*(lsf_new + i)) >> 1);
+            }
+            else
+            {
+                temp2 = *(lsf_new + i) >> 1;
+            }
+            *(lsf_out + i) = add(
+                                 temp1,
+                                 temp2,
+                                 pOverflow);
+        }
+    }
+
+    else if (i_subfr == 80)
+    {
+        for (i = M - 1; i >= 0; i--)
+        {
+            if (*(lsf_old + i) < 0)
+            {
+                temp1 = ~(~(*(lsf_old + i)) >> 2);
+            }
+            else
+            {
+                temp1 = *(lsf_old + i) >> 2;
+            }
+            if (*(lsf_new + i) < 0)
+            {
+                temp2 = ~(~(*(lsf_new + i)) >> 2);
+            }
+            else
+            {
+                temp2 = *(lsf_new + i) >> 2;
+            }
+            *(lsf_out + i) = add((Word16)temp1,
+                                 (Word16)(*(lsf_new + i) - temp2),
+                                 pOverflow);
+
+        }
+    }
+
+    else if (i_subfr == 120)
+    {
+        for (i = M - 1; i >= 0; i--)
+        {
+            *(lsf_out + i) = *(lsf_new + i);
+        }
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.cpp b/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.cpp
new file mode 100644
index 0000000..9b65c7a
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.cpp
@@ -0,0 +1,317 @@
+/* ------------------------------------------------------------------
+ * 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/lsp_avg.c
+ Functions:
+
+
+     Date: 04/14/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed the functions lsp_avg_init and lsp_avg_exit.
+ The lsp_avg related structure is no longer dynamically allocated.
+
+ Also, placed code in the proper PV Software Template.
+
+ Description: Per review comments, updated the inputs/outputs section
+ for the function lsp_avg.
+
+ Description: Changed to accept the pOverflow flag for EPOC compatibility.
+
+ Description: Per review comments, I added a description of pOverflow
+ to the input/output section of the template.  I also removed an unnecessary
+ include file, <stdio.h>
+
+ Description: Removed q_plsf_5.tab from Include section and added
+              q_plsf_5_tbl.h to Include section. Changed "mean_lsf"
+              to "mean_lsf_5" in lsp_avg_reset().
+
+ 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
+
+    LSP averaging and history
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "lsp_avg.h"
+#include "basic_op.h"
+#include "oper_32b.h"
+#include "copy.h"
+#include "q_plsf_5_tbl.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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp_avg_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structure of type lsp_avgState
+
+ Outputs:
+    fields of the structure pointed to by state are initialized.
+
+ Returns:
+    return_value = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+lsp_avg.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int lsp_avg_reset (lsp_avgState *st)
+{
+  if (st == (lsp_avgState *) NULL){
+      // fprintf(stderr, "lsp_avg_reset: invalid parameter\n");
+      return -1;
+  }
+
+  Copy(mean_lsf, &st->lsp_meanSave[0], M);
+
+  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 lsp_avg_reset(lsp_avgState *st)
+{
+    if (st == (lsp_avgState *) NULL)
+    {
+        /* fprintf(stderr, "lsp_avg_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    Copy(mean_lsf_5, &st->lsp_meanSave[0], M);
+
+    return 0;
+}
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: lsp_avg
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st  = pointer to structure of type lsp_avgState
+    lsp = pointer to Word16, which reflects the state of the state machine
+
+ Outputs:
+    st = pointer to structure of type lsp_avgState
+    pOverflow = pointer to type Flag -- overflow indicator
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+lsp_avg.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+
+void lsp_avg (
+    lsp_avgState *st,         // i/o : State struct                 Q15
+    Word16 *lsp               // i   : state of the state machine   Q15
+)
+{
+    Word16 i;
+    Word32 L_tmp;            // Q31
+
+    for (i = 0; i < M; i++) {
+
+       // mean = 0.84*mean
+       L_tmp = L_deposit_h(st->lsp_meanSave[i]);
+       L_tmp = L_msu(L_tmp, EXPCONST, st->lsp_meanSave[i]);
+
+       // Add 0.16 of newest LSPs to mean
+       L_tmp = L_mac(L_tmp, EXPCONST, lsp[i]);
+
+       // Save means
+       st->lsp_meanSave[i] = pv_round(L_tmp);   // Q15
+    }
+
+    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 lsp_avg(
+    lsp_avgState *st,         /* i/o : State struct                 Q15 */
+    Word16 *lsp,              /* i   : state of the state machine   Q15 */
+    Flag   *pOverflow         /* o   : Flag set when overflow occurs    */
+)
+{
+    Word16 i;
+    Word32 L_tmp;            /* Q31 */
+
+    for (i = 0; i < M; i++)
+    {
+
+        /* mean = 0.84*mean */
+        L_tmp = L_deposit_h(st->lsp_meanSave[i]);
+        L_tmp = L_msu(L_tmp, EXPCONST, st->lsp_meanSave[i], pOverflow);
+
+        /* Add 0.16 of newest LSPs to mean */
+        L_tmp = L_mac(L_tmp, EXPCONST, lsp[i], pOverflow);
+
+        /* Save means */
+        st->lsp_meanSave[i] = pv_round(L_tmp, pOverflow);   /* Q15 */
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.h b/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.h
new file mode 100644
index 0000000..b289c08
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/lsp_avg.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/lsp_avg.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: Per review comments, I removed the prototype definition
+ of lsp_avg_init and lsp_avg_exit.
+
+ 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 lsp_avg.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef lsp_avg_h
+#define lsp_avg_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.
+    ----------------------------------------------------------------------------*/
+#define EXPCONST          5243               /* 0.16 in Q15 */
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 lsp_meanSave[M];          /* Averaged LSPs saved for efficiency  */
+    } lsp_avgState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 lsp_avg_reset(
+        lsp_avgState *state
+    );
+
+
+    void lsp_avg(
+        lsp_avgState *st,     /* i/o : State struct                 Q15 */
+        Word16 *lsp,          /* i   : LSP vector                   Q15 */
+        Flag   *pOverflow     /* o   : Flag set when overflow occurs    */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LSP_LSF_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ph_disp.cpp b/media/libstagefright/codecs/amrnb/dec/src/ph_disp.cpp
new file mode 100644
index 0000000..da5445b
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ph_disp.cpp
@@ -0,0 +1,898 @@
+/* ------------------------------------------------------------------
+ * 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/ph_disp.c
+ Functions:
+            ph_disp_reset
+            ph_disp_lock
+            ph_disp_release
+            ph_disp
+
+     Date: 04/05/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: Clarified grouping in the equation to calculated L_temp from the
+          product of state->prevCbGain and ONFACTPLUS1 in the ph_disp
+          function.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              coding template. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header file of the math functions
+              used in the file.
+
+ Description: Removed the functions ph_disp_init and ph_disp_exit.
+ The ph_disp related structure is no longer dynamically allocated.
+
+ Description: Pass in pointer to overflow flag for EPOC compatibility.
+              Change code for ph_disp() function to reflect this. Remove
+              inclusion of ph_disp.tab. This table will now be referenced
+              externally.
+
+ Description: Optimized ph_disp() to reduce clock cycle usage. Updated
+              copyright year and removed unused files in Include section.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ Description: Changed round function name to pv_round to avoid conflict with
+              round function in C standard library.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the function that performs adaptive phase dispersion of
+ the excitation signal. The phase dispersion initialization, reset, and
+ exit functions are included in this file, as well as, the phase dispersion
+ lock and release functions.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "ph_disp.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: ph_disp_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type ph_dispState
+
+ Outputs:
+    Structure pointed to by state is initialized 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 resets the variables used by the phase dispersion function.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ph_disp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int ph_disp_reset (ph_dispState *state)
+{
+  Word16 i;
+
+   if (state == (ph_dispState *) NULL){
+      fprint(stderr, "ph_disp_reset: invalid parameter\n");
+      return -1;
+   }
+   for (i=0; i<PHDGAINMEMSIZE; i++)
+   {
+       state->gainMem[i] = 0;
+   }
+   state->prevState = 0;
+   state->prevCbGain = 0;
+   state->lockFull = 0;
+   state->onset = 0;          // assume no onset in start
+
+   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 ph_disp_reset(ph_dispState *state)
+{
+    register Word16 i;
+
+    if (state == (ph_dispState *) NULL)
+    {
+        /*  fprint(stderr, "ph_disp_reset: invalid parameter\n");  */
+        return(-1);
+    }
+    for (i = 0; i < PHDGAINMEMSIZE; i++)
+    {
+        state->gainMem[i] = 0;
+    }
+    state->prevState = 0;
+    state->prevCbGain = 0;
+    state->lockFull = 0;
+    state->onset = 0;          /* assume no onset in start */
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ph_disp_lock
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type ph_dispState
+
+ Outputs:
+    lockFull field of the structure pointed to by state is set to 1
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function sets the lockFull flag to indicate a lock condition.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ph_disp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void ph_disp_lock (ph_dispState *state)
+{
+  state->lockFull = 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 ph_disp_lock(ph_dispState *state)
+{
+    state->lockFull = 1;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ph_disp_release
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type ph_dispState
+
+ Outputs:
+    lockFull field of the structure pointed to by state is set to 0
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function clears the lockFull flag to indicate an unlocked state.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ph_disp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void ph_disp_release (ph_dispState *state)
+{
+  state->lockFull = 0;
+  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 ph_disp_release(ph_dispState *state)
+{
+    state->lockFull = 0;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: ph_disp
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type ph_dispState
+    mode = codec mode (enum Mode)
+    x = LTP excitation signal buffer (Word16)
+    cbGain = codebook gain (Word16)
+    ltpGain = LTP gain (Word16)
+    inno = innovation buffer (Word16)
+    pitch_fac = pitch factor used to scale the LTP excitation (Word16)
+    tmp_shift = shift factor applied to sum of scaled LTP excitation and
+                innovation before rounding (Word16)
+    pOverflow = pointer to overflow indicator (Flag)
+
+ Outputs:
+    structure pointed to by state contains the updated gainMem array,
+      prevState, prevCbGain, and onset fields
+    x buffer contains the new excitation signal
+    inno buffer contains the new innovation signal
+    pOverflow -> 1 if there is overflow
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs adaptive phase dispersion, i.e., forming of total
+ excitation for the synthesis part of the decoder.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ph_disp.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+void ph_disp (
+      ph_dispState *state, // i/o     : State struct
+      enum Mode mode,      // i       : codec mode
+      Word16 x[],          // i/o Q0  : in:  LTP excitation signal
+                           //           out: total excitation signal
+      Word16 cbGain,       // i   Q1  : Codebook gain
+      Word16 ltpGain,      // i   Q14 : LTP gain
+      Word16 inno[],       // i/o Q13 : Innovation vector (Q12 for 12.2)
+      Word16 pitch_fac,    // i   Q14 : pitch factor used to scale the
+                                        LTP excitation (Q13 for 12.2)
+      Word16 tmp_shift     // i   Q0  : shift factor applied to sum of
+                                        scaled LTP ex & innov. before
+                                        rounding
+)
+{
+   Word16 i, i1;
+   Word16 tmp1;
+   Word32 L_temp;
+   Word16 impNr;           // indicator for amount of disp./filter used
+
+   Word16 inno_sav[L_SUBFR];
+   Word16 ps_poss[L_SUBFR];
+   Word16 j, nze, nPulse, ppos;
+   const Word16 *ph_imp;   // Pointer to phase dispersion filter
+
+   // Update LTP gain memory
+   for (i = PHDGAINMEMSIZE-1; i > 0; i--)
+   {
+       state->gainMem[i] = state->gainMem[i-1];
+   }
+   state->gainMem[0] = ltpGain;
+
+   // basic adaption of phase dispersion
+   if (sub(ltpGain, PHDTHR2LTP) < 0) {    // if (ltpGain < 0.9)
+       if (sub(ltpGain, PHDTHR1LTP) > 0)
+       {  // if (ltpGain > 0.6
+          impNr = 1; // medium dispersion
+       }
+       else
+       {
+          impNr = 0; // maximum dispersion
+       }
+   }
+   else
+   {
+      impNr = 2; // no dispersion
+   }
+
+   // onset indicator
+   // onset = (cbGain  > onFact * cbGainMem[0])
+   tmp1 = pv_round(L_shl(L_mult(state->prevCbGain, ONFACTPLUS1), 2));
+   if (sub(cbGain, tmp1) > 0)
+   {
+       state->onset = ONLENGTH;
+   }
+   else
+   {
+       if (state->onset > 0)
+       {
+           state->onset = sub (state->onset, 1);
+       }
+   }
+
+   // if not onset, check ltpGain buffer and use max phase dispersion if
+      half or more of the ltpGain-parameters say so
+   if (state->onset == 0)
+   {
+       // Check LTP gain memory and set filter accordingly
+       i1 = 0;
+       for (i = 0; i < PHDGAINMEMSIZE; i++)
+       {
+           if (sub(state->gainMem[i], PHDTHR1LTP) < 0)
+           {
+               i1 = add (i1, 1);
+           }
+       }
+       if (sub(i1, 2) > 0)
+       {
+           impNr = 0;
+       }
+
+   }
+   // Restrict decrease in phase dispersion to one step if not onset
+   if ((sub(impNr, add(state->prevState, 1)) > 0) && (state->onset == 0))
+   {
+       impNr = sub (impNr, 1);
+   }
+   // if onset, use one step less phase dispersion
+   if((sub(impNr, 2) < 0) && (state->onset > 0))
+   {
+       impNr = add (impNr, 1);
+   }
+
+   // disable for very low levels
+   if(sub(cbGain, 10) < 0)
+   {
+       impNr = 2;
+   }
+
+   if(sub(state->lockFull, 1) == 0)
+   {
+       impNr = 0;
+   }
+
+   // update static memory
+   state->prevState = impNr;
+   state->prevCbGain = cbGain;
+
+   // do phase dispersion for all modes but 12.2 and 7.4;
+   // don't modify the innovation if impNr >=2 (= no phase disp)
+   if (sub(mode, MR122) != 0 &&
+       sub(mode, MR102) != 0 &&
+       sub(mode, MR74) != 0 &&
+       sub(impNr, 2) < 0)
+   {
+       // track pulse positions, save innovation,
+          and initialize new innovation
+       nze = 0;
+       for (i = 0; i < L_SUBFR; i++)
+       {
+           if (inno[i] != 0)
+           {
+               ps_poss[nze] = i;
+               nze = add (nze, 1);
+           }
+           inno_sav[i] = inno[i];
+           inno[i] = 0;
+       }
+       // Choose filter corresponding to codec mode and dispersion criterium
+       if (sub (mode, MR795) == 0)
+       {
+           if (impNr == 0)
+           {
+               ph_imp = ph_imp_low_MR795;
+           }
+           else
+           {
+               ph_imp = ph_imp_mid_MR795;
+           }
+       }
+       else
+       {
+           if (impNr == 0)
+           {
+               ph_imp = ph_imp_low;
+           }
+           else
+           {
+               ph_imp = ph_imp_mid;
+           }
+       }
+
+       // Do phase dispersion of innovation
+       for (nPulse = 0; nPulse < nze; nPulse++)
+       {
+           ppos = ps_poss[nPulse];
+
+           // circular convolution with impulse response
+           j = 0;
+           for (i = ppos; i < L_SUBFR; i++)
+           {
+               // inno[i1] += inno_sav[ppos] * ph_imp[i1-ppos]
+               tmp1 = mult(inno_sav[ppos], ph_imp[j++]);
+               inno[i] = add(inno[i], tmp1);
+           }
+
+           for (i = 0; i < ppos; i++)
+           {
+               // inno[i] += inno_sav[ppos] * ph_imp[L_SUBFR-ppos+i]
+               tmp1 = mult(inno_sav[ppos], ph_imp[j++]);
+               inno[i] = add(inno[i], tmp1);
+           }
+       }
+   }
+
+   // compute total excitation for synthesis part of decoder
+   // (using modified innovation if phase dispersion is active)
+   for (i = 0; i < L_SUBFR; i++)
+   {
+       // x[i] = gain_pit*x[i] + cbGain*code[i];
+       L_temp = L_mult (        x[i],    pitch_fac);
+                                                // 12.2: Q0 * Q13
+                                                //  7.4: Q0 * Q14
+       L_temp = L_mac  (L_temp, inno[i], cbGain);
+                                                // 12.2: Q12 * Q1
+                                                //  7.4: Q13 * Q1
+       L_temp = L_shl (L_temp, tmp_shift);                 // Q16
+       x[i] = pv_round (L_temp);
+   }
+
+   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 ph_disp(
+    ph_dispState *state,    /* i/o     : State struct                       */
+    enum Mode mode,         /* i       : codec mode                         */
+    Word16 x[],             /* i/o Q0  : in:  LTP excitation signal         */
+    /*           out: total excitation signal       */
+    Word16 cbGain,          /* i   Q1  : Codebook gain                      */
+    Word16 ltpGain,         /* i   Q14 : LTP gain                           */
+    Word16 inno[],          /* i/o Q13 : Innovation vector (Q12 for 12.2)   */
+    Word16 pitch_fac,       /* i   Q14 : pitch factor used to scale the
+                                         LTP excitation (Q13 for 12.2)      */
+    Word16 tmp_shift,       /* i   Q0  : shift factor applied to sum of
+                                         scaled LTP ex & innov. before
+                                         rounding                           */
+    Flag   *pOverflow       /* i/o     : oveflow indicator                  */
+)
+{
+    register Word16 i, i1;
+    register Word16 tmp1;
+    Word32 L_temp;
+    Word32 L_temp2;
+    Word16 impNr;           /* indicator for amount of disp./filter used */
+
+    Word16 inno_sav[L_SUBFR];
+    Word16 ps_poss[L_SUBFR];
+    register Word16 nze, nPulse;
+    Word16 ppos;
+    const Word16 *ph_imp;   /* Pointer to phase dispersion filter */
+
+    Word16 *p_inno;
+    Word16 *p_inno_sav;
+    Word16 *p_x;
+    const Word16 *p_ph_imp;
+    Word16 c_inno_sav;
+
+    /* Update LTP gain memory */
+    /* Unrolled FOR loop below since PHDGAINMEMSIZE is assumed to stay */
+    /* the same.                                                       */
+    /* for (i = PHDGAINMEMSIZE-1; i > 0; i--)                          */
+    /* {                                                               */
+    /*    state->gainMem[i] = state->gainMem[i-1];                     */
+    /* }                                                               */
+    state->gainMem[4] = state->gainMem[3];
+    state->gainMem[3] = state->gainMem[2];
+    state->gainMem[2] = state->gainMem[1];
+    state->gainMem[1] = state->gainMem[0];
+    state->gainMem[0] = ltpGain;
+
+    /* basic adaption of phase dispersion */
+
+    if (ltpGain < PHDTHR2LTP)    /* if (ltpGain < 0.9) */
+    {
+        if (ltpGain > PHDTHR1LTP)
+        {  /* if (ltpGain > 0.6 */
+            impNr = 1; /* medium dispersion */
+        }
+        else
+        {
+            impNr = 0; /* maximum dispersion */
+        }
+    }
+    else
+    {
+        impNr = 2; /* no dispersion */
+    }
+
+    /* onset indicator */
+    /* onset = (cbGain  > onFact * cbGainMem[0]) */
+
+    L_temp = ((Word32) state->prevCbGain * ONFACTPLUS1) << 1;
+
+    /* (L_temp << 2) calculation with saturation check */
+    if (L_temp > (Word32) 0X1fffffffL)
+    {
+        *pOverflow = 1;
+        L_temp = MAX_32;
+    }
+    else if (L_temp < (Word32) 0xe0000000L)
+    {
+        *pOverflow = 1;
+        L_temp = MIN_32;
+    }
+    else
+    {
+        L_temp <<= 2;
+    }
+
+    tmp1 = pv_round(L_temp, pOverflow);
+
+    if (cbGain > tmp1)
+    {
+        state->onset = ONLENGTH;
+    }
+    else
+    {
+
+        if (state->onset > 0)
+        {
+            state->onset -= 1;
+        }
+    }
+
+    /* if not onset, check ltpGain buffer and use max phase dispersion if
+       half or more of the ltpGain-parameters say so */
+    if (state->onset == 0)
+    {
+        /* Check LTP gain memory and set filter accordingly */
+        i1 = 0;
+        for (i = 0; i < PHDGAINMEMSIZE; i++)
+        {
+            if (state->gainMem[i] < PHDTHR1LTP)
+            {
+                i1 += 1;
+            }
+        }
+
+        if (i1 > 2)
+        {
+            impNr = 0;
+        }
+    }
+    /* Restrict decrease in phase dispersion to one step if not onset */
+    if ((impNr > ((state->prevState) + 1)) && (state->onset == 0))
+    {
+        impNr -= 1;
+    }
+
+    /* if onset, use one step less phase dispersion */
+    if ((impNr < 2) && (state->onset > 0))
+    {
+        impNr += 1;
+    }
+
+    /* disable for very low levels */
+    if (cbGain < 10)
+    {
+        impNr = 2;
+    }
+
+    if (state->lockFull == 1)
+    {
+        impNr = 0;
+    }
+
+    /* update static memory */
+    state->prevState = impNr;
+    state->prevCbGain = cbGain;
+
+    /* do phase dispersion for all modes but 12.2 and 7.4;
+       don't modify the innovation if impNr >=2 (= no phase disp) */
+    if ((mode != MR122) && (mode != MR102) && (mode != MR74) && (impNr < 2))
+    {
+        /* track pulse positions, save innovation,
+           and initialize new innovation          */
+        nze = 0;
+        p_inno = &inno[0];
+        p_inno_sav = &inno_sav[0];
+
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            if (*(p_inno) != 0)
+            {
+                ps_poss[nze] = i;
+                nze += 1;
+            }
+            *(p_inno_sav++) = *(p_inno);
+            *(p_inno++) = 0;
+        }
+
+        /* Choose filter corresponding to codec mode and dispersion criterium */
+        if (mode == MR795)
+        {
+            if (impNr == 0)
+            {
+                ph_imp = ph_imp_low_MR795;
+            }
+            else
+            {
+                ph_imp = ph_imp_mid_MR795;
+            }
+        }
+        else
+        {
+            if (impNr == 0)
+            {
+                ph_imp = ph_imp_low;
+            }
+            else
+            {
+                ph_imp = ph_imp_mid;
+            }
+        }
+
+        /* Do phase dispersion of innovation */
+        for (nPulse = 0; nPulse < nze; nPulse++)
+        {
+            ppos = ps_poss[nPulse];
+
+            /* circular convolution with impulse response */
+            c_inno_sav = inno_sav[ppos];
+            p_inno = &inno[ppos];
+            p_ph_imp = ph_imp;
+
+            for (i = ppos; i < L_SUBFR; i++)
+            {
+                /* inno[i1] += inno_sav[ppos] * ph_imp[i1-ppos] */
+                L_temp = ((Word32) c_inno_sav * *(p_ph_imp++)) >> 15;
+                tmp1 = (Word16) L_temp;
+                *(p_inno) = add(*(p_inno), tmp1, pOverflow);
+                p_inno += 1;
+            }
+
+            p_inno = &inno[0];
+
+            for (i = 0; i < ppos; i++)
+            {
+                /* inno[i] += inno_sav[ppos] * ph_imp[L_SUBFR-ppos+i] */
+                L_temp = ((Word32) c_inno_sav * *(p_ph_imp++)) >> 15;
+                tmp1 = (Word16) L_temp;
+                *(p_inno) = add(*(p_inno), tmp1, pOverflow);
+                p_inno += 1;
+            }
+        }
+    }
+
+    /* compute total excitation for synthesis part of decoder
+       (using modified innovation if phase dispersion is active) */
+    p_inno = &inno[0];
+    p_x = &x[0];
+
+    for (i = 0; i < L_SUBFR; i++)
+    {
+        /* x[i] = gain_pit*x[i] + cbGain*code[i]; */
+        L_temp = L_mult(x[i], pitch_fac, pOverflow);
+        /* 12.2: Q0 * Q13 */
+        /*  7.4: Q0 * Q14 */
+        L_temp2 = ((Word32) * (p_inno++) * cbGain) << 1;
+        L_temp = L_add(L_temp, L_temp2, pOverflow);
+        /* 12.2: Q12 * Q1 */
+        /*  7.4: Q13 * Q1 */
+        L_temp = L_shl(L_temp, tmp_shift, pOverflow);                  /* Q16 */
+        *(p_x++) = pv_round(L_temp, pOverflow);
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/ph_disp.h b/media/libstagefright/codecs/amrnb/dec/src/ph_disp.h
new file mode 100644
index 0000000..58e2e4f
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/ph_disp.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/include/ph_disp.h
+
+
+     Date: 08/11/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template. Updated function prototype declaration for
+              ph_disp(). Included extern declaration for ph_imp_low_MR795 and
+              ph_imp_mid_MR795
+
+ 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 Phase dispersion of excitation signal ph_disp() function.
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PH_DISP_H
+#define PH_DISP_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.
+    ----------------------------------------------------------------------------*/
+#define PHDGAINMEMSIZE 5
+#define PHDTHR1LTP     9830  /* 0.6 in Q14 */
+#define PHDTHR2LTP     14746 /* 0.9 in Q14 */
+#define ONFACTPLUS1    16384 /* 2.0 in Q13   */
+#define ONLENGTH 2
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+    extern Word16 ph_imp_low_MR795[];
+    extern Word16 ph_imp_mid_MR795[];
+    extern Word16 ph_imp_low[];
+    extern Word16 ph_imp_mid[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+    typedef struct
+    {
+        Word16 gainMem[PHDGAINMEMSIZE];
+        Word16 prevState;
+        Word16 prevCbGain;
+        Word16 lockFull;
+        Word16 onset;
+    } ph_dispState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:   ph_disp_reset
+    ;  Purpose:    Initializes state memory
+    ;
+    ----------------------------------------------------------------------------*/
+    Word16 ph_disp_reset(ph_dispState *state);
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:   ph_disp_exit
+    ;  Purpose:    The memory used for state memory is freed
+    ;
+    ----------------------------------------------------------------------------*/
+    void ph_disp_exit(ph_dispState **state);
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:   ph_disp_lock
+    ;  Purpose:    mark phase dispersion as locked in state struct
+    ;
+    ----------------------------------------------------------------------------*/
+    void ph_disp_lock(ph_dispState *state);
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:   ph_disp_release
+    ;  Purpose:    mark phase dispersion as unlocked in state struct
+    ;
+    ----------------------------------------------------------------------------*/
+
+    void ph_disp_release(ph_dispState *state);
+
+    /*----------------------------------------------------------------------------
+    ;
+    ;  Function:   ph_disp
+    ;  Purpose:    perform phase dispersion according to the specified codec
+    ;              mode and computes total excitation for synthesis part
+    ;              if decoder
+    ;
+    ----------------------------------------------------------------------------*/
+
+    void ph_disp(
+        ph_dispState *state,    /* i/o     : State struct                       */
+        enum Mode mode,         /* i       : codec mode                         */
+        Word16 x[],             /* i/o Q0  : in:  LTP excitation signal         */
+        /*           out: total excitation signal       */
+        Word16 cbGain,          /* i   Q1  : Codebook gain                      */
+        Word16 ltpGain,         /* i   Q14 : LTP gain                           */
+        Word16 inno[],          /* i/o Q13 : Innovation vector (Q12 for 12.2)   */
+        Word16 pitch_fac,       /* i   Q14 : pitch factor used to scale the
+                                         LTP excitation (Q13 for 12.2)      */
+        Word16 tmp_shift,       /* i   Q0  : shift factor applied to sum of
+                                         scaled LTP ex & innov. before
+                                         rounding                           */
+        Flag   *pOverflow       /* i/o     : oveflow indicator                  */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _PH_DISP_H_ */
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/post_pro.cpp b/media/libstagefright/codecs/amrnb/dec/src/post_pro.cpp
new file mode 100644
index 0000000..ce31793
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/post_pro.cpp
@@ -0,0 +1,395 @@
+/* ------------------------------------------------------------------
+ * 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/post_pro.c
+ Functions:
+           Post_Process_reset
+           Post_Process
+
+     Date: 04/03/2000
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Updated template used to PV coding template. First attempt at
+          optimizing C code.
+
+ Description: Deleted variables listed in the Local Stores Needed/Modified
+          sections. Optimized the "else" portion of the first "if"
+          statement in Post_Process function.
+
+ Description: Made grouping more explicit in the calculation of
+          signal[i] << 1 in the Post_Process function.
+
+ Description: Added setting of Overflow flag in inlined code.
+
+ Description: Synchronized file with UMTS version 3.2.0. Updated coding
+              template. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header file of the math functions
+              used in the file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Updated copyright year.
+              2. Fixed typecasting issue with TI C compiler.
+              3. Used short-hand notation for math operations, e.g., "+=",
+                 in the code.
+
+ Description: Removed the functions post_pro_init and post_pro_exit.
+ The post_pro related structure is no longer dynamically allocated.
+
+ Description: Added pOverflow as a passed in variable as per changes needed
+              for the EPOC release.
+
+ Description: Optimized file to reduce clock cycle usage. Updated copyright
+              year and removed unused files in Include section.
+
+ 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
+
+ This file contains the function that performs post-processing on the output
+ speech. Post-processing include filtering the output speech through a second
+ order high pass filter with cutoff frequency of 60 Hz, and up-scaling the
+ output speech by a factor of 2. In addition to the post-processing function
+ itself, a post-processing initialization function, post-processing reset
+ function, and post-processing exit function are also included in this file.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "post_pro.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
+----------------------------------------------------------------------------*/
+
+/* filter coefficients (fc = 60 Hz) */
+static const Word16 b[3] = {7699, -15398, 7699};
+static const Word16 a[3] = {8192, 15836, -7667};
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Post_Process_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to a structure of type Post_ProcessState
+
+ Outputs:
+    structure pointed to by state will have all its fields initialized
+      to zero
+
+ Returns:
+    return_value = 0, if reset was successful; -1, otherwise (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function initializes state memory to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ post_pro.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Post_Process_reset (Post_ProcessState *state)
+{
+  if (state == (Post_ProcessState *) NULL){
+      fprint(stderr, "Post_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 Post_Process_reset(Post_ProcessState *state)
+{
+    if (state == (Post_ProcessState *) NULL)
+    {
+        /*  fprint(stderr, "Post_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: Post_Process
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type Post_ProcessState
+    signal = buffer containing the input signal (Word16)
+    lg = length of the input signal (Word16)
+    pOverflow = pointer to overflow indicator of type Flag
+
+ Outputs:
+    structure pointed to by st contains new filter input and output values
+    signal buffer contains the HP filtered and up-scaled input signal
+    pOverflow points to 1 if overflow occurs in the math functions called
+              else it points to 0.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    a = buffer containing filter coefficients
+    b = buffer containing filter coefficients
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs post-processing on the output speech signal. First,
+ the output speech goes through a second order high pass filter with a
+ cutoff frequency of 60 Hz. Then, the filtered output speech is multiplied
+ by a factor of 2. The algorithm implemented follows the following difference
+ equation:
+
+ 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
+
+ post_pro.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Post_Process (
+    Post_ProcessState *st,  //i/o : post process state
+    Word16 signal[],        //i/o : signal
+    Word16 lg               //i   : length 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, 2);
+
+        //Multiplication by two of output speech with saturation.
+        signal[i] = pv_round(L_shl(L_tmp, 1));
+
+        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]
+
+------------------------------------------------------------------------------
+*/
+
+void Post_Process(
+    Post_ProcessState *st,  /* i/o : post process state                   */
+    Word16 signal[],        /* i/o : signal                               */
+    Word16 lg,              /* i   : length of signal                     */
+    Flag   *pOverflow
+)
+{
+    Word16 i, x2;
+    Word32 L_tmp;
+
+    Word16 *p_signal;
+    Word16 c_a1 = a[1];
+    Word16 c_a2 = a[2];
+    Word16 c_b0 = b[0];
+    Word16 c_b1 = b[1];
+    Word16 c_b2 = b[2];
+
+    p_signal = &signal[0];
+
+    for (i = 0; i < lg; i++)
+    {
+        x2 = st->x1;
+        st->x1 = st->x0;
+        st->x0 = *(p_signal);
+
+        /*  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) * c_a1;
+        L_tmp += (((Word32) st->y1_lo) * c_a1) >> 15;
+        L_tmp += ((Word32) st->y2_hi) * c_a2;
+        L_tmp += (((Word32) st->y2_lo) * c_a2) >> 15;
+        L_tmp += ((Word32) st->x0) * c_b0;
+        L_tmp += ((Word32) st->x1) * c_b1;
+        L_tmp += ((Word32) x2) * c_b2;
+        L_tmp <<= 3;
+
+
+        /* Multiplication by two of output speech with saturation. */
+
+        *(p_signal++) = pv_round(L_shl(L_tmp, 1, pOverflow), pOverflow);
+
+        st->y2_hi = st->y1_hi;
+        st->y2_lo = st->y1_lo;
+
+        st->y1_hi = (Word16)(L_tmp >> 16);
+        st->y1_lo = (Word16)((L_tmp >> 1) - ((Word32) st->y1_hi << 15));
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/post_pro.h b/media/libstagefright/codecs/amrnb/dec/src/post_pro.h
new file mode 100644
index 0000000..85e5888
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/post_pro.h
@@ -0,0 +1,140 @@
+/* ------------------------------------------------------------------
+ * 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/post_pro.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             : post_pro.h
+      Purpose          : Postprocessing of output speech.
+
+                         - 2nd order high pass filtering with cut
+                           off frequency at 60 Hz.
+                         - Multiplication of output by two.
+------------------------------------------------------------------------------
+*/
+
+#ifndef _POST_PRO_H_
+#define _POST_PRO_H_
+#define post_pro_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 y2_hi;
+        Word16 y2_lo;
+        Word16 y1_hi;
+        Word16 y1_lo;
+        Word16 x0;
+        Word16 x1;
+    } Post_ProcessState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+
+    Word16 Post_Process_reset(Post_ProcessState *st);
+    /* reset of Post processing state (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void Post_Process_exit(Post_ProcessState **st);
+    /* de-initialize Post processing state (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void Post_Process(
+        Post_ProcessState *st,  /* i/o : post process state                   */
+        Word16 signal[],        /* i/o : signal                               */
+        Word16 lg,              /* i   : lenght of signal                     */
+        Flag *pOverflow
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _POST_PRO_H_ */
+
+
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/preemph.cpp b/media/libstagefright/codecs/amrnb/dec/src/preemph.cpp
new file mode 100644
index 0000000..9864325
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/preemph.cpp
@@ -0,0 +1,272 @@
+/* ------------------------------------------------------------------
+ * 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/preemph.c
+ Functions:
+
+     Date: 02/04/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Removed the functions preemphasis_init and preemphasis_exit.
+ The preemphasis related structure is no longer dynamically allocated.
+ Placed file in the appropriate PV Software Template format.
+
+ Description: 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
+
+ Purpose          : Preemphasis filtering
+ Description      : Filtering through 1 - g z^-1
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "preemph.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:  preemphasis_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- double pointer to preemphasisState
+
+ Outputs:
+    st -- double ponter to preemphasisState
+
+ 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
+
+ preemph.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 preemphasis_reset(preemphasisState *state)
+{
+    if (state == (preemphasisState *) NULL)
+    {
+        /* fprintf(stderr, "preemphasis_reset: invalid parameter\n"); */
+        return -1;
+    }
+
+    state->mem_pre = 0;
+
+    return 0;
+}
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME:  preemphasis
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st -- Pointer to preemphasisState -- preemphasis filter state
+    signal -- array of type Word16 -- input signal overwritten by the output
+    g -- Word16 -- preemphasis coefficient
+    L -- Word16 -- size of filtering
+
+ Outputs:
+    st -- Pointer to preemphasisState -- preemphasis filter state
+    signal -- array of type Word16 -- input signal overwritten by the output
+    pOverflow -- pointer to type Flag -- overflow indicator
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Filtering through 1 - g z^-1
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ preemph.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 preemphasis(
+    preemphasisState *st, /* (i/o) : preemphasis filter state               */
+    Word16 *signal,       /* (i/o) : input signal overwritten by the output */
+    Word16 g,             /* (i)   : preemphasis coefficient                */
+    Word16 L,             /* (i)   : size of filtering                      */
+    Flag  *pOverflow      /* (o)   : overflow indicator                     */
+)
+{
+    Word16 *p1;
+    Word16 *p2;
+    Word16 temp;
+    Word16 temp2;
+    Word16 i;
+
+    p1 = signal + L - 1;
+    p2 = p1 - 1;
+    temp = *p1;
+
+    for (i = 0; i <= L - 2; i++)
+    {
+        temp2 = mult(g, *(p2--), pOverflow);
+        *p1 = sub(*p1, temp2, pOverflow);
+
+        p1--;
+    }
+
+    temp2 = mult(g, st->mem_pre, pOverflow);
+
+    *p1 = sub(*p1, temp2, pOverflow);
+
+    st->mem_pre = temp;
+
+    return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/preemph.h b/media/libstagefright/codecs/amrnb/dec/src/preemph.h
new file mode 100644
index 0000000..20bab71
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/preemph.h
@@ -0,0 +1,140 @@
+/* ------------------------------------------------------------------
+ * 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/preemph.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, preemph.c
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef preemph_h
+#define preemph_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 mem_pre;          /* filter state */
+    } preemphasisState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    Word16 preemphasis_reset(preemphasisState *st);
+    /* reset of preemphasis filter (i.e. set state memory to zero)
+       returns 0 on success
+     */
+    void preemphasis_exit(preemphasisState **st);
+    /* de-initialize preemphasis filter (i.e. free status struct)
+       stores NULL in *st
+     */
+
+    void preemphasis(
+        preemphasisState *st, /* (i/o): preemphasis filter state                */
+        Word16 *signal,    /* (i/o): input signal overwritten by the output     */
+        Word16 g,          /* (i)  : preemphasis coefficient                    */
+        Word16 L,          /* (i)  : size of filtering                          */
+        Flag   *pOverflow  /* (o)  : overflow indicator                         */
+    );
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* preemph_H_ */
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/pstfilt.cpp b/media/libstagefright/codecs/amrnb/dec/src/pstfilt.cpp
new file mode 100644
index 0000000..0336990
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/pstfilt.cpp
@@ -0,0 +1,578 @@
+/* ------------------------------------------------------------------
+ * 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/pstfilt.c
+ Functions:
+            Post_Filter_reset
+            Post_Filter
+
+     Date: 04/14/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. Removed unnecessary include files.
+
+ Description: Replaced basic_op.h with the header file of the math functions
+              used in the file.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Updated copyright year.
+              2. Modified FOR loops to count down.
+              3. Fixed typecasting issue with TI C compiler.
+              4. Added "break" statement after overflow condition occurs.
+
+ Description: Removed the functions pstfilt_init and pstfilt_exit.
+ The pst_filt related structure is no longer dynamically allocated.
+
+ Description: Modified code for EPOC changes where pOverflow is passed in
+              rather than allowing overflow to be a global variable.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the function that performs adaptive post-filtering on the
+ synthesized speech. It also contains the functions that initialize, reset,
+ and exit the post-filtering function.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <string.h>
+
+#include "pstfilt.h"
+#include "typedef.h"
+#include "mode.h"
+#include "basicop_malloc.h"
+#include "basic_op.h"
+#include "weight_a.h"
+#include "residu.h"
+#include "copy.h"
+#include "syn_filt.h"
+#include "preemph.h"
+#include "cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define L_H 22  /* size of truncated impulse response of A(z/g1)/A(z/g2) */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL VARIABLE DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* Spectral expansion factors */
+static const Word16 gamma3_MR122[M] =
+{
+    22938, 16057, 11240, 7868, 5508,
+    3856, 2699, 1889, 1322, 925
+};
+
+static const Word16 gamma3[M] =
+{
+    18022, 9912, 5451, 2998, 1649, 907, 499, 274, 151, 83
+};
+
+static const Word16 gamma4_MR122[M] =
+{
+    24576, 18432, 13824, 10368, 7776,
+    5832, 4374, 3281, 2461, 1846
+};
+
+static const Word16 gamma4[M] =
+{
+    22938, 16057, 11240, 7868, 5508, 3856, 2699, 1889, 1322, 925
+};
+
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Post_Filter_reset
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to structure of type Post_FilterState
+
+ Outputs:
+    fields of the structure pointed to by state is initialized to zero
+
+ 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 Post_Filter function
+ to zero.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pstfilt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Post_Filter_reset (Post_FilterState *state)
+{
+  if (state == (Post_FilterState *) NULL){
+      fprintf(stderr, "Post_Filter_reset: invalid parameter\n");
+      return -1;
+  }
+
+  Set_zero (state->mem_syn_pst, M);
+  Set_zero (state->res2, L_SUBFR);
+  Set_zero (state->synth_buf, L_FRAME + M);
+  agc_reset(state->agc_state);
+  preemphasis_reset(state->preemph_state);
+
+  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 Post_Filter_reset(Post_FilterState *state)
+{
+    if (state == (Post_FilterState *) NULL)
+    {
+        /*fprintf(stderr, "Post_Filter_reset: invalid parameter\n");  */
+        return(-1);
+    }
+
+    memset(state->mem_syn_pst, 0, sizeof(Word16)*M);
+    memset(state->res2, 0, sizeof(Word16)*L_SUBFR);
+    memset(state->synth_buf, 0, sizeof(Word16)*(L_FRAME + M));
+    agc_reset(&(state->agc_state));
+    preemphasis_reset(&(state->preemph_state));
+
+    return(0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Post_Filter
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to a structure of type Post_FilterState
+    mode = AMR mode
+    syn = pointer to a buffer containing synthesized speech; upon
+          exiting this function, it will contain the post-filtered
+          synthesized speech
+    Az_4 = pointer to the interpolated LPC parameters for all subframes
+    pOverflow = pointer to overflow indicator of type Flag
+
+ Outputs:
+    fields of the structure pointed to by st contains the updated field
+      values
+    syn buffer contains the post-filtered synthesized speech
+    pOverflow = 1 if overflow occurrs in the math functions called else
+                it is zero.
+
+ Returns:
+    return_value = 0 (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs the post-filtering on the synthesized speech. The
+ post-filtering process is described as follows:
+ (1) inverse filtering of syn[] through A(z/0.7) to get res2[]
+ (2) tilt compensation filtering; 1 - MU*k*z^-1
+ (3) synthesis filtering through 1/A(z/0.75)
+ (4) adaptive gain control
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ pstfilt.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Post_Filter (
+    Post_FilterState *st, // i/o : post filter states
+    enum Mode mode,       // i   : AMR mode
+    Word16 *syn,          // i/o : synthesis speech (postfiltered is output)
+    Word16 *Az_4          // i   : interpolated LPC parameters in all subfr.
+)
+{
+     *-------------------------------------------------------------------*
+     *           Declaration of parameters                               *
+     *-------------------------------------------------------------------*
+
+    Word16 Ap3[MP1], Ap4[MP1];  // bandwidth expanded LP parameters
+    Word16 *Az;                 // pointer to Az_4:
+                                //  LPC parameters in each subframe
+    Word16 i_subfr;             // index for beginning of subframe
+    Word16 h[L_H];
+
+    Word16 i;
+    Word16 temp1, temp2;
+    Word32 L_tmp;
+    Word16 *syn_work = &st->synth_buf[M];
+
+
+     *-----------------------------------------------------*
+     * Post filtering                                      *
+     *-----------------------------------------------------*
+
+    Copy (syn, syn_work , L_FRAME);
+
+    Az = Az_4;
+
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+       // Find weighted filter coefficients Ap3[] and ap[4]
+
+       if (sub(mode, MR122) == 0 || sub(mode, MR102) == 0)
+       {
+          Weight_Ai (Az, gamma3_MR122, Ap3);
+          Weight_Ai (Az, gamma4_MR122, Ap4);
+       }
+       else
+       {
+          Weight_Ai (Az, gamma3, Ap3);
+          Weight_Ai (Az, gamma4, Ap4);
+       }
+
+       // filtering of synthesis speech by A(z/0.7) to find res2[]
+
+       Residu (Ap3, &syn_work[i_subfr], st->res2, L_SUBFR);
+
+       // tilt compensation filter
+
+       // impulse response of A(z/0.7)/A(z/0.75)
+
+       Copy (Ap3, h, M + 1);
+       Set_zero (&h[M + 1], L_H - M - 1);
+       Syn_filt (Ap4, h, h, L_H, &h[M + 1], 0);
+
+       // 1st correlation of h[]
+
+       L_tmp = L_mult (h[0], h[0]);
+       for (i = 1; i < L_H; i++)
+       {
+          L_tmp = L_mac (L_tmp, h[i], h[i]);
+       }
+       temp1 = extract_h (L_tmp);
+
+       L_tmp = L_mult (h[0], h[1]);
+       for (i = 1; i < L_H - 1; i++)
+       {
+          L_tmp = L_mac (L_tmp, h[i], h[i + 1]);
+       }
+       temp2 = extract_h (L_tmp);
+
+       if (temp2 <= 0)
+       {
+          temp2 = 0;
+       }
+       else
+       {
+          temp2 = mult (temp2, MU);
+          temp2 = div_s (temp2, temp1);
+       }
+
+       preemphasis (st->preemph_state, st->res2, temp2, L_SUBFR);
+
+       // filtering through  1/A(z/0.75)
+
+       Syn_filt (Ap4, st->res2, &syn[i_subfr], L_SUBFR, st->mem_syn_pst, 1);
+
+       // scale output to input
+
+       agc (st->agc_state, &syn_work[i_subfr], &syn[i_subfr],
+            AGC_FAC, L_SUBFR);
+
+       Az += MP1;
+    }
+
+    // update syn_work[] buffer
+
+    Copy (&syn_work[L_FRAME - M], &syn_work[-M], M);
+
+    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 Post_Filter(
+    Post_FilterState *st, /* i/o : post filter states                        */
+    enum Mode mode,       /* i   : AMR mode                                  */
+    Word16 *syn,          /* i/o : synthesis speech (postfiltered is output) */
+    Word16 *Az_4,         /* i   : interpolated LPC parameters in all subfr. */
+    Flag   *pOverflow
+)
+{
+    Word16 Ap3[MP1];
+    Word16 Ap4[MP1];            /* bandwidth expanded LP parameters */
+    Word16 *Az;                 /* pointer to Az_4:                 */
+    /*  LPC parameters in each subframe */
+    register Word16 i_subfr;    /* index for beginning of subframe  */
+    Word16 h[L_H];
+
+    register Word16 i;
+    Word16 temp1;
+    Word16 temp2;
+    Word32 L_tmp;
+    Word32 L_tmp2;
+    Word16 *syn_work = &st->synth_buf[M];
+
+
+    /*-----------------------------------------------------*
+     * Post filtering                                      *
+     *-----------------------------------------------------*/
+
+    Copy(syn, syn_work , L_FRAME);
+
+    Az = Az_4;
+
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        /* Find weighted filter coefficients Ap3[] and ap[4] */
+
+        if (mode == MR122 || mode == MR102)
+        {
+            Weight_Ai(Az, gamma3_MR122, Ap3);
+            Weight_Ai(Az, gamma4_MR122, Ap4);
+        }
+        else
+        {
+            Weight_Ai(Az, gamma3, Ap3);
+            Weight_Ai(Az, gamma4, Ap4);
+        }
+
+        /* filtering of synthesis speech by A(z/0.7) to find res2[] */
+
+        Residu(Ap3, &syn_work[i_subfr], st->res2, L_SUBFR);
+
+        /* tilt compensation filter */
+
+        /* impulse response of A(z/0.7)/A(z/0.75) */
+
+        Copy(Ap3, h, M + 1);
+        memset(&h[M + 1], 0, sizeof(Word16)*(L_H - M - 1));
+        Syn_filt(Ap4, h, h, L_H, &h[M + 1], 0);
+
+        /* 1st correlation of h[] */
+
+        L_tmp = 0;
+
+        for (i = L_H - 1; i >= 0; i--)
+        {
+            L_tmp2 = ((Word32) h[i]) * h[i];
+
+            if (L_tmp2 != (Word32) 0x40000000L)
+            {
+                L_tmp2 = L_tmp2 << 1;
+            }
+            else
+            {
+                *pOverflow = 1;
+                L_tmp2 = MAX_32;
+                break;
+            }
+
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+        }
+        temp1 = (Word16)(L_tmp >> 16);
+
+        L_tmp = 0;
+
+        for (i = L_H - 2; i >= 0; i--)
+        {
+            L_tmp2 = ((Word32) h[i]) * h[i + 1];
+
+            if (L_tmp2 != (Word32) 0x40000000L)
+            {
+                L_tmp2 = L_tmp2 << 1;
+            }
+            else
+            {
+                *pOverflow = 1;
+                L_tmp2 = MAX_32;
+                break;
+            }
+
+            L_tmp = L_add(L_tmp, L_tmp2, pOverflow);
+        }
+        temp2 = (Word16)(L_tmp >> 16);
+
+        if (temp2 <= 0)
+        {
+            temp2 = 0;
+        }
+        else
+        {
+            L_tmp = (((Word32) temp2) * MU) >> 15;
+
+            /* Sign-extend product */
+            if (L_tmp & (Word32) 0x00010000L)
+            {
+                L_tmp = L_tmp | (Word32) 0xffff0000L;
+            }
+            temp2 = (Word16) L_tmp;
+
+            temp2 = div_s(temp2, temp1);
+        }
+
+        preemphasis(&(st->preemph_state), st->res2, temp2, L_SUBFR, pOverflow);
+
+        /* filtering through  1/A(z/0.75) */
+
+        Syn_filt(Ap4, st->res2, &syn[i_subfr], L_SUBFR, st->mem_syn_pst, 1);
+
+        /* scale output to input */
+
+        agc(&(st->agc_state), &syn_work[i_subfr], &syn[i_subfr],
+            AGC_FAC, L_SUBFR, pOverflow);
+
+        Az += MP1;
+    }
+
+    /* update syn_work[] buffer */
+
+    Copy(&syn_work[L_FRAME - M], &syn_work[-M], M);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrnb/dec/src/pstfilt.h b/media/libstagefright/codecs/amrnb/dec/src/pstfilt.h
new file mode 100644
index 0000000..29c0d84
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/pstfilt.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/pstfilt.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             : pstfilt.h
+      Purpose          : Performs adaptive postfiltering on the synthesis
+                       : speech
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef _PSTFILT_H_
+#define _PSTFILT_H_
+#define pstfilt_h "$Id $"
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "typedef.h"
+#include "mode.h"
+#include "cnst.h"
+#include "preemph.h"
+#include "agc.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 res2[L_SUBFR];
+        Word16 mem_syn_pst[M];
+        preemphasisState preemph_state;
+        agcState agc_state;
+        Word16 synth_buf[M + L_FRAME];
+    } Post_FilterState;
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; [List function prototypes here]
+    ----------------------------------------------------------------------------*/
+    Word16 Post_Filter_reset(Post_FilterState *st);
+    /* reset post filter (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void Post_Filter(
+        Post_FilterState *st, /* i/o : post filter states                        */
+        enum Mode mode,       /* i   : AMR mode                                  */
+        Word16 *syn,          /* i/o : synthesis speech (postfiltered is output) */
+        Word16 *Az_4,         /* i   : interpolated LPC parameters in all subfr. */
+        Flag   *pOverflow
+    );
+    /* filters the signal syn using the parameters in Az_4 to calculate filter
+       coefficients.
+       The filter must be set up using Post_Filter_init prior to the first call
+       to Post_Filter. Post_FilterState is updated to mirror the current state
+       of the filter
+
+       return 0 on success
+     */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* _PSTFILT_H_ */
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/pvgsmamrdecoder.cpp b/media/libstagefright/codecs/amrnb/dec/src/pvgsmamrdecoder.cpp
new file mode 100644
index 0000000..95b0b47
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/pvgsmamrdecoder.cpp
@@ -0,0 +1,77 @@
+/* ------------------------------------------------------------------
+ * 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 "PVGSMAMRDecoder.h"
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF CPVGSMAMRDecoder::CPVGSMAMRDecoder()
+{
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF CPVGSMAMRDecoder::~CPVGSMAMRDecoder()
+{
+    delete iDecState;
+    iDecState = NULL;
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF int32 CPVGSMAMRDecoder::InitDecoder(void)
+{
+    return GSMInitDecode(&iDecState, (int8*)"Decoder");
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF int32 CPVGSMAMRDecoder::DecodeFrame(Frame_Type_3GPP aType,
+        uint8* aCompressedBlock,
+        uint8* aAudioBuffer,
+        int32 aFormat)
+{
+    return AMRDecode(iDecState, aType, aCompressedBlock, (Word16*)aAudioBuffer, (Word16) aFormat);
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF int32 CPVGSMAMRDecoder::ResetDecoder(void)
+{
+    return Speech_Decode_Frame_reset(iDecState);
+}
+
+
+/////////////////////////////////////////////////////////////////////////////
+OSCL_EXPORT_REF void CPVGSMAMRDecoder::TerminateDecoder(void)
+{
+    GSMDecodeFrameExit(&iDecState);
+    iDecState = NULL;
+}
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/qgain475_tab.cpp b/media/libstagefright/codecs/amrnb/dec/src/qgain475_tab.cpp
new file mode 100644
index 0000000..fbcd412
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/qgain475_tab.cpp
@@ -0,0 +1,435 @@
+/* ------------------------------------------------------------------
+ * 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/qgain475_tab.c
+
+     Date: 12/09/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Created this file from the reference, qgain475.tab.
+
+ Description: Added #ifdef __cplusplus and removed "extern" from table
+              definition.
+
+ Description: Put "extern" back.
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "qgain475_tab.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]
+    ----------------------------------------------------------------------------*/
+
+    /* 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
+     *
+     */
+    extern 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
+    };
+
+
+    /*--------------------------------------------------------------------------*/
+#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] qua_gain.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/dec/src/sp_dec.cpp b/media/libstagefright/codecs/amrnb/dec/src/sp_dec.cpp
new file mode 100644
index 0000000..2989b74
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/sp_dec.cpp
@@ -0,0 +1,699 @@
+/* ------------------------------------------------------------------
+ * 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_dec.c
+ Functions: GSMInitDecode
+            Speech_Decode_Frame_reset
+            GSMDecodeFrameExit
+            GSMFrameDecode
+
+     Date: 08/03/2001
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Add PV coding template. Filled out template sections and
+              reformatted code to follow C coding standard. Removed code that
+              handles SID in GSMFrameDecode.
+
+ Description: Made the following changes per comments from Phase 2/3 review:
+              1. Updated to more recent PV C coding template.
+              2. Took out all the tabs in the file and replaced with spaces.
+              3. Deleted bit_offset from input list of GSMFrameDecode.
+
+ Description: Changing several variables passed into these functions of type
+              Speech_Decode_FrameState to type void.
+
+ Description: Cleaning up brackets and line spacing for statements with
+              brackets as per a review comments.
+
+ Description: Synchronized file with UMTS version 3.2.0. Removed unnecessary
+              include files.
+
+ Description: Removed all references to malloc/free, except for the top-level
+ malloc in GSMInitDecode, and corresponding free in GSMDecodeFrameExit.
+
+ Also, modified function calls throughout to reflect the fact that the members
+ of the structure Decoder_amrState are no longer pointers to be set via
+ malloc, but full-blown structures.  (Changes of the type D_plsfState *lsfState
+ to D_plsfState lsfState)
+
+ Description: Created overflow and pass the variable into the decoder.
+
+ Description: Changed inititlaization of the pointer to overflow flag. Removed
+              code related to MOPS counter.
+
+ Description:  Replaced OSCL mem type functions and eliminated include
+               files that now are chosen by OSCL definitions
+
+ Description:  Replaced "int" and/or "char" with defined types.
+               Added proper casting (Word32) to some left shifting operations
+
+ Description:
+
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that initialize, invoke, reset, and exit
+ the GSM AMR decoder.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include <stdlib.h>
+
+#include "sp_dec.h"
+#include "typedef.h"
+#include "cnst.h"
+#include "dec_amr.h"
+#include "pstfilt.h"
+#include "bits2prm.h"
+#include "mode.h"
+#include "post_pro.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: GSMInitDecode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to an array of pointers to structures of type
+            Speech_Decode_FrameState
+    no_hp_post_MR122 = flag to turn off high-pass post filter for 12.2 kbps
+                       mode (Flag)
+    id = pointer to an array whose contents are of type char
+
+ Outputs:
+    decoder_amrState field of the structure pointed to by the pointer pointed
+       to by state is set to NULL
+    post_state field of the structure pointed to by the pointer pointed to
+      by state is set to NULL
+    postHP_state field of the structure pointed to by the pointer pointed to
+      by state is set to NULL
+    no_hp_post_MR122 field of the structure pointed to by the pointer pointed
+      to by state is set to the input no_hp_post_MR122
+
+ 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 used by the GSM AMR decoder.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: Original function name of Speech_Decode_Frame_init was changed to
+       GSMInitDecode in the Code section.
+
+int Speech_Decode_Frame_init (Speech_Decode_FrameState **state,
+                              char *id)
+{
+  Speech_Decode_FrameState* s;
+
+  if (state == (Speech_Decode_FrameState **) NULL){
+      fprintf(stderr, "Speech_Decode_Frame_init: invalid parameter\n");
+      return -1;
+  }
+  *state = NULL;
+
+  // allocate memory
+  if ((s= (Speech_Decode_FrameState *)
+          malloc(sizeof(Speech_Decode_FrameState))) == NULL) {
+      fprintf(stderr, "Speech_Decode_Frame_init: can not malloc state "
+              "structure\n");
+      return -1;
+  }
+  s->decoder_amrState = NULL;
+  s->post_state = NULL;
+  s->postHP_state = NULL;
+
+  if (Decoder_amr_init(&s->decoder_amrState) ||
+      Post_Filter_init(&s->post_state) ||
+      Post_Process_init(&s->postHP_state) ) {
+      Speech_Decode_Frame_exit(&s);
+      return -1;
+  }
+
+  s->complexityCounter = getCounterId(id);
+
+  Speech_Decode_Frame_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 GSMInitDecode(void **state_data,
+                     Word8 * id)
+{
+    Speech_Decode_FrameState* s;
+    OSCL_UNUSED_ARG(id);
+
+    if (state_data == NULL)
+    {
+        /*  fprintf(stderr, "Speech_Decode_Frame_init:
+                             invalid parameter\n");  */
+        return (-1);
+    }
+    *state_data = NULL;
+
+    /* allocate memory */
+    if ((s = (Speech_Decode_FrameState *)
+             malloc(sizeof(Speech_Decode_FrameState))) == NULL)
+    {
+        /*  fprintf(stderr, "Speech_Decode_Frame_init: can not malloc state "
+            "structure\n");  */
+        return (-1);
+    }
+
+    if (Decoder_amr_init(&s->decoder_amrState)
+            || Post_Process_reset(&s->postHP_state))
+    {
+        Speech_Decode_FrameState *tmp = s;
+        /*
+         *  dereferencing type-punned pointer avoid
+         *  breaking strict-aliasing rules
+         */
+        void** tempVoid = (void**) tmp;
+        GSMDecodeFrameExit(tempVoid);
+        return (-1);
+    }
+
+
+    Speech_Decode_Frame_reset(s);
+    *state_data = (void *)s;
+
+    return (0);
+}
+
+
+/****************************************************************************/
+
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: Speech_Decode_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 the state memory used by the GSM AMR decoder.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+int Speech_Decode_Frame_reset (Speech_Decode_FrameState *state)
+{
+  if (state == (Speech_Decode_FrameState *) NULL){
+      fprintf(stderr, "Speech_Decode_Frame_reset: invalid parameter\n");
+      return -1;
+  }
+
+  Decoder_amr_reset(state->decoder_amrState, (enum Mode)0);
+  Post_Filter_reset(state->post_state);
+  Post_Process_reset(state->postHP_state);
+
+  state->prev_mode = (enum Mode)0;
+
+  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_Decode_Frame_reset(void *state_data)
+{
+
+    Speech_Decode_FrameState *state =
+        (Speech_Decode_FrameState *) state_data;
+
+    if (state_data ==  NULL)
+    {
+        /*  fprintf(stderr, "Speech_Decode_Frame_reset:
+                             invalid parameter\n");  */
+        return (-1);
+    }
+
+    Decoder_amr_reset(&(state->decoder_amrState), MR475);
+    Post_Filter_reset(&(state->post_state));
+    Post_Process_reset(&(state->postHP_state));
+
+    state->prev_mode = MR475;
+
+    return (0);
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: GSMDecodeFrameExit
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    state = pointer to an array of pointers to structures of type
+            Speech_Decode_FrameState
+
+ Outputs:
+    state contents is set to NULL
+
+ Returns:
+    None
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function frees up the memory used for the state memory of the GSM AMR
+ decoder.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: The original function name of Speech_Decode_Frame_exit was changed to
+       GSMDecodeFrameExit in the Code section.
+
+void Speech_Decode_Frame_exit (Speech_Decode_FrameState **state)
+{
+  if (state == NULL || *state == NULL)
+      return;
+
+  Decoder_amr_exit(&(*state)->decoder_amrState);
+  Post_Filter_exit(&(*state)->post_state);
+  Post_Process_exit(&(*state)->postHP_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 GSMDecodeFrameExit(void **state_data)
+{
+
+    Speech_Decode_FrameState **state =
+        (Speech_Decode_FrameState **) state_data;
+
+    if (state == NULL || *state == NULL)
+    {
+        return;
+    }
+
+    /* deallocate memory */
+    free(*state);
+    *state = NULL;
+
+    return;
+}
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: GSMFrameDecode
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    st = pointer to structures of type Speech_Decode_FrameState
+    mode = GSM AMR codec mode (enum Mode)
+    serial = pointer to the serial bit stream buffer (unsigned char)
+    frame_type = GSM AMR receive frame type (enum RXFrameType)
+    synth = pointer to the output synthesis speech buffer (Word16)
+
+ Outputs:
+    synth contents are truncated to 13 bits if NO13BIT is not defined,
+      otherwise, its contents are left at 16 bits
+
+ Returns:
+    return_value = set to zero (int)
+
+ Global Variables Used:
+    None
+
+ Local Variables Needed:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function is the entry point to the GSM AMR decoder. The following
+ operations are performed on one received frame: First, the codec
+ parameters are parsed from the buffer pointed to by serial according to
+ frame_type. Then the AMR decoder is invoked via a call to Decoder_amr. Post
+ filtering of the decoded data is done via a call to Post_Filter function.
+ Lastly, the decoded data is post-processed via a call to Post_Process
+ function. If NO13BIT is not defined, the contents of the buffer pointed to
+ by synth is truncated to 13 bits. It remains unchanged otherwise.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ sp_dec.c, UMTS GSM AMR speech codec, R99 - Version 3.2.0, March 2, 2001
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ Note: The original function name of Speech_Decode_Frame_exit was changed to
+       GSMFrameDecode in the Code section.
+
+int Speech_Decode_Frame (
+    Speech_Decode_FrameState *st, // io: post filter states
+    enum Mode mode,               // i : AMR mode
+    Word16 *serial,               // i : serial bit stream
+    enum RXFrameType frame_type,  // i : Frame type
+    Word16 *synth                 // o : synthesis speech (postfiltered
+                                  //     output)
+)
+{
+  Word16 parm[MAX_PRM_SIZE + 1];  // Synthesis parameters
+  Word16 Az_dec[AZ_SIZE];         // Decoded Az for post-filter
+                                  // in 4 subframes
+
+#if !defined(NO13BIT)
+  Word16 i;
+#endif
+
+  setCounter(st->complexityCounter);
+  Reset_WMOPS_counter ();          // reset WMOPS counter for the new frame
+
+  // Serial to parameters
+  if ((frame_type == RX_SID_BAD) ||
+      (frame_type == RX_SID_UPDATE)) {
+    // Override mode to MRDTX
+    Bits2prm (MRDTX, serial, parm);
+  } else {
+    Bits2prm (mode, serial, parm);
+  }
+
+  // Synthesis
+  Decoder_amr(st->decoder_amrState, mode, parm, frame_type,
+              synth, Az_dec);
+
+  Post_Filter(st->post_state, mode, synth, Az_dec);   // Post-filter
+
+  // post HP filter, and 15->16 bits
+  Post_Process(st->postHP_state, synth, L_FRAME);
+
+#if !defined(NO13BIT)
+  // Truncate to 13 bits
+  for (i = 0; i < L_FRAME; i++)
+  {
+     synth[i] = synth[i] & 0xfff8;
+  }
+#endif
+
+  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 GSMFrameDecode(
+    Speech_Decode_FrameState *st, /* io: post filter states                */
+    enum Mode mode,               /* i : AMR mode                          */
+    Word16 *serial,               /* i : serial bit stream                 */
+    enum RXFrameType frame_type,  /* i : Frame type                        */
+    Word16 *synth)                /* o : synthesis speech (postfiltered    */
+/*     output)                           */
+
+{
+    Word16 parm[MAX_PRM_SIZE + 1];  /* Synthesis parameters                */
+    Word16 Az_dec[AZ_SIZE];         /* Decoded Az for post-filter          */
+    /* in 4 subframes                      */
+    Flag *pOverflow = &(st->decoder_amrState.overflow);  /* Overflow flag  */
+
+#if !defined(NO13BIT)
+    Word16 i;
+#endif
+
+    /* Serial to parameters   */
+    if ((frame_type == RX_SID_BAD) ||
+            (frame_type == RX_SID_UPDATE))
+    {
+        /* Override mode to MRDTX */
+        Bits2prm(MRDTX, serial, parm);
+    }
+    else
+    {
+        Bits2prm(mode, serial, parm);
+    }
+
+    /* Synthesis */
+    Decoder_amr(
+        &(st->decoder_amrState),
+        mode,
+        parm,
+        frame_type,
+        synth,
+        Az_dec);
+
+    /* Post-filter */
+    Post_Filter(
+        &(st->post_state),
+        mode,
+        synth,
+        Az_dec,
+        pOverflow);
+
+    /* post HP filter, and 15->16 bits */
+    Post_Process(
+        &(st->postHP_state),
+        synth,
+        L_FRAME,
+        pOverflow);
+
+#if !defined(NO13BIT)
+    /* Truncate to 13 bits */
+    for (i = 0; i < L_FRAME; i++)
+    {
+        synth[i] = synth[i] & 0xfff8;
+    }
+#endif
+
+    return;
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrnb/dec/src/sp_dec.h b/media/libstagefright/codecs/amrnb/dec/src/sp_dec.h
new file mode 100644
index 0000000..3150feb
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/sp_dec.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.
+****************************************************************************************/
+/*
+*****************************************************************************
+*
+*      GSM AMR speech codec   Version 2.0.0   February 8, 1999
+*
+*****************************************************************************
+*
+*      File             : sp_dec.h
+*      Purpose          : Decoding and post filtering of one speech frame.
+*
+
+ Description:  Replaced "int" and/or "char" with OSCL defined types.
+
+*****************************************************************************
+*/
+#ifndef sp_dec_h
+#define sp_dec_h "$Id $"
+
+/*
+*****************************************************************************
+*                         INCLUDE FILES
+*****************************************************************************
+*/
+#include "typedef.h"
+#include "cnst.h"
+#include "dec_amr.h"
+#include "pstfilt.h"
+#include "post_pro.h"
+#include "mode.h"
+
+/*
+*****************************************************************************
+*                         DEFINITION OF DATA TYPES
+*****************************************************************************
+*/
+typedef struct
+{
+    Decoder_amrState  decoder_amrState;
+    Post_FilterState  post_state;
+    Post_ProcessState postHP_state;
+    enum Mode prev_mode;
+} Speech_Decode_FrameState;
+
+/*
+*****************************************************************************
+*                         DECLARATION OF PROTOTYPES
+*****************************************************************************
+*/
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+    Word16 GSMInitDecode(void **state_data,
+    Word8 *id);
+    /* initialize one instance of the speech decoder
+       Stores pointer to filter status struct in *st. This pointer has to
+       be passed to Speech_Decode_Frame in each call.
+       returns 0 on success
+     */
+
+    Word16 Speech_Decode_Frame_reset(void *state_data);
+    /* reset speech decoder (i.e. set state memory to zero)
+       returns 0 on success
+     */
+
+    void GSMDecodeFrameExit(void **state_data);
+    /* de-initialize speech decoder (i.e. free status struct)
+       stores NULL in *s
+     */
+
+    void GSMFrameDecode(
+        Speech_Decode_FrameState *st, /* io: post filter states                */
+        enum Mode mode,               /* i : AMR mode                          */
+        Word16 *serial,               /* i : serial bit stream                 */
+        enum RXFrameType frame_type,  /* i : Frame type                        */
+        Word16 *synth                 /* o : synthesis speech (postfiltered    */
+        /*     output)                           */
+    );
+    /*    return 0 on success
+     */
+#if defined(__cplusplus)
+}
+#endif
+#endif
diff --git a/media/libstagefright/codecs/amrnb/dec/src/wmf_to_ets.cpp b/media/libstagefright/codecs/amrnb/dec/src/wmf_to_ets.cpp
new file mode 100644
index 0000000..4dfbb67
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/dec/src/wmf_to_ets.cpp
@@ -0,0 +1,190 @@
+/* ------------------------------------------------------------------
+ * 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/wmf_to_ets.c
+ Funtions: wmf_to_ets
+
+     Date: 01/21/2002
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description: Changing mode to frame_type_3gpp for DTX support. Modifying for
+              loops for optimized code. Updating as per review comments.
+
+ Description: Changed MRDTX to AMR_SID in the code and added bitreorder_tab.h
+              in the Include section.
+
+ Description:
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "frame_type_3gpp.h"
+#include "wmf_to_ets.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: wmf_to_ets
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    frame_type_3gpp = decoder speech bit rate (enum Frame_Type_3GPP)
+    wmf_input_ptr   = pointer to input encoded speech bits in WMF (non-IF2) format
+                     (Word8)
+    ets_output_ptr  = pointer to output encoded speech bits in ETS format (Word16)
+
+ Outputs:
+    ets_output_ptr  = pointer to encoded speech bits in the ETS format (Word16)
+
+ 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 WMF (non-IF2) (Wireless Multi-media Forum) to ETS (European
+ Telecommunication Standard). WMF format has the encoded speech bits byte
+ aligned with MSB to LSB going left to right. ETS format has the encoded speech
+ bits each separate with only one bit stored in each word.
+
+------------------------------------------------------------------------------
+ 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 wmf_to_ets(
+    enum Frame_Type_3GPP frame_type_3gpp,
+    UWord8   *wmf_input_ptr,
+    Word16   *ets_output_ptr)
+{
+
+    Word16 i;
+
+    /*
+     * The following section of code accesses bits in the WMF method of
+     * bit ordering. Each bit is given its own location in the buffer pointed
+     * to by ets_output_ptr. If the frame_type_3gpp is less than MRDTX then
+     * the elements are reordered within the buffer pointed to by ets_output_ptr.
+     */
+
+    if (frame_type_3gpp < AMR_SID)
+    {
+        /* The table numOfBits[] can be found in bitreorder.c. */
+        for (i = numOfBits[frame_type_3gpp] - 1; i >= 0; i--)
+        {
+            /* The table reorderBits[][] can be found in bitreorder.c. */
+            ets_output_ptr[reorderBits[frame_type_3gpp][i]] =
+                (wmf_input_ptr[i>>3] >> ((~i) & 0x7)) & 0x01;
+        }
+    }
+    else
+    {
+        /* The table numOfBits[] can be found in bitreorder.c. */
+        for (i = numOfBits[frame_type_3gpp] - 1; i >= 0; i--)
+        {
+            ets_output_ptr[i] = (wmf_input_ptr[i>>3] >> ((~i) & 0x7)) & 0x01;
+        }
+    }
+
+    return;
+}
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..0d3acac
--- /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..a33cdf74
--- /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/codecs/amrnb/patent_disclaimer.txt b/media/libstagefright/codecs/amrnb/patent_disclaimer.txt
new file mode 100644
index 0000000..b4bf11d
--- /dev/null
+++ b/media/libstagefright/codecs/amrnb/patent_disclaimer.txt
@@ -0,0 +1,9 @@
+
+THIS IS NOT A GRANT OF PATENT RIGHTS.
+
+Google makes no representation or warranty that the codecs for which
+source code is made available hereunder are unencumbered by
+third-party patents.  Those intending to use this source code in
+hardware or software products are advised that implementations of
+these codecs, including in open source software or shareware, may
+require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/amrwb/AMRWBDecoder.cpp b/media/libstagefright/codecs/amrwb/AMRWBDecoder.cpp
new file mode 100644
index 0000000..c9d38c0
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/AMRWBDecoder.cpp
@@ -0,0 +1,222 @@
+/*
+ * 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 "AMRWBDecoder.h"
+
+#include "pvamrwbdecoder.h"
+
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+static const int32_t kNumSamplesPerFrame = 320;
+static const int32_t kSampleRate = 16000;
+
+AMRWBDecoder::AMRWBDecoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mBufferGroup(NULL),
+      mState(NULL),
+      mDecoderBuf(NULL),
+      mDecoderCookie(NULL),
+      mAnchorTimeUs(0),
+      mNumSamplesOutput(0),
+      mInputBuffer(NULL) {
+}
+
+AMRWBDecoder::~AMRWBDecoder() {
+    if (mStarted) {
+        stop();
+    }
+}
+
+status_t AMRWBDecoder::start(MetaData *params) {
+    CHECK(!mStarted);
+
+    mBufferGroup = new MediaBufferGroup;
+    mBufferGroup->add_buffer(
+            new MediaBuffer(kNumSamplesPerFrame * sizeof(int16_t)));
+
+    int32_t memReq = pvDecoder_AmrWbMemRequirements();
+    mDecoderBuf = malloc(memReq);
+
+    pvDecoder_AmrWb_Init(&mState, mDecoderBuf, &mDecoderCookie);
+
+    mSource->start();
+
+    mAnchorTimeUs = 0;
+    mNumSamplesOutput = 0;
+    mStarted = true;
+
+    return OK;
+}
+
+status_t AMRWBDecoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    delete mBufferGroup;
+    mBufferGroup = NULL;
+
+    free(mDecoderBuf);
+    mDecoderBuf = NULL;
+
+    mSource->stop();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> AMRWBDecoder::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_RAW);
+    meta->setInt32(kKeyChannelCount, numChannels);
+    meta->setInt32(kKeySampleRate, sampleRate);
+
+    int64_t durationUs;
+    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
+        meta->setInt64(kKeyDuration, durationUs);
+    }
+
+    return meta;
+}
+
+static size_t getFrameSize(unsigned FT) {
+    static const size_t kFrameSizeWB[9] = {
+        132, 177, 253, 285, 317, 365, 397, 461, 477
+    };
+
+    size_t frameSize = kFrameSizeWB[FT];
+
+    // Round up bits to bytes and add 1 for the header byte.
+    frameSize = (frameSize + 7) / 8 + 1;
+
+    return frameSize;
+}
+
+status_t AMRWBDecoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    status_t err;
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        CHECK(seekTimeUs >= 0);
+
+        mNumSamplesOutput = 0;
+
+        if (mInputBuffer) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+    } else {
+        seekTimeUs = -1;
+    }
+
+    if (mInputBuffer == NULL) {
+        err = mSource->read(&mInputBuffer, options);
+
+        if (err != OK) {
+            return err;
+        }
+
+        int64_t timeUs;
+        if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
+            mAnchorTimeUs = timeUs;
+            mNumSamplesOutput = 0;
+        } else {
+            // We must have a new timestamp after seeking.
+            CHECK(seekTimeUs < 0);
+        }
+    }
+
+    MediaBuffer *buffer;
+    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
+
+    const uint8_t *inputPtr =
+        (const uint8_t *)mInputBuffer->data() + mInputBuffer->range_offset();
+
+    int16 mode = ((inputPtr[0] >> 3) & 0x0f);
+    size_t frameSize = getFrameSize(mode);
+    CHECK(mInputBuffer->range_length() >= frameSize);
+
+    int16 frameType;
+    RX_State rx_state;
+    mime_unsorting(
+            const_cast<uint8_t *>(&inputPtr[1]),
+            mInputSampleBuffer,
+            &frameType, &mode, 1, &rx_state);
+
+    int16_t *outPtr = (int16_t *)buffer->data();
+
+    int16_t numSamplesOutput;
+    pvDecoder_AmrWb(
+            mode, mInputSampleBuffer,
+            outPtr,
+            &numSamplesOutput,
+            mDecoderBuf, frameType, mDecoderCookie);
+
+    CHECK_EQ(numSamplesOutput, kNumSamplesPerFrame);
+
+    for (int i = 0; i < kNumSamplesPerFrame; ++i) {
+        /* Delete the 2 LSBs (14-bit output) */
+        outPtr[i] &= 0xfffC;
+    }
+
+    buffer->set_range(0, numSamplesOutput * sizeof(int16_t));
+
+    mInputBuffer->set_range(
+            mInputBuffer->range_offset() + frameSize,
+            mInputBuffer->range_length() - frameSize);
+
+    if (mInputBuffer->range_length() == 0) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    buffer->meta_data()->setInt64(
+            kKeyTime,
+            mAnchorTimeUs
+                + (mNumSamplesOutput * 1000000) / kSampleRate);
+
+    mNumSamplesOutput += kNumSamplesPerFrame;
+
+    *out = buffer;
+
+    return OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/amrwb/Android.mk b/media/libstagefright/codecs/amrwb/Android.mk
new file mode 100644
index 0000000..ab591d7
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/Android.mk
@@ -0,0 +1,56 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        AMRWBDecoder.cpp \
+	src/agc2_amr_wb.cpp \
+ 	src/band_pass_6k_7k.cpp \
+ 	src/dec_acelp_2p_in_64.cpp \
+ 	src/dec_acelp_4p_in_64.cpp \
+ 	src/dec_alg_codebook.cpp \
+ 	src/dec_gain2_amr_wb.cpp \
+ 	src/deemphasis_32.cpp \
+ 	src/dtx_decoder_amr_wb.cpp \
+ 	src/get_amr_wb_bits.cpp \
+ 	src/highpass_400hz_at_12k8.cpp \
+ 	src/highpass_50hz_at_12k8.cpp \
+ 	src/homing_amr_wb_dec.cpp \
+ 	src/interpolate_isp.cpp \
+ 	src/isf_extrapolation.cpp \
+ 	src/isp_az.cpp \
+ 	src/isp_isf.cpp \
+ 	src/lagconceal.cpp \
+ 	src/low_pass_filt_7k.cpp \
+ 	src/median5.cpp \
+ 	src/mime_io.cpp \
+ 	src/noise_gen_amrwb.cpp \
+ 	src/normalize_amr_wb.cpp \
+ 	src/oversamp_12k8_to_16k.cpp \
+ 	src/phase_dispersion.cpp \
+ 	src/pit_shrp.cpp \
+ 	src/pred_lt4.cpp \
+ 	src/preemph_amrwb_dec.cpp \
+ 	src/pvamrwb_math_op.cpp \
+ 	src/pvamrwbdecoder.cpp \
+ 	src/q_gain2_tab.cpp \
+ 	src/qisf_ns.cpp \
+ 	src/qisf_ns_tab.cpp \
+ 	src/qpisf_2s.cpp \
+ 	src/qpisf_2s_tab.cpp \
+ 	src/scale_signal.cpp \
+ 	src/synthesis_amr_wb.cpp \
+ 	src/voice_factor.cpp \
+ 	src/wb_syn_filt.cpp \
+ 	src/weight_amrwb_lpc.cpp
+
+LOCAL_C_INCLUDES := \
+        frameworks/base/media/libstagefright/include \
+        $(LOCAL_PATH)/src \
+        $(LOCAL_PATH)/include
+
+LOCAL_CFLAGS := \
+        -DOSCL_UNUSED_ARG= -DOSCL_IMPORT_REF=
+
+LOCAL_MODULE := libstagefright_amrwbdec
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/amrwb/include/pvamrwbdecoder_api.h b/media/libstagefright/codecs/amrwb/include/pvamrwbdecoder_api.h
new file mode 100644
index 0000000..457c21f
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/include/pvamrwbdecoder_api.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Name: pvamrwbdecoder_api.h
+
+     Date: 05/02/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Main header file for the Packet Video AMR Wide  Band  decoder library. The
+ constants, structures, and functions defined within this file, along with
+ a basic data types header file, is all that is needed to use and communicate
+ with the library. The internal data structures within the library are
+ purposely hidden.
+
+ ---* Need description of the input buffering. *-------
+
+ ---* Need an example of calling the library here *----
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (Normally header files do not have a reference section)
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef _PVAMRWBDECODER_API_H
+#define _PVAMRWBDECODER_API_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES
+    ; Include all pre-processor statements here.
+    ----------------------------------------------------------------------------*/
+
+#define AMR_WB_PCM_FRAME   320             /* Frame size at 16kHz     */
+
+
+#define NBBITS_7k     132                  /* 6.60k  */
+#define NBBITS_9k     177                  /* 8.85k  */
+#define NBBITS_12k    253                  /* 12.65k */
+#define NBBITS_14k    285                  /* 14.25k */
+#define NBBITS_16k    317                  /* 15.85k */
+#define NBBITS_18k    365                  /* 18.25k */
+#define NBBITS_20k    397                  /* 19.85k */
+#define NBBITS_23k    461                  /* 23.05k */
+#define NBBITS_24k    477                  /* 23.85k */
+
+#define NBBITS_SID    35
+
+#define KAMRWB_NB_BITS_MAX   NBBITS_24k
+#define KAMRWB_NB_BYTES_MAX  ((KAMRWB_NB_BITS_MAX>>3)+1)
+
+#define NUM_OF_MODES  10
+
+
+    const int16 AMR_WB_COMPRESSED[NUM_OF_MODES] =
+    {
+        NBBITS_7k,
+        NBBITS_9k,
+        NBBITS_12k,
+        NBBITS_14k,
+        NBBITS_16k,
+        NBBITS_18k,
+        NBBITS_20k,
+        NBBITS_23k,
+        NBBITS_24k,
+        NBBITS_SID
+    };
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ; Declare variables used in this module but defined elsewhere
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* PVMP4AUDIODECODER_API_H */
+
+
diff --git a/media/libstagefright/codecs/amrwb/patent_disclaimer.txt b/media/libstagefright/codecs/amrwb/patent_disclaimer.txt
new file mode 100644
index 0000000..b4bf11d
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/patent_disclaimer.txt
@@ -0,0 +1,9 @@
+
+THIS IS NOT A GRANT OF PATENT RIGHTS.
+
+Google makes no representation or warranty that the codecs for which
+source code is made available hereunder are unencumbered by
+third-party patents.  Those intending to use this source code in
+hardware or software products are advised that implementations of
+these codecs, including in open source software or shareware, may
+require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/amrwb/src/agc2_amr_wb.cpp b/media/libstagefright/codecs/amrwb/src/agc2_amr_wb.cpp
new file mode 100644
index 0000000..2e53d13
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/agc2_amr_wb.cpp
@@ -0,0 +1,190 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: agc2_amr_wb.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 * sig_in,            (i)     : postfilter input signal
+     int16 * sig_out,           (i/o)   : postfilter output signal
+     int16 l_trm                (i)     : subframe size
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Performs adaptive gain control
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_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
+----------------------------------------------------------------------------*/
+
+void agc2_amr_wb(
+    int16 * sig_in,          /* (i)     : postfilter input signal  */
+    int16 * sig_out,         /* (i/o)   : postfilter output signal */
+    int16 l_trm              /* (i)     : subframe size            */
+)
+{
+
+    int16 i, exp;
+    int16 gain_in, gain_out, g0;
+    int32 s;
+
+    int16 temp;
+
+    /* calculate gain_out with exponent */
+
+    temp = sig_out[0] >> 2;
+    s = fxp_mul_16by16(temp, temp) << 1;
+    for (i = 1; i < l_trm; i++)
+    {
+        temp = sig_out[i] >> 2;
+        s = mac_16by16_to_int32(s, temp, temp);
+    }
+
+
+    if (s == 0)
+    {
+        return;
+    }
+    exp = normalize_amr_wb(s) - 1;
+    gain_out = amr_wb_round(s << exp);
+
+    /* calculate gain_in with exponent */
+
+    temp = sig_in[0] >> 2;
+    s = mul_16by16_to_int32(temp, temp);
+    for (i = 1; i < l_trm; i++)
+    {
+        temp = sig_in[i] >> 2;
+        s = mac_16by16_to_int32(s, temp, temp);
+    }
+
+
+    if (s == 0)
+    {
+        g0 = 0;
+    }
+    else
+    {
+        i = normalize_amr_wb(s);
+        gain_in = amr_wb_round(s << i);
+        exp -= i;
+
+        /*
+         *  g0 = sqrt(gain_in/gain_out)
+         */
+
+        s = div_16by16(gain_out, gain_in);
+        s = shl_int32(s, 7);                   /* s = gain_out / gain_in */
+        s = shr_int32(s, exp);                 /* add exponent */
+
+        s = one_ov_sqrt(s);
+        g0 = amr_wb_round(shl_int32(s, 9));
+    }
+    /* sig_out(n) = gain(n) sig_out(n) */
+
+    for (i = 0; i < l_trm; i++)
+    {
+        sig_out[i] = extract_h(shl_int32(fxp_mul_16by16(sig_out[i], g0), 3));
+
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/band_pass_6k_7k.cpp b/media/libstagefright/codecs/amrwb/src/band_pass_6k_7k.cpp
new file mode 100644
index 0000000..97c7402
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/band_pass_6k_7k.cpp
@@ -0,0 +1,240 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: band_pass_6k_7k.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 in/out: memory (size=30)
+     int16 x[]                   scratch mem ( size= 60)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   15th order band pass 6kHz to 7kHz FIR filter.
+
+   frequency:  4kHz   5kHz  5.5kHz  6kHz  6.5kHz 7kHz  7.5kHz  8kHz
+   dB loss:   -60dB  -45dB  -13dB   -3dB   0dB   -3dB  -13dB  -45dB
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwbdecoder_cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define L_FIR 30
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* filter coefficients (gain=4.0) */
+
+const int16 fir_6k_7k[L_FIR] =
+{
+    -32,     47,     32,    -27,
+    -369,   1122,  -1421,      0,
+    3798,  -8880,  12349, -10984,
+    3548,   7766, -18001,
+    22118,
+    -18001,   7766,   3548, -10984,
+    12349,  -8880,   3798,      0,
+    -1421,   1122,   -369,    -27,
+    32,     47
+};
+
+/*----------------------------------------------------------------------------
+; 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 band_pass_6k_7k_init(int16 mem[])         /* mem[30] */
+{
+    pv_memset((void *)mem, 0, L_FIR*sizeof(*mem));
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void band_pass_6k_7k(
+    int16 signal[],                      /* input:  signal                  */
+    int16 lg,                            /* input:  length of input         */
+    int16 mem[],                         /* in/out: memory (size=30)        */
+    int16 x[]
+)
+{
+    int16 i, j;
+    int32 L_tmp1;
+    int32 L_tmp2;
+    int32 L_tmp3;
+    int32 L_tmp4;
+
+    int16 *pt_sign = signal;
+
+    pv_memcpy((void *)x, (void *)mem, L_FIR*sizeof(*x));
+
+
+    for (i = 0; i < lg >> 2; i++)
+    {
+
+        x[(i<<2) + L_FIR    ] = *(pt_sign) >> 2;        /* gain of filter = 4 */
+        x[(i<<2) + L_FIR + 1] = *(pt_sign + 1) >> 2;    /* gain of filter = 4 */
+        x[(i<<2) + L_FIR + 2] = *(pt_sign + 2) >> 2;    /* gain of filter = 4 */
+        x[(i<<2) + L_FIR + 3] = *(pt_sign + 3) >> 2;    /* gain of filter = 4 */
+
+        L_tmp1 = 0x00004000;
+        L_tmp2 = 0x00004000;
+        L_tmp3 = 0x00004000;
+        L_tmp4 = 0x00004000;
+
+        L_tmp1 -= ((int32)x[(i<<2)+L_FIR  ] << 5);
+        L_tmp2 -= ((int32)x[(i<<2)+L_FIR+1] << 5);
+        L_tmp3 -= ((int32)x[(i<<2)+L_FIR+2] << 5);
+        L_tmp4 -= ((int32)x[(i<<2)+L_FIR+3] << 5);
+
+        L_tmp1 -= ((int32)x[(i<<2)] << 5);
+        L_tmp2 -= ((int32)x[(i<<2)+1] << 5);
+        L_tmp3 -= ((int32)x[(i<<2)+2] << 5);
+        L_tmp4 -= ((int32)x[(i<<2)+3] << 5);
+
+
+        for (j = 1; j < L_FIR - 1; j += 4)
+        {
+            int16 tmp1 = x[(i<<2)+j  ];
+            int16 tmp2 = x[(i<<2)+j+1];
+            int16 tmp3 = x[(i<<2)+j+2];
+
+            L_tmp1 = fxp_mac_16by16(tmp1, fir_6k_7k[j  ], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp2, fir_6k_7k[j  ], L_tmp2);
+            L_tmp1 = fxp_mac_16by16(tmp2, fir_6k_7k[j+1], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp3, fir_6k_7k[j+1], L_tmp2);
+            L_tmp3 = fxp_mac_16by16(tmp3, fir_6k_7k[j  ], L_tmp3);
+            L_tmp1 = fxp_mac_16by16(tmp3, fir_6k_7k[j+2], L_tmp1);
+
+            tmp1 = x[(i<<2)+j+3];
+            tmp2 = x[(i<<2)+j+4];
+
+            L_tmp2 = fxp_mac_16by16(tmp1, fir_6k_7k[j+2], L_tmp2);
+            L_tmp4 = fxp_mac_16by16(tmp1, fir_6k_7k[j  ], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp1, fir_6k_7k[j+1], L_tmp3);
+            L_tmp1 = fxp_mac_16by16(tmp1, fir_6k_7k[j+3], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp2, fir_6k_7k[j+3], L_tmp2);
+            L_tmp4 = fxp_mac_16by16(tmp2, fir_6k_7k[j+1], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp2, fir_6k_7k[j+2], L_tmp3);
+
+            tmp1 = x[(i<<2)+j+5];
+            tmp2 = x[(i<<2)+j+6];
+
+            L_tmp4 = fxp_mac_16by16(tmp1, fir_6k_7k[j+2], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp1, fir_6k_7k[j+3], L_tmp3);
+            L_tmp4 = fxp_mac_16by16(tmp2, fir_6k_7k[j+3], L_tmp4);
+
+        }
+
+        L_tmp1 = fxp_mac_16by16(x[(i<<2)+j  ], fir_6k_7k[L_FIR-1  ], L_tmp1);
+        L_tmp2 = fxp_mac_16by16(x[(i<<2)+j+1], fir_6k_7k[L_FIR-1  ], L_tmp2);
+        L_tmp3 = fxp_mac_16by16(x[(i<<2)+j+2], fir_6k_7k[L_FIR-1  ], L_tmp3);
+        L_tmp4 = fxp_mac_16by16(x[(i<<2)+j+3], fir_6k_7k[L_FIR-1  ], L_tmp4);
+
+
+        *(pt_sign++) = (int16)(L_tmp1 >> 15);
+        *(pt_sign++) = (int16)(L_tmp2 >> 15);
+        *(pt_sign++) = (int16)(L_tmp3 >> 15);
+        *(pt_sign++) = (int16)(L_tmp4 >> 15);
+
+    }
+
+    pv_memcpy((void *)mem, (void *)(x + lg), L_FIR*sizeof(*mem));
+
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/dec_acelp_2p_in_64.cpp b/media/libstagefright/codecs/amrwb/src/dec_acelp_2p_in_64.cpp
new file mode 100644
index 0000000..740bc16
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dec_acelp_2p_in_64.cpp
@@ -0,0 +1,157 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: dec_acelp_2p_in_64.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 index,          (i):   12 bits index
+     int16 code[]          (o): Q9 algebraic (fixed) codebook excitation
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   12 bits algebraic codebook decoder.
+   2 tracks x 32 positions per track = 64 samples.
+
+   12 bits --> 2 pulses in a frame of 64 samples.
+
+   All pulses can have two (2) possible amplitudes: +1 or -1.
+   Each pulse can have 32 possible positions.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define L_CODE    64                       /* codevector length  */
+#define NB_TRACK  2                        /* number of track    */
+#define NB_POS    32                       /* number of position */
+
+
+/*----------------------------------------------------------------------------
+; 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 dec_acelp_2p_in_64(
+    int16 index,        /* (i):   12 bits index                          */
+    int16 code[]        /* (o): Q9 algebraic (fixed) codebook excitation */
+)
+{
+    int16 i;
+
+    pv_memset(code, 0, L_CODE*sizeof(*code));
+
+    /* decode the positions and signs of pulses and build the codeword */
+
+    i = (index >> 5) & 0x003E;
+
+    if (((index >> 6) & NB_POS) == 0)
+    {
+        code[i] = 512;
+    }
+    else
+    {
+        code[i] = -512;
+    }
+
+    i = ((index & 0x001F) << 1) + 1;
+
+    if ((index & NB_POS) == 0)
+    {
+        code[i] = 512;
+    }
+    else
+    {
+        code[i] = -512;
+    }
+
+}
diff --git a/media/libstagefright/codecs/amrwb/src/dec_acelp_4p_in_64.cpp b/media/libstagefright/codecs/amrwb/src/dec_acelp_4p_in_64.cpp
new file mode 100644
index 0000000..4868822
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dec_acelp_4p_in_64.cpp
@@ -0,0 +1,265 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: dec_acelp_4p_in_64.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 index[],    (i) : index (20): 5+5+5+5 = 20 bits.
+                       (i) : index (36): 9+9+9+9 = 36 bits.
+                       (i) : index (44): 13+9+13+9 = 44 bits.
+                       (i) : index (52): 13+13+13+13 = 52 bits.
+                       (i) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.
+                       (i) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.
+                       (i) : index (88): 11+11+11+11+11+11+11+11 = 88 bits.
+     int16 nbbits,     (i) : 20, 36, 44, 52, 64, 72 or 88 bits
+     int16 code[]      (o) Q9: algebraic (fixed) codebook excitation
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   20, 36, 44, 52, 64, 72, 88 bits algebraic codebook decoder.
+   4 tracks x 16 positions per track = 64 samples.
+
+   20 bits --> 4 pulses in a frame of 64 samples.
+   36 bits --> 8 pulses in a frame of 64 samples.
+   44 bits --> 10 pulses in a frame of 64 samples.
+   52 bits --> 12 pulses in a frame of 64 samples.
+   64 bits --> 16 pulses in a frame of 64 samples.
+   72 bits --> 18 pulses in a frame of 64 samples.
+   88 bits --> 24 pulses in a frame of 64 samples.
+
+   All pulses can have two (2) possible amplitudes: +1 or -1.
+   Each pulse can have sixteen (16) possible positions.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+#include "q_pulse.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define L_CODE    64                       /* codevector length  */
+#define NB_TRACK  4                        /* number of track    */
+#define NB_POS    16                       /* number of position */
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void add_pulses(int16 pos[], int16 nb_pulse, int16 track, int16 code[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 dec_acelp_4p_in_64(
+    int16 index[],  /* (i) : index (20): 5+5+5+5 = 20 bits.                 */
+    /* (i) : index (36): 9+9+9+9 = 36 bits.                 */
+    /* (i) : index (44): 13+9+13+9 = 44 bits.               */
+    /* (i) : index (52): 13+13+13+13 = 52 bits.             */
+    /* (i) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.     */
+    /* (i) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.   */
+    /* (i) : index (88): 11+11+11+11+11+11+11+11 = 88 bits. */
+    int16 nbbits,   /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits              */
+    int16 code[]    /* (o) Q9: algebraic (fixed) codebook excitation        */
+)
+{
+    int16 k, pos[6];
+    int32 L_index;
+    pv_memset(code, 0, L_CODE*sizeof(*code));
+
+    /* decode the positions and signs of pulses and build the codeword */
+
+
+    switch (nbbits)
+    {
+        case 20:
+            for (k = 0; k < NB_TRACK; k++)
+            {
+                L_index = index[k];
+                dec_1p_N1(L_index, 4, 0, pos);
+                add_pulses(pos, 1, k, code);
+            }
+            break;
+
+        case  36:
+            for (k = 0; k < NB_TRACK; k++)
+            {
+                L_index = index[k];
+                dec_2p_2N1(L_index, 4, 0, pos);
+                add_pulses(pos, 2, k, code);
+            }
+            break;
+        case 44:
+            for (k = 0; k < NB_TRACK - 2; k++)
+            {
+                L_index = index[k];
+                dec_3p_3N1(L_index, 4, 0, pos);
+                add_pulses(pos, 3, k, code);
+            }
+            for (k = 2; k < NB_TRACK; k++)
+            {
+                L_index = index[k];
+                dec_2p_2N1(L_index, 4, 0, pos);
+                add_pulses(pos, 2, k, code);
+            }
+            break;
+        case 52:
+            for (k = 0; k < NB_TRACK; k++)
+            {
+                L_index = index[k];
+                dec_3p_3N1(L_index, 4, 0, pos);
+                add_pulses(pos, 3, k, code);
+            }
+            break;
+        case 64:
+            for (k = 0; k < NB_TRACK; k++)
+            {
+                L_index = ((int32)index[k] << 14) + index[k + NB_TRACK];
+                dec_4p_4N(L_index, 4, 0, pos);
+                add_pulses(pos, 4, k, code);
+            }
+            break;
+        case 72:
+            for (k = 0; k < NB_TRACK - 2; k++)
+            {
+                L_index = ((int32)index[k] << 10) + index[k + NB_TRACK];
+                dec_5p_5N(L_index, 4, 0, pos);
+                add_pulses(pos, 5, k, code);
+            }
+            for (k = 2; k < NB_TRACK; k++)
+            {
+                L_index = ((int32)index[k] << 14) + index[k + NB_TRACK];
+                dec_4p_4N(L_index, 4, 0, pos);
+                add_pulses(pos, 4, k, code);
+            }
+            break;
+        case 88:
+            for (k = 0; k < NB_TRACK; k++)
+            {
+                L_index = ((int32)index[k] << 11) + index[k + NB_TRACK];
+                dec_6p_6N_2(L_index, 4, 0, pos);
+                add_pulses(pos, 6, k, code);
+            }
+        default:
+            break;
+    }
+
+
+}
+
+
+
+void add_pulses(int16 pos[], int16 nb_pulse, int16 track, int16 code[])
+{
+    int16 i, k;
+
+    for (k = 0; k < nb_pulse; k++)
+    {
+        /* i = ((pos[k] & (NB_POS-1))*NB_TRACK) + track; */
+        i = ((pos[k] & (NB_POS - 1)) << 2) + track;
+
+        if ((pos[k] & NB_POS) == 0)
+        {
+            code[i] +=  512;
+        }
+        else
+        {
+            code[i] -=  512;
+        }
+    }
+
+}
diff --git a/media/libstagefright/codecs/amrwb/src/dec_alg_codebook.cpp b/media/libstagefright/codecs/amrwb/src/dec_alg_codebook.cpp
new file mode 100644
index 0000000..44fdc09
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dec_alg_codebook.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: dec_alg_codebook.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        decoding of algebraic codebook
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "q_pulse.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define NB_POS 16                          /* pos in track, mask for sign bit */
+
+/*----------------------------------------------------------------------------
+; 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 dec_1p_N1(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 pos1;
+    int32 mask, i;
+
+    mask = ((1 << N) - 1);
+    /*-------------------------------------------------------*
+     * Decode 1 pulse with N+1 bits:                         *
+     *-------------------------------------------------------*/
+    pos1 = ((index & mask) + offset);
+
+    i = ((index >> N) & 1L);            /* i = ((index >> N) & 1); */
+
+    if (i == 1)
+    {
+        pos1 += NB_POS;
+    }
+    pos[0] = pos1;
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_2p_2N1(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 pos1, pos2, tmp;
+    int32 mask, i;
+
+    mask = (int32)(sub_int16(shl_int16(1, N), 1)); /* mask = ((1<<N)-1); */
+    /*-------------------------------------------------------*
+     * Decode 2 pulses with 2*N+1 bits:                      *
+     *-------------------------------------------------------*/
+    /* pos1 = (((index >> N) & mask) + offset); */
+    pos1 = (int16)(add_int32((shr_int32(index, N) & mask), (int32)(offset)));
+    tmp = shl_int16(N, 1);
+    i = (index >> tmp) & 1L;         /* i = (index >> (2*N)) & 1; */
+    pos2 = add_int16((int16)(index & mask), offset); /* pos2 = ((index & mask) + offset); */
+
+    if (pos2 < pos1)              /* ((pos2 - pos1) < 0) */
+    {
+        if (i == 1)
+        {                                  /* (i == 1) */
+            pos1 += NB_POS;      /* pos1 += NB_POS; */
+        }
+        else
+        {
+            pos2 += NB_POS;      /* pos2 += NB_POS;  */
+        }
+    }
+    else
+    {
+        if (i == 1)
+        {                                  /* (i == 1) */
+            pos1 += NB_POS;      /* pos1 += NB_POS; */
+            pos2 += NB_POS;      /* pos2 += NB_POS; */
+        }
+    }
+
+    pos[0] = pos1;
+    pos[1] = pos2;
+
+    return;
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_3p_3N1(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 j, tmp;
+    int32 mask, idx;
+
+    /*-------------------------------------------------------*
+     * Decode 3 pulses with 3*N+1 bits:                      *
+     *-------------------------------------------------------*/
+    tmp = sub_int16(shl_int16(N, 1), 1);               /* mask = ((1<<((2*N)-1))-1); */
+
+    mask = ((1 << ((2 * N) - 1)) - 1);
+
+    idx = index & mask;
+    j = offset;
+    tmp = (N << 1) - 1;
+
+
+    if (((index >> tmp) & 1L) != 0L)
+    {                                      /* if (((index >> ((2*N)-1)) & 1) == 1){ */
+        j += (1 << (N - 1)); /* j += (1<<(N-1)); */
+    }
+    dec_2p_2N1(idx, (int16)(N - 1), j, pos);
+
+    mask = ((1 << (N + 1)) - 1);
+    tmp = N << 1;                     /* idx = (index >> (2*N)) & mask; */
+    idx = (index >> tmp) & mask;
+
+    dec_1p_N1(idx, N, offset, pos + 2);
+
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_4p_4N1(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 j, tmp;
+    int32 mask, idx;
+
+    /*-------------------------------------------------------*
+     * Decode 4 pulses with 4*N+1 bits:                      *
+     *-------------------------------------------------------*/
+    tmp = (N << 1) - 1;
+    mask = (1L << tmp) - 1L;
+    idx = index & mask;
+    j = offset;
+    tmp = (N << 1) - 1;
+
+
+    if (((index >> tmp) & 1L) != 0L)
+    {                                      /* (((index >> ((2*N)-1)) & 1) == 1) */
+        j += (1 << (N - 1)); /* j += (1<<(N-1)); */
+    }
+    dec_2p_2N1(idx, (int16)(N - 1), j, pos);
+
+
+    tmp = (N << 1) + 1;             /* mask = ((1<<((2*N)+1))-1); */
+    mask = (1L << tmp) - 1L;
+    idx = (index >> (N << 1)) & mask;   /* idx = (index >> (2*N)) & mask; */
+    dec_2p_2N1(idx, N, offset, pos + 2);      /* dec_2p_2N1(idx, N, offset, pos+2); */
+
+    return;
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_4p_4N(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 j, n_1, tmp;
+
+    /*-------------------------------------------------------*
+     * Decode 4 pulses with 4*N bits:                        *
+     *-------------------------------------------------------*/
+
+    n_1 = N - 1;
+    j = offset + (1 << n_1);          /* j = offset + (1 << n_1); */
+
+    tmp = (N << 2) - 2;
+
+    switch ((index >> tmp) & 3)
+    {                                      /* ((index >> ((4*N)-2)) & 3) */
+        case 0:
+            tmp = (n_1 << 2) + 1;
+
+            if ((index >> tmp) & 1)
+            {                                  /* (((index >> ((4*n_1)+1)) & 1) == 0) */
+                dec_4p_4N1(index, n_1, j, pos);
+            }
+            else
+            {
+                dec_4p_4N1(index, n_1, offset, pos);
+            }
+            break;
+        case 1:
+            tmp = (3 * n_1) + 1; /* dec_1p_N1((index>>((3*n_1)+1)), n_1, offset, pos) */
+            dec_1p_N1(index >> tmp, n_1, offset, pos);
+            dec_3p_3N1(index, n_1, j, pos + 1);
+            break;
+        case 2:
+            tmp = (n_1 << 1) + 1;       /* dec_2p_2N1((index>>((2*n_1)+1)), n_1, offset, pos); */
+            dec_2p_2N1(index >> tmp, n_1, offset, pos);
+            dec_2p_2N1(index, n_1, j, pos + 2);
+            break;
+        case 3:
+            tmp = n_1 + 1;                 /* dec_3p_3N1((index>>(n_1+1)), n_1, offset, pos); */
+            dec_3p_3N1(index >> tmp, n_1, offset, pos);
+            dec_1p_N1(index, n_1, j, pos + 3);
+            break;
+    }
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_5p_5N(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 j, n_1, tmp;
+    int32 idx;
+
+    /*-------------------------------------------------------*
+     * Decode 5 pulses with 5*N bits:                        *
+     *-------------------------------------------------------*/
+
+    n_1 = (int16)(N - 1);
+    j = add_int16(offset, shl_int16(1, n_1));          /* j = offset + (1 << n_1); */
+    tmp = (N << 1) + 1;             /* idx = (index >> ((2*N)+1)); */
+    idx = index >> tmp;
+    tmp = (5 * N) - 1;    /* ((5*N)-1)) */
+
+
+    if ((index >> tmp) & 1)    /* ((index >> ((5*N)-1)) & 1)  */
+    {
+        dec_3p_3N1(idx, n_1, j, pos);
+        dec_2p_2N1(index, N, offset, pos + 3);
+    }
+    else
+    {
+        dec_3p_3N1(idx, n_1, offset, pos);
+        dec_2p_2N1(index, N, offset, pos + 3);
+    }
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_6p_6N_2(int32 index, int16 N, int16 offset, int16 pos[])
+{
+    int16 j, n_1, offsetA, offsetB;
+
+    n_1 = N - 1;
+    j = offset + (1 << n_1);       /* j = offset + (1 << n_1); */
+
+
+    /* !!  N and n_1 are constants -> it doesn't need to be operated by Basic Operators */
+
+    offsetA = offsetB = j;
+
+    if (((index >> (6*N - 5)) & 1L) == 0)
+    {                                      /* if (((index >> ((6*N)-5)) & 1) == 0) */
+        offsetA = offset;
+    }
+    else
+    {
+        offsetB = offset;
+    }
+
+
+    switch ((index >> (6*N - 4)) & 3)
+    {                                      /* (index >> ((6*N)-4)) & 3 */
+        case 0:
+            dec_5p_5N(index >> N, n_1, offsetA, pos);  /* dec_5p_5N(index>>N, n_1, offsetA, pos); */
+            dec_1p_N1(index, n_1, offsetA, pos + 5);
+            break;
+        case 1:
+            dec_5p_5N(index >> N, n_1, offsetA, pos);  /* dec_5p_5N(index>>N, n_1, offsetA, pos); */
+            dec_1p_N1(index, n_1, offsetB, pos + 5);
+            break;
+        case 2:
+            dec_4p_4N(index >> (2*n_1 + 1), n_1, offsetA, pos); /* dec_4p_4N(index>>((2*n_1)+1 ), n_1, offsetA, pos); */
+            dec_2p_2N1(index, n_1, offsetB, pos + 4);
+            break;
+        case 3:
+            dec_3p_3N1(index >> (3*n_1 + 1), n_1, offset, pos); /* dec_3p_3N1(index>>((3*n_1)+ 1), n_1, offset, pos); */
+            dec_3p_3N1(index, n_1, j, pos + 3);
+            break;
+    }
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/dec_gain2_amr_wb.cpp b/media/libstagefright/codecs/amrwb/src/dec_gain2_amr_wb.cpp
new file mode 100644
index 0000000..8cae559
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dec_gain2_amr_wb.cpp
@@ -0,0 +1,404 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: dec_gain2_amr_wb.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 index,                 (i)     : index of quantization.
+     int16 nbits,                 (i)     : number of bits (6 or 7)
+     int16 code[],                (i) Q9  : Innovative vector.
+     int16 L_subfr,               (i)     : Subframe lenght.
+     int16 * gain_pit,            (o) Q14 : Pitch gain.
+     int32 * gain_cod,            (o) Q16 : Code gain.
+     int16 bfi,                   (i)     : bad frame indicator
+     int16 prev_bfi,              (i)     : Previous BF indicator
+     int16 state,                 (i)     : State of BFH
+     int16 unusable_frame,        (i)     : UF indicator
+     int16 vad_hist,              (i)     : number of non-speech frames
+     int16 * mem                  (i/o)   : static memory (4 words)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Decode the pitch and codebook gains
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+#include "qisf_ns.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define MEAN_ENER    30
+#define PRED_ORDER   4
+
+#define L_LTPHIST 5
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+const int16 pdown_unusable[7] = {32767, 31130, 29491, 24576, 7537, 1638, 328};
+const int16 cdown_unusable[7] = {32767, 16384, 8192, 8192, 8192, 4915, 3277};
+
+const int16 pdown_usable[7] = {32767, 32113, 31457, 24576, 7537, 1638, 328};
+const int16 cdown_usable[7] = {32767, 32113, 32113, 32113, 32113, 32113, 22938};
+
+
+/* MA prediction coeff ={0.5, 0.4, 0.3, 0.2} in Q13 */
+const int16 pred[PRED_ORDER] = {4096, 3277, 2458, 1638};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/* output  :static memory (4 words)      */
+void dec_gain2_amr_wb_init(int16 * mem)
+{
+
+    /* 4nd order quantizer energy predictor (init to -14.0 in Q10) */
+    mem[0] = -14336;                          /* past_qua_en[0] */
+    mem[1] = -14336;                          /* past_qua_en[1] */
+    mem[2] = -14336;                          /* past_qua_en[2] */
+    mem[3] = -14336;                          /* past_qua_en[3] */
+    /* 4  *past_gain_pit  */
+    /* 5  *past_gain_code  */
+    /* 6  *prev_gc  */
+    /* next 5  pbuf[]  */
+    /* next 5  gbuf[]  */
+    /* next 5  pbuf2[]  */
+    pv_memset((void *)&mem[4], 0, 18*sizeof(*mem));
+
+    mem[22] = 21845;
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dec_gain2_amr_wb(
+    int16 index,               /* (i)     : index of quantization.      */
+    int16 nbits,               /* (i)     : number of bits (6 or 7)     */
+    int16 code[],              /* (i) Q9  : Innovative vector.          */
+    int16 L_subfr,             /* (i)     : Subframe lenght.            */
+    int16 * gain_pit,          /* (o) Q14 : Pitch gain.                 */
+    int32 * gain_cod,          /* (o) Q16 : Code gain.                  */
+    int16 bfi,                 /* (i)     : bad frame indicator         */
+    int16 prev_bfi,            /* (i)     : Previous BF indicator       */
+    int16 state,               /* (i)     : State of BFH                */
+    int16 unusable_frame,      /* (i)     : UF indicator                */
+    int16 vad_hist,            /* (i)     : number of non-speech frames */
+    int16 * mem                /* (i/o)   : static memory (4 words)     */
+)
+{
+    const int16 *p;
+    int16 *past_gain_pit, *past_gain_code, *past_qua_en, *gbuf, *pbuf, *prev_gc;
+    int16 *pbuf2;
+    int16 i, tmp, exp, frac, gcode0, exp_gcode0, qua_ener, gcode_inov;
+    int16 tmp1, g_code;
+    int16 tmp2;
+    int32 L_tmp;
+
+    past_qua_en = mem;
+    past_gain_pit = mem + 4;
+    past_gain_code = mem + 5;
+    prev_gc = mem + 6;
+    pbuf = mem + 7;
+    gbuf = mem + 12;
+    pbuf2 = mem + 17;
+
+    /*
+     *  Find energy of code and compute:
+     *
+     *    L_tmp = 1.0 / sqrt(energy of code/ L_subfr)
+     */
+
+    L_tmp = Dot_product12(code, code, L_subfr, &exp);
+    exp -= 24;                /* exp: -18 (code in Q9), -6 (/L_subfr) */
+
+    one_ov_sqrt_norm(&L_tmp, &exp);
+
+    gcode_inov = extract_h(shl_int32(L_tmp, exp - 3));  /* g_code_inov in Q12 */
+
+    /*
+     * Case of erasure.
+     */
+
+    if (bfi != 0)
+    {
+        tmp = median5(&pbuf[2]);
+        *past_gain_pit = tmp;
+
+        if (*past_gain_pit > 15565)
+        {
+            *past_gain_pit = 15565;        /* 0.95 in Q14 */
+
+        }
+
+        if (unusable_frame != 0)
+        {
+            *gain_pit = mult_int16(pdown_unusable[state], *past_gain_pit);
+        }
+        else
+        {
+            *gain_pit = mult_int16(pdown_usable[state], *past_gain_pit);
+        }
+        tmp = median5(&gbuf[2]);
+
+        if (vad_hist > 2)
+        {
+            *past_gain_code = tmp;
+        }
+        else
+        {
+
+            if (unusable_frame != 0)
+            {
+                *past_gain_code = mult_int16(cdown_unusable[state], tmp);
+            }
+            else
+            {
+                *past_gain_code = mult_int16(cdown_usable[state], tmp);
+            }
+        }
+
+        /* update table of past quantized energies */
+
+        tmp  = past_qua_en[3];
+        tmp1 = past_qua_en[2];
+        L_tmp  = tmp;
+        L_tmp += tmp1;
+        past_qua_en[3] = tmp;
+        tmp  = past_qua_en[1];
+        tmp1 = past_qua_en[0];
+        L_tmp += tmp;
+        L_tmp += tmp1;
+        past_qua_en[2] = tmp;
+        qua_ener = (int16)(L_tmp >> 3);
+        past_qua_en[1] = tmp1;
+
+
+        qua_ener -= 3072;    /* -3 in Q10 */
+
+        if (qua_ener < -14336)
+        {
+            qua_ener = -14336;                /* -14 in Q10 */
+        }
+
+        past_qua_en[0] = qua_ener;
+
+
+        for (i = 1; i < 5; i++)
+        {
+            gbuf[i - 1] = gbuf[i];
+            pbuf[i - 1] = pbuf[i];
+        }
+        gbuf[4] = *past_gain_code;
+        pbuf[4] = *past_gain_pit;
+
+
+        /* adjust gain according to energy of code */
+        /* past_gain_code(Q3) * gcode_inov(Q12) => Q16 */
+        *gain_cod = mul_16by16_to_int32(*past_gain_code, gcode_inov);
+
+        return;
+    }
+    /*
+     * Compute gcode0
+     *  = Sum(i=0,1) pred[i]*past_qua_en[i] + mean_ener - ener_code
+     */
+
+    L_tmp = L_deposit_h(MEAN_ENER);        /* MEAN_ENER in Q16 */
+    L_tmp = shl_int32(L_tmp, 8);               /* From Q16 to Q24 */
+    L_tmp = mac_16by16_to_int32(L_tmp, pred[0], past_qua_en[0]);      /* Q13*Q10 -> Q24 */
+    L_tmp = mac_16by16_to_int32(L_tmp, pred[1], past_qua_en[1]);      /* Q13*Q10 -> Q24 */
+    L_tmp = mac_16by16_to_int32(L_tmp, pred[2], past_qua_en[2]);      /* Q13*Q10 -> Q24 */
+    L_tmp = mac_16by16_to_int32(L_tmp, pred[3], past_qua_en[3]);      /* Q13*Q10 -> Q24 */
+
+    gcode0 = extract_h(L_tmp);             /* From Q24 to Q8  */
+
+    /*
+     * gcode0 = pow(10.0, gcode0/20)
+     *        = pow(2, 3.321928*gcode0/20)
+     *        = pow(2, 0.166096*gcode0)
+     */
+
+    L_tmp = ((int32)gcode0 * 5443) >> 7;      /* *0.166096 in Q15 -> Q24     */
+
+    int32_to_dpf(L_tmp, &exp_gcode0, &frac);  /* Extract exponant of gcode0  */
+
+    gcode0 = (int16)(power_of_2(14, frac));    /* Put 14 as exponant so that  */
+    /* output of Pow2() will be:   */
+    /* 16384 < Pow2() <= 32767     */
+    exp_gcode0 -= 14;
+
+    /* Read the quantized gains */
+
+    if (nbits == 6)
+    {
+        p = &t_qua_gain6b[index<<1];
+    }
+    else
+    {
+        p = &t_qua_gain7b[index<<1];
+    }
+    *gain_pit = *p++;                         /* selected pitch gain in Q14 */
+    g_code = *p++;                            /* selected code gain in Q11  */
+
+    L_tmp = mul_16by16_to_int32(g_code, gcode0);        /* Q11*Q0 -> Q12 */
+    L_tmp = shl_int32(L_tmp, exp_gcode0 + 4);   /* Q12 -> Q16 */
+
+    *gain_cod = L_tmp;                        /* gain of code in Q16 */
+
+    if (prev_bfi == 1)
+    {
+        L_tmp = mul_16by16_to_int32(*prev_gc, 5120);    /* prev_gc(Q3) * 1.25(Q12) = Q16 */
+        /* if((*gain_cod > ((*prev_gc) * 1.25)) && (*gain_cod > 100.0)) */
+
+        if ((*gain_cod > L_tmp) && (*gain_cod > 6553600))
+        {
+            *gain_cod = L_tmp;
+        }
+    }
+    /* keep past gain code in Q3 for frame erasure (can saturate) */
+    *past_gain_code = amr_wb_round(shl_int32(*gain_cod, 3));
+    *past_gain_pit = *gain_pit;
+
+
+    *prev_gc = *past_gain_code;
+    tmp  = gbuf[1];
+    tmp1 = pbuf[1];
+    tmp2 = pbuf2[1];
+    for (i = 1; i < 5; i++)
+    {
+        gbuf[i - 1]  = tmp;
+        pbuf[i - 1]  = tmp1;
+        pbuf2[i - 1] = tmp2;
+        tmp  = gbuf[i];
+        tmp1 = pbuf[i];
+        tmp2 = pbuf2[i];
+    }
+    gbuf[4] = *past_gain_code;
+    pbuf[4] = *past_gain_pit;
+    pbuf2[4] = *past_gain_pit;
+
+
+    /* adjust gain according to energy of code */
+    int32_to_dpf(*gain_cod, &exp, &frac);
+    L_tmp = mul_32by16(exp, frac, gcode_inov);
+
+    *gain_cod = shl_int32(L_tmp, 3);              /* gcode_inov in Q12 */
+
+
+    past_qua_en[3] = past_qua_en[2];
+    past_qua_en[2] = past_qua_en[1];
+    past_qua_en[1] = past_qua_en[0];
+
+    /*
+     * qua_ener = 20*log10(g_code)
+     *          = 6.0206*log2(g_code)
+     *          = 6.0206*(log2(g_codeQ11) - 11)
+     */
+    L_tmp = (int32)g_code;
+    amrwb_log_2(L_tmp, &exp, &frac);
+    exp -= 11;
+    L_tmp = mul_32by16(exp, frac, 24660);   /* x 6.0206 in Q12 */
+
+    /* update table of past quantized energies */
+
+    past_qua_en[0] = (int16)(L_tmp >> 3); /* result in Q10 */
+
+    return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/deemphasis_32.cpp b/media/libstagefright/codecs/amrwb/src/deemphasis_32.cpp
new file mode 100644
index 0000000..b80555b
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/deemphasis_32.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: deemphasis_32.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 x_hi[],               (i)     : input signal (bit31..16)
+     int16 x_lo[],               (i)     : input signal (bit15..4)
+     int16 y[],                  (o)     : output signal (x16)
+     int16 mu,                   (i) Q15 : deemphasis factor
+     int16 L,                    (i)     : vector size
+     int16 * mem                 (i/o)   : memory (y[-1])
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    32-bits filtering through 1/(1-mu z^-1)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+    Deemphasis H(z) = 1/(1 - 0.68z^(-1))   where mu = 0.67999 in Q15
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_acelp.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 deemphasis_32(
+    int16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+    int16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+    int16 y[],                           /* (o)     : output signal (x16)      */
+    int16 mu,                            /* (i) Q15 : deemphasis factor        */
+    int16 L,                             /* (i)     : vector size              */
+    int16 * mem                          /* (i/o)   : memory (y[-1])           */
+)
+{
+    int16 i;
+    int32 L_tmp;
+    int16 lo, hi;
+
+    L_tmp  = ((int32)x_hi[0]) << 16;
+    L_tmp += ((int32)x_lo[0]) << 4;
+    L_tmp  = shl_int32(L_tmp, 3);
+
+    L_tmp = fxp_mac_16by16(*mem, mu, L_tmp),
+
+            L_tmp = shl_int32(L_tmp, 1);               /* saturation can occur here */
+    y[0] = amr_wb_round(L_tmp);
+
+    lo = x_lo[1];
+    hi = x_hi[1];
+    for (i = 1; i < L - 1; i++)
+    {
+        L_tmp  = ((int32)hi) << 16;
+        L_tmp += ((int32)lo) << 4;
+        L_tmp  = shl_int32(L_tmp, 3);
+        L_tmp  = fxp_mac_16by16(y[i - 1], mu, L_tmp),
+                 L_tmp  = shl_int32(L_tmp, 1);           /* saturation can occur here */
+        y[i]   = amr_wb_round(L_tmp);
+        lo     = x_lo[i+1];
+        hi     = x_hi[i+1];
+    }
+    L_tmp  = ((int32)hi) << 16;
+    L_tmp += ((int32)lo) << 4;
+    L_tmp  = shl_int32(L_tmp, 3);
+    L_tmp  = fxp_mac_16by16(y[i - 1], mu, L_tmp),
+             L_tmp  = shl_int32(L_tmp, 1);           /* saturation can occur here */
+    y[i]   = amr_wb_round(L_tmp);
+
+    *mem = y[L - 1];
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/dtx.h b/media/libstagefright/codecs/amrwb/src/dtx.h
new file mode 100644
index 0000000..a81f089
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dtx.h
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/dtx.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+    Static memory, constants and frametypes for the DTX
+------------------------------------------------------------------------------
+*/
+#ifndef DTX_H
+#define DTX_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; MACROS
+    ; Define module specific macros here
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; EXTERNAL VARIABLES REFERENCES
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; DEFINES AND SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+#define DTX_MAX_EMPTY_THRESH 50
+#define DTX_HIST_SIZE 8
+#define DTX_HIST_SIZE_MIN_ONE 7
+#define DTX_ELAPSED_FRAMES_THRESH (24 + 7 -1)
+#define DTX_HANG_CONST 7                   /* yields eight frames of SP HANGOVER  */
+#define INV_MED_THRESH 14564
+#define ISF_GAP  128                       /* 50 */
+#define ONE_MINUS_ISF_GAP 16384 - ISF_GAP
+
+#define ISF_GAP   128
+#define ISF_DITH_GAP   448
+#define ISF_FACTOR_LOW 256
+#define ISF_FACTOR_STEP 2
+
+#define GAIN_THR 180
+#define GAIN_FACTOR 75
+
+    typedef struct
+    {
+        int16 isf_hist[M * DTX_HIST_SIZE];
+        int16 log_en_hist[DTX_HIST_SIZE];
+        int16 hist_ptr;
+        int16 log_en_index;
+        int16 cng_seed;
+
+        /* DTX handler stuff */
+        int16 dtxHangoverCount;
+        int16 decAnaElapsedCount;
+        int32 D[28];
+        int32 sumD[DTX_HIST_SIZE];
+    } dtx_encState;
+
+#define SPEECH 0
+#define DTX 1
+#define DTX_MUTE 2
+
+#define TX_SPEECH 0
+#define TX_SID_FIRST 1
+#define TX_SID_UPDATE 2
+#define TX_NO_DATA 3
+
+#define RX_SPEECH_GOOD 0
+#define RX_SPEECH_PROBABLY_DEGRADED 1
+#define RX_SPEECH_LOST 2
+#define RX_SPEECH_BAD 3
+#define RX_SID_FIRST 4
+#define RX_SID_UPDATE 5
+#define RX_SID_BAD 6
+#define RX_NO_DATA 7
+
+    /*****************************************************************************
+     *
+     * DEFINITION OF DATA TYPES
+     *****************************************************************************/
+
+    typedef struct
+    {
+        int16 since_last_sid;
+        int16 true_sid_period_inv;
+        int16 log_en;
+        int16 old_log_en;
+        int16 level;
+        int16 isf[M];
+        int16 isf_old[M];
+        int16 cng_seed;
+
+        int16 isf_hist[M * DTX_HIST_SIZE];
+        int16 log_en_hist[DTX_HIST_SIZE];
+        int16 hist_ptr;
+
+        int16 dtxHangoverCount;
+        int16 decAnaElapsedCount;
+
+        int16 sid_frame;
+        int16 valid_data;
+        int16 dtxHangoverAdded;
+
+        int16 dtxGlobalState;                 /* contains previous state */
+        /* updated in main decoder */
+
+        int16 data_updated;                   /* marker to know if CNI data is ever renewed */
+
+        int16 dither_seed;
+        int16 CN_dith;
+
+    } dtx_decState;
+
+    int16 dtx_enc_init(dtx_encState ** st, int16 isf_init[]);
+    int16 dtx_enc_reset(dtx_encState * st, int16 isf_init[]);
+    void dtx_enc_exit(dtx_encState ** st);
+
+    int16 dtx_enc(
+        dtx_encState * st,                    /* i/o : State struct                                         */
+        int16 isf[M],                        /* o   : CN ISF vector                                        */
+        int16 * exc2,                        /* o   : CN excitation                                        */
+        int16 ** prms
+    );
+
+    int16 dtx_buffer(
+        dtx_encState * st,                    /* i/o : State struct                    */
+        int16 isf_new[],                     /* i   : isf vector                      */
+        int32 enr,                           /* i   : residual energy (in L_FRAME)    */
+        int16 codec_mode
+    );
+
+    void tx_dtx_handler(dtx_encState * st,     /* i/o : State struct           */
+                        int16 vad_flag,                      /* i   : vad decision           */
+                        int16 * usedMode                     /* i/o : mode changed or not    */
+                       );
+
+    void Qisf_ns(
+        int16 * isf1,                        /* input : ISF in the frequency domain (0..0.5) */
+        int16 * isf_q,                       /* output: quantized ISF                        */
+        int16 * indice                       /* output: quantization indices                 */
+    );
+
+
+    int16 dtx_dec_amr_wb_reset(dtx_decState * st, const int16 isf_init[]);
+
+    int16 dtx_dec_amr_wb(
+        dtx_decState * st,                    /* i/o : State struct                                          */
+        int16 * exc2,                        /* o   : CN excitation                                          */
+        int16 new_state,                     /* i   : New DTX state                                          */
+        int16 isf[],                         /* o   : CN ISF vector                                          */
+        int16 ** prms
+    );
+
+    void dtx_dec_amr_wb_activity_update(
+        dtx_decState * st,
+        int16 isf[],
+        int16 exc[]);
+
+
+    int16 rx_amr_wb_dtx_handler(
+        dtx_decState * st,                    /* i/o : State struct     */
+        int16 frame_type                     /* i   : Frame type       */
+    );
+
+    void Disf_ns(
+        int16 * indice,                      /* input:  quantization indices                  */
+        int16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+    );
+
+    void aver_isf_history(
+        int16 isf_old[],
+        int16 indices[],
+        int32 isf_aver[]
+    );
+    void find_frame_indices(
+        int16 isf_old_tx[],
+        int16 indices[],
+        dtx_encState * st
+    );
+
+    int16 dithering_control(
+        dtx_encState * st
+    );
+    void CN_dithering(
+        int16 isf[M],
+        int32 * L_log_en_int,
+        int16 * dither_seed
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /*  DTX_H  */
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/dtx_decoder_amr_wb.cpp b/media/libstagefright/codecs/amrwb/src/dtx_decoder_amr_wb.cpp
new file mode 100644
index 0000000..7c798cc
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/dtx_decoder_amr_wb.cpp
@@ -0,0 +1,984 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: dtx_decoder_amr_wb.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    DTX functions
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"  /* prototype of functions    */
+#include "get_amr_wb_bits.h"
+#include "dtx.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
+----------------------------------------------------------------------------*/
+/*
+ * Function    : dtx_dec_amr_wb_reset
+ */
+int16 dtx_dec_amr_wb_reset(dtx_decState * st, const int16 isf_init[])
+{
+    int16 i;
+
+
+    if (st == (dtx_decState *) NULL)
+    {
+        /* dtx_dec_amr_wb_reset invalid parameter */
+        return (-1);
+    }
+    st->since_last_sid = 0;
+    st->true_sid_period_inv = (1 << 13);      /* 0.25 in Q15 */
+
+    st->log_en = 3500;
+    st->old_log_en = 3500;
+    /* low level noise for better performance in  DTX handover cases */
+
+    st->cng_seed = RANDOM_INITSEED;
+
+    st->hist_ptr = 0;
+
+    /* Init isf_hist[] and decoder log frame energy */
+    pv_memcpy((void *)st->isf, (void *)isf_init, M*sizeof(*isf_init));
+
+    pv_memcpy((void *)st->isf_old, (void *)isf_init, M*sizeof(*isf_init));
+
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        pv_memcpy((void *)&st->isf_hist[i * M], (void *)isf_init, M*sizeof(*isf_init));
+        st->log_en_hist[i] = st->log_en;
+    }
+
+    st->dtxHangoverCount = DTX_HANG_CONST;
+    st->decAnaElapsedCount = 32767;
+
+    st->sid_frame = 0;
+    st->valid_data = 0;
+    st->dtxHangoverAdded = 0;
+
+    st->dtxGlobalState = SPEECH;
+    st->data_updated = 0;
+
+    st->dither_seed = RANDOM_INITSEED;
+    st->CN_dith = 0;
+
+    return 0;
+}
+
+
+/*
+     Table of new SPD synthesis states
+
+                           |     previous SPD_synthesis_state
+     Incoming              |
+     frame_type            | SPEECH       | DTX           | DTX_MUTE
+     ---------------------------------------------------------------
+     RX_SPEECH_GOOD ,      |              |               |
+     RX_SPEECH_PR_DEGRADED | SPEECH       | SPEECH        | SPEECH
+     ----------------------------------------------------------------
+     RX_SPEECH_BAD,        | SPEECH       | DTX           | DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_FIRST,         | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_UPDATE,        | DTX          | DTX           | DTX
+     ----------------------------------------------------------------
+     RX_SID_BAD,           | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_NO_DATA,           | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
+     RX_SPARE              |(class2 garb.)|               |
+     ----------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+/*
+ * Function    : dtx_dec_amr_wb
+ */
+int16 dtx_dec_amr_wb(
+    dtx_decState * st,                    /* i/o : State struct         */
+    int16 * exc2,                        /* o   : CN excitation        */
+    int16 new_state,                     /* i   : New DTX state        */
+    int16 isf[],                         /* o   : CN ISF vector        */
+    int16 ** prms
+)
+{
+    int16 log_en_index;
+    int16 ind[7];
+    int16 i, j;
+    int16 int_fac;
+    int16 gain;
+
+    int32 L_isf[M], L_log_en_int, level32, ener32;
+    int16 ptr;
+    int16 tmp_int_length;
+    int16 tmp, exp, exp0, log_en_int_e, log_en_int_m, level;
+
+    /* This function is called if synthesis state is not SPEECH the globally passed  inputs to this function
+     * are st->sid_frame st->valid_data st->dtxHangoverAdded new_state  (SPEECH, DTX, DTX_MUTE) */
+
+    if ((st->dtxHangoverAdded != 0) &&
+            (st->sid_frame != 0))
+    {
+        /* sid_first after dtx hangover period */
+        /* or sid_upd after dtxhangover        */
+
+        /* consider  twice the last frame */
+        ptr = st->hist_ptr + 1;
+
+        if (ptr == DTX_HIST_SIZE)
+            ptr = 0;
+
+        pv_memcpy((void *)&st->isf_hist[ptr * M], (void *)&st->isf_hist[st->hist_ptr * M], M*sizeof(*st->isf_hist));
+
+        st->log_en_hist[ptr] = st->log_en_hist[st->hist_ptr];
+
+        /* compute mean log energy and isf from decoded signal (SID_FIRST) */
+        st->log_en = 0;
+        for (i = 0; i < M; i++)
+        {
+            L_isf[i] = 0;
+        }
+
+        /* average energy and isf */
+        for (i = 0; i < DTX_HIST_SIZE; i++)
+        {
+            /* Division by DTX_HIST_SIZE = 8 has been done in dtx_buffer log_en is in Q10 */
+            st->log_en = add_int16(st->log_en, st->log_en_hist[i]);
+
+            for (j = 0; j < M; j++)
+            {
+                L_isf[j] = add_int32(L_isf[j], (int32)(st->isf_hist[i * M + j]));
+            }
+        }
+
+        /* st->log_en in Q9 */
+        st->log_en >>=  1;
+
+        /* Add 2 in Q9, in order to have only positive values for Pow2 */
+        /* this value is subtracted back after Pow2 function */
+        st->log_en += 1024;
+
+        if (st->log_en < 0)
+            st->log_en = 0;
+
+        for (j = 0; j < M; j++)
+        {
+            st->isf[j] = (int16)(L_isf[j] >> 3);  /* divide by 8 */
+        }
+
+    }
+
+    if (st->sid_frame != 0)
+    {
+        /* Set old SID parameters, always shift */
+        /* even if there is no new valid_data   */
+
+        pv_memcpy((void *)st->isf_old, (void *)st->isf, M*sizeof(*st->isf));
+
+        st->old_log_en = st->log_en;
+
+        if (st->valid_data != 0)           /* new data available (no CRC) */
+        {
+            /* st->true_sid_period_inv = 1.0f/st->since_last_sid; */
+            /* Compute interpolation factor, since the division only works * for values of since_last_sid <
+             * 32 we have to limit the      * interpolation to 32 frames                                  */
+            tmp_int_length = st->since_last_sid;
+
+
+            if (tmp_int_length > 32)
+            {
+                tmp_int_length = 32;
+            }
+
+            if (tmp_int_length >= 2)
+            {
+                st->true_sid_period_inv = div_16by16(1 << 10, shl_int16(tmp_int_length, 10));
+            }
+            else
+            {
+                st->true_sid_period_inv = 1 << 14;      /* 0.5 it Q15 */
+            }
+
+            ind[0] = Serial_parm(6, prms);
+            ind[1] = Serial_parm(6, prms);
+            ind[2] = Serial_parm(6, prms);
+            ind[3] = Serial_parm(5, prms);
+            ind[4] = Serial_parm(5, prms);
+
+            Disf_ns(ind, st->isf);
+
+            log_en_index = Serial_parm(6, prms);
+
+            /* read background noise stationarity information */
+            st->CN_dith = Serial_parm_1bit(prms);
+
+            /* st->log_en = (float)log_en_index / 2.625 - 2.0;  */
+            /* log2(E) in Q9 (log2(E) lies in between -2:22) */
+            st->log_en = shl_int16(log_en_index, 15 - 6);
+
+            /* Divide by 2.625  */
+            st->log_en = mult_int16(st->log_en, 12483);
+            /* Subtract 2 in Q9 is done later, after Pow2 function  */
+
+            /* no interpolation at startup after coder reset        */
+            /* or when SID_UPD has been received right after SPEECH */
+
+            if ((st->data_updated == 0) || (st->dtxGlobalState == SPEECH))
+            {
+                pv_memcpy((void *)st->isf_old, (void *)st->isf, M*sizeof(*st->isf));
+
+                st->old_log_en = st->log_en;
+            }
+        }                                  /* endif valid_data */
+    }                                      /* endif sid_frame */
+
+
+    if ((st->sid_frame != 0) && (st->valid_data != 0))
+    {
+        st->since_last_sid = 0;
+    }
+    /* Interpolate SID info */
+    int_fac = shl_int16(st->since_last_sid, 10); /* Q10 */
+    int_fac = mult_int16(int_fac, st->true_sid_period_inv);   /* Q10 * Q15 -> Q10 */
+
+    /* Maximize to 1.0 in Q10 */
+
+    if (int_fac > 1024)
+    {
+        int_fac = 1024;
+    }
+    int_fac = shl_int16(int_fac, 4);             /* Q10 -> Q14 */
+
+    L_log_en_int = mul_16by16_to_int32(int_fac, st->log_en); /* Q14 * Q9 -> Q24 */
+
+    for (i = 0; i < M; i++)
+    {
+        isf[i] = mult_int16(int_fac, st->isf[i]);/* Q14 * Q15 -> Q14 */
+    }
+
+    int_fac = 16384 - int_fac;         /* 1-k in Q14 */
+
+    /* ( Q14 * Q9 -> Q24 ) + Q24 -> Q24 */
+    L_log_en_int = mac_16by16_to_int32(L_log_en_int, int_fac, st->old_log_en);
+
+    for (i = 0; i < M; i++)
+    {
+        /* Q14 + (Q14 * Q15 -> Q14) -> Q14 */
+        isf[i] = add_int16(isf[i], mult_int16(int_fac, st->isf_old[i]));
+        isf[i] = shl_int16(isf[i], 1);           /* Q14 -> Q15 */
+    }
+
+    /* If background noise is non-stationary, insert comfort noise dithering */
+    if (st->CN_dith != 0)
+    {
+        CN_dithering(isf, &L_log_en_int, &st->dither_seed);
+    }
+    /* L_log_en_int corresponds to log2(E)+2 in Q24, i.e log2(gain)+1 in Q25 */
+    /* Q25 -> Q16 */
+    L_log_en_int >>= 9;
+
+    /* Find integer part  */
+    log_en_int_e = extract_h(L_log_en_int);
+
+    /* Find fractional part */
+    log_en_int_m = (int16)(sub_int32(L_log_en_int, L_deposit_h(log_en_int_e)) >> 1);
+
+    /* Subtract 2 from L_log_en_int in Q9, i.e divide the gain by 2 (energy by 4) */
+    /* Add 16 in order to have the result of pow2 in Q16 */
+    log_en_int_e += 15;
+
+    /* level = (float)( pow( 2.0f, log_en ) );  */
+    level32 = power_of_2(log_en_int_e, log_en_int_m); /* Q16 */
+
+    exp0 = normalize_amr_wb(level32);
+    level32 <<= exp0;        /* level in Q31 */
+    exp0 = 15 - exp0;
+    level = (int16)(level32 >> 16);          /* level in Q15 */
+
+    /* generate white noise vector */
+    for (i = 0; i < L_FRAME; i++)
+    {
+        exc2[i] = noise_gen_amrwb(&(st->cng_seed)) >> 4;
+    }
+
+    /* gain = level / sqrt(ener) * sqrt(L_FRAME) */
+
+    /* energy of generated excitation */
+    ener32 = Dot_product12(exc2, exc2, L_FRAME, &exp);
+
+    one_ov_sqrt_norm(&ener32, &exp);
+
+    gain = extract_h(ener32);
+
+    gain = mult_int16(level, gain);              /* gain in Q15 */
+
+    exp += exp0;
+
+    /* Multiply by sqrt(L_FRAME)=16, i.e. shift left by 4 */
+    exp += 4;
+
+    for (i = 0; i < L_FRAME; i++)
+    {
+        tmp = mult_int16(exc2[i], gain);         /* Q0 * Q15 */
+        exc2[i] = shl_int16(tmp, exp);
+    }
+
+
+    if (new_state == DTX_MUTE)
+    {
+        /* mute comfort noise as it has been quite a long time since last SID update  was performed                            */
+
+        tmp_int_length = st->since_last_sid;
+
+        if (tmp_int_length > 32)
+        {
+            tmp_int_length = 32;
+        }
+
+        st->true_sid_period_inv = div_16by16(1 << 10, shl_int16(tmp_int_length, 10));
+
+        st->since_last_sid = 0;
+        st->old_log_en = st->log_en;
+        /* subtract 1/8 in Q9 (energy), i.e -3/8 dB */
+        st->log_en -= 64;
+    }
+    /* reset interpolation length timer if data has been updated.        */
+
+    if ((st->sid_frame != 0) &&
+            ((st->valid_data != 0) ||
+             ((st->valid_data == 0) && (st->dtxHangoverAdded) != 0)))
+    {
+        st->since_last_sid = 0;
+        st->data_updated = 1;
+    }
+    return 0;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void dtx_dec_amr_wb_activity_update(
+    dtx_decState * st,
+    int16 isf[],
+    int16 exc[])
+{
+    int16 i;
+
+    int32 L_frame_en;
+    int16 log_en_e, log_en_m, log_en;
+
+
+    st->hist_ptr++;
+
+    if (st->hist_ptr == DTX_HIST_SIZE)
+    {
+        st->hist_ptr = 0;
+    }
+    pv_memcpy((void *)&st->isf_hist[st->hist_ptr * M], (void *)isf, M*sizeof(*isf));
+
+
+    /* compute log energy based on excitation frame energy in Q0 */
+    L_frame_en = 0;
+    for (i = 0; i < L_FRAME; i++)
+    {
+        L_frame_en = mac_16by16_to_int32(L_frame_en, exc[i], exc[i]);
+    }
+    L_frame_en >>= 1;
+
+    /* log_en = (float)log10(L_frame_en/(float)L_FRAME)/(float)log10(2.0f); */
+    amrwb_log_2(L_frame_en, &log_en_e, &log_en_m);
+
+    /* convert exponent and mantissa to int16 Q7. Q7 is used to simplify averaging in dtx_enc */
+    log_en = shl_int16(log_en_e, 7);             /* Q7 */
+    log_en += log_en_m >> 8;
+
+    /* Divide by L_FRAME = 256, i.e subtract 8 in Q7 = 1024 */
+    log_en -= 1024;
+
+    /* insert into log energy buffer */
+    st->log_en_hist[st->hist_ptr] = log_en;
+
+    return;
+}
+
+
+/*
+     Table of new SPD synthesis states
+
+                           |     previous SPD_synthesis_state
+     Incoming              |
+     frame_type            | SPEECH       | DTX           | DTX_MUTE
+     ---------------------------------------------------------------
+     RX_SPEECH_GOOD ,      |              |               |
+     RX_SPEECH_PR_DEGRADED | SPEECH       | SPEECH        | SPEECH
+     ----------------------------------------------------------------
+     RX_SPEECH_BAD,        | SPEECH       | DTX           | DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_FIRST,         | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_SID_UPDATE,        | DTX          | DTX           | DTX
+     ----------------------------------------------------------------
+     RX_SID_BAD,           | DTX          | DTX/(DTX_MUTE)| DTX_MUTE
+     ----------------------------------------------------------------
+     RX_NO_DATA,           | SPEECH       | DTX/(DTX_MUTE)| DTX_MUTE
+     RX_SPARE              |(class2 garb.)|               |
+     ----------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+int16 rx_amr_wb_dtx_handler(
+    dtx_decState * st,                    /* i/o : State struct     */
+    int16 frame_type                     /* i   : Frame type       */
+)
+{
+    int16 newState;
+    int16 encState;
+
+    /* DTX if SID frame or previously in DTX{_MUTE} and (NO_RX OR BAD_SPEECH) */
+
+
+
+    if ((frame_type == RX_SID_FIRST)  ||
+            (frame_type == RX_SID_UPDATE) ||
+            (frame_type == RX_SID_BAD)    ||
+            (((st->dtxGlobalState == DTX) ||
+              (st->dtxGlobalState == DTX_MUTE)) &&
+             ((frame_type == RX_NO_DATA)    ||
+              (frame_type == RX_SPEECH_BAD) ||
+              (frame_type == RX_SPEECH_LOST))))
+    {
+        newState = DTX;
+
+        /* stay in mute for these input types */
+
+        if ((st->dtxGlobalState == DTX_MUTE) &&
+                ((frame_type == RX_SID_BAD) ||
+                 (frame_type == RX_SID_FIRST) ||
+                 (frame_type == RX_SPEECH_LOST) ||
+                 (frame_type == RX_NO_DATA)))
+        {
+            newState = DTX_MUTE;
+        }
+        /* evaluate if noise parameters are too old                     */
+        /* since_last_sid is reset when CN parameters have been updated */
+        st->since_last_sid = add_int16(st->since_last_sid, 1);
+
+        /* no update of sid parameters in DTX for a long while */
+
+        if (st->since_last_sid > DTX_MAX_EMPTY_THRESH)
+        {
+            newState = DTX_MUTE;
+        }
+    }
+    else
+    {
+        newState = SPEECH;
+        st->since_last_sid = 0;
+    }
+
+    /* reset the decAnaElapsed Counter when receiving CNI data the first time, to robustify counter missmatch
+     * after handover this might delay the bwd CNI analysis in the new decoder slightly. */
+
+    if ((st->data_updated == 0) &&
+            (frame_type == RX_SID_UPDATE))
+    {
+        st->decAnaElapsedCount = 0;
+    }
+    /* update the SPE-SPD DTX hangover synchronization */
+    /* to know when SPE has added dtx hangover         */
+    st->decAnaElapsedCount = add_int16(st->decAnaElapsedCount, 1);
+    st->dtxHangoverAdded = 0;
+
+
+    if ((frame_type == RX_SID_FIRST) ||
+            (frame_type == RX_SID_UPDATE) ||
+            (frame_type == RX_SID_BAD) ||
+            (frame_type == RX_NO_DATA))
+    {
+        encState = DTX;
+    }
+    else
+    {
+        encState = SPEECH;
+    }
+
+
+    if (encState == SPEECH)
+    {
+        st->dtxHangoverCount = DTX_HANG_CONST;
+    }
+    else
+    {
+
+        if (st->decAnaElapsedCount > DTX_ELAPSED_FRAMES_THRESH)
+        {
+            st->dtxHangoverAdded = 1;
+            st->decAnaElapsedCount = 0;
+            st->dtxHangoverCount = 0;
+        }
+        else if (st->dtxHangoverCount == 0)
+        {
+            st->decAnaElapsedCount = 0;
+        }
+        else
+        {
+            st->dtxHangoverCount--;
+        }
+    }
+
+    if (newState != SPEECH)
+    {
+        /* DTX or DTX_MUTE CN data is not in a first SID, first SIDs are marked as SID_BAD but will do
+         * backwards analysis if a hangover period has been added according to the state machine above */
+
+        st->sid_frame = 0;
+        st->valid_data = 0;
+
+
+        if (frame_type == RX_SID_FIRST)
+        {
+            st->sid_frame = 1;
+        }
+        else if (frame_type == RX_SID_UPDATE)
+        {
+            st->sid_frame = 1;
+            st->valid_data = 1;
+        }
+        else if (frame_type == RX_SID_BAD)
+        {
+            st->sid_frame = 1;
+            st->dtxHangoverAdded = 0;      /* use old data */
+        }
+    }
+    return newState;
+    /* newState is used by both SPEECH AND DTX synthesis routines */
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void aver_isf_history(
+    int16 isf_old[],
+    int16 indices[],
+    int32 isf_aver[]
+)
+{
+    int16 i, j, k;
+    int16 isf_tmp[2 * M];
+    int32 L_tmp;
+
+    /* Memorize in isf_tmp[][] the ISF vectors to be replaced by */
+    /* the median ISF vector prior to the averaging               */
+    for (k = 0; k < 2; k++)
+    {
+
+        if (indices[k] + 1 != 0)
+        {
+            for (i = 0; i < M; i++)
+            {
+                isf_tmp[k * M + i] = isf_old[indices[k] * M + i];
+                isf_old[indices[k] * M + i] = isf_old[indices[2] * M + i];
+            }
+        }
+    }
+
+    /* Perform the ISF averaging */
+    for (j = 0; j < M; j++)
+    {
+        L_tmp = 0;
+
+        for (i = 0; i < DTX_HIST_SIZE; i++)
+        {
+            L_tmp = add_int32(L_tmp, (int32)(isf_old[i * M + j]));
+        }
+        isf_aver[j] = L_tmp;
+    }
+
+    /* Retrieve from isf_tmp[][] the ISF vectors saved prior to averaging */
+    for (k = 0; k < 2; k++)
+    {
+
+        if (indices[k] + 1 != 0)
+        {
+            for (i = 0; i < M; i++)
+            {
+                isf_old[indices[k] * M + i] = isf_tmp[k * M + i];
+            }
+        }
+    }
+
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void find_frame_indices(
+    int16 isf_old_tx[],
+    int16 indices[],
+    dtx_encState * st
+)
+{
+    int32 L_tmp, summin, summax, summax2nd;
+    int16 i, j, tmp;
+    int16 ptr;
+
+    /* Remove the effect of the oldest frame from the column */
+    /* sum sumD[0..DTX_HIST_SIZE-1]. sumD[DTX_HIST_SIZE] is    */
+    /* not updated since it will be removed later.           */
+
+    tmp = DTX_HIST_SIZE_MIN_ONE;
+    j = -1;
+    for (i = 0; i < DTX_HIST_SIZE_MIN_ONE; i++)
+    {
+        j += tmp;
+        st->sumD[i] = sub_int32(st->sumD[i], st->D[j]);
+        tmp--;
+    }
+
+    /* Shift the column sum sumD. The element sumD[DTX_HIST_SIZE-1]    */
+    /* corresponding to the oldest frame is removed. The sum of     */
+    /* the distances between the latest isf and other isfs, */
+    /* i.e. the element sumD[0], will be computed during this call. */
+    /* Hence this element is initialized to zero.                   */
+
+    for (i = DTX_HIST_SIZE_MIN_ONE; i > 0; i--)
+    {
+        st->sumD[i] = st->sumD[i - 1];
+    }
+    st->sumD[0] = 0;
+
+    /* Remove the oldest frame from the distance matrix.           */
+    /* Note that the distance matrix is replaced by a one-         */
+    /* dimensional array to save static memory.                    */
+
+    tmp = 0;
+    for (i = 27; i >= 12; i -= tmp)
+    {
+        tmp++;
+        for (j = tmp; j > 0; j--)
+        {
+            st->D[i - j + 1] = st->D[i - j - tmp];
+        }
+    }
+
+    /* Compute the first column of the distance matrix D            */
+    /* (squared Euclidean distances from isf1[] to isf_old_tx[][]). */
+
+    ptr = st->hist_ptr;
+    for (i = 1; i < DTX_HIST_SIZE; i++)
+    {
+        /* Compute the distance between the latest isf and the other isfs. */
+        ptr--;
+
+        if (ptr < 0)
+        {
+            ptr = DTX_HIST_SIZE_MIN_ONE;
+        }
+        L_tmp = 0;
+        for (j = 0; j < M; j++)
+        {
+            tmp = sub_int16(isf_old_tx[st->hist_ptr * M + j], isf_old_tx[ptr * M + j]);
+            L_tmp = mac_16by16_to_int32(L_tmp, tmp, tmp);
+        }
+        st->D[i - 1] = L_tmp;
+
+        /* Update also the column sums. */
+        st->sumD[0] = add_int32(st->sumD[0], st->D[i - 1]);
+        st->sumD[i] = add_int32(st->sumD[i], st->D[i - 1]);
+    }
+
+    /* Find the minimum and maximum distances */
+    summax = st->sumD[0];
+    summin = st->sumD[0];
+    indices[0] = 0;
+    indices[2] = 0;
+    for (i = 1; i < DTX_HIST_SIZE; i++)
+    {
+
+        if (st->sumD[i] > summax)
+        {
+            indices[0] = i;
+            summax = st->sumD[i];
+        }
+
+        if (st->sumD[i] < summin)
+        {
+            indices[2] = i;
+            summin = st->sumD[i];
+        }
+    }
+
+    /* Find the second largest distance */
+    summax2nd = -2147483647L;
+    indices[1] = -1;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+
+        if ((st->sumD[i] > summax2nd) && (i != indices[0]))
+        {
+            indices[1] = i;
+            summax2nd = st->sumD[i];
+        }
+    }
+
+    for (i = 0; i < 3; i++)
+    {
+        indices[i] = sub_int16(st->hist_ptr, indices[i]);
+
+        if (indices[i] < 0)
+        {
+            indices[i] = add_int16(indices[i], DTX_HIST_SIZE);
+        }
+    }
+
+    /* If maximum distance/MED_THRESH is smaller than minimum distance */
+    /* then the median ISF vector replacement is not performed         */
+    tmp = normalize_amr_wb(summax);
+    summax <<= tmp;
+    summin <<= tmp;
+    L_tmp = mul_16by16_to_int32(amr_wb_round(summax), INV_MED_THRESH);
+
+    if (L_tmp <= summin)
+    {
+        indices[0] = -1;
+    }
+    /* If second largest distance/MED_THRESH is smaller than     */
+    /* minimum distance then the median ISF vector replacement is    */
+    /* not performed                                                 */
+    summax2nd = shl_int32(summax2nd, tmp);
+    L_tmp = mul_16by16_to_int32(amr_wb_round(summax2nd), INV_MED_THRESH);
+
+    if (L_tmp <= summin)
+    {
+        indices[1] = -1;
+    }
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+int16 dithering_control(dtx_encState * st)
+{
+    int16 i, tmp, mean, CN_dith, gain_diff;
+    int32 ISF_diff;
+
+    /* determine how stationary the spectrum of background noise is */
+    ISF_diff = 0;
+    for (i = 0; i < 8; i++)
+    {
+        ISF_diff = add_int32(ISF_diff, st->sumD[i]);
+    }
+    if ((ISF_diff >> 26) > 0)
+    {
+        CN_dith = 1;
+    }
+    else
+    {
+        CN_dith = 0;
+    }
+
+    /* determine how stationary the energy of background noise is */
+    mean = 0;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        mean = add_int16(mean, st->log_en_hist[i]);
+    }
+    mean >>= 3;
+    gain_diff = 0;
+    for (i = 0; i < DTX_HIST_SIZE; i++)
+    {
+        tmp = sub_int16(st->log_en_hist[i], mean);
+        tmp = tmp - (tmp < 0);
+
+        gain_diff += tmp ^(tmp >> 15);    /*  tmp ^sign(tmp)  */;
+    }
+    if (gain_diff > GAIN_THR)
+    {
+        CN_dith = 1;
+    }
+    return CN_dith;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void CN_dithering(
+    int16 isf[M],
+    int32 * L_log_en_int,
+    int16 * dither_seed
+)
+{
+    int16 temp, temp1, i, dither_fac, rand_dith;
+    int16 rand_dith2;
+
+    /* Insert comfort noise dithering for energy parameter */
+    rand_dith = noise_gen_amrwb(dither_seed) >> 1;
+    rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
+    rand_dith += rand_dith2;
+    *L_log_en_int = add_int32(*L_log_en_int, mul_16by16_to_int32(rand_dith, GAIN_FACTOR));
+
+    if (*L_log_en_int < 0)
+    {
+        *L_log_en_int = 0;
+    }
+    /* Insert comfort noise dithering for spectral parameters (ISF-vector) */
+    dither_fac = ISF_FACTOR_LOW;
+
+    rand_dith = noise_gen_amrwb(dither_seed) >> 1;
+    rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
+    rand_dith +=  rand_dith2;
+    temp = add_int16(isf[0], mult_int16_r(rand_dith, dither_fac));
+
+    /* Make sure that isf[0] will not get negative values */
+    if (temp < ISF_GAP)
+    {
+        isf[0] = ISF_GAP;
+    }
+    else
+    {
+        isf[0] = temp;
+    }
+
+    for (i = 1; i < M - 1; i++)
+    {
+        dither_fac = add_int16(dither_fac, ISF_FACTOR_STEP);
+
+        rand_dith = noise_gen_amrwb(dither_seed) >> 1;
+        rand_dith2 = noise_gen_amrwb(dither_seed) >> 1;
+        rand_dith +=  rand_dith2;
+        temp = add_int16(isf[i], mult_int16_r(rand_dith, dither_fac));
+        temp1 = sub_int16(temp, isf[i - 1]);
+
+        /* Make sure that isf spacing remains at least ISF_DITH_GAP Hz */
+        if (temp1 < ISF_DITH_GAP)
+        {
+            isf[i] = isf[i - 1] + ISF_DITH_GAP;
+        }
+        else
+        {
+            isf[i] = temp;
+        }
+    }
+
+    /* Make sure that isf[M-2] will not get values above 16384 */
+    if (isf[M - 2] > 16384)
+    {
+        isf[M - 2] = 16384;
+    }
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/e_pv_amrwbdec.h b/media/libstagefright/codecs/amrwb/src/e_pv_amrwbdec.h
new file mode 100644
index 0000000..251a3ce
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/e_pv_amrwbdec.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: e_pv_amrwbdec.h
+ Funtions:
+
+
+     Date: 05/03/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef E_PV_AMRWBDEC_H
+#define E_PV_AMRWBDEC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvamrwbdecoder_cnst.h"             /* coder constant parameters */
+#include "dtx.h"
+
+/*----------------------------------------------------------------------------
+; 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
+{
+    int16 old_exc[PIT_MAX + L_INTERPOL];  /* old excitation vector */
+    int16 ispold[M];                      /* old isp (immittance spectral pairs)*/
+    int16 isfold[M];                      /* old isf (frequency domain) */
+    int16 isf_buf[L_MEANBUF * M];         /* isf buffer(frequency domain) */
+    int16 past_isfq[M];                   /* past isf quantizer */
+    int16 tilt_code;                      /* tilt of code */
+    int16 Q_old;                          /* old scaling factor */
+    int16 Qsubfr[4];                      /* old maximum scaling factor */
+    int32 L_gc_thres;                     /* threshold for noise enhancer */
+    int16 mem_syn_hi[M];                  /* modified synthesis memory (MSB) */
+    int16 mem_syn_lo[M];                  /* modified synthesis memory (LSB) */
+    int16 mem_deemph;                     /* speech deemph filter memory */
+    int16 mem_sig_out[6];                 /* hp50 filter memory for synthesis */
+    int16 mem_oversamp[2 * L_FILT];       /* synthesis oversampled filter memory */
+    int16 mem_syn_hf[M16k];               /* HF synthesis memory */
+    int16 mem_hf[2 * L_FILT16k];          /* HF band-pass filter memory */
+    int16 mem_hf2[2 * L_FILT16k];         /* HF band-pass filter memory */
+    int16 mem_hf3[2 * L_FILT16k];         /* HF band-pass filter memory */
+    int16 seed;                           /* random memory for frame erasure */
+    int16 seed2;                          /* random memory for HF generation */
+    int16 old_T0;                         /* old pitch lag */
+    int16 old_T0_frac;                    /* old pitch fraction lag */
+    int16 lag_hist[5];
+    int16 dec_gain[23];                   /* gain decoder memory */
+    int16 seed3;                          /* random memory for lag concealment */
+    int16 disp_mem[8];                    /* phase dispersion memory */
+    int16 mem_hp400[6];                   /* hp400 filter memory for synthesis */
+
+    int16 prev_bfi;
+    int16 state;
+    int16 first_frame;
+    dtx_decState dtx_decSt;
+    int16 vad_hist;
+
+} Decoder_State;
+
+typedef struct
+{
+    Decoder_State state;
+    int16 ScratchMem[L_SUBFR + L_SUBFR16k + ((L_SUBFR + M + M16k +1)<<1) + \
+                     (2*L_FRAME + 1) + PIT_MAX + L_INTERPOL + NB_SUBFR*(M+1) \
+                     + 3*(M+L_SUBFR) + M16k];
+} PV_AmrWbDec;
+
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
diff --git a/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.cpp b/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.cpp
new file mode 100644
index 0000000..d7287f3
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.cpp
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: get_amr_wb_bits.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 no_of_bits,        input : number of bits
+     int16 ** prms            bitstream pointer
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns no_of_bits from serial bit stream
+    Serial_parm -> convert serial stream to parameters
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "get_amr_wb_bits.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
+----------------------------------------------------------------------------*/
+
+
+int16 Serial_parm(                        /* Return the parameter    */
+    int16 no_of_bits,                    /* input : number of bits  */
+    int16 ** prms
+)
+{
+    int16 value = 0;
+
+    for (int16 i = no_of_bits >> 1; i != 0; i--)
+    {
+        value <<= 2;
+
+        if (*((*prms)++) == BIT_1)
+        {
+            value |= 2;
+        }
+
+        if (*((*prms)++) == BIT_1)
+        {
+            value |= 1;
+        }
+
+    }
+
+    if (no_of_bits&1)
+    {
+        value <<= 1;
+
+        if (*((*prms)++) == BIT_1)
+        {
+            value |= 1;
+        }
+
+    }
+
+    return (value);
+}
+
+
+int16 Serial_parm_1bit(int16 ** prms)                 /* Return the parameter    */
+{
+    int16 value = 0;
+
+    if (*((*prms)++) == BIT_1)
+    {
+        value = 1;
+    }
+    return (value);
+}
diff --git a/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.h b/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.h
new file mode 100644
index 0000000..48e43db
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/get_amr_wb_bits.h
@@ -0,0 +1,60 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*--------------------------------------------------------------------------*
+ *                       get_amr_wb_bits.h                                  *
+ *--------------------------------------------------------------------------*
+ *       Number of bits for different modes                                 *
+ *--------------------------------------------------------------------------*/
+
+#ifndef GET_AMR_WB_BITS_H
+#define GET_AMR_WB_BITS_H
+
+
+#include "pv_amr_wb_type_defs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    int16 Serial_parm(                        /* Return the parameter    */
+        int16 no_of_bits,                    /* input : number of bits  */
+        int16 ** prms
+    );
+
+    int16 Serial_parm_1bit(                        /* Return the parameter    */
+        int16 ** prms
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/amrwb/src/highpass_400hz_at_12k8.cpp b/media/libstagefright/codecs/amrwb/src/highpass_400hz_at_12k8.cpp
new file mode 100644
index 0000000..6503454
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/highpass_400hz_at_12k8.cpp
@@ -0,0 +1,201 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: highpass_400Hz_at_12k8.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 filter memory [6]
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   2nd order high pass filter with cut off frequency at 400 Hz.
+   Designed with cheby2 function in MATLAB.
+   Optimized for fixed-point to get the following frequency response:
+
+    frequency:     0Hz   100Hz  200Hz  300Hz  400Hz  630Hz  1.5kHz  3kHz
+    dB loss:     -infdB  -30dB  -20dB  -10dB  -3dB   +6dB    +1dB    0dB
+
+   Algorithm:
+
+    y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]
+                     + a[1]*y[i-1] + a[2]*y[i-2];
+
+    int16 b[3] = {3660, -7320,  3660};       in Q12
+    int16 a[3] = {4096,  7320, -3540};       in Q12
+
+    float -->   b[3] = {0.893554687, -1.787109375,  0.893554687};
+                a[3] = {1.000000000,  1.787109375, -0.864257812};
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_acelp.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
+----------------------------------------------------------------------------*/
+/* Initialization of static values */
+
+void highpass_400Hz_at_12k8_init(int16 mem[])
+{
+    pv_memset((void *)mem, 0, 6*sizeof(*mem));
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void highpass_400Hz_at_12k8(
+    int16 signal[],                      /* input signal / output is divided by 16 */
+    int16 lg,                            /* lenght of signal    */
+    int16 mem[]                          /* filter memory [6]   */
+)
+{
+    int16 i, x2;
+    int16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+    int32 L_tmp1;
+    int32 L_tmp2;
+
+    y2_hi = mem[0];
+    y2_lo = mem[1];
+    y1_hi = mem[2];
+    y1_lo = mem[3];
+    x0    = mem[4];
+    x1    = mem[5];
+
+    for (i = 0; i < lg; i++)
+    {
+
+        /* y[i] = b[0]*x[i] + b[1]*x[i-1] + b[0]*x[i-2]  */
+        /* + a[0]*y[i-1] + a[1] * y[i-2];  */
+
+        L_tmp1 = fxp_mac_16by16(y1_lo, 29280, 8192L);
+        L_tmp2 = fxp_mul_16by16(y1_hi, 29280);
+        L_tmp1 = fxp_mac_16by16(y2_lo, -14160, L_tmp1);
+        L_tmp2 = fxp_mac_16by16(y2_hi, -14160, L_tmp2);
+        x2 = x1;
+        x1 = x0;
+        x0 = signal[i];
+        L_tmp2 = fxp_mac_16by16(x2, 915, L_tmp2);
+        L_tmp2 = fxp_mac_16by16(x1, -1830, L_tmp2);
+        L_tmp2 = fxp_mac_16by16(x0, 915, L_tmp2);
+
+        L_tmp1 = (L_tmp1 >> 13) + (L_tmp2 << 2);  /* coeff Q12 --> Q13 */
+
+        y2_hi = y1_hi;
+        y2_lo = y1_lo;
+        /* signal is divided by 16 to avoid overflow in energy computation */
+        signal[i] = (int16)((L_tmp1 + 0x00008000) >> 16);
+
+        y1_hi = (int16)(L_tmp1 >> 16);
+        y1_lo = (int16)((L_tmp1 - (y1_hi << 16)) >> 1);
+
+
+    }
+
+
+    mem[0] = y2_hi;
+    mem[1] = y2_lo;
+    mem[2] = y1_hi;
+    mem[3] = y1_lo;
+    mem[4] = x0;
+    mem[5] = x1;
+
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/highpass_50hz_at_12k8.cpp b/media/libstagefright/codecs/amrwb/src/highpass_50hz_at_12k8.cpp
new file mode 100644
index 0000000..c70c163
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/highpass_50hz_at_12k8.cpp
@@ -0,0 +1,205 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: highpass_50Hz_at_12k8.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 filter memory [6]
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   2nd order high pass filter with cut off frequency at 31 Hz.
+   Designed with cheby2 function in MATLAB.
+   Optimized for fixed-point to get the following frequency response:
+
+    frequency:     0Hz    14Hz  24Hz   31Hz   37Hz   41Hz   47Hz
+    dB loss:     -infdB  -15dB  -6dB   -3dB  -1.5dB  -1dB  -0.5dB
+
+  Algorithm:
+
+    y[i] = b[0]*x[i] + b[1]*x[i-1] + b[2]*x[i-2]
+                     + a[1]*y[i-1] + a[2]*y[i-2];
+
+    int16 b[3] = {4053, -8106, 4053};         in Q12
+    int16 a[3] = {8192, 16211, -8021};        in Q12
+
+    float -->   b[3] = {0.989501953, -1.979003906,  0.989501953};
+                a[3] = {1.000000000,  1.978881836, -0.979125977};
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.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 highpass_50Hz_at_12k8_init(int16 mem[])
+{
+    pv_memset((void *)mem, 0, 6*sizeof(*mem));
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void highpass_50Hz_at_12k8(
+    int16 signal[],                      /* input/output signal */
+    int16 lg,                            /* lenght of signal    */
+    int16 mem[]                          /* filter memory [6]   */
+)
+{
+    int16 i, x2;
+    int16 y2_hi, y2_lo, y1_hi, y1_lo, x0, x1;
+    int32 L_tmp1;
+    int32 L_tmp2;
+    int16 *pt_sign = signal;
+
+    y2_hi = mem[0];
+    y2_lo = mem[1];
+    y1_hi = mem[2];
+    y1_lo = mem[3];
+    x0    = mem[4];
+    x1    = mem[5];
+
+
+    for (i = lg; i != 0; i--)
+    {
+
+        /* y[i] = b[0]*x[i] + b[1]*x[i-1] + b[0]*x[i-2]  */
+        /* + a[0]*y[i-1] + a[1] * y[i-2];  */
+
+        L_tmp1 = fxp_mac_16by16(y1_lo, 16211, 8192L);
+        L_tmp1 = fxp_mac_16by16(y2_lo, -8021, L_tmp1);
+        L_tmp2 = fxp_mul_16by16(y1_hi, 32422);
+        L_tmp2 = fxp_mac_16by16(y2_hi, -16042, L_tmp2);
+
+        x2 = x1;
+        x1 = x0;
+        x0 = *pt_sign;
+        L_tmp2 = fxp_mac_16by16(x2,  8106, L_tmp2);
+        L_tmp2 = fxp_mac_16by16(x1, -16212, L_tmp2);
+        L_tmp2 = fxp_mac_16by16(x0,  8106, L_tmp2);
+
+
+        L_tmp1 = ((L_tmp1 >> 14) + L_tmp2) << 2;
+
+        y2_hi = y1_hi;
+        y2_lo = y1_lo;
+        y1_hi = (int16)(L_tmp1 >> 16);
+        y1_lo = (int16)((L_tmp1 - (y1_hi << 16)) >> 1);
+
+        /* coeff Q14 --> Q15 with saturation */
+        *(pt_sign++) = amr_wb_shl1_round(L_tmp1);
+
+    }
+
+
+    mem[0] = y2_hi;
+    mem[1] = y2_lo;
+    mem[2] = y1_hi;
+    mem[3] = y1_lo;
+    mem[4] = x0;
+    mem[5] = x1;
+
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp b/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
new file mode 100644
index 0000000..59c6c0a
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/homing_amr_wb_dec.cpp
@@ -0,0 +1,370 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: homing_amr_wb_dec.cpp
+
+     Date: 4/25/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+
+
+
+INPUT AND OUTPUT DEFINITIONS
+
+Input
+    int16 input_frame[],            16-bit input frame
+    int16 mode                      16-bit mode
+    int16 nparms                    16-bit number of parameters
+Returns
+    Int16 i             number of leading zeros on x
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Performs the homing routines
+
+    int16 dhf_test(int16 input_frame[], int16 mode, int16 nparms)
+    int16 decoder_homing_frame_test(int16 input_frame[], int16 mode)
+    int16 decoder_homing_frame_test_first(int16 input_frame[], int16 mode)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "get_amr_wb_bits.h"
+#include "pvamrwbdecoder_api.h"
+#include "pvamrwbdecoder.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define DHF_PARMS_MAX 32 /* homing frame pattern             */
+#define NUM_OF_SPMODES 9
+
+#define PRML 15
+#define PRMN_7k NBBITS_7k/PRML + 1
+#define PRMN_9k NBBITS_9k/PRML + 1
+#define PRMN_12k NBBITS_12k/PRML + 1
+#define PRMN_14k NBBITS_14k/PRML + 1
+#define PRMN_16k NBBITS_16k/PRML + 1
+#define PRMN_18k NBBITS_18k/PRML + 1
+#define PRMN_20k NBBITS_20k/PRML + 1
+#define PRMN_23k NBBITS_23k/PRML + 1
+#define PRMN_24k NBBITS_24k/PRML + 1
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int16 dhf_test(int16 input_frame[], int32 mode, int16 nparms);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int16 prmnofsf[NUM_OF_SPMODES] =
+{
+    63,  81, 100,
+    108, 116, 128,
+    136, 152, 156
+};
+
+
+const int16 dfh_M7k[PRMN_7k] =
+{
+    3168, 29954, 29213, 16121,
+    64, 13440, 30624, 16430,
+    19008
+};
+
+const int16 dfh_M9k[PRMN_9k] =
+{
+    3168, 31665,  9943, 9123,
+    15599,  4358, 20248, 2048,
+    17040, 27787, 16816, 13888
+};
+
+const int16 dfh_M12k[PRMN_12k] =
+{
+    3168, 31665,  9943,  9128,
+    3647,  8129, 30930, 27926,
+    18880, 12319,   496,  1042,
+    4061, 20446, 25629, 28069,
+    13948
+};
+
+const int16 dfh_M14k[PRMN_14k] =
+{
+    3168, 31665,  9943,  9131,
+    24815,   655, 26616, 26764,
+    7238, 19136,  6144,    88,
+    4158, 25733, 30567, 30494,
+    221, 20321, 17823
+};
+
+const int16 dfh_M16k[PRMN_16k] =
+{
+    3168, 31665,  9943,  9131,
+    24815,   700,  3824,  7271,
+    26400,  9528,  6594, 26112,
+    108,  2068, 12867, 16317,
+    23035, 24632,  7528,  1752,
+    6759, 24576
+};
+
+const int16 dfh_M18k[PRMN_18k] =
+{
+    3168, 31665,  9943,  9135,
+    14787, 14423, 30477, 24927,
+    25345, 30154,   916,  5728,
+    18978,  2048,   528, 16449,
+    2436,  3581, 23527, 29479,
+    8237, 16810, 27091, 19052,
+    0
+};
+
+const int16 dfh_M20k[PRMN_20k] =
+{
+    3168, 31665,  9943,  9129,
+    8637, 31807, 24646,   736,
+    28643,  2977,  2566, 25564,
+    12930, 13960,  2048,   834,
+    3270,  4100, 26920, 16237,
+    31227, 17667, 15059, 20589,
+    30249, 29123, 0
+};
+
+const int16 dfh_M23k[PRMN_23k] =
+{
+    3168, 31665,  9943,  9132,
+    16748,  3202, 28179, 16317,
+    30590, 15857, 19960,  8818,
+    21711, 21538,  4260, 16690,
+    20224,  3666,  4194,  9497,
+    16320, 15388,  5755, 31551,
+    14080,  3574, 15932,    50,
+    23392, 26053, 31216
+};
+
+const int16 dfh_M24k[PRMN_24k] =
+{
+    3168, 31665,  9943,  9134,
+    24776,  5857, 18475, 28535,
+    29662, 14321, 16725,  4396,
+    29353, 10003, 17068, 20504,
+    720,     0,  8465, 12581,
+    28863, 24774,  9709, 26043,
+    7941, 27649, 13965, 15236,
+    18026, 22047, 16681,  3968
+};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+int16 dhf_test(int16 input_frame[], int32 mode, int16 nparms)
+{
+    int16 i, j, tmp, shift;
+    int16 param[DHF_PARMS_MAX];
+    int16 *prms;
+
+    /* overall table with the parameters of the
+    decoder homing frames for all modes */
+
+    const int16 *dhf[] =
+    {
+        dfh_M7k,
+        dfh_M9k,
+        dfh_M12k,
+        dfh_M14k,
+        dfh_M16k,
+        dfh_M18k,
+        dfh_M20k,
+        dfh_M23k,
+        dfh_M24k,
+        dfh_M24k
+    };
+
+    prms = input_frame;
+    j = 0;
+    i = 0;
+
+    if (mode != MRDTX)
+    {
+        if (mode != MODE_24k)
+        {
+            /* convert the received serial bits */
+            tmp = nparms - 15;
+            while (tmp > j)
+            {
+                param[i] = Serial_parm(15, &prms);
+                j += 15;
+                i++;
+            }
+            tmp = nparms - j;
+            param[i] = Serial_parm(tmp, &prms);
+            shift = 15 - tmp;
+            param[i] = shl_int16(param[i], shift);
+        }
+        else
+        {
+            /*If mode is 23.85Kbit/s, remove high band energy bits */
+            for (i = 0; i < 10; i++)
+            {
+                param[i] = Serial_parm(15, &prms);
+            }
+            param[10] = Serial_parm(15, &prms) & 0x61FF;
+
+            for (i = 11; i < 17; i++)
+            {
+                param[i] = Serial_parm(15, &prms);
+            }
+            param[17] = Serial_parm(15, &prms) & 0xE0FF;
+
+            for (i = 18; i < 24; i++)
+            {
+                param[i] = Serial_parm(15, &prms);
+            }
+            param[24] = Serial_parm(15, &prms) & 0x7F0F;
+
+            for (i = 25; i < 31; i++)
+            {
+                param[i] = Serial_parm(15, &prms);
+            }
+
+            tmp = Serial_parm(8, &prms);
+            param[31] = shl_int16(tmp, 7);
+            shift = 0;
+        }
+
+        /* check if the parameters matches the parameters of the corresponding decoder homing frame */
+        tmp = i;
+        j = 0;
+        for (i = 0; i < tmp; i++)
+        {
+            j = (param[i] ^ dhf[mode][i]);
+            if (j)
+            {
+                break;
+            }
+        }
+        tmp = 0x7fff;
+        tmp >>= shift;
+        tmp = shl_int16(tmp, shift);
+        tmp = (dhf[mode][i] & tmp);
+        tmp = (param[i] ^ tmp);
+        j = (int16)(j | tmp);
+
+    }
+    else
+    {
+        j = 1;
+    }
+
+    return (!j);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+int16 pvDecoder_AmrWb_homing_frame_test(int16 input_frame[], int16 mode)
+{
+    /* perform test for COMPLETE parameter frame */
+    return dhf_test(input_frame, mode, AMR_WB_COMPRESSED[mode]);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+int16 pvDecoder_AmrWb_homing_frame_test_first(int16 input_frame[], int16 mode)
+{
+    /* perform test for FIRST SUBFRAME of parameter frame ONLY */
+    return dhf_test(input_frame, mode, prmnofsf[mode]);
+}
diff --git a/media/libstagefright/codecs/amrwb/src/interpolate_isp.cpp b/media/libstagefright/codecs/amrwb/src/interpolate_isp.cpp
new file mode 100644
index 0000000..3ccebdb
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/interpolate_isp.cpp
@@ -0,0 +1,146 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: interpolate_isp.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 isp_old[],         input : isps from past frame
+     int16 isp_new[],         input : isps from present frame
+     const int16 frac[],      input : fraction for 3 first subfr (Q15)
+     int16 Az[]               output: LP coefficients in 4 subframes
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Interpolation of the LP parameters in 4 subframes
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define MP1 (M+1)
+
+/*----------------------------------------------------------------------------
+; 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 interpolate_isp(
+    int16 isp_old[],       /* input : isps from past frame              */
+    int16 isp_new[],       /* input : isps from present frame           */
+    const int16 frac[],    /* input : fraction for 3 first subfr (Q15)  */
+    int16 Az[]             /* output: LP coefficients in 4 subframes    */
+)
+{
+    int16 i, k, fac_old, fac_new;
+    int16 isp[M];
+    int32 L_tmp;
+
+    for (k = 0; k < 3; k++)
+    {
+        fac_new = frac[k];
+        fac_old = add_int16(sub_int16(32767, fac_new), 1);  /* 1.0 - fac_new */
+
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = mul_16by16_to_int32(isp_old[i], fac_old);
+            L_tmp = mac_16by16_to_int32(L_tmp, isp_new[i], fac_new);
+            isp[i] = amr_wb_round(L_tmp);
+        }
+        Isp_Az(isp, Az, M, 0);
+        Az += MP1;
+    }
+
+    /* 4th subframe: isp_new (frac=1.0) */
+
+    Isp_Az(isp_new, Az, M, 0);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/isf_extrapolation.cpp b/media/libstagefright/codecs/amrwb/src/isf_extrapolation.cpp
new file mode 100644
index 0000000..72d353a
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/isf_extrapolation.cpp
@@ -0,0 +1,274 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: isf_extrapolation.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    int16 HfIsf[]    (i/o)  isf vector
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Conversion of 16th-order 12.8kHz ISF vector
+    into 20th-order 16kHz ISF vector
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwb_math_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define INV_LENGTH 2731                    /* 1/12 */
+
+/*----------------------------------------------------------------------------
+; 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 isf_extrapolation(int16 HfIsf[])
+{
+    int16 IsfDiff[M - 2];
+    int32 IsfCorr[3];
+    int32 L_tmp;
+    int16 coeff, mean, tmp, tmp2, tmp3;
+    int16 exp, exp2, hi, lo;
+    int16 i, MaxCorr;
+
+    HfIsf[M16k - 1] = HfIsf[M - 1];
+
+    /* Difference vector */
+    for (i = 1; i < (M - 1); i++)
+    {
+        IsfDiff[i - 1] = sub_int16(HfIsf[i], HfIsf[i - 1]);
+    }
+    L_tmp = 0;
+
+    /* Mean of difference vector */
+    for (i = 3; i < (M - 1); i++)
+    {
+        L_tmp = mac_16by16_to_int32(L_tmp, IsfDiff[i - 1], INV_LENGTH);
+
+    }
+    mean = amr_wb_round(L_tmp);
+
+    IsfCorr[0] = 0;
+
+    tmp = 0;
+    for (i = 0; i < (M - 2); i++)
+    {
+        if (IsfDiff[i] > tmp)
+        {
+            tmp = IsfDiff[i];
+        }
+    }
+    exp = norm_s(tmp);
+    for (i = 0; i < (M - 2); i++)
+    {
+        IsfDiff[i] = shl_int16(IsfDiff[i], exp);
+    }
+    mean = shl_int16(mean, exp);
+    for (i = 7; i < (M - 2); i++)
+    {
+        tmp2 = sub_int16(IsfDiff[i], mean);
+        tmp3 = sub_int16(IsfDiff[i - 2], mean);
+        L_tmp = mul_16by16_to_int32(tmp2, tmp3);
+        int32_to_dpf(L_tmp, &hi, &lo);
+        L_tmp = mpy_dpf_32(hi, lo, hi, lo);
+        IsfCorr[0] = add_int32(IsfCorr[0], L_tmp);
+    }
+    IsfCorr[1] = 0;
+    for (i = 7; i < (M - 2); i++)
+    {
+        tmp2 = sub_int16(IsfDiff[i], mean);
+        tmp3 = sub_int16(IsfDiff[i - 3], mean);
+        L_tmp = mul_16by16_to_int32(tmp2, tmp3);
+        int32_to_dpf(L_tmp, &hi, &lo);
+        L_tmp = mpy_dpf_32(hi, lo, hi, lo);
+        IsfCorr[1] = add_int32(IsfCorr[1], L_tmp);
+    }
+    IsfCorr[2] = 0;
+    for (i = 7; i < (M - 2); i++)
+    {
+        tmp2 = sub_int16(IsfDiff[i], mean);
+        tmp3 = sub_int16(IsfDiff[i - 4], mean);
+        L_tmp = mul_16by16_to_int32(tmp2, tmp3);
+        int32_to_dpf(L_tmp, &hi, &lo);
+        L_tmp = mpy_dpf_32(hi, lo, hi, lo);
+        IsfCorr[2] = add_int32(IsfCorr[2], L_tmp);
+    }
+
+    if (IsfCorr[0] > IsfCorr[1])
+    {
+        MaxCorr = 0;
+    }
+    else
+    {
+        MaxCorr = 1;
+    }
+
+
+    if (IsfCorr[2] > IsfCorr[MaxCorr])
+    {
+        MaxCorr = 2;
+    }
+
+    MaxCorr++;             /* Maximum correlation of difference vector */
+
+    for (i = M - 1; i < (M16k - 1); i++)
+    {
+        tmp = sub_int16(HfIsf[i - 1 - MaxCorr], HfIsf[i - 2 - MaxCorr]);
+        HfIsf[i] = add_int16(HfIsf[i - 1], tmp);
+    }
+
+    /* tmp=7965+(HfIsf[2]-HfIsf[3]-HfIsf[4])/6; */
+    tmp = add_int16(HfIsf[4], HfIsf[3]);
+    tmp = sub_int16(HfIsf[2], tmp);
+    tmp = mult_int16(tmp, 5461);
+    tmp += 20390;
+
+
+    if (tmp > 19456)
+    {                                      /* Maximum value of ISF should be at most 7600 Hz */
+        tmp = 19456;
+    }
+    tmp = sub_int16(tmp, HfIsf[M - 2]);
+    tmp2 = sub_int16(HfIsf[M16k - 2], HfIsf[M - 2]);
+
+    exp2 = norm_s(tmp2);
+    exp = norm_s(tmp);
+    exp--;
+    tmp <<= exp;
+    tmp2 <<= exp2;
+    coeff = div_16by16(tmp, tmp2);              /* Coefficient for stretching the ISF vector */
+    exp = exp2 - exp;
+
+    for (i = M - 1; i < (M16k - 1); i++)
+    {
+        tmp = mult_int16(sub_int16(HfIsf[i], HfIsf[i - 1]), coeff);
+        IsfDiff[i - (M - 1)] = shl_int16(tmp, exp);
+    }
+
+    for (i = M; i < (M16k - 1); i++)
+    {
+        /* The difference between ISF(n) and ISF(n-2) should be at least 500 Hz */
+        tmp = IsfDiff[i - (M - 1)] + IsfDiff[i - M] - 1280;
+
+        if (tmp < 0)
+        {
+
+            if (IsfDiff[i - (M - 1)] > IsfDiff[i - M])
+            {
+                IsfDiff[i - M] = 1280 - IsfDiff[i - (M - 1)];
+            }
+            else
+            {
+                IsfDiff[i - (M - 1)] = 1280 - IsfDiff[i - M];
+            }
+        }
+    }
+
+    for (i = M - 1; i < (M16k - 1); i++)
+    {
+        HfIsf[i] = add_int16(HfIsf[i - 1], IsfDiff[i - (M - 1)]);
+    }
+
+    for (i = 0; i < (M16k - 1); i++)
+    {
+        HfIsf[i] = mult_int16(HfIsf[i], 26214);  /* Scale the ISF vector correctly for 16000 kHz */
+    }
+
+    Isf_isp(HfIsf, HfIsf, M16k);
+
+    return;
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/isp_az.cpp b/media/libstagefright/codecs/amrwb/src/isp_az.cpp
new file mode 100644
index 0000000..40093f5
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/isp_az.cpp
@@ -0,0 +1,403 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: isp_az.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 isp[],              (i) Q15 : Immittance spectral pairs
+     int16 a[],                (o) Q12 : predictor coefficients (order=M)
+     int16 m,                  (i)     : order
+     int16 adaptive_scaling    (i) 0   : adaptive scaling disabled
+                                   1   : adaptive scaling enabled
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Compute the LPC coefficients from isp (order=M)
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwb_math_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NC (M/2)
+#define NC16k (M16k/2)
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void Get_isp_pol(int16 * isp, int32 * f, int16 n);
+    void Get_isp_pol_16kHz(int16 * isp, int32 * f, int16 n);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 Isp_Az(
+    int16 isp[],            /* (i) Q15 : Immittance spectral pairs         */
+    int16 a[],              /* (o) Q12 : predictor coefficients (order=M)  */
+    int16 m,                /* (i)     : order                     */
+    int16 adaptive_scaling  /* (i) 0   : adaptive scaling disabled */
+    /*     1   : adaptive scaling enabled  */
+)
+{
+    int16 i, j;
+    int32 f1[NC16k + 1], f2[NC16k];
+    int16 nc;
+    int32 t0;
+    int32 t1;
+    int16 q, q_sug;
+    int32 tmax;
+
+    nc = m >> 1;
+
+
+    if (nc > 8)
+    {
+        Get_isp_pol_16kHz(&isp[0], f1, nc);
+        for (i = 0; i <= nc; i++)
+        {
+            f1[i] = shl_int32(f1[i], 2);
+        }
+        Get_isp_pol_16kHz(&isp[1], f2, nc - 1);
+        for (i = 0; i <= nc - 1; i++)
+        {
+            f2[i] = shl_int32(f2[i], 2);
+        }
+    }
+    else
+    {
+        Get_isp_pol(&isp[0], f1, nc);
+        Get_isp_pol(&isp[1], f2, nc - 1);
+    }
+
+    /*
+     *  Multiply F2(z) by (1 - z^-2)
+     */
+
+    for (i = nc - 1; i > 1; i--)
+    {
+        f2[i] -= f2[i - 2];      /* f2[i] -= f2[i-2]; */
+    }
+
+    /*
+     *  Scale F1(z) by (1+isp[m-1])  and  F2(z) by (1-isp[m-1])
+     */
+
+    for (i = 0; i < nc; i++)
+    {
+        /* f1[i] *= (1.0 + isp[M-1]); */
+
+        /* f2[i] *= (1.0 - isp[M-1]); */
+        t0 = f1[i];
+        t1 = f2[i];
+        t0 = fxp_mul32_by_16b(t0, isp[m - 1]) << 1;
+        t1 = fxp_mul32_by_16b(t1, isp[m - 1]) << 1;
+        f1[i] += t0;
+        f2[i] -= t1;
+
+    }
+
+    /*
+     *  A(z) = (F1(z)+F2(z))/2
+     *  F1(z) is symmetric and F2(z) is antisymmetric
+     */
+
+    /* a[0] = 1.0; */
+    a[0] = 4096;
+    tmax = 1;
+    j = m - 1;
+    for (i = 1;  i < nc; i++)
+    {
+        /* a[i] = 0.5*(f1[i] + f2[i]); */
+
+        t0 = add_int32(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+        /* compute t1 = abs(t0) */
+        t1 = t0 - (t0 < 0);
+        t1 = t1 ^(t1 >> 31);  /* t1 = t1 ^sign(t1) */
+
+        tmax |= t1;
+        /* from Q23 to Q12 and * 0.5 */
+        a[i] = (int16)((t0 >> 12) + ((t0 >> 11) & 1));
+
+
+        /* a[j] = 0.5*(f1[i] - f2[i]); */
+
+        t0 = sub_int32(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+        /* compute t1 = abs(t0) */
+        t1 = t0 - (t0 < 0);
+        t1 = t1 ^(t1 >> 31);  /* t1 = t1 ^sign(t1) */
+
+        tmax |= t1;
+
+        /* from Q23 to Q12 and * 0.5 */
+        a[j--] = (int16)((t0 >> 12) + ((t0 >> 11) & 1));
+
+    }
+
+    /* rescale data if overflow has occured and reprocess the loop */
+
+
+    if (adaptive_scaling == 1)
+    {
+        q = 4 - normalize_amr_wb(tmax);        /* adaptive scaling enabled */
+    }
+    else
+    {
+        q = 0;                   /* adaptive scaling disabled */
+    }
+
+
+    if (q > 0)
+    {
+        q_sug = 12 + q;
+        for (i = 1, j = m - 1; i < nc; i++, j--)
+        {
+            /* a[i] = 0.5*(f1[i] + f2[i]); */
+
+            t0 = add_int32(f1[i], f2[i]);          /* f1[i] + f2[i]             */
+            /* from Q23 to Q12 and * 0.5 */
+            a[i] = (int16)((t0 >> q_sug) + ((t0 >> (q_sug - 1)) & 1));
+
+
+            /* a[j] = 0.5*(f1[i] - f2[i]); */
+
+            t0 = sub_int32(f1[i], f2[i]);          /* f1[i] - f2[i]             */
+            /* from Q23 to Q12 and * 0.5 */
+            a[j] = (int16)((t0 >> q_sug) + ((t0 >> (q_sug - 1)) & 1));
+
+        }
+        a[0] >>=  q;
+    }
+    else
+    {
+        q_sug = 12;
+        q     = 0;
+    }
+
+    /* a[NC] = 0.5*f1[NC]*(1.0 + isp[M-1]); */
+
+
+    t0 = (int32)(((int64)f1[nc] * isp[m - 1]) >> 16) << 1;
+
+
+    t0 = add_int32(f1[nc], t0);
+
+    /* from Q23 to Q12 and * 0.5 */
+    a[nc] = (int16)((t0 >> q_sug) + ((t0 >> (q_sug - 1)) & 1));
+    a[m] = shr_rnd(isp[m - 1], (3 + q));           /* from Q15 to Q12          */
+
+    /* a[m] = isp[m-1]; */
+
+
+    return;
+}
+
+
+
+/*
+Get_isp_pol
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+   isp[]   : isp vector (cosine domaine)         in Q15
+   f[]     : the coefficients of F1 or F2        in Q23
+   n       : == NC for F1(z); == NC-1 for F2(z)
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Find the polynomial F1(z) or F2(z) from the ISPs.
+  This is performed by expanding the product polynomials:
+
+  F1(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )
+          i=0,2,4,6,8
+  F2(z) =   product   ( 1 - 2 isp_i z^-1 + z^-2 )
+          i=1,3,5,7
+
+  where isp_i are the ISPs in the cosine domain.
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void Get_isp_pol(int16 * isp, int32 * f, int16 n)
+{
+    int16 i, j;
+    int32 t0;
+
+
+    /* All computation in Q23 */
+
+    f[0] = 0x00800000;                        /* f[0] = 1.0;        in Q23  */
+    f[1] = -isp[0] << 9;                      /* f[1] = -2.0*isp[0] in Q23  */
+
+    f += 2;                                   /* Advance f pointer          */
+    isp += 2;                                 /* Advance isp pointer        */
+
+    for (i = 2; i <= n; i++)
+    {
+        *f = f[-2];
+
+        for (j = 1; j < i; j++)
+        {
+
+            t0 = fxp_mul32_by_16b(f[-1], *isp);
+            t0 = shl_int32(t0, 2);
+
+            *f -= t0;                      /* *f -= t0            */
+            *(f) += f[-2];                 /* *f += f[-2]         */
+            f--;
+
+
+        }
+        *f -= *isp << 9;
+
+        f += i;                            /* Advance f pointer   */
+        isp += 2;                          /* Advance isp pointer */
+    }
+}
+
+void Get_isp_pol_16kHz(int16 * isp, int32 * f, int16 n)
+{
+    int16 i, j;
+    int32 t0;
+
+    /* All computation in Q23 */
+
+    f[0] = 0x00200000;                        /* f[0] = 0.25;        in Q23  */
+
+    f[1] = -isp[0] << 7;                      /* f[1] = -0.5*isp[0] in Q23  */
+
+    f += 2;                                   /* Advance f pointer          */
+    isp += 2;                                 /* Advance isp pointer        */
+
+    for (i = 2; i <= n; i++)
+    {
+        *f = f[-2];
+
+        for (j = 1; j < i; j++, f--)
+        {
+            t0 = fxp_mul32_by_16b(f[-1], *isp);
+            t0 = shl_int32(t0, 2);
+
+            *f -= t0;                      /* *f -= t0            */
+            *f += f[-2];                   /* *f += f[-2]         */
+        }
+        *f -= *isp << 7;
+        f += i;                            /* Advance f pointer   */
+        isp += 2;                          /* Advance isp pointer */
+    }
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/isp_isf.cpp b/media/libstagefright/codecs/amrwb/src/isp_isf.cpp
new file mode 100644
index 0000000..41db7e3
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/isp_isf.cpp
@@ -0,0 +1,175 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: isp_isf.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 isf[],       (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5)
+     int16 isp[],       (o) Q15 : isp[m] (range: -1<=val<1)
+     int16 m            (i)     : LPC order
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+     Isf_isp   Transformation isf to isp
+
+   The transformation from isf[i] to isp[i] is
+   approximated by a look-up table and interpolation.
+
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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
+----------------------------------------------------------------------------*/
+
+/* Look-up table for transformations */
+
+/* table of cos(x) in Q15 */
+
+const int16 table[129] =
+{
+    32767,
+    32758,  32729,  32679,  32610,  32522,  32413,  32286,  32138,
+    31972,  31786,  31581,  31357,  31114,  30853,  30572,  30274,
+    29957,  29622,  29269,  28899,  28511,  28106,  27684,  27246,
+    26791,  26320,  25833,  25330,  24812,  24279,  23732,  23170,
+    22595,  22006,  21403,  20788,  20160,  19520,  18868,  18205,
+    17531,  16846,  16151,  15447,  14733,  14010,  13279,  12540,
+    11793,  11039,  10279,   9512,   8740,   7962,   7180,   6393,
+    5602,   4808,   4011,   3212,   2411,   1608,    804,      0,
+    -804,  -1608,  -2411,  -3212,  -4011,  -4808,  -5602,  -6393,
+    -7180,  -7962,  -8740,  -9512, -10279, -11039, -11793, -12540,
+    -13279, -14010, -14733, -15447, -16151, -16846, -17531, -18205,
+    -18868, -19520, -20160, -20788, -21403, -22006, -22595, -23170,
+    -23732, -24279, -24812, -25330, -25833, -26320, -26791, -27246,
+    -27684, -28106, -28511, -28899, -29269, -29622, -29957, -30274,
+    -30572, -30853, -31114, -31357, -31581, -31786, -31972, -32138,
+    -32286, -32413, -32522, -32610, -32679, -32729, -32758, -32768
+};
+
+
+/*----------------------------------------------------------------------------
+; 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 Isf_isp(
+    int16 isf[],     /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+    int16 isp[],     /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+    int16 m          /* (i)     : LPC order                                */
+)
+{
+    int16 i, ind, offset;
+    int32 L_tmp;
+
+    for (i = 0; i < m - 1; i++)
+    {
+        isp[i] = isf[i];
+    }
+    isp[m - 1] = shl_int16(isf[m - 1], 1);
+
+    for (i = 0; i < m; i++)
+    {
+        ind = isp[i] >> 7;            /* ind    = b7-b15 of isf[i] */
+        offset = (isp[i] & 0x007f);       /* offset = b0-b6  of isf[i] */
+
+        /* isp[i] = table[ind]+ ((table[ind+1]-table[ind])*offset) / 128 */
+
+        L_tmp = mul_16by16_to_int32(table[ind + 1] - table[ind], offset);
+        isp[i] = add_int16(table[ind], (int16)(L_tmp >> 8));
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/lagconceal.cpp b/media/libstagefright/codecs/amrwb/src/lagconceal.cpp
new file mode 100644
index 0000000..c699808
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/lagconceal.cpp
@@ -0,0 +1,364 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: lagconceal.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 gain_hist[],                     (i)  : Gain history
+     int16 lag_hist[],                      (i)  : Subframe size
+     int16 * T0,                            (i/o): current lag
+     int16 * old_T0,                        (i/o): previous lag
+     int16 * seed,
+     int16 unusable_frame
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Concealment of LTP lags during bad frames
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define L_LTPHIST 5
+#define ONE_PER_3 10923
+#define ONE_PER_LTPHIST 6554
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+void insertion_sort(int16 array[], int16 n);
+void insert(int16 array[], int16 num, int16 x);
+
+/*----------------------------------------------------------------------------
+; 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 Init_Lagconc(int16 lag_hist[])
+{
+    int16 i;
+
+    for (i = 0; i < L_LTPHIST; i++)
+    {
+        lag_hist[i] = 64;
+    }
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void lagconceal(
+    int16 gain_hist[],                   /* (i) : Gain history     */
+    int16 lag_hist[],                    /* (i) : Subframe size    */
+    int16 * T0,
+    int16 * old_T0,
+    int16 * seed,
+    int16 unusable_frame
+)
+{
+    int16 maxLag, minLag, lastLag, lagDif, meanLag = 0;
+    int16 lag_hist2[L_LTPHIST] = {0};
+    int16 i, tmp, tmp2;
+    int16 minGain, lastGain, secLastGain;
+    int16 D, D2;
+
+    /* Is lag index such that it can be aplied directly or does it has to be subtituted */
+
+    lastGain = gain_hist[4];
+    secLastGain = gain_hist[3];
+
+    lastLag = lag_hist[0];
+
+    /******* SMALLEST history lag *******/
+    minLag = lag_hist[0];
+    /*******  BIGGEST history lag *******/
+    maxLag = lag_hist[0];
+    for (i = 1; i < L_LTPHIST; i++)
+    {
+        if (lag_hist[i] < minLag)
+        {
+            minLag = lag_hist[i];
+        }
+        if (lag_hist[i] > maxLag)
+        {
+            maxLag = lag_hist[i];
+        }
+    }
+    /***********SMALLEST history gain***********/
+    minGain = gain_hist[0];
+    for (i = 1; i < L_LTPHIST; i++)
+    {
+
+        if (gain_hist[i] < minGain)
+        {
+            minGain = gain_hist[i];
+        }
+    }
+    /***Difference between MAX and MIN lag**/
+    lagDif = sub_int16(maxLag, minLag);
+
+
+    if (unusable_frame != 0)
+    {
+        /* LTP-lag for RX_SPEECH_LOST */
+        /**********Recognition of the LTP-history*********/
+
+        if ((minGain > 8192) && (lagDif < 10))
+        {
+            *T0 = *old_T0;
+        }
+        else if (lastGain > 8192 && secLastGain > 8192)
+        {
+            *T0 = lag_hist[0];
+        }
+        else
+        {
+            /********SORT************/
+            /* The sorting of the lag history */
+            for (i = 0; i < L_LTPHIST; i++)
+            {
+                lag_hist2[i] = lag_hist[i];
+            }
+            insertion_sort(lag_hist2, 5);
+
+            /* Lag is weighted towards bigger lags */
+            /* and random variation is added */
+            lagDif = sub_int16(lag_hist2[4], lag_hist2[2]);
+
+
+            if (lagDif > 40)
+            {
+                lagDif = 40;
+            }
+
+            D = noise_gen_amrwb(seed);              /* D={-1, ...,1} */
+            /* D2={-lagDif/2..lagDif/2} */
+            tmp = lagDif >> 1;
+            D2 = mult_int16(tmp, D);
+            tmp = add_int16(add_int16(lag_hist2[2], lag_hist2[3]), lag_hist2[4]);
+            *T0 = add_int16(mult_int16(tmp, ONE_PER_3), D2);
+        }
+        /* New lag is not allowed to be bigger or smaller than last lag values */
+
+        if (*T0 > maxLag)
+        {
+            *T0 = maxLag;
+        }
+
+        if (*T0 < minLag)
+        {
+            *T0 = minLag;
+        }
+    }
+    else
+    {
+        /* LTP-lag for RX_BAD_FRAME */
+
+        /***********MEAN lag**************/
+        meanLag = 0;
+        for (i = 0; i < L_LTPHIST; i++)
+        {
+            meanLag = add_int16(meanLag, lag_hist[i]);
+        }
+        meanLag = mult_int16(meanLag, ONE_PER_LTPHIST);
+
+        tmp  = *T0 - maxLag;
+        tmp2 = *T0 - lastLag;
+
+        if ((lagDif < 10) && (*T0 > (minLag - 5)) && (tmp < 5))
+        {
+            *T0 = *T0;
+        }
+        else if ((lastGain > 8192) && (secLastGain > 8192) && ((tmp2 + 10) > 0 && tmp2 < 10))
+        {
+            *T0 = *T0;
+        }
+        else if ((minGain < 6554) && (lastGain == minGain) && (*T0 > minLag && *T0 < maxLag))
+        {
+            *T0 = *T0;
+        }
+        else if ((lagDif < 70) && (*T0 > minLag) && (*T0 < maxLag))
+        {
+            *T0 = *T0;
+        }
+        else if ((*T0 > meanLag) && (*T0 < maxLag))
+        {
+            *T0 = *T0;
+        }
+        else
+        {
+
+
+            if ((minGain > 8192) & (lagDif < 10))
+            {
+                *T0 = lag_hist[0];
+            }
+            else if ((lastGain > 8192) && (secLastGain > 8192))
+            {
+                *T0 = lag_hist[0];
+            }
+            else
+            {
+                /********SORT************/
+                /* The sorting of the lag history */
+                for (i = 0; i < L_LTPHIST; i++)
+                {
+                    lag_hist2[i] = lag_hist[i];
+                }
+                insertion_sort(lag_hist2, 5);
+
+                /* Lag is weighted towards bigger lags */
+                /* and random variation is added */
+                lagDif = sub_int16(lag_hist2[4], lag_hist2[2]);
+
+                if (lagDif > 40)
+                {
+                    lagDif = 40;
+                }
+
+                D = noise_gen_amrwb(seed);          /* D={-1,.., 1} */
+                /* D2={-lagDif/2..lagDif/2} */
+                tmp = lagDif >> 1;
+                D2 = mult_int16(tmp, D);
+                tmp = add_int16(add_int16(lag_hist2[2], lag_hist2[3]), lag_hist2[4]);
+                *T0 = add_int16(mult_int16(tmp, ONE_PER_3), D2);
+            }
+            /* New lag is not allowed to be bigger or smaller than last lag values */
+
+            if (*T0 > maxLag)
+            {
+                *T0 = maxLag;
+            }
+
+            if (*T0 < minLag)
+            {
+                *T0 = minLag;
+            }
+        }
+    }
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void insertion_sort(int16 array[], int16 n)
+{
+    int16 i;
+
+    for (i = 0; i < n; i++)
+    {
+        insert(array, i, array[i]);
+    }
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void insert(int16 array[], int16 n, int16 x)
+{
+    int16 i;
+
+    for (i = (n - 1); i >= 0; i--)
+    {
+
+        if (x < array[i])
+        {
+            array[i + 1] = array[i];
+        }
+        else
+        {
+            break;
+        }
+    }
+    array[i + 1] = x;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/low_pass_filt_7k.cpp b/media/libstagefright/codecs/amrwb/src/low_pass_filt_7k.cpp
new file mode 100644
index 0000000..ec1d6e0
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/low_pass_filt_7k.cpp
@@ -0,0 +1,220 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: low_pass_filt_7k.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 in/out: memory (size=30)
+     int16 x[]                   scratch mem ( size= 60)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+        15th order high pass 7kHz FIR filter
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define L_FIR 30
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int16 fir_7k[L_FIR+1] =
+{
+    -21, 47, -89, 146, -203,
+    229, -177, 0, 335, -839,
+    1485, -2211, 2931, -3542, 3953,
+    28682, 3953, -3542, 2931, -2211,
+    1485, -839, 335, 0, -177,
+    229, -203, 146, -89, 47,
+    -21
+};
+
+/*----------------------------------------------------------------------------
+; 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 low_pass_filt_7k_init(int16 mem[])            /* mem[30] */
+{
+    pv_memset((void *)mem, 0, (L_FIR)*sizeof(*mem));
+
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void low_pass_filt_7k(
+    int16 signal[],                      /* input:  signal                  */
+    int16 lg,                            /* input:  length of input         */
+    int16 mem[],                         /* in/out: memory (size=30)        */
+    int16 x[]
+)
+{
+    int16 i, j;
+    int32 L_tmp1;
+    int32 L_tmp2;
+    int32 L_tmp3;
+    int32 L_tmp4;
+
+    pv_memcpy((void *)x, (void *)mem, (L_FIR)*sizeof(*x));
+
+    for (i = 0; i < lg >> 2; i++)
+    {
+        x[(i<<2) + L_FIR    ] = signal[(i<<2)];
+        x[(i<<2) + L_FIR + 1] = signal[(i<<2)+1];
+        x[(i<<2) + L_FIR + 2] = signal[(i<<2)+2];
+        x[(i<<2) + L_FIR + 3] = signal[(i<<2)+3];
+
+        L_tmp1 = fxp_mac_16by16(x[(i<<2)] + signal[(i<<2)], fir_7k[0], 0x00004000);
+        L_tmp2 = fxp_mac_16by16(x[(i<<2)+1] + signal[(i<<2)+1], fir_7k[0], 0x00004000);
+        L_tmp3 = fxp_mac_16by16(x[(i<<2)+2] + signal[(i<<2)+2], fir_7k[0], 0x00004000);
+        L_tmp4 = fxp_mac_16by16(x[(i<<2)+3] + signal[(i<<2)+3], fir_7k[0], 0x00004000);
+
+        for (j = 1; j < L_FIR - 1; j += 4)
+        {
+
+
+            int16 tmp1 = x[(i<<2)+j  ];
+            int16 tmp2 = x[(i<<2)+j+1];
+            int16 tmp3 = x[(i<<2)+j+2];
+
+            L_tmp1 = fxp_mac_16by16(tmp1, fir_7k[j  ], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp2, fir_7k[j  ], L_tmp2);
+            L_tmp1 = fxp_mac_16by16(tmp2, fir_7k[j+1], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp3, fir_7k[j+1], L_tmp2);
+            L_tmp3 = fxp_mac_16by16(tmp3, fir_7k[j  ], L_tmp3);
+            L_tmp1 = fxp_mac_16by16(tmp3, fir_7k[j+2], L_tmp1);
+
+            tmp1 = x[(i<<2)+j+3];
+            tmp2 = x[(i<<2)+j+4];
+
+            L_tmp2 = fxp_mac_16by16(tmp1, fir_7k[j+2], L_tmp2);
+            L_tmp4 = fxp_mac_16by16(tmp1, fir_7k[j  ], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp1, fir_7k[j+1], L_tmp3);
+            L_tmp1 = fxp_mac_16by16(tmp1, fir_7k[j+3], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(tmp2, fir_7k[j+3], L_tmp2);
+            L_tmp4 = fxp_mac_16by16(tmp2, fir_7k[j+1], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp2, fir_7k[j+2], L_tmp3);
+
+            tmp1 = x[(i<<2)+j+5];
+            tmp2 = x[(i<<2)+j+6];
+
+            L_tmp4 = fxp_mac_16by16(tmp1, fir_7k[j+2], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(tmp1, fir_7k[j+3], L_tmp3);
+            L_tmp4 = fxp_mac_16by16(tmp2, fir_7k[j+3], L_tmp4);
+
+        }
+
+        L_tmp1 = fxp_mac_16by16(x[(i<<2)+j  ], fir_7k[j  ], L_tmp1);
+        L_tmp2 = fxp_mac_16by16(x[(i<<2)+j+1], fir_7k[j  ], L_tmp2);
+        L_tmp3 = fxp_mac_16by16(x[(i<<2)+j+2], fir_7k[j  ], L_tmp3);
+        L_tmp4 = fxp_mac_16by16(x[(i<<2)+j+3], fir_7k[j  ], L_tmp4);
+
+        signal[(i<<2)] = (int16)(L_tmp1 >> 15);
+        signal[(i<<2)+1] = (int16)(L_tmp2 >> 15);
+        signal[(i<<2)+2] = (int16)(L_tmp3 >> 15);
+        signal[(i<<2)+3] = (int16)(L_tmp4 >> 15);
+
+    }
+
+    pv_memcpy((void *)mem, (void *)(x + lg), (L_FIR)*sizeof(*mem));
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/median5.cpp b/media/libstagefright/codecs/amrwb/src/median5.cpp
new file mode 100644
index 0000000..b922de5
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/median5.cpp
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: median5.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+   INPUT
+       X[-2:2]   16-bit integers.
+
+   RETURN VALUE
+       The median of {X[-2], X[-1],..., X[2]}.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+      Returns the median of the set {X[-2], X[-1],..., X[2]},
+      whose elements are 16-bit integers.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwb_math_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
+----------------------------------------------------------------------------*/
+
+int16 median5(int16 x[])
+{
+    int16 x1, x2, x3, x4, x5;
+    int16 tmp;
+
+    x1 = x[-2];
+    x2 = x[-1];
+    x3 = x[0];
+    x4 = x[1];
+    x5 = x[2];
+
+
+
+    if (x2 < x1)
+    {
+        tmp = x1;
+        x1 = x2;
+        x2 = tmp;
+    }
+    if (x3 < x1)
+    {
+        tmp = x1;
+        x1 = x3;
+        x3 = tmp;
+    }
+    if (x4 < x1)
+    {
+        tmp = x1;
+        x1 = x4;
+        x4 = tmp;
+    }
+    if (x5 < x1)
+    {
+        x5 = x1;
+    }
+    if (x3 < x2)
+    {
+        tmp = x2;
+        x2 = x3;
+        x3 = tmp;
+    }
+    if (x4 < x2)
+    {
+        tmp = x2;
+        x2 = x4;
+        x4 = tmp;
+    }
+    if (x5 < x2)
+    {
+        x5 = x2;
+    }
+    if (x4 < x3)
+    {
+        x3 = x4;
+    }
+    if (x5 < x3)
+    {
+        x3 = x5;
+    }
+    return (x3);
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/mime_io.cpp b/media/libstagefright/codecs/amrwb/src/mime_io.cpp
new file mode 100644
index 0000000..9ff8816
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/mime_io.cpp
@@ -0,0 +1,729 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/mime_io.cpp
+
+     Date: 05/07/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ [Describe what the module does by using the variable names
+ listed in the Input and Output Definitions Section above.]
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ [List requirements to be satisfied by this module.]
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [List all references used in designing this module.]
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ ------------------------------------------------------------------------------
+ RESOURCES USED
+
+ STACK USAGE:
+
+ DATA MEMORY USED: x words
+
+ PROGRAM MEMORY USED: x words
+
+ CLOCK CYCLES:
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_api.h"
+#include "pvamrwbdecoder.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "dtx.h"
+#include "mime_io.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define MRSID 9
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+const uint8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C,
+                            0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C
+                           };
+
+/* number of speech bits for all modes */
+const int16 unpacked_size[16] =
+{
+    132,  177, 253, 285,
+    317,  365, 397, 461,
+    477,   35,   0,   0,
+    0,    0,   0,   0
+};
+
+/* size of packed frame for each mode, excluding TOC byte */
+const int16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58,
+                               60,  5,  0,  0,  0,  0,  0,  0
+                              };
+
+/* number of unused speech bits in packed format for each mode */
+const int16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0};
+
+/* sorting tables for all modes */
+
+const int16 sort_660[132] =
+{
+    0,   5,   6,   7,  61,  84, 107, 130,  62,  85,
+    8,   4,  37,  38,  39,  40,  58,  81, 104, 127,
+    60,  83, 106, 129, 108, 131, 128,  41,  42,  80,
+    126,   1,   3,  57, 103,  82, 105,  59,   2,  63,
+    109, 110,  86,  19,  22,  23,  64,  87,  18,  20,
+    21,  17,  13,  88,  43,  89,  65, 111,  14,  24,
+    25,  26,  27,  28,  15,  16,  44,  90,  66, 112,
+    9,  11,  10,  12,  67, 113,  29,  30,  31,  32,
+    34,  33,  35,  36,  45,  51,  68,  74,  91,  97,
+    114, 120,  46,  69,  92, 115,  52,  75,  98, 121,
+    47,  70,  93, 116,  53,  76,  99, 122,  48,  71,
+    94, 117,  54,  77, 100, 123,  49,  72,  95, 118,
+    55,  78, 101, 124,  50,  73,  96, 119,  56,  79,
+    102, 125
+};
+
+const int16 sort_885[177] =
+{
+    0,   4,   6,   7,   5,   3,  47,  48,  49, 112,
+    113, 114,  75, 106, 140, 171,  80, 111, 145, 176,
+    77, 108, 142, 173,  78, 109, 143, 174,  79, 110,
+    144, 175,  76, 107, 141, 172,  50, 115,  51,   2,
+    1,  81, 116, 146,  19,  21,  12,  17,  18,  20,
+    16,  25,  13,  10,  14,  24,  23,  22,  26,   8,
+    15,  52, 117,  31,  82, 147,   9,  33,  11,  83,
+    148,  53, 118,  28,  27,  84, 149,  34,  35,  29,
+    46,  32,  30,  54, 119,  37,  36,  39,  38,  40,
+    85, 150,  41,  42,  43,  44,  45,  55,  60,  65,
+    70,  86,  91,  96, 101, 120, 125, 130, 135, 151,
+    156, 161, 166,  56,  87, 121, 152,  61,  92, 126,
+    157,  66,  97, 131, 162,  71, 102, 136, 167,  57,
+    88, 122, 153,  62,  93, 127, 158,  67,  98, 132,
+    163,  72, 103, 137, 168,  58,  89, 123, 154,  63,
+    94, 128, 159,  68,  99, 133, 164,  73, 104, 138,
+    169,  59,  90, 124, 155,  64,  95, 129, 160,  69,
+    100, 134, 165,  74, 105, 139, 170
+};
+
+const int16 sort_1265[253] =
+{
+    0,   4,   6,  93, 143, 196, 246,   7,   5,   3,
+    47,  48,  49,  50,  51, 150, 151, 152, 153, 154,
+    94, 144, 197, 247,  99, 149, 202, 252,  96, 146,
+    199, 249,  97, 147, 200, 250, 100, 203,  98, 148,
+    201, 251,  95, 145, 198, 248,  52,   2,   1, 101,
+    204, 155,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    156,  31, 102, 205,   9,  33,  11, 103, 206,  54,
+    157,  28,  27, 104, 207,  34,  35,  29,  46,  32,
+    30,  55, 158,  37,  36,  39,  38,  40, 105, 208,
+    41,  42,  43,  44,  45,  56, 106, 159, 209,  57,
+    66,  75,  84, 107, 116, 125, 134, 160, 169, 178,
+    187, 210, 219, 228, 237,  58, 108, 161, 211,  62,
+    112, 165, 215,  67, 117, 170, 220,  71, 121, 174,
+    224,  76, 126, 179, 229,  80, 130, 183, 233,  85,
+    135, 188, 238,  89, 139, 192, 242,  59, 109, 162,
+    212,  63, 113, 166, 216,  68, 118, 171, 221,  72,
+    122, 175, 225,  77, 127, 180, 230,  81, 131, 184,
+    234,  86, 136, 189, 239,  90, 140, 193, 243,  60,
+    110, 163, 213,  64, 114, 167, 217,  69, 119, 172,
+    222,  73, 123, 176, 226,  78, 128, 181, 231,  82,
+    132, 185, 235,  87, 137, 190, 240,  91, 141, 194,
+    244,  61, 111, 164, 214,  65, 115, 168, 218,  70,
+    120, 173, 223,  74, 124, 177, 227,  79, 129, 182,
+    232,  83, 133, 186, 236,  88, 138, 191, 241,  92,
+    142, 195, 245
+};
+
+const int16 sort_1425[285] =
+{
+    0,   4,   6, 101, 159, 220, 278,   7,   5,   3,
+    47,  48,  49,  50,  51, 166, 167, 168, 169, 170,
+    102, 160, 221, 279, 107, 165, 226, 284, 104, 162,
+    223, 281, 105, 163, 224, 282, 108, 227, 106, 164,
+    225, 283, 103, 161, 222, 280,  52,   2,   1, 109,
+    228, 171,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    172,  31, 110, 229,   9,  33,  11, 111, 230,  54,
+    173,  28,  27, 112, 231,  34,  35,  29,  46,  32,
+    30,  55, 174,  37,  36,  39,  38,  40, 113, 232,
+    41,  42,  43,  44,  45,  56, 114, 175, 233,  62,
+    120, 181, 239,  75, 133, 194, 252,  57, 115, 176,
+    234,  63, 121, 182, 240,  70, 128, 189, 247,  76,
+    134, 195, 253,  83, 141, 202, 260,  92, 150, 211,
+    269,  84, 142, 203, 261,  93, 151, 212, 270,  85,
+    143, 204, 262,  94, 152, 213, 271,  86, 144, 205,
+    263,  95, 153, 214, 272,  64, 122, 183, 241,  77,
+    135, 196, 254,  65, 123, 184, 242,  78, 136, 197,
+    255,  87, 145, 206, 264,  96, 154, 215, 273,  58,
+    116, 177, 235,  66, 124, 185, 243,  71, 129, 190,
+    248,  79, 137, 198, 256,  88, 146, 207, 265,  97,
+    155, 216, 274,  59, 117, 178, 236,  67, 125, 186,
+    244,  72, 130, 191, 249,  80, 138, 199, 257,  89,
+    147, 208, 266,  98, 156, 217, 275,  60, 118, 179,
+    237,  68, 126, 187, 245,  73, 131, 192, 250,  81,
+    139, 200, 258,  90, 148, 209, 267,  99, 157, 218,
+    276,  61, 119, 180, 238,  69, 127, 188, 246,  74,
+    132, 193, 251,  82, 140, 201, 259,  91, 149, 210,
+    268, 100, 158, 219, 277
+};
+
+const int16 sort_1585[317] =
+{
+    0,   4,   6, 109, 175, 244, 310,   7,   5,   3,
+    47,  48,  49,  50,  51, 182, 183, 184, 185, 186,
+    110, 176, 245, 311, 115, 181, 250, 316, 112, 178,
+    247, 313, 113, 179, 248, 314, 116, 251, 114, 180,
+    249, 315, 111, 177, 246, 312,  52,   2,   1, 117,
+    252, 187,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    188,  31, 118, 253,   9,  33,  11, 119, 254,  54,
+    189,  28,  27, 120, 255,  34,  35,  29,  46,  32,
+    30,  55, 190,  37,  36,  39,  38,  40, 121, 256,
+    41,  42,  43,  44,  45,  56, 122, 191, 257,  63,
+    129, 198, 264,  76, 142, 211, 277,  89, 155, 224,
+    290, 102, 168, 237, 303,  57, 123, 192, 258,  70,
+    136, 205, 271,  83, 149, 218, 284,  96, 162, 231,
+    297,  62, 128, 197, 263,  75, 141, 210, 276,  88,
+    154, 223, 289, 101, 167, 236, 302,  58, 124, 193,
+    259,  71, 137, 206, 272,  84, 150, 219, 285,  97,
+    163, 232, 298,  59, 125, 194, 260,  64, 130, 199,
+    265,  67, 133, 202, 268,  72, 138, 207, 273,  77,
+    143, 212, 278,  80, 146, 215, 281,  85, 151, 220,
+    286,  90, 156, 225, 291,  93, 159, 228, 294,  98,
+    164, 233, 299, 103, 169, 238, 304, 106, 172, 241,
+    307,  60, 126, 195, 261,  65, 131, 200, 266,  68,
+    134, 203, 269,  73, 139, 208, 274,  78, 144, 213,
+    279,  81, 147, 216, 282,  86, 152, 221, 287,  91,
+    157, 226, 292,  94, 160, 229, 295,  99, 165, 234,
+    300, 104, 170, 239, 305, 107, 173, 242, 308,  61,
+    127, 196, 262,  66, 132, 201, 267,  69, 135, 204,
+    270,  74, 140, 209, 275,  79, 145, 214, 280,  82,
+    148, 217, 283,  87, 153, 222, 288,  92, 158, 227,
+    293,  95, 161, 230, 296, 100, 166, 235, 301, 105,
+    171, 240, 306, 108, 174, 243, 309
+};
+
+const int16 sort_1825[365] =
+{
+    0,   4,   6, 121, 199, 280, 358,   7,   5,   3,
+    47,  48,  49,  50,  51, 206, 207, 208, 209, 210,
+    122, 200, 281, 359, 127, 205, 286, 364, 124, 202,
+    283, 361, 125, 203, 284, 362, 128, 287, 126, 204,
+    285, 363, 123, 201, 282, 360,  52,   2,   1, 129,
+    288, 211,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    212,  31, 130, 289,   9,  33,  11, 131, 290,  54,
+    213,  28,  27, 132, 291,  34,  35,  29,  46,  32,
+    30,  55, 214,  37,  36,  39,  38,  40, 133, 292,
+    41,  42,  43,  44,  45,  56, 134, 215, 293, 198,
+    299, 136, 120, 138,  60, 279,  58,  62, 357, 139,
+    140, 295, 156,  57, 219, 297,  63, 217, 137, 170,
+    300, 222,  64, 106,  61,  78, 294,  92, 142, 141,
+    135, 221, 296, 301, 343,  59, 298, 184, 329, 315,
+    220, 216, 265, 251, 218, 237, 352, 223, 157,  86,
+    171,  87, 164, 351, 111, 302,  65, 178, 115, 323,
+    72, 192, 101, 179,  93,  73, 193, 151, 337, 309,
+    143, 274,  69, 324, 165, 150,  97, 338, 110, 310,
+    330, 273,  68, 107, 175, 245, 114,  79, 113, 189,
+    246, 259, 174,  71, 185,  96, 344, 100, 322,  83,
+    334, 316, 333, 252, 161, 348, 147,  82, 269, 232,
+    260, 308, 353, 347, 163, 231, 306, 320, 188, 270,
+    146, 177, 266, 350, 256,  85, 149, 116, 191, 160,
+    238, 258, 336, 305, 255,  88, 224,  99, 339, 230,
+    228, 227, 272, 242, 241, 319, 233, 311, 102,  74,
+    180, 275,  66, 194, 152, 325, 172, 247, 244, 261,
+    117, 158, 166, 354,  75, 144, 108, 312,  94, 186,
+    303,  80, 234,  89, 195, 112, 340, 181, 345, 317,
+    326, 276, 239, 167, 118, 313,  70, 355, 327, 253,
+    190, 176, 271, 104,  98, 153, 103,  90,  76, 267,
+    277, 248, 225, 262, 182,  84, 154, 235, 335, 168,
+    331, 196, 341, 249, 162, 307, 148, 349, 263, 321,
+    257, 243, 229, 356, 159, 119,  67, 187, 173, 145,
+    240,  77, 304, 332, 314, 342, 109, 254,  81, 278,
+    105,  91, 346, 318, 183, 250, 197, 328,  95, 155,
+    169, 268, 226, 236, 264
+};
+
+const int16 sort_1985[397] =
+{
+    0,   4,   6, 129, 215, 304, 390,   7,   5,   3,
+    47,  48,  49,  50,  51, 222, 223, 224, 225, 226,
+    130, 216, 305, 391, 135, 221, 310, 396, 132, 218,
+    307, 393, 133, 219, 308, 394, 136, 311, 134, 220,
+    309, 395, 131, 217, 306, 392,  52,   2,   1, 137,
+    312, 227,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    228,  31, 138, 313,   9,  33,  11, 139, 314,  54,
+    229,  28,  27, 140, 315,  34,  35,  29,  46,  32,
+    30,  55, 230,  37,  36,  39,  38,  40, 141, 316,
+    41,  42,  43,  44,  45,  56, 142, 231, 317,  63,
+    73,  92, 340,  82, 324, 149, 353, 159, 334, 165,
+    338, 178, 163, 254,  77, 168, 257, 153, 343,  57,
+    248, 238,  79, 252, 166,  67,  80, 201, 101, 267,
+    143, 164, 341, 255, 339, 187, 376, 318,  78, 328,
+    362, 115, 232, 242, 253, 290, 276,  62,  58, 158,
+    68,  93, 179, 319, 148, 169, 154,  72, 385, 329,
+    333, 344, 102,  83, 144, 233, 323, 124, 243, 192,
+    354, 237,  64, 247, 202, 209, 150, 116, 335, 268,
+    239, 299, 188, 196, 298,  94, 195, 258, 123, 363,
+    384, 109, 325, 371, 170, 370,  84, 110, 295, 180,
+    74, 210, 191, 106, 291, 205, 367, 381, 377, 206,
+    355, 122, 119, 120, 383, 160, 105, 108, 277, 380,
+    294, 284, 285, 345, 208, 269, 249, 366, 386, 300,
+    297, 259, 125, 369, 197,  97, 194, 286, 211, 281,
+    280, 183, 372,  87, 155, 283,  59, 348, 327, 184,
+    76, 111, 330, 203, 349,  69,  98, 152, 145, 189,
+    66, 320, 337, 173, 358, 251, 198, 174, 263, 262,
+    126, 241, 193,  88, 388, 117,  95, 387, 112, 359,
+    287, 244, 103, 272, 301, 171, 162, 234, 273, 127,
+    373, 181, 292,  85, 378, 302, 121, 107, 364, 346,
+    356, 212, 278, 213,  65, 382, 288, 207, 113, 175,
+    99, 296, 374, 368, 199, 260, 185, 336, 331, 161,
+    270, 264, 250, 240,  75, 350, 151,  60,  89, 321,
+    156, 274, 360, 326,  70, 282, 167, 146, 352,  81,
+    91, 389, 266, 245, 177, 235, 190, 256, 204, 342,
+    128, 118, 303, 104, 379, 182, 114, 375, 200,  96,
+    293, 172, 214, 365, 279,  86, 289, 351, 347, 357,
+    261, 186, 176, 271,  90, 100, 147, 322, 275, 361,
+    71, 332,  61, 265, 157, 246, 236
+};
+
+const int16 sort_2305[461] =
+{
+    0,   4,   6, 145, 247, 352, 454,   7,   5,   3,
+    47,  48,  49,  50,  51, 254, 255, 256, 257, 258,
+    146, 248, 353, 455, 151, 253, 358, 460, 148, 250,
+    355, 457, 149, 251, 356, 458, 152, 359, 150, 252,
+    357, 459, 147, 249, 354, 456,  52,   2,   1, 153,
+    360, 259,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    260,  31, 154, 361,   9,  33,  11, 155, 362,  54,
+    261,  28,  27, 156, 363,  34,  35,  29,  46,  32,
+    30,  55, 262,  37,  36,  39,  38,  40, 157, 364,
+    41,  42,  43,  44,  45,  56, 158, 263, 365, 181,
+    192, 170,  79,  57, 399,  90, 159, 297, 377, 366,
+    275,  68, 183, 388, 286, 194, 299, 92 ,  70, 182,
+    401, 172,  59,  91,  58, 400, 368, 161,  81, 160,
+    264, 171,  80, 389, 390, 378, 379, 193, 298,  69,
+    266, 265, 367, 277, 288, 276, 287, 184,  60, 195,
+    82,  93,  71, 369, 402, 173, 162, 444, 300, 391,
+    98,  76, 278,  61, 267, 374, 135, 411, 167, 102,
+    380, 200,  87, 178,  65,  94, 204, 124,  72, 342,
+    189, 305, 381, 396, 433, 301, 226, 407, 289, 237,
+    113, 215, 185, 128, 309, 403, 116, 320, 196, 331,
+    370, 422, 174,  64, 392,  83, 425, 219, 134, 188,
+    432, 112, 427, 139, 279, 163, 436, 208, 447, 218,
+    236, 229,  97, 294, 385, 230, 166, 268, 177, 443,
+    225, 426, 101, 272, 138, 127, 290, 117, 347, 199,
+    414,  95, 140, 240, 410, 395, 209, 129, 283, 346,
+    105, 241, 437,  86, 308, 448, 203, 345, 186, 107,
+    220, 415, 334, 319, 106, 313, 118, 123,  73, 207,
+    421, 214, 384, 373, 438,  62, 371, 341,  75, 449,
+    168, 323, 164, 242, 416, 324, 304, 197, 335, 404,
+    271,  63, 191, 325,  96, 169, 231, 280, 312, 187,
+    406,  84, 201, 100,  67, 382, 175, 336, 202, 330,
+    269, 393, 376, 383, 293, 307, 409, 179, 285, 314,
+    302, 372, 398, 190, 180,  89,  99, 103, 232,  78,
+    88,  77, 136, 387, 165, 198, 394, 125, 176, 428,
+    74, 375, 238, 227,  66, 273, 282, 141, 306, 412,
+    114,  85, 130, 348, 119, 291, 296, 386, 233, 397,
+    303, 405, 284, 445, 423, 221, 210, 205, 450, 108,
+    274, 434, 216, 343, 337, 142, 243, 321, 408, 451,
+    310, 292, 120, 109, 281, 439, 270, 429, 332, 295,
+    418, 211, 315, 222, 326, 131, 430, 244, 327, 349,
+    417, 316, 143, 338, 440, 234, 110, 212, 452, 245,
+    121, 419, 350, 223, 132, 441, 328, 413, 317, 339,
+    126, 104, 137, 446, 344, 239, 435, 115, 333, 206,
+    322, 217, 228, 424, 453, 311, 351, 111, 442, 224,
+    213, 122, 431, 340, 235, 246, 133, 144, 420, 329,
+    318
+};
+
+const int16 sort_2385[477] =
+{
+    0,   4,   6, 145, 251, 360, 466,   7,   5,   3,
+    47,  48,  49,  50,  51, 262, 263, 264, 265, 266,
+    146, 252, 361, 467, 151, 257, 366, 472, 148, 254,
+    363, 469, 149, 255, 364, 470, 156, 371, 150, 256,
+    365, 471, 147, 253, 362, 468,  52,   2,   1, 157,
+    372, 267,  19,  21,  12,  17,  18,  20,  16,  25,
+    13,  10,  14,  24,  23,  22,  26,   8,  15,  53,
+    268,  31, 152, 153, 154, 155, 258, 259, 260, 261,
+    367, 368, 369, 370, 473, 474, 475, 476, 158, 373,
+    9,  33,  11, 159, 374,  54, 269,  28,  27, 160,
+    375,  34,  35,  29,  46,  32,  30,  55, 270, 37,
+    36,  39,  38,  40, 161, 376,  41,  42,  43,  44,
+    45,  56, 162, 271, 377, 185, 196, 174,  79,  57,
+    411,  90, 163, 305, 389, 378, 283,  68, 187, 400,
+    294, 198, 307,  92,  70, 186, 413, 176,  59,  91,
+    58, 412, 380, 165,  81, 164, 272, 175,  80, 401,
+    402, 390, 391, 197, 306,  69, 274, 273, 379, 285,
+    296, 284, 295, 188,  60, 199,  82,  93,  71, 381,
+    414, 177, 166, 456, 308, 403,  98,  76, 286,  61,
+    275, 386, 135, 423, 171, 102, 392, 204,  87, 182,
+    65,  94, 208, 124,  72, 350, 193, 313, 393, 408,
+    445, 309, 230, 419, 297, 241, 113, 219, 189, 128,
+    317, 415, 116, 328, 200, 339, 382, 434, 178,  64,
+    404,  83, 437, 223, 134, 192, 444, 112, 439, 139,
+    287, 167, 448, 212, 459, 222, 240, 233,  97, 302,
+    397, 234, 170, 276, 181, 455, 229, 438, 101, 280,
+    138, 127, 298, 117, 355, 203, 426,  95, 140, 244,
+    422, 407, 213, 129, 291, 354, 105, 245, 449,  86,
+    316, 460, 207, 353, 190, 107, 224, 427, 342, 327,
+    106, 321, 118, 123,  73, 211, 433, 218, 396, 385,
+    450,  62, 383, 349,  75, 461, 172, 331, 168, 246,
+    428, 332, 312, 201, 343, 416, 279,  63, 195, 333,
+    96, 173, 235, 288, 320, 191, 418,  84, 205, 100,
+    67, 394, 179, 344, 206, 338, 277, 405, 388, 395,
+    301, 315, 421, 183, 293, 322, 310, 384, 410, 194,
+    184,  89,  99, 103, 236,  78,  88,  77, 136, 399,
+    169, 202, 406, 125, 180, 440,  74, 387, 242, 231,
+    66, 281, 290, 141, 314, 424, 114,  85, 130, 356,
+    119, 299, 304, 398, 237, 409, 311, 417, 292, 457,
+    435, 225, 214, 209, 462, 108, 282, 446, 220, 351,
+    345, 142, 247, 329, 420, 463, 318, 300, 120, 109,
+    289, 451, 278, 441, 340, 303, 430, 215, 323, 226,
+    334, 131, 442, 248, 335, 357, 429, 324, 143, 346,
+    452, 238, 110, 216, 464, 249, 121, 431, 358, 227,
+    132, 453, 336, 425, 325, 347, 126, 104, 137, 458,
+    352, 243, 447, 115, 341, 210, 330, 221, 232, 436,
+    465, 319, 359, 111, 454, 228, 217, 122, 443, 348,
+    239, 250, 133, 144, 432, 337, 326
+};
+
+const int16 sort_SID[35] =
+{
+    0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
+    10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+    20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
+    30, 31, 32, 33, 34
+};
+
+
+/*----------------------------------------------------------------------------
+; 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 mime_unsorting(uint8 unsorted_bits[],
+                    int16 sorted_bits_into_int16[],
+                    int16 * frame_type,
+                    int16 * mode,
+                    uint8 quality,
+                    RX_State *st)
+{
+
+    int16 i;
+    int16 j;
+    uint8 temp = 0;
+    uint8 *unsorted_bits_ptr = (uint8*)unsorted_bits;
+
+    /* pointer table for bit sorting tables */
+    const int16 *AmrWbSortingTables[16] =
+    {
+        sort_660,   sort_885, sort_1265, sort_1425,
+        sort_1585,  sort_1825, sort_1985, sort_2305,
+        sort_2385,   sort_SID,      NULL,      NULL,
+        NULL,       NULL,      NULL,      NULL
+    };
+
+    const int16 * pt_AmrWbSortingTables  = AmrWbSortingTables[*mode];
+
+    /* clear compressed speech bit buffer */
+    pv_memset(sorted_bits_into_int16,
+              0,
+              unpacked_size[*mode]*sizeof(*sorted_bits_into_int16));
+
+    /* unpack and unsort speech or SID bits */
+
+
+    for (i = unpacked_size[*mode] >> 3; i != 0; i--)
+    {
+        temp = *(unsorted_bits_ptr++);
+
+        for (j = 2; j != 0; j--)
+        {
+            switch (temp & 0xf0)
+            {
+                case 0xf0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0xe0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    break;
+                case 0xd0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0xc0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables += 2;
+                    break;
+                case 0xb0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0xa0:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    break;
+                case 0x90:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables += 2;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0x80:
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables += 3;
+                    break;
+                case 0x70:
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0x60:
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    break;
+                case 0x50:
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0x40:
+                    pt_AmrWbSortingTables++;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables += 2;
+                    break;
+                case 0x30:
+                    pt_AmrWbSortingTables += 2;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                case 0x20:
+                    pt_AmrWbSortingTables += 2;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    pt_AmrWbSortingTables++;
+                    break;
+                case 0x10:
+                    pt_AmrWbSortingTables += 3;
+                    sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+                    break;
+                default:
+                    pt_AmrWbSortingTables += 4;
+                    break;
+            }
+            temp <<= 4;
+        }
+    }
+
+    if (unpacked_size[*mode] % 4)
+    {
+        temp <<= 1;
+
+        if (temp & 0x80)
+        {
+            sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1;
+        }
+    }
+
+    /* set frame type */
+    switch (*mode)
+    {
+        case MODE_7k:
+        case MODE_9k:
+        case MODE_12k:
+        case MODE_14k:
+        case MODE_16k:
+        case MODE_18k:
+        case MODE_20k:
+        case MODE_23k:
+        case MODE_24k:
+            if (quality)
+            {
+                *frame_type = RX_SPEECH_GOOD;
+            }
+            else
+            {
+                *frame_type = RX_SPEECH_BAD;
+            }
+            break;
+
+        case MRSID:
+            if (quality)
+            {
+                if (temp & 0x80)
+                {
+                    *frame_type = RX_SID_UPDATE;
+                }
+                else
+                {
+                    *frame_type = RX_SID_FIRST;
+                }
+            }
+            else
+            {
+                *frame_type = RX_SID_BAD;
+            }
+
+            /* set mode index */
+            *mode = st->prev_mode;
+            break;
+        case 14:        /* SPEECH_LOST */
+            *frame_type = RX_SPEECH_LOST;
+            *mode = st->prev_mode;
+            break;
+        case 15:        /* NO_DATA */
+            *frame_type = RX_NO_DATA;
+            *mode = st->prev_mode;
+            break;
+        default:        /* replace frame with unused mode index by NO_DATA frame */
+            *frame_type = RX_NO_DATA;
+            *mode = st->prev_mode;
+            break;
+    }
+
+    st->prev_mode = *mode;
+
+}
+
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/mime_io.h b/media/libstagefright/codecs/amrwb/src/mime_io.h
new file mode 100644
index 0000000..3be1d9c
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/mime_io.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/mime_io.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef MIME_IO_H
+#define MIME_IO_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+----------------------------------------------------------------------------*/
+
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+extern const uint8 toc_byte[16];
+
+/* number of speech bits for all modes */
+extern const int16 unpacked_size[16];
+
+/* size of packed frame for each mode, excluding TOC byte */
+extern const int16 packed_size[16];
+
+/* number of unused speech bits in packed format for each mode */
+extern const int16 unused_size[16];
+
+/* sorting tables for all modes */
+
+extern const int16 sort_660[132];
+
+extern const int16 sort_885[177];
+
+extern const int16 sort_1265[253];
+
+extern const int16 sort_1425[285];
+
+extern const int16 sort_1585[317];
+
+extern const int16 sort_1825[365];
+
+extern const int16 sort_1985[397];
+
+extern const int16 sort_2305[461];
+
+extern const int16 sort_2385[477];
+
+extern const int16 sort_SID[35];
+
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+#endif  /* MIME_IO_H */
diff --git a/media/libstagefright/codecs/amrwb/src/noise_gen_amrwb.cpp b/media/libstagefright/codecs/amrwb/src/noise_gen_amrwb.cpp
new file mode 100644
index 0000000..2c1059f
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/noise_gen_amrwb.cpp
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: noise_gen_amrwb.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    int16 * seed          seed for the random ng
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Signed 16 bits random generator
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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
+----------------------------------------------------------------------------*/
+
+int16 noise_gen_amrwb(int16 * seed)
+{
+    /*  int16 seed = 21845; */
+    *seed = (int16)fxp_mac_16by16(*seed, 31821, 13849L);
+
+    return (*seed);
+}
diff --git a/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.cpp b/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.cpp
new file mode 100644
index 0000000..0325311
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.cpp
@@ -0,0 +1,183 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: normalize_amr_wb.cpp
+
+     Date: 12/10/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    Int32 x             32-bit integer non-zero input
+Returns
+    Int16 i             number of leading zeros on x
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns number of leading zeros on the non-zero input
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "normalize_amr_wb.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
+----------------------------------------------------------------------------*/
+
+#if defined(PV_ARM_V5)
+#elif defined(PV_ARM_GCC_V5)
+
+/* function is inlined in header file */
+
+
+#else
+
+int16 normalize_amr_wb(int32 x)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int16 i;
+
+
+    if (x > 0x0FFFFFFF)
+    {
+        i = 0;  /* most likely case */
+    }
+    else if (x > 0x00FFFFFF)
+    {
+        i = 3;  /* second most likely case */
+    }
+    else if (x > 0x0000FFFF)
+    {
+        i  = x > 0x000FFFFF ?  7 :  11;
+    }
+    else
+    {
+        if (x > 0x000000FF)
+        {
+            i  = x > 0x00000FFF ?  15 :  19;
+        }
+        else
+        {
+            i  = x > 0x0000000F ?  23 :  27;
+        }
+    }
+
+
+    x <<= i;
+
+    switch (x & 0x78000000)
+    {
+        case 0x08000000:
+            i += 3;
+            break;
+
+        case 0x18000000:
+        case 0x10000000:
+            i += 2;
+            break;
+        case 0x28000000:
+        case 0x20000000:
+        case 0x38000000:
+        case 0x30000000:
+            i++;
+
+        default:
+            ;
+    }
+
+    return i;
+
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.h b/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.h
new file mode 100644
index 0000000..e4c80ef
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/normalize_amr_wb.h
@@ -0,0 +1,120 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./c/include/normalize_amr_wb.h
+
+     Date: 12/10/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef NORMALIZE_AMR_WB_H
+#define NORMALIZE_AMR_WB_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+#if defined(PV_ARM_V5)
+
+__inline int16 normalize_amr_wb(int32 x)
+{
+    int32 y;
+    __asm
+    {
+        clz y, x;
+        sub y, y, #1
+    }
+    return (y);
+}
+
+
+#elif defined(PV_ARM_GCC_V5)
+
+
+__inline int16 normalize_amr_wb(int32 x)
+{
+    register int32 y;
+    register int32 ra = x;
+
+
+    asm volatile(
+        "clz %0, %1\n\t"
+        "sub %0, %0, #1"
+    : "=&r*i"(y)
+                : "r"(ra));
+    return (y);
+
+}
+
+#else
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int16 normalize_amr_wb(int32 x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
+
+#endif  /* PV_NORMALIZE_H */
diff --git a/media/libstagefright/codecs/amrwb/src/oversamp_12k8_to_16k.cpp b/media/libstagefright/codecs/amrwb/src/oversamp_12k8_to_16k.cpp
new file mode 100644
index 0000000..143c26e
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/oversamp_12k8_to_16k.cpp
@@ -0,0 +1,342 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: oversamp_12k8_to_16k.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 in/out: memory (size=30)
+     int16 x[]                   scratch mem ( size= 60)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Oversamp_16k : oversampling from 12.8kHz to 16kHz.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwbdecoder_cnst.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define FAC4   4
+#define FAC5   5
+#define INV_FAC5   6554                    /* 1/5 in Q15 */
+#define DOWN_FAC  26215                    /* 4/5 in Q15 */
+#define UP_FAC    20480                    /* 5/4 in Q14 */
+#define NB_COEF_DOWN  15
+#define NB_COEF_UP    12
+#define N_LOOP_COEF_UP    4
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    /* Local functions */
+
+    void AmrWbUp_samp(
+        int16 * sig_d,                       /* input:  signal to oversampling  */
+        int16 * sig_u,                       /* output: oversampled signal      */
+        int16 L_frame                        /* input:  length of output        */
+    );
+
+
+    int16 AmrWbInterpol(                      /* return result of interpolation */
+        int16 * x,                           /* input vector                   */
+        const int16 * fir,                   /* filter coefficient             */
+        int16 nb_coef                        /* number of coefficients         */
+    );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+
+/* 1/5 resolution interpolation filter  (in Q14)  */
+/* -1.5dB @ 6kHz,    -6dB @ 6.4kHz, -10dB @ 6.6kHz,
+    -20dB @ 6.9kHz, -25dB @ 7kHz,   -55dB @ 8kHz  */
+
+
+const int16 fir_up[4][24] =
+{
+
+    {
+        -1,        12,       -33,       68,       -119,       191,
+        -291,       430,      -634,       963,     -1616,      3792,
+        15317,     -2496,      1288,      -809,       542,      -369,
+        247,      -160,        96,       -52,        23,        -6,
+    },
+    {
+        -4,        24,       -62,       124,      -213,       338,
+        -510,       752,     -1111,      1708,     -2974,      8219,
+        12368,     -3432,      1881,     -1204,       812,      -552,
+        368,      -235,       139,       -73,        30,        -7,
+    },
+    {
+        -7,        30,       -73,       139,      -235,       368,
+        -552,       812,     -1204,      1881,     -3432,     12368,
+        8219,     -2974,      1708,     -1111,       752,      -510,
+        338,      -213,       124,       -62,        24,        -4,
+    },
+    {
+        -6,        23,       -52,        96,      -160,       247,
+        -369,       542,      -809,      1288,     -2496,     15317,
+        3792,     -1616,       963,      -634,       430,      -291,
+        191,      -119,        68,       -33,        12,        -1,
+    }
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/* output: memory (2*NB_COEF_UP) set to zeros  */
+void oversamp_12k8_to_16k_init(int16 mem[])
+{
+    pv_memset((void *)mem, 0, (2*NB_COEF_UP)*sizeof(*mem));
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void oversamp_12k8_to_16k(
+    int16 sig12k8[],                     /* input:  signal to oversampling  */
+    int16 lg,                            /* input:  length of input         */
+    int16 sig16k[],                      /* output: oversampled signal      */
+    int16 mem[],                         /* in/out: memory (2*NB_COEF_UP)   */
+    int16 signal[]
+)
+{
+    int16 lg_up;
+
+    pv_memcpy((void *)signal,
+              (void *)mem,
+              (2*NB_COEF_UP)*sizeof(*mem));
+
+    pv_memcpy((void *)(signal + (2*NB_COEF_UP)),
+              (void *)sig12k8,
+              lg*sizeof(*sig12k8));
+
+    lg_up = lg + (lg >> 2); /* 5/4 of lg */
+
+    AmrWbUp_samp(signal + NB_COEF_UP, sig16k, lg_up);
+
+    pv_memcpy((void *)mem,
+              (void *)(signal + lg),
+              (2*NB_COEF_UP)*sizeof(*signal));
+
+    return;
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void AmrWbUp_samp(
+    int16 * sig_d,                       /* input:  signal to oversampling  */
+    int16 * sig_u,                       /* output: oversampled signal      */
+    int16 L_frame                        /* input:  length of output        */
+)
+{
+
+    int32 i;
+    int16 frac;
+    int16 * pt_sig_u = sig_u;
+
+    frac = 1;
+    for (int16 j = 0; j < L_frame; j++)
+    {
+        i = ((int32)j * INV_FAC5) >> 13;       /* integer part = pos * 1/5 */
+
+        frac--;
+        if (frac)
+        {
+            *(pt_sig_u++) = AmrWbInterpol(&sig_d[i],
+                                          fir_up[(FAC5-1) - frac],
+                                          N_LOOP_COEF_UP);
+        }
+        else
+        {
+            *(pt_sig_u++) = sig_d[i+12 - NB_COEF_UP ];
+            frac = FAC5;
+        }
+    }
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+/* Fractional interpolation of signal at position (frac/resol) */
+
+
+int16 AmrWbInterpol(                      /* return result of interpolation */
+    int16 * x,                           /* input vector                   */
+    const int16 *fir,                    /* filter coefficient             */
+    int16 nb_coef                        /* number of coefficients         */
+)
+{
+    int32 L_sum;
+    const int16 *pt_fir = fir;
+
+    int16 tmp1, tmp2, tmp3, tmp4;
+    int16 *pt_x = x - nb_coef - (nb_coef << 1) + 1;
+
+
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), 0x00002000L);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+    tmp1 = *(pt_x++);
+    tmp2 = *(pt_x++);
+    tmp3 = *(pt_x++);
+    tmp4 = *(pt_x++);
+    L_sum = fxp_mac_16by16(tmp1, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp2, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp3, *(pt_fir++), L_sum);
+    L_sum = fxp_mac_16by16(tmp4, *(pt_fir++), L_sum);
+
+
+    L_sum = shl_int32(L_sum, 2);               /* saturation can occur here */
+
+    return ((int16(L_sum >> 16)));
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/phase_dispersion.cpp b/media/libstagefright/codecs/amrwb/src/phase_dispersion.cpp
new file mode 100644
index 0000000..f90a534
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/phase_dispersion.cpp
@@ -0,0 +1,261 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: phase_dispersion.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 gain_code,               (i) Q0  : gain of code
+     int16 gain_pit,                (i) Q14 : gain of pitch
+     int16 code[],                  (i/o)   : code vector
+     int16 mode,                    (i)     : level, 0=hi, 1=lo, 2=off
+     int16 disp_mem[],              (i/o)   : static memory (size = 8)
+     int16 ScratchMem[]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    post-processing to enhance noise in low bit rate.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "pvamrwb_math_op.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define pitch_0_9  14746                   /* 0.9 in Q14 */
+#define pitch_0_6  9830                    /* 0.6 in Q14 */
+#define L_SUBFR 64
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/* impulse response with phase dispersion */
+
+/* 2.0 - 6.4 kHz phase dispersion */
+const int16 ph_imp_low[L_SUBFR] =
+{
+    20182,  9693,  3270, -3437, 2864, -5240,  1589, -1357,
+    600,  3893, -1497,  -698, 1203, -5249,  1199,  5371,
+    -1488,  -705, -2887,  1976,  898,   721, -3876,  4227,
+    -5112,  6400, -1032, -4725, 4093, -4352,  3205,  2130,
+    -1996, -1835,  2648, -1786, -406,   573,  2484, -3608,
+    3139, -1363, -2566,  3808, -639, -2051,  -541,  2376,
+    3932, -6262,  1432, -3601, 4889,   370,   567, -1163,
+    -2854,  1914,    39, -2418, 3454,  2975, -4021,  3431
+};
+
+/* 3.2 - 6.4 kHz phase dispersion */
+const int16 ph_imp_mid[L_SUBFR] =
+{
+    24098, 10460, -5263,  -763,  2048,  -927,  1753, -3323,
+    2212,   652, -2146,  2487, -3539,  4109, -2107,  -374,
+    -626,  4270, -5485,  2235,  1858, -2769,   744,  1140,
+    -763, -1615,  4060, -4574,  2982, -1163,   731, -1098,
+    803,   167,  -714,   606,  -560,   639,    43, -1766,
+    3228, -2782,   665,   763,   233, -2002,  1291,  1871,
+    -3470,  1032,  2710, -4040,  3624, -4214,  5292, -4270,
+    1563,   108,  -580,  1642, -2458,   957,  544,   2540
+};
+
+/*----------------------------------------------------------------------------
+; 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 phase_dispersion(
+    int16 gain_code,             /* (i) Q0  : gain of code             */
+    int16 gain_pit,              /* (i) Q14 : gain of pitch            */
+    int16 code[],                /* (i/o)   : code vector              */
+    int16 mode,                  /* (i)     : level, 0=hi, 1=lo, 2=off */
+    int16 disp_mem[],            /* (i/o)   : static memory (size = 8) */
+    int16 ScratchMem[]
+)
+{
+    int16 i, j, state;
+    int16 *prev_gain_pit, *prev_gain_code, *prev_state;
+    int16 *code2 = ScratchMem;
+
+    prev_state = disp_mem;
+    prev_gain_code = disp_mem + 1;
+    prev_gain_pit = disp_mem + 2;
+
+    pv_memset((void *)code2, 0, (2*L_SUBFR)*sizeof(*code2));
+
+
+    if (gain_pit < pitch_0_6)
+    {
+        state = 0;
+    }
+    else if (gain_pit < pitch_0_9)
+    {
+        state = 1;
+    }
+    else
+    {
+        state = 2;
+    }
+
+    for (i = 5; i > 0; i--)
+    {
+        prev_gain_pit[i] = prev_gain_pit[i - 1];
+    }
+    prev_gain_pit[0] = gain_pit;
+
+    if (sub_int16(gain_code, *prev_gain_code) > shl_int16(*prev_gain_code, 1))
+    {
+        /* onset */
+        if (state < 2)
+        {
+            state++;
+        }
+    }
+    else
+    {
+        j = 0;
+        for (i = 0; i < 6; i++)
+        {
+            if (prev_gain_pit[i] < pitch_0_6)
+            {
+                j++;
+            }
+        }
+
+        if (j > 2)
+        {
+            state = 0;
+        }
+        if (state > *prev_state + 1)
+        {
+            state--;
+        }
+    }
+
+    *prev_gain_code = gain_code;
+    *prev_state = state;
+
+    /* circular convolution */
+
+    state += mode;              /* level of dispersion */
+
+    if (state == 0)
+    {
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            if (code[i] != 0)
+            {
+                for (j = 0; j < L_SUBFR; j++)
+                {
+                    code2[i + j] = add_int16(code2[i + j], mult_int16_r(code[i], ph_imp_low[j]));
+                }
+            }
+        }
+    }
+    else if (state == 1)
+    {
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            if (code[i] != 0)
+            {
+                for (j = 0; j < L_SUBFR; j++)
+                {
+                    code2[i + j] = add_int16(code2[i + j], mult_int16_r(code[i], ph_imp_mid[j]));
+                }
+            }
+        }
+    }
+    if (state < 2)
+    {
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            code[i] = add_int16(code2[i], code2[i + L_SUBFR]);
+        }
+    }
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/pit_shrp.cpp b/media/libstagefright/codecs/amrwb/src/pit_shrp.cpp
new file mode 100644
index 0000000..4bfcf9c
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pit_shrp.cpp
@@ -0,0 +1,132 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: pit_shrp.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 * x,           in/out: impulse response (or algebraic code)
+     int16 pit_lag,       input : pitch lag
+     int16 sharp,         input : pitch sharpening factor (Q15)
+     int16 L_subfr        input : subframe size
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Performs Pitch sharpening routine
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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 Pit_shrp(
+    int16 * x,         /* in/out: impulse response (or algebraic code) */
+    int16 pit_lag,     /* input : pitch lag                            */
+    int16 sharp,       /* input : pitch sharpening factor (Q15)        */
+    int16 L_subfr      /* input : subframe size                        */
+)
+{
+    int16 i;
+    int32 L_tmp;
+
+    for (i = pit_lag; i < L_subfr; i++)
+    {
+        L_tmp = mac_16by16_to_int32((int32)x[i] << 16, x[i - pit_lag], sharp);
+        x[i] = amr_wb_round(L_tmp);
+
+    }
+
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/pred_lt4.cpp b/media/libstagefright/codecs/amrwb/src/pred_lt4.cpp
new file mode 100644
index 0000000..d5a7984
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pred_lt4.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: pred_lt4.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             input signal / output is divided by 16
+     int16 lg,                   lenght of signal
+     int16 mem[]                 in/out: memory (size=30)
+     int16 x[]                   scratch mem ( size= 60)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Compute the result of long term prediction with fractionnal
+   interpolation of resolution 1/4.
+
+   On return exc[0..L_subfr-1] contains the interpolated signal
+     (adaptive codebook excitation)
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define UP_SAMP      4
+#define L_INTERPOL2  16
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* 1/4 resolution interpolation filter (-3 dB at 0.856*fs/2) in Q14 */
+
+
+const int16 inter4_2[UP_SAMP][ 2*L_INTERPOL2] =
+{
+    {
+        0,       -2,        4,       -2,      -10,       38,
+        -88,      165,     -275,      424,     -619,      871,
+        -1207,     1699,    -2598,     5531,    14031,    -2147,
+        780,     -249,      -16,      153,     -213,      226,
+        -209,      175,     -133,       91,      -55,       28,
+        -10,        2
+    },
+    {
+        1,       -7,       19,      -33,       47,      -52,
+        43,       -9,      -60,      175,     -355,      626,
+        -1044,     1749,    -3267,    10359,    10359,    -3267,
+        1749,    -1044,      626,     -355,      175,      -60,
+        -9,       43,      -52,       47,      -33,       19,
+        -7,        1
+    },
+    {
+        2,      -10,       28,      -55,       91,     -133,
+        175,     -209,      226,     -213,      153,      -16,
+        -249,      780,    -2147,    14031,     5531,    -2598,
+        1699,    -1207,      871,     -619,      424,     -275,
+        165,      -88,       38,      -10,       -2,        4,
+        -2,        0
+    },
+    {
+        1,       -7,       22,      -49,       92,     -153,
+        231,     -325,      431,     -544,      656,     -762,
+        853,     -923,      968,    15401,      968,     -923,
+        853,     -762,      656,     -544,      431,     -325,
+        231,     -153,       92,      -49,       22,       -7,
+        1,        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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void Pred_lt4(
+    int16 exc[],                         /* in/out: excitation buffer */
+    int16 T0,                            /* input : integer pitch lag */
+    int16 frac,                          /* input : fraction of lag   */
+    int16 L_subfr                        /* input : subframe size     */
+)
+{
+    int16 i, j, *pt_exc;
+    int32 L_sum1;
+    int32 L_sum2;
+    int32 L_sum3;
+    int32 L_sum4;
+    pt_exc = &exc[-T0];
+
+    const int16 *pt_inter4_2;
+
+    frac = -frac;
+
+    if (frac < 0)
+    {
+        frac += UP_SAMP;
+        pt_exc--;
+
+    }
+    pt_exc -= (L_INTERPOL2 - 1);
+
+    pt_inter4_2 = inter4_2[UP_SAMP-1 - frac];
+
+    for (j = 0; j < (L_subfr >> 2); j++)
+    {
+
+        L_sum1 = 0x00002000;  /* pre-roundig */
+        L_sum2 = 0x00002000;
+        L_sum3 = 0x00002000;
+        L_sum4 = 0x00002000;
+
+        for (i = 0; i < L_INTERPOL2 << 1; i += 4)
+        {
+            int16 tmp1 = pt_exc[i  ];
+            int16 tmp2 = pt_exc[i+1];
+            int16 tmp3 = pt_exc[i+2];
+
+
+            L_sum1 = fxp_mac_16by16(tmp1, pt_inter4_2[i  ], L_sum1);
+            L_sum2 = fxp_mac_16by16(tmp2, pt_inter4_2[i  ], L_sum2);
+            L_sum1 = fxp_mac_16by16(tmp2, pt_inter4_2[i+1], L_sum1);
+            L_sum2 = fxp_mac_16by16(tmp3, pt_inter4_2[i+1], L_sum2);
+            L_sum3 = fxp_mac_16by16(tmp3, pt_inter4_2[i  ], L_sum3);
+            L_sum1 = fxp_mac_16by16(tmp3, pt_inter4_2[i+2], L_sum1);
+
+            tmp1 = pt_exc[i+3];
+            tmp2 = pt_exc[i+4];
+
+            L_sum4 = fxp_mac_16by16(tmp1, pt_inter4_2[i  ], L_sum4);
+            L_sum3 = fxp_mac_16by16(tmp1, pt_inter4_2[i+1], L_sum3);
+            L_sum2 = fxp_mac_16by16(tmp1, pt_inter4_2[i+2], L_sum2);
+            L_sum1 = fxp_mac_16by16(tmp1, pt_inter4_2[i+3], L_sum1);
+            L_sum4 = fxp_mac_16by16(tmp2, pt_inter4_2[i+1], L_sum4);
+            L_sum2 = fxp_mac_16by16(tmp2, pt_inter4_2[i+3], L_sum2);
+            L_sum3 = fxp_mac_16by16(tmp2, pt_inter4_2[i+2], L_sum3);
+
+            tmp1 = pt_exc[i+5];
+            tmp2 = pt_exc[i+6];
+
+            L_sum4 = fxp_mac_16by16(tmp1, pt_inter4_2[i+2], L_sum4);
+            L_sum3 = fxp_mac_16by16(tmp1, pt_inter4_2[i+3], L_sum3);
+            L_sum4 = fxp_mac_16by16(tmp2, pt_inter4_2[i+3], L_sum4);
+
+        }
+
+
+
+        exc[(j<<2)] = (int16)(L_sum1 >> 14);
+        exc[(j<<2)+1] = (int16)(L_sum2 >> 14);
+        exc[(j<<2)+2] = (int16)(L_sum3 >> 14);
+        exc[(j<<2)+3] = (int16)(L_sum4 >> 14);
+
+        pt_exc += 4;
+
+    }
+
+    if (L_subfr&1)
+    {
+        L_sum1 = 0x00002000;
+
+        for (i = 0; i < 2*L_INTERPOL2; i += 4)
+        {
+            int16 tmp1 = pt_exc[i  ];
+            int16 tmp2 = pt_exc[i+1];
+            L_sum1 = fxp_mac_16by16(tmp1, pt_inter4_2[i  ], L_sum1);
+            L_sum1 = fxp_mac_16by16(tmp2, pt_inter4_2[i+1], L_sum1);
+            tmp1 = pt_exc[i+2];
+            tmp2 = pt_exc[i+3];
+            L_sum1 = fxp_mac_16by16(tmp1, pt_inter4_2[i+2], L_sum1);
+            L_sum1 = fxp_mac_16by16(tmp2, pt_inter4_2[i+3], L_sum1);
+
+        }
+
+        exc[(j<<2)] = (int16)((L_sum1) >> 14);
+
+    }
+
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/preemph_amrwb_dec.cpp b/media/libstagefright/codecs/amrwb/src/preemph_amrwb_dec.cpp
new file mode 100644
index 0000000..3eb5cda
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/preemph_amrwb_dec.cpp
@@ -0,0 +1,130 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: preemph_amrwb_dec.cpp
+
+     Date: 12/10/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 x[],         (i/o)   : input signal overwritten by the output
+     int16 mu,          (i) Q15 : preemphasis coefficient
+     int16 lg           (i)     : lenght of filtering
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Preemphasis: filtering through 1 - g z^-1
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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 preemph_amrwb_dec(
+    int16 x[],         /* (i/o)   : input signal overwritten by the output */
+    int16 mu,          /* (i) Q15 : preemphasis coefficient                */
+    int16 lg           /* (i)     : lenght of filtering                    */
+)
+{
+    int16 i;
+    int32 L_tmp;
+
+    for (i = lg - 1; i != 0; i--)
+    {
+        L_tmp = msu_16by16_from_int32((int32)x[i] << 16, x[i - 1], mu);
+        x[i] = amr_wb_round(L_tmp);
+    }
+
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/pv_amr_wb_type_defs.h b/media/libstagefright/codecs/amrwb/src/pv_amr_wb_type_defs.h
new file mode 100644
index 0000000..1ebcb86
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pv_amr_wb_type_defs.h
@@ -0,0 +1,173 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/pv_amr_wb_type_defs.h
+
+     Date: 12/12/2006
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file was derived from a number of standards bodies. The type
+ definitions below were created from some of the best practices observed
+ in the standards bodies.
+
+ This file is dependent on limits.h for defining the bit widths. In an
+ ANSI C environment limits.h is expected to always be present and contain
+ the following definitions:
+
+     SCHAR_MIN
+     SCHAR_MAX
+     UCHAR_MAX
+
+     INT_MAX
+     INT_MIN
+     UINT_MAX
+
+     SHRT_MIN
+     SHRT_MAX
+     USHRT_MAX
+
+     LONG_MIN
+     LONG_MAX
+     ULONG_MAX
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_AMR_WB_TYPE_DEFS_H
+#define PV_AMR_WB_TYPE_DEFS_H
+
+#include <stdint.h>
+
+typedef int8_t        Word8;
+typedef uint8_t       UWord8;
+
+/*----------------------------------------------------------------------------
+; Define generic signed and unsigned int
+----------------------------------------------------------------------------*/
+typedef signed int  Int;
+
+typedef unsigned int    UInt;
+
+/*----------------------------------------------------------------------------
+; Define 16 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+#ifndef INT16_MIN
+#define INT16_MIN   (-32768)
+#endif
+
+#ifndef INT16_MAX
+#define INT16_MAX   32767
+#endif
+
+/*----------------------------------------------------------------------------
+; Define 32 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+
+
+#ifndef INT32_MIN
+#define INT32_MIN   (-2147483647 - 1)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX   2147483647
+#endif
+
+
+#ifndef UINT32_MIN
+#define UINT32_MIN  0
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX  0xffffffff
+#endif
+
+
+/*----------------------------------------------------------------------------
+; Define 64 bit signed and unsigned words
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Define boolean type
+----------------------------------------------------------------------------*/
+
+#ifndef Flag
+typedef Int Flag;
+#endif
+
+#ifndef Bool
+typedef Int     Bool;
+#endif
+#ifndef FALSE
+#define FALSE       0
+#endif
+
+#ifndef TRUE
+#define TRUE        1
+#endif
+
+#ifndef OFF
+#define OFF     0
+#endif
+#ifndef ON
+#define ON      1
+#endif
+
+#ifndef NO
+#define NO      0
+#endif
+#ifndef YES
+#define YES     1
+#endif
+
+#ifndef SUCCESS
+#define SUCCESS     0
+#endif
+
+#ifndef  NULL
+#define  NULL       0
+#endif
+
+typedef int16_t int16;
+typedef int32_t int32;
+typedef int64_t int64;
+typedef uint8_t uint8;
+
+#endif  /* PV_AMR_WB_TYPE_DEFS_H */
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.cpp b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.cpp
new file mode 100644
index 0000000..d1ec790
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.cpp
@@ -0,0 +1,627 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*___________________________________________________________________________
+
+    This file contains mathematic operations in fixed point.
+
+    mult_int16_r()     : Same as mult_int16 with rounding
+    shr_rnd()          : Same as shr(var1,var2) but with rounding
+    div_16by16()       : fractional integer division
+    one_ov_sqrt()      : Compute 1/sqrt(L_x)
+    one_ov_sqrt_norm() : Compute 1/sqrt(x)
+    power_of_2()       : power of 2
+    Dot_product12()    : Compute scalar product of <x[],y[]> using accumulator
+    Isqrt()            : inverse square root (16 bits precision).
+    amrwb_log_2()      : log2 (16 bits precision).
+
+    These operations are not standard double precision operations.
+    They are used where low complexity is important and the full 32 bits
+    precision is not necessary. For example, the function Div_32() has a
+    24 bits precision which is enough for our purposes.
+
+    In this file, the values use theses representations:
+
+    int32 L_32     : standard signed 32 bits format
+    int16 hi, lo   : L_32 = hi<<16 + lo<<1  (DPF - Double Precision Format)
+    int32 frac, int16 exp : L_32 = frac << exp-31  (normalised format)
+    int16 int, frac        : L_32 = int.frac        (fractional format)
+ ----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : mult_int16_r
+
+     Purpose :
+
+     Same as mult_int16 with rounding, i.e.:
+       mult_int16_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and
+       mult_int16_r(-32768,-32768) = 32767.
+
+     Complexity weight : 2
+
+     Inputs :
+
+      var1
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+     Outputs :
+
+      none
+
+     Return Value :
+
+      var_out
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+ ----------------------------------------------------------------------------*/
+
+int16 mult_int16_r(int16 var1, int16 var2)
+{
+    int32 L_product_arr;
+
+    L_product_arr = (int32) var1 * (int32) var2;      /* product */
+    L_product_arr += (int32) 0x00004000L;      /* round */
+    L_product_arr >>= 15;       /* shift */
+    if ((L_product_arr >> 15) != (L_product_arr >> 31))
+    {
+        L_product_arr = (L_product_arr >> 31) ^ MAX_16;
+    }
+
+    return ((int16)L_product_arr);
+}
+
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : shr_rnd
+
+     Purpose :
+
+     Same as shr(var1,var2) but with rounding. Saturate the result in case of|
+     underflows or overflows :
+      - If var2 is greater than zero :
+            if (sub(shl_int16(shr(var1,var2),1),shr(var1,sub(var2,1))))
+            is equal to zero
+                       then
+                       shr_rnd(var1,var2) = shr(var1,var2)
+                       else
+                       shr_rnd(var1,var2) = add_int16(shr(var1,var2),1)
+      - If var2 is less than or equal to zero :
+                       shr_rnd(var1,var2) = shr(var1,var2).
+
+     Complexity weight : 2
+
+     Inputs :
+
+      var1
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x0000 0000 <= var2 <= 0x0000 7fff.
+
+     Outputs :
+
+      none
+
+     Return Value :
+
+      var_out
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+ ----------------------------------------------------------------------------*/
+
+int16 shr_rnd(int16 var1, int16 var2)
+{
+    int16 var_out;
+
+    var_out = (int16)(var1 >> (var2 & 0xf));
+    if (var2)
+    {
+        if ((var1 & ((int16) 1 << (var2 - 1))) != 0)
+        {
+            var_out++;
+        }
+    }
+    return (var_out);
+}
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : div_16by16
+
+     Purpose :
+
+     Produces a result which is the fractional integer division of var1  by
+     var2; var1 and var2 must be positive and var2 must be greater or equal
+     to var1; the result is positive (leading bit equal to 0) and truncated
+     to 16 bits.
+     If var1 = var2 then div(var1,var2) = 32767.
+
+     Complexity weight : 18
+
+     Inputs :
+
+      var1
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x0000 0000 <= var1 <= var2 and var2 != 0.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range : var1 <= var2 <= 0x0000 7fff and var2 != 0.
+
+     Outputs :
+
+      none
+
+     Return Value :
+
+      var_out
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x0000 0000 <= var_out <= 0x0000 7fff.
+               It's a Q15 value (point between b15 and b14).
+ ----------------------------------------------------------------------------*/
+
+int16 div_16by16(int16 var1, int16 var2)
+{
+
+    int16 var_out = 0;
+    register int16 iteration;
+    int32 L_num;
+    int32 L_denom;
+    int32 L_denom_by_2;
+    int32 L_denom_by_4;
+
+    if ((var1 > var2) || (var1 < 0))
+    {
+        return 0; // used to exit(0);
+    }
+    if (var1)
+    {
+        if (var1 != var2)
+        {
+
+            L_num = (int32) var1;
+            L_denom = (int32) var2;
+            L_denom_by_2 = (L_denom << 1);
+            L_denom_by_4 = (L_denom << 2);
+            for (iteration = 5; iteration > 0; iteration--)
+            {
+                var_out <<= 3;
+                L_num   <<= 3;
+
+                if (L_num >= L_denom_by_4)
+                {
+                    L_num -= L_denom_by_4;
+                    var_out |= 4;
+                }
+
+                if (L_num >= L_denom_by_2)
+                {
+                    L_num -= L_denom_by_2;
+                    var_out |=  2;
+                }
+
+                if (L_num >= (L_denom))
+                {
+                    L_num -= (L_denom);
+                    var_out |=  1;
+                }
+
+            }
+        }
+        else
+        {
+            var_out = MAX_16;
+        }
+    }
+
+    return (var_out);
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : one_ov_sqrt
+
+         Compute 1/sqrt(L_x).
+         if L_x is negative or zero, result is 1 (7fffffff).
+
+  Algorithm:
+
+     1- Normalization of L_x.
+     2- call Isqrt_n(L_x, exponant)
+     3- L_y = L_x << exponant
+ ----------------------------------------------------------------------------*/
+int32 one_ov_sqrt(     /* (o) Q31 : output value (range: 0<=val<1)         */
+    int32 L_x         /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+)
+{
+    int16 exp;
+    int32 L_y;
+
+    exp = normalize_amr_wb(L_x);
+    L_x <<= exp;                 /* L_x is normalized */
+    exp = 31 - exp;
+
+    one_ov_sqrt_norm(&L_x, &exp);
+
+    L_y = shl_int32(L_x, exp);                 /* denormalization   */
+
+    return (L_y);
+}
+
+/*----------------------------------------------------------------------------
+
+     Function Name : one_ov_sqrt_norm
+
+         Compute 1/sqrt(value).
+         if value is negative or zero, result is 1 (frac=7fffffff, exp=0).
+
+  Algorithm:
+
+     The function 1/sqrt(value) is approximated by a table and linear
+     interpolation.
+
+     1- If exponant is odd then shift fraction right once.
+     2- exponant = -((exponant-1)>>1)
+     3- i = bit25-b30 of fraction, 16 <= i <= 63 ->because of normalization.
+     4- a = bit10-b24
+     5- i -=16
+     6- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+ ----------------------------------------------------------------------------*/
+static const int16 table_isqrt[49] =
+{
+    32767, 31790, 30894, 30070, 29309, 28602, 27945, 27330, 26755, 26214,
+    25705, 25225, 24770, 24339, 23930, 23541, 23170, 22817, 22479, 22155,
+    21845, 21548, 21263, 20988, 20724, 20470, 20225, 19988, 19760, 19539,
+    19326, 19119, 18919, 18725, 18536, 18354, 18176, 18004, 17837, 17674,
+    17515, 17361, 17211, 17064, 16921, 16782, 16646, 16514, 16384
+};
+
+void one_ov_sqrt_norm(
+    int32 * frac,                        /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+    int16 * exp                          /* (i/o)    : exponent (value = frac x 2^exponent) */
+)
+{
+    int16 i, a, tmp;
+
+
+    if (*frac <= (int32) 0)
+    {
+        *exp = 0;
+        *frac = 0x7fffffffL;
+        return;
+    }
+
+    if ((*exp & 1) == 1)  /* If exponant odd -> shift right */
+        *frac >>= 1;
+
+    *exp = negate_int16((*exp -  1) >> 1);
+
+    *frac >>= 9;
+    i = extract_h(*frac);                  /* Extract b25-b31 */
+    *frac >>= 1;
+    a = (int16)(*frac);                  /* Extract b10-b24 */
+    a = (int16)(a & (int16) 0x7fff);
+
+    i -= 16;
+
+    *frac = L_deposit_h(table_isqrt[i]);   /* table[i] << 16         */
+    tmp = table_isqrt[i] - table_isqrt[i + 1];      /* table[i] - table[i+1]) */
+
+    *frac = msu_16by16_from_int32(*frac, tmp, a);          /* frac -=  tmp*a*2       */
+
+    return;
+}
+
+/*----------------------------------------------------------------------------
+
+     Function Name : power_2()
+
+       L_x = pow(2.0, exponant.fraction)         (exponant = interger part)
+           = pow(2.0, 0.fraction) << exponant
+
+  Algorithm:
+
+     The function power_2(L_x) is approximated by a table and linear
+     interpolation.
+
+     1- i = bit10-b15 of fraction,   0 <= i <= 31
+     2- a = bit0-b9   of fraction
+     3- L_x = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+     4- L_x = L_x >> (30-exponant)     (with rounding)
+ ----------------------------------------------------------------------------*/
+const int16 table_pow2[33] =
+{
+    16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911,
+    20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726,
+    25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706,
+    31379, 32066, 32767
+};
+
+int32 power_of_2(                         /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
+    int16 exponant,                      /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+    int16 fraction                       /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+)
+{
+    int16 exp, i, a, tmp;
+    int32 L_x;
+
+    L_x = fraction << 5;          /* L_x = fraction<<6           */
+    i = (fraction >> 10);                  /* Extract b10-b16 of fraction */
+    a = (int16)(L_x);                    /* Extract b0-b9   of fraction */
+    a = (int16)(a & (int16) 0x7fff);
+
+    L_x = ((int32)table_pow2[i]) << 15;    /* table[i] << 16        */
+    tmp = table_pow2[i] - table_pow2[i + 1];        /* table[i] - table[i+1] */
+    L_x -= ((int32)tmp * a);             /* L_x -= tmp*a*2        */
+
+    exp = 29 - exponant ;
+
+    if (exp)
+    {
+        L_x = ((L_x >> exp) + ((L_x >> (exp - 1)) & 1));
+    }
+
+    return (L_x);
+}
+
+/*----------------------------------------------------------------------------
+ *
+ *   Function Name : Dot_product12()
+ *
+ *       Compute scalar product of <x[],y[]> using accumulator.
+ *
+ *       The result is normalized (in Q31) with exponent (0..30).
+ *
+ *  Algorithm:
+ *
+ *       dot_product = sum(x[i]*y[i])     i=0..N-1
+ ----------------------------------------------------------------------------*/
+
+int32 Dot_product12(   /* (o) Q31: normalized result (1 < val <= -1) */
+    int16 x[],        /* (i) 12bits: x vector                       */
+    int16 y[],        /* (i) 12bits: y vector                       */
+    int16 lg,         /* (i)    : vector length                     */
+    int16 * exp       /* (o)    : exponent of result (0..+30)       */
+)
+{
+    int16 i, sft;
+    int32 L_sum;
+    int16 *pt_x = x;
+    int16 *pt_y = y;
+
+    L_sum = 1L;
+
+
+    for (i = lg >> 3; i != 0; i--)
+    {
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+        L_sum = mac_16by16_to_int32(L_sum, *(pt_x++), *(pt_y++));
+    }
+
+    /* Normalize acc in Q31 */
+
+    sft = normalize_amr_wb(L_sum);
+    L_sum <<= sft;
+
+    *exp = 30 - sft;                    /* exponent = 0..30 */
+
+    return (L_sum);
+}
+
+/* Table for Log2() */
+const int16 Log2_norm_table[33] =
+{
+    0, 1455, 2866, 4236, 5568, 6863, 8124, 9352, 10549, 11716,
+    12855, 13967, 15054, 16117, 17156, 18172, 19167, 20142, 21097, 22033,
+    22951, 23852, 24735, 25603, 26455, 27291, 28113, 28922, 29716, 30497,
+    31266, 32023, 32767
+};
+
+/*----------------------------------------------------------------------------
+ *
+ *   FUNCTION:   Lg2_normalized()
+ *
+ *   PURPOSE:   Computes log2(L_x, exp),  where   L_x is positive and
+ *              normalized, and exp is the normalisation exponent
+ *              If L_x is negative or zero, the result is 0.
+ *
+ *   DESCRIPTION:
+ *        The function Log2(L_x) is approximated by a table and linear
+ *        interpolation. The following steps are used to compute Log2(L_x)
+ *
+ *           1- exponent = 30-norm_exponent
+ *           2- i = bit25-b31 of L_x;  32<=i<=63  (because of normalization).
+ *           3- a = bit10-b24
+ *           4- i -=32
+ *           5- fraction = table[i]<<16 - (table[i] - table[i+1]) * a * 2
+ *
+----------------------------------------------------------------------------*/
+void Lg2_normalized(
+    int32 L_x,         /* (i) : input value (normalized)                    */
+    int16 exp,         /* (i) : norm_l (L_x)                                */
+    int16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+    int16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+)
+{
+    int16 i, a, tmp;
+    int32 L_y;
+
+    if (L_x <= (int32) 0)
+    {
+        *exponent = 0;
+        *fraction = 0;;
+        return;
+    }
+
+    *exponent = 30 - exp;
+
+    L_x >>= 9;
+    i = extract_h(L_x);                 /* Extract b25-b31 */
+    L_x >>= 1;
+    a = (int16)(L_x);                 /* Extract b10-b24 of fraction */
+    a &= 0x7fff;
+
+    i -= 32;
+
+    L_y = L_deposit_h(Log2_norm_table[i]);             /* table[i] << 16        */
+    tmp = Log2_norm_table[i] - Log2_norm_table[i + 1]; /* table[i] - table[i+1] */
+    L_y = msu_16by16_from_int32(L_y, tmp, a);           /* L_y -= tmp*a*2        */
+
+    *fraction = extract_h(L_y);
+
+    return;
+}
+
+
+
+/*----------------------------------------------------------------------------
+ *
+ *   FUNCTION:   amrwb_log_2()
+ *
+ *   PURPOSE:   Computes log2(L_x),  where   L_x is positive.
+ *              If L_x is negative or zero, the result is 0.
+ *
+ *   DESCRIPTION:
+ *        normalizes L_x and then calls Lg2_normalized().
+ *
+ ----------------------------------------------------------------------------*/
+void amrwb_log_2(
+    int32 L_x,         /* (i) : input value                                 */
+    int16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+    int16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1) */
+)
+{
+    int16 exp;
+
+    exp = normalize_amr_wb(L_x);
+    Lg2_normalized(shl_int32(L_x, exp), exp, exponent, fraction);
+}
+
+
+/*****************************************************************************
+ *
+ *  These operations are not standard double precision operations.           *
+ *  They are used where single precision is not enough but the full 32 bits  *
+ *  precision is not necessary. For example, the function Div_32() has a     *
+ *  24 bits precision which is enough for our purposes.                      *
+ *                                                                           *
+ *  The double precision numbers use a special representation:               *
+ *                                                                           *
+ *     L_32 = hi<<16 + lo<<1                                                 *
+ *                                                                           *
+ *  L_32 is a 32 bit integer.                                                *
+ *  hi and lo are 16 bit signed integers.                                    *
+ *  As the low part also contains the sign, this allows fast multiplication. *
+ *                                                                           *
+ *      0x8000 0000 <= L_32 <= 0x7fff fffe.                                  *
+ *                                                                           *
+ *  We will use DPF (Double Precision Format )in this file to specify        *
+ *  this special format.                                                     *
+ *****************************************************************************
+*/
+
+
+/*----------------------------------------------------------------------------
+ *
+ *  Function int32_to_dpf()
+ *
+ *  Extract from a 32 bit integer two 16 bit DPF.
+ *
+ *  Arguments:
+ *
+ *   L_32      : 32 bit integer.
+ *               0x8000 0000 <= L_32 <= 0x7fff ffff.
+ *   hi        : b16 to b31 of L_32
+ *   lo        : (L_32 - hi<<16)>>1
+ *
+ ----------------------------------------------------------------------------*/
+
+void int32_to_dpf(int32 L_32, int16 *hi, int16 *lo)
+{
+    *hi = (int16)(L_32 >> 16);
+    *lo = (int16)((L_32 - (*hi << 16)) >> 1);
+    return;
+}
+
+
+/*----------------------------------------------------------------------------
+ * Function mpy_dpf_32()
+ *
+ *   Multiply two 32 bit integers (DPF). The result is divided by 2**31
+ *
+ *   L_32 = (hi1*hi2)<<1 + ( (hi1*lo2)>>15 + (lo1*hi2)>>15 )<<1
+ *
+ *   This operation can also be viewed as the multiplication of two Q31
+ *   number and the result is also in Q31.
+ *
+ * Arguments:
+ *
+ *  hi1         hi part of first number
+ *  lo1         lo part of first number
+ *  hi2         hi part of second number
+ *  lo2         lo part of second number
+ *
+ ----------------------------------------------------------------------------*/
+
+int32 mpy_dpf_32(int16 hi1, int16 lo1, int16 hi2, int16 lo2)
+{
+    int32 L_32;
+
+    L_32 = mul_16by16_to_int32(hi1, hi2);
+    L_32 = mac_16by16_to_int32(L_32, mult_int16(hi1, lo2), 1);
+    L_32 = mac_16by16_to_int32(L_32, mult_int16(lo1, hi2), 1);
+
+    return (L_32);
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
new file mode 100644
index 0000000..8951e5c
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwb_math_op.h
@@ -0,0 +1,132 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/pvamrwb_math_op.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVAMRWB_MATH_OP_H
+#define PVAMRWB_MATH_OP_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; DEFINES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    int32 one_ov_sqrt(      /* (o) Q31 : output value (range: 0<=val<1)         */
+        int32 L_x          /* (i) Q0  : input value  (range: 0<=val<=7fffffff) */
+    );
+    void one_ov_sqrt_norm(
+        int32 * frac,      /* (i/o) Q31: normalized value (1.0 < frac <= 0.5) */
+        int16 * exp        /* (i/o)    : exponent (value = frac x 2^exponent) */
+    );
+    int32 power_of_2(       /* (o) Q0  : result       (range: 0<=val<=0x7fffffff) */
+        int16 exponant,    /* (i) Q0  : Integer part.      (range: 0<=val<=30)   */
+        int16 fraction     /* (i) Q15 : Fractionnal part.  (range: 0.0<=val<1.0) */
+    );
+    int32 Dot_product12(    /* (o) Q31: normalized result (1 < val <= -1) */
+        int16 x[],         /* (i) 12bits: x vector                       */
+        int16 y[],         /* (i) 12bits: y vector                       */
+        int16 lg,          /* (i)    : vector length                     */
+        int16 * exp        /* (o)    : exponent of result (0..+30)       */
+    );
+
+
+    void amrwb_log_2(
+        int32 L_x,        /* (i) : input value                                 */
+        int16 *exponent,  /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        int16 *fraction   /* (o) : Fractional part of Log2. (range: 0<=val<1)*/
+    );
+
+    void Lg2_normalized(
+        int32 L_x,         /* (i) : input value (normalized)                    */
+        int16 exp,         /* (i) : norm_l (L_x)                                */
+        int16 *exponent,   /* (o) : Integer part of Log2.   (range: 0<=val<=30) */
+        int16 *fraction    /* (o) : Fractional part of Log2. (range: 0<=val<1)  */
+    );
+
+
+    int16 mult_int16_r(int16 var1, int16 var2);          /* Mult with round, 2 */
+    int16 shr_rnd(int16 var1, int16 var2);         /* Shift right with round, 2  */
+
+    int16 div_16by16(int16 var1, int16 var2);       /* Short division,       18  */
+
+
+    void int32_to_dpf(int32 L_32, int16 *hi, int16 *lo);
+    int32 mpy_dpf_32(int16 hi1, int16 lo1, int16 hi2, int16 lo2);
+
+
+#define norm_s( x)    (normalize_amr_wb(  x) - 16)
+
+
+#define extract_h( x)    (int16)(x>>16)
+#define L_deposit_h( x)    (int32)(x<<16)
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /*  PVAMRWB_MATH_OP_H */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.cpp b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.cpp
new file mode 100644
index 0000000..b8cfefa
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.cpp
@@ -0,0 +1,1149 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: pvamrwbdecoder.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 mode,                      input : used mode
+     int16 prms[],                    input : parameter vector
+     int16 synth16k[],                output: synthesis speech
+     int16 * frame_length,            output:  lenght of the frame
+     void *spd_state,                 i/o   : State structure
+     int16 frame_type,                input : received frame type
+     int16 ScratchMem[]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Performs the main decoder routine AMR WB ACELP coding algorithm with 20 ms
+   speech frames for wideband speech signals.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "e_pv_amrwbdec.h"
+#include "get_amr_wb_bits.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_api.h"
+#include "pvamrwbdecoder.h"
+#include "synthesis_amr_wb.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+/* LPC interpolation coef {0.45, 0.8, 0.96, 1.0}; in Q15 */
+static const int16 interpol_frac[NB_SUBFR] = {14746, 26214, 31457, 32767};
+
+
+/* isp tables for initialization */
+
+static const int16 isp_init[M] =
+{
+    32138, 30274, 27246, 23170, 18205, 12540, 6393, 0,
+    -6393, -12540, -18205, -23170, -27246, -30274, -32138, 1475
+};
+
+static const int16 isf_init[M] =
+{
+    1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192,
+    9216, 10240, 11264, 12288, 13312, 14336, 15360, 3840
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+ FUNCTION DESCRIPTION   pvDecoder_AmrWb_Init
+
+   Initialization of variables for the decoder section.
+
+----------------------------------------------------------------------------*/
+
+
+
+
+void pvDecoder_AmrWb_Init(void **spd_state, void *pt_st, int16 **ScratchMem)
+{
+    /* Decoder states */
+    Decoder_State *st = &(((PV_AmrWbDec *)pt_st)->state);
+
+    *ScratchMem = ((PV_AmrWbDec *)pt_st)->ScratchMem;
+    /*
+     *  Init dtx decoding
+     */
+    dtx_dec_amr_wb_reset(&(st->dtx_decSt), isf_init);
+
+    pvDecoder_AmrWb_Reset((void *) st, 1);
+
+    *spd_state = (void *) st;
+
+    return;
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void pvDecoder_AmrWb_Reset(void *st, int16 reset_all)
+{
+    int16 i;
+
+    Decoder_State *dec_state;
+
+    dec_state = (Decoder_State *) st;
+
+    pv_memset((void *)dec_state->old_exc,
+              0,
+              (PIT_MAX + L_INTERPOL)*sizeof(*dec_state->old_exc));
+
+    pv_memset((void *)dec_state->past_isfq,
+              0,
+              M*sizeof(*dec_state->past_isfq));
+
+
+    dec_state->old_T0_frac = 0;               /* old pitch value = 64.0 */
+    dec_state->old_T0 = 64;
+    dec_state->first_frame = 1;
+    dec_state->L_gc_thres = 0;
+    dec_state->tilt_code = 0;
+
+    pv_memset((void *)dec_state->disp_mem,
+              0,
+              8*sizeof(*dec_state->disp_mem));
+
+
+    /* scaling memories for excitation */
+    dec_state->Q_old = Q_MAX;
+    dec_state->Qsubfr[3] = Q_MAX;
+    dec_state->Qsubfr[2] = Q_MAX;
+    dec_state->Qsubfr[1] = Q_MAX;
+    dec_state->Qsubfr[0] = Q_MAX;
+
+    if (reset_all != 0)
+    {
+        /* routines initialization */
+
+        dec_gain2_amr_wb_init(dec_state->dec_gain);
+        oversamp_12k8_to_16k_init(dec_state->mem_oversamp);
+        band_pass_6k_7k_init(dec_state->mem_hf);
+        low_pass_filt_7k_init(dec_state->mem_hf3);
+        highpass_50Hz_at_12k8_init(dec_state->mem_sig_out);
+        highpass_400Hz_at_12k8_init(dec_state->mem_hp400);
+        Init_Lagconc(dec_state->lag_hist);
+
+        /* isp initialization */
+
+        pv_memcpy((void *)dec_state->ispold, (void *)isp_init, M*sizeof(*isp_init));
+
+        pv_memcpy((void *)dec_state->isfold, (void *)isf_init, M*sizeof(*isf_init));
+        for (i = 0; i < L_MEANBUF; i++)
+        {
+            pv_memcpy((void *)&dec_state->isf_buf[i * M],
+                      (void *)isf_init,
+                      M*sizeof(*isf_init));
+        }
+        /* variable initialization */
+
+        dec_state->mem_deemph = 0;
+
+        dec_state->seed  = 21845;              /* init random with 21845 */
+        dec_state->seed2 = 21845;
+        dec_state->seed3 = 21845;
+
+        dec_state->state = 0;
+        dec_state->prev_bfi = 0;
+
+        /* Static vectors to zero */
+
+        pv_memset((void *)dec_state->mem_syn_hf,
+                  0,
+                  M16k*sizeof(*dec_state->mem_syn_hf));
+
+        pv_memset((void *)dec_state->mem_syn_hi,
+                  0,
+                  M*sizeof(*dec_state->mem_syn_hi));
+
+        pv_memset((void *)dec_state->mem_syn_lo,
+                  0,
+                  M*sizeof(*dec_state->mem_syn_lo));
+
+
+        dtx_dec_amr_wb_reset(&(dec_state->dtx_decSt), isf_init);
+        dec_state->vad_hist = 0;
+
+    }
+    return;
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+int32 pvDecoder_AmrWbMemRequirements()
+{
+    return(sizeof(PV_AmrWbDec));
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+/*              Main decoder routine.                                       */
+
+int32 pvDecoder_AmrWb(
+    int16 mode,              /* input : used mode                     */
+    int16 prms[],            /* input : parameter vector              */
+    int16 synth16k[],        /* output: synthesis speech              */
+    int16 * frame_length,    /* output:  lenght of the frame          */
+    void *spd_state,         /* i/o   : State structure               */
+    int16 frame_type,        /* input : received frame type           */
+    int16 ScratchMem[]
+)
+{
+
+    /* Decoder states */
+    Decoder_State *st;
+
+    int16 *ScratchMem2 = &ScratchMem[ L_SUBFR + L_SUBFR16k + ((L_SUBFR + M + M16k +1)<<1)];
+
+
+    /* Excitation vector */
+
+
+    int16 *old_exc = ScratchMem2;
+
+    int16 *Aq = &old_exc[(L_FRAME + 1) + PIT_MAX + L_INTERPOL];/* A(z)   quantized for the 4 subframes */
+
+    int16 *ispnew  = &Aq[NB_SUBFR * (M + 1)];/* immittance spectral pairs at 4nd sfr */
+    int16 *isf     = &ispnew[M];             /* ISF (frequency domain) at 4nd sfr    */
+    int16 *isf_tmp = &isf[M];
+    int16 *code    = &isf_tmp[M];             /* algebraic codevector                 */
+    int16 *excp    = &code[L_SUBFR];
+    int16 *exc2    = &excp[L_SUBFR];         /* excitation vector                    */
+    int16 *HfIsf   = &exc2[L_FRAME];
+
+
+    int16 *exc;
+
+    /* LPC coefficients */
+
+    int16 *p_Aq;                          /* ptr to A(z) for the 4 subframes      */
+
+
+
+    int16 fac, stab_fac, voice_fac, Q_new = 0;
+    int32 L_tmp, L_gain_code;
+
+    /* Scalars */
+
+    int16 i, j, i_subfr, index, ind[8], tmp;
+    int32 max;
+    int16 T0, T0_frac, pit_flag, T0_max, select, T0_min = 0;
+    int16 gain_pit, gain_code;
+    int16 newDTXState, bfi, unusable_frame, nb_bits;
+    int16 vad_flag;
+    int16 pit_sharp;
+
+    int16 corr_gain = 0;
+
+    st = (Decoder_State *) spd_state;
+
+    /* mode verification */
+
+    nb_bits = AMR_WB_COMPRESSED[mode];
+
+    *frame_length = AMR_WB_PCM_FRAME;
+
+    /* find the new  DTX state  SPEECH OR DTX */
+    newDTXState = rx_amr_wb_dtx_handler(&(st->dtx_decSt), frame_type);
+
+
+    if (newDTXState != SPEECH)
+    {
+        dtx_dec_amr_wb(&(st->dtx_decSt), exc2, newDTXState, isf, &prms);
+    }
+    /* SPEECH action state machine  */
+
+    if ((frame_type == RX_SPEECH_BAD) ||
+            (frame_type == RX_SPEECH_PROBABLY_DEGRADED))
+    {
+        /* bfi for all index, bits are not usable */
+        bfi = 1;
+        unusable_frame = 0;
+    }
+    else if ((frame_type == RX_NO_DATA) ||
+             (frame_type == RX_SPEECH_LOST))
+    {
+        /* bfi only for lsf, gains and pitch period */
+        bfi = 1;
+        unusable_frame = 1;
+    }
+    else
+    {
+        bfi = 0;
+        unusable_frame = 0;
+    }
+
+    if (bfi != 0)
+    {
+        st->state += 1;
+
+        if (st->state > 6)
+        {
+            st->state = 6;
+        }
+    }
+    else
+    {
+        st->state >>=  1;
+    }
+
+    /* If this frame is the first speech frame after CNI period,
+     * set the BFH state machine to an appropriate state depending
+     * on whether there was DTX muting before start of speech or not
+     * If there was DTX muting, the first speech frame is muted.
+     * If there was no DTX muting, the first speech frame is not
+     * muted. The BFH state machine starts from state 5, however, to
+     * keep the audible noise resulting from a SID frame which is
+     * erroneously interpreted as a good speech frame as small as
+     * possible (the decoder output in this case is quickly muted)
+     */
+
+    if (st->dtx_decSt.dtxGlobalState == DTX)
+    {
+        st->state = 5;
+        st->prev_bfi = 0;
+    }
+    else if (st->dtx_decSt.dtxGlobalState == DTX_MUTE)
+    {
+        st->state = 5;
+        st->prev_bfi = 1;
+    }
+
+    if (newDTXState == SPEECH)
+    {
+        vad_flag = Serial_parm_1bit(&prms);
+
+        if (bfi == 0)
+        {
+            if (vad_flag == 0)
+            {
+                st->vad_hist = add_int16(st->vad_hist, 1);
+            }
+            else
+            {
+                st->vad_hist = 0;
+            }
+        }
+    }
+    /*
+     *  DTX-CNG
+     */
+
+    if (newDTXState != SPEECH)     /* CNG mode */
+    {
+        /* increase slightly energy of noise below 200 Hz */
+
+        /* Convert ISFs to the cosine domain */
+        Isf_isp(isf, ispnew, M);
+
+        Isp_Az(ispnew, Aq, M, 1);
+
+        pv_memcpy((void *)isf_tmp, (void *)st->isfold, M*sizeof(*isf_tmp));
+
+
+        for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+        {
+            j = i_subfr >> 6;
+
+            for (i = 0; i < M; i++)
+            {
+                L_tmp = mul_16by16_to_int32(isf_tmp[i], sub_int16(32767, interpol_frac[j]));
+                L_tmp = mac_16by16_to_int32(L_tmp, isf[i], interpol_frac[j]);
+                HfIsf[i] = amr_wb_round(L_tmp);
+            }
+
+            synthesis_amr_wb(Aq,
+                             &exc2[i_subfr],
+                             0,
+                             &synth16k[i_subfr *5/4],
+                             (short) 1,
+                             HfIsf,
+                             nb_bits,
+                             newDTXState,
+                             st,
+                             bfi,
+                             ScratchMem);
+        }
+
+        /* reset speech coder memories */
+        pvDecoder_AmrWb_Reset(st, 0);
+
+        pv_memcpy((void *)st->isfold, (void *)isf, M*sizeof(*isf));
+
+        st->prev_bfi = bfi;
+        st->dtx_decSt.dtxGlobalState = newDTXState;
+
+        return 0;
+    }
+    /*
+     *  ACELP
+     */
+
+    /* copy coder memory state into working space (internal memory for DSP) */
+
+    pv_memcpy((void *)old_exc, (void *)st->old_exc, (PIT_MAX + L_INTERPOL)*sizeof(*old_exc));
+
+    exc = old_exc + PIT_MAX + L_INTERPOL;
+
+    /* Decode the ISFs */
+
+    if (nb_bits > NBBITS_7k)        /* all rates but 6.6 Kbps */
+    {
+        ind[0] = Serial_parm(8, &prms);     /* index of 1st ISP subvector */
+        ind[1] = Serial_parm(8, &prms);     /* index of 2nd ISP subvector */
+        ind[2] = Serial_parm(6, &prms);     /* index of 3rd ISP subvector */
+        ind[3] = Serial_parm(7, &prms);     /* index of 4th ISP subvector */
+        ind[4] = Serial_parm(7, &prms);     /* index of 5th ISP subvector */
+        ind[5] = Serial_parm(5, &prms);     /* index of 6th ISP subvector */
+        ind[6] = Serial_parm(5, &prms);     /* index of 7th ISP subvector */
+
+        Dpisf_2s_46b(ind, isf, st->past_isfq, st->isfold, st->isf_buf, bfi, 1);
+    }
+    else
+    {
+        ind[0] = Serial_parm(8, &prms);
+        ind[1] = Serial_parm(8, &prms);
+        ind[2] = Serial_parm(14, &prms);
+        ind[3] = ind[2] & 0x007F;
+        ind[2] >>= 7;
+        ind[4] = Serial_parm(6, &prms);
+
+        Dpisf_2s_36b(ind, isf, st->past_isfq, st->isfold, st->isf_buf, bfi, 1);
+    }
+
+    /* Convert ISFs to the cosine domain */
+
+    Isf_isp(isf, ispnew, M);
+
+    if (st->first_frame != 0)
+    {
+        st->first_frame = 0;
+        pv_memcpy((void *)st->ispold, (void *)ispnew, M*sizeof(*ispnew));
+
+    }
+    /* Find the interpolated ISPs and convert to a[] for all subframes */
+    interpolate_isp(st->ispold, ispnew, interpol_frac, Aq);
+
+    /* update ispold[] for the next frame */
+    pv_memcpy((void *)st->ispold, (void *)ispnew, M*sizeof(*ispnew));
+
+    /* Check stability on isf : distance between old isf and current isf */
+
+    L_tmp = 0;
+    for (i = 0; i < M - 1; i++)
+    {
+        tmp = sub_int16(isf[i], st->isfold[i]);
+        L_tmp = mac_16by16_to_int32(L_tmp, tmp, tmp);
+    }
+    tmp = extract_h(shl_int32(L_tmp, 8));
+    tmp = mult_int16(tmp, 26214);                /* tmp = L_tmp*0.8/256 */
+
+    tmp = 20480 - tmp;                 /* 1.25 - tmp */
+    stab_fac = shl_int16(tmp, 1);                /* Q14 -> Q15 with saturation */
+
+    if (stab_fac < 0)
+    {
+        stab_fac = 0;
+    }
+    pv_memcpy((void *)isf_tmp, (void *)st->isfold, M*sizeof(*isf_tmp));
+
+    pv_memcpy((void *)st->isfold, (void *)isf, M*sizeof(*isf));
+
+    /*
+     *          Loop for every subframe in the analysis frame
+     *
+     * The subframe size is L_SUBFR and the loop is repeated L_FRAME/L_SUBFR
+     *  times
+     *     - decode the pitch delay and filter mode
+     *     - decode algebraic code
+     *     - decode pitch and codebook gains
+     *     - find voicing factor and tilt of code for next subframe.
+     *     - find the excitation and compute synthesis speech
+     */
+
+    p_Aq = Aq;                                /* pointer to interpolated LPC parameters */
+
+
+    /*
+     *   Sub process next 3 subframes
+     */
+
+
+    for (i_subfr = 0; i_subfr < L_FRAME; i_subfr += L_SUBFR)
+    {
+        pit_flag = i_subfr;
+
+
+        if ((i_subfr == 2*L_SUBFR) && (nb_bits > NBBITS_7k))
+        {
+            pit_flag = 0;        /* set to 0 for 3rd subframe, <=> is not 6.6 kbps */
+        }
+        /*-------------------------------------------------*
+         * - Decode pitch lag                              *
+         * Lag indeces received also in case of BFI,       *
+         * so that the parameter pointer stays in sync.    *
+         *-------------------------------------------------*/
+
+        if (pit_flag == 0)
+        {
+
+            if (nb_bits <= NBBITS_9k)
+            {
+                index = Serial_parm(8, &prms);
+
+                if (index < (PIT_FR1_8b - PIT_MIN) * 2)
+                {
+                    T0 = PIT_MIN + (index >> 1);
+                    T0_frac = sub_int16(index, shl_int16(sub_int16(T0, PIT_MIN), 1));
+                    T0_frac = shl_int16(T0_frac, 1);
+                }
+                else
+                {
+                    T0 = add_int16(index, PIT_FR1_8b - ((PIT_FR1_8b - PIT_MIN) * 2));
+                    T0_frac = 0;
+                }
+            }
+            else
+            {
+                index = Serial_parm(9, &prms);
+
+                if (index < (PIT_FR2 - PIT_MIN) * 4)
+                {
+                    T0 = PIT_MIN + (index >> 2);
+                    T0_frac = sub_int16(index, shl_int16(sub_int16(T0, PIT_MIN), 2));
+                }
+                else if (index < (((PIT_FR2 - PIT_MIN) << 2) + ((PIT_FR1_9b - PIT_FR2) << 1)))
+                {
+                    index -= (PIT_FR2 - PIT_MIN) << 2;
+                    T0 = PIT_FR2 + (index >> 1);
+                    T0_frac = sub_int16(index, shl_int16(sub_int16(T0, PIT_FR2), 1));
+                    T0_frac = shl_int16(T0_frac, 1);
+                }
+                else
+                {
+                    T0 = add_int16(index, (PIT_FR1_9b - ((PIT_FR2 - PIT_MIN) * 4) - ((PIT_FR1_9b - PIT_FR2) * 2)));
+                    T0_frac = 0;
+                }
+            }
+
+            /* find T0_min and T0_max for subframe 2 and 4 */
+
+            T0_min = T0 - 8;
+
+            if (T0_min < PIT_MIN)
+            {
+                T0_min = PIT_MIN;
+            }
+            T0_max = T0_min + 15;
+
+            if (T0_max > PIT_MAX)
+            {
+                T0_max = PIT_MAX;
+                T0_min = PIT_MAX - 15;
+            }
+        }
+        else
+        {                                  /* if subframe 2 or 4 */
+
+            if (nb_bits <= NBBITS_9k)
+            {
+                index = Serial_parm(5, &prms);
+
+                T0 = T0_min + (index >> 1);
+                T0_frac = sub_int16(index, shl_int16(T0 - T0_min, 1));
+                T0_frac = shl_int16(T0_frac, 1);
+            }
+            else
+            {
+                index = Serial_parm(6, &prms);
+
+                T0 = T0_min + (index >> 2);
+                T0_frac = sub_int16(index, shl_int16(T0 - T0_min, 2));
+            }
+        }
+
+        /* check BFI after pitch lag decoding */
+
+        if (bfi != 0)                      /* if frame erasure */
+        {
+            lagconceal(&(st->dec_gain[17]), st->lag_hist, &T0, &(st->old_T0), &(st->seed3), unusable_frame);
+            T0_frac = 0;
+        }
+        /*
+         *  Find the pitch gain, the interpolation filter
+         *  and the adaptive codebook vector.
+         */
+
+        Pred_lt4(&exc[i_subfr], T0, T0_frac, L_SUBFR + 1);
+
+
+        if (unusable_frame)
+        {
+            select = 1;
+        }
+        else
+        {
+
+            if (nb_bits <= NBBITS_9k)
+            {
+                select = 0;
+            }
+            else
+            {
+                select = Serial_parm_1bit(&prms);
+            }
+        }
+
+
+        if (select == 0)
+        {
+            /* find pitch excitation with lp filter */
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                L_tmp  = ((int32) exc[i-1+i_subfr] + exc[i+1+i_subfr]);
+                L_tmp *= 5898;
+                L_tmp += ((int32) exc[i+i_subfr] * 20972);
+
+                code[i] = amr_wb_round(L_tmp << 1);
+            }
+            pv_memcpy((void *)&exc[i_subfr], (void *)code, L_SUBFR*sizeof(*code));
+
+        }
+        /*
+         * Decode innovative codebook.
+         * Add the fixed-gain pitch contribution to code[].
+         */
+
+        if (unusable_frame != 0)
+        {
+            /* the innovative code doesn't need to be scaled (see Q_gain2) */
+            for (i = 0; i < L_SUBFR; i++)
+            {
+                code[i] = noise_gen_amrwb(&(st->seed)) >> 3;
+            }
+        }
+        else if (nb_bits <= NBBITS_7k)
+        {
+            ind[0] = Serial_parm(12, &prms);
+            dec_acelp_2p_in_64(ind[0], code);
+        }
+        else if (nb_bits <= NBBITS_9k)
+        {
+            for (i = 0; i < 4; i++)
+            {
+                ind[i] = Serial_parm(5, &prms);
+            }
+            dec_acelp_4p_in_64(ind, 20, code);
+        }
+        else if (nb_bits <= NBBITS_12k)
+        {
+            for (i = 0; i < 4; i++)
+            {
+                ind[i] = Serial_parm(9, &prms);
+            }
+            dec_acelp_4p_in_64(ind, 36, code);
+        }
+        else if (nb_bits <= NBBITS_14k)
+        {
+            ind[0] = Serial_parm(13, &prms);
+            ind[1] = Serial_parm(13, &prms);
+            ind[2] = Serial_parm(9, &prms);
+            ind[3] = Serial_parm(9, &prms);
+            dec_acelp_4p_in_64(ind, 44, code);
+        }
+        else if (nb_bits <= NBBITS_16k)
+        {
+            for (i = 0; i < 4; i++)
+            {
+                ind[i] = Serial_parm(13, &prms);
+            }
+            dec_acelp_4p_in_64(ind, 52, code);
+        }
+        else if (nb_bits <= NBBITS_18k)
+        {
+            for (i = 0; i < 4; i++)
+            {
+                ind[i] = Serial_parm(2, &prms);
+            }
+            for (i = 4; i < 8; i++)
+            {
+                ind[i] = Serial_parm(14, &prms);
+            }
+            dec_acelp_4p_in_64(ind, 64, code);
+        }
+        else if (nb_bits <= NBBITS_20k)
+        {
+            ind[0] = Serial_parm(10, &prms);
+            ind[1] = Serial_parm(10, &prms);
+            ind[2] = Serial_parm(2, &prms);
+            ind[3] = Serial_parm(2, &prms);
+            ind[4] = Serial_parm(10, &prms);
+            ind[5] = Serial_parm(10, &prms);
+            ind[6] = Serial_parm(14, &prms);
+            ind[7] = Serial_parm(14, &prms);
+            dec_acelp_4p_in_64(ind, 72, code);
+        }
+        else
+        {
+            for (i = 0; i < 8; i++)
+            {
+                ind[i] = Serial_parm(11, &prms);
+            }
+
+            dec_acelp_4p_in_64(ind, 88, code);
+        }
+
+        preemph_amrwb_dec(code, st->tilt_code, L_SUBFR);
+
+        tmp = T0;
+
+        if (T0_frac > 2)
+        {
+            tmp++;
+        }
+        Pit_shrp(code, tmp, PIT_SHARP, L_SUBFR);
+
+        /*
+         *  Decode codebooks gains.
+         */
+
+        if (nb_bits <= NBBITS_9k)
+        {
+            index = Serial_parm(6, &prms); /* codebook gain index */
+
+            dec_gain2_amr_wb(index,
+                             6,
+                             code,
+                             L_SUBFR,
+                             &gain_pit,
+                             &L_gain_code,
+                             bfi,
+                             st->prev_bfi,
+                             st->state,
+                             unusable_frame,
+                             st->vad_hist,
+                             st->dec_gain);
+        }
+        else
+        {
+            index = Serial_parm(7, &prms); /* codebook gain index */
+
+            dec_gain2_amr_wb(index,
+                             7,
+                             code,
+                             L_SUBFR,
+                             &gain_pit,
+                             &L_gain_code,
+                             bfi,
+                             st->prev_bfi,
+                             st->state,
+                             unusable_frame,
+                             st->vad_hist,
+                             st->dec_gain);
+        }
+
+        /* find best scaling to perform on excitation (Q_new) */
+
+        tmp = st->Qsubfr[0];
+        for (i = 1; i < 4; i++)
+        {
+            if (st->Qsubfr[i] < tmp)
+            {
+                tmp = st->Qsubfr[i];
+            }
+        }
+
+        /* limit scaling (Q_new) to Q_MAX: see pv_amr_wb_cnst.h and syn_filt_32() */
+
+        if (tmp > Q_MAX)
+        {
+            tmp = Q_MAX;
+        }
+        Q_new = 0;
+        L_tmp = L_gain_code;                  /* L_gain_code in Q16 */
+
+
+        while ((L_tmp < 0x08000000L) && (Q_new < tmp))
+        {
+            L_tmp <<= 1;
+            Q_new += 1;
+
+        }
+        gain_code = amr_wb_round(L_tmp);          /* scaled gain_code with Qnew */
+
+        scale_signal(exc + i_subfr - (PIT_MAX + L_INTERPOL),
+                     PIT_MAX + L_INTERPOL + L_SUBFR,
+                     (int16)(Q_new - st->Q_old));
+
+        st->Q_old = Q_new;
+
+
+        /*
+         * Update parameters for the next subframe.
+         * - tilt of code: 0.0 (unvoiced) to 0.5 (voiced)
+         */
+
+
+        if (bfi == 0)
+        {
+            /* LTP-Lag history update */
+            for (i = 4; i > 0; i--)
+            {
+                st->lag_hist[i] = st->lag_hist[i - 1];
+            }
+            st->lag_hist[0] = T0;
+
+            st->old_T0 = T0;
+            st->old_T0_frac = 0;              /* Remove fraction in case of BFI */
+        }
+        /* find voice factor in Q15 (1=voiced, -1=unvoiced) */
+
+        /*
+         * Scale down by 1/8
+         */
+        for (i = L_SUBFR - 1; i >= 0; i--)
+        {
+            exc2[i] = (exc[i_subfr + i] + (0x0004 * (exc[i_subfr + i] != MAX_16))) >> 3;
+        }
+
+
+        /* post processing of excitation elements */
+
+        if (nb_bits <= NBBITS_9k)
+        {
+            pit_sharp = shl_int16(gain_pit, 1);
+
+            if (pit_sharp > 16384)
+            {
+                for (i = 0; i < L_SUBFR; i++)
+                {
+                    tmp = mult_int16(exc2[i], pit_sharp);
+                    L_tmp = mul_16by16_to_int32(tmp, gain_pit);
+                    L_tmp >>= 1;
+                    excp[i] = amr_wb_round(L_tmp);
+                }
+            }
+        }
+        else
+        {
+            pit_sharp = 0;
+        }
+
+        voice_fac = voice_factor(exc2, -3, gain_pit, code, gain_code, L_SUBFR);
+
+        /* tilt of code for next subframe: 0.5=voiced, 0=unvoiced */
+
+        st->tilt_code = (voice_fac >> 2) + 8192;
+
+        /*
+         * - Find the total excitation.
+         * - Find synthesis speech corresponding to exc[].
+         * - Find maximum value of excitation for next scaling
+         */
+
+        pv_memcpy((void *)exc2, (void *)&exc[i_subfr], L_SUBFR*sizeof(*exc2));
+        max = 1;
+
+        for (i = 0; i < L_SUBFR; i++)
+        {
+            L_tmp = mul_16by16_to_int32(code[i], gain_code);
+            L_tmp = shl_int32(L_tmp, 5);
+            L_tmp = mac_16by16_to_int32(L_tmp, exc[i + i_subfr], gain_pit);
+            L_tmp = shl_int32(L_tmp, 1);
+            tmp = amr_wb_round(L_tmp);
+            exc[i + i_subfr] = tmp;
+            tmp = tmp - (tmp < 0);
+            max |= tmp ^(tmp >> 15);  /* |= tmp ^sign(tmp) */
+        }
+
+
+        /* tmp = scaling possible according to max value of excitation */
+        tmp = add_int16(norm_s(max), Q_new) - 1;
+
+        st->Qsubfr[3] = st->Qsubfr[2];
+        st->Qsubfr[2] = st->Qsubfr[1];
+        st->Qsubfr[1] = st->Qsubfr[0];
+        st->Qsubfr[0] = tmp;
+
+        /*
+         * phase dispersion to enhance noise in low bit rate
+         */
+
+
+        if (nb_bits <= NBBITS_7k)
+        {
+            j = 0;      /* high dispersion for rate <= 7.5 kbit/s */
+        }
+        else if (nb_bits <= NBBITS_9k)
+        {
+            j = 1;      /* low dispersion for rate <= 9.6 kbit/s */
+        }
+        else
+        {
+            j = 2;      /* no dispersion for rate > 9.6 kbit/s */
+        }
+
+        /* L_gain_code in Q16 */
+
+        phase_dispersion((int16)(L_gain_code >> 16),
+                         gain_pit,
+                         code,
+                         j,
+                         st->disp_mem,
+                         ScratchMem);
+
+        /*
+         * noise enhancer
+         * - Enhance excitation on noise. (modify gain of code)
+         *   If signal is noisy and LPC filter is stable, move gain
+         *   of code 1.5 dB toward gain of code threshold.
+         *   This decrease by 3 dB noise energy variation.
+         */
+
+        tmp = 16384 - (voice_fac >> 1);  /* 1=unvoiced, 0=voiced */
+        fac = mult_int16(stab_fac, tmp);
+
+        L_tmp = L_gain_code;
+
+        if (L_tmp < st->L_gc_thres)
+        {
+            L_tmp += fxp_mul32_by_16b(L_gain_code, 6226) << 1;
+
+            if (L_tmp > st->L_gc_thres)
+            {
+                L_tmp = st->L_gc_thres;
+            }
+        }
+        else
+        {
+            L_tmp = fxp_mul32_by_16b(L_gain_code, 27536) << 1;
+
+            if (L_tmp < st->L_gc_thres)
+            {
+                L_tmp = st->L_gc_thres;
+            }
+        }
+        st->L_gc_thres = L_tmp;
+
+        L_gain_code = fxp_mul32_by_16b(L_gain_code, (32767 - fac)) << 1;
+
+
+        L_gain_code = add_int32(L_gain_code, fxp_mul32_by_16b(L_tmp, fac) << 1);
+
+        /*
+         * pitch enhancer
+         * - Enhance excitation on voice. (HP filtering of code)
+         *   On voiced signal, filtering of code by a smooth fir HP
+         *   filter to decrease energy of code in low frequency.
+         */
+
+        tmp = (voice_fac >> 3) + 4096;/* 0.25=voiced, 0=unvoiced */
+
+        /* build excitation */
+
+        gain_code = amr_wb_round(shl_int32(L_gain_code, Q_new));
+
+        L_tmp = (int32)(code[0] << 16);
+        L_tmp = msu_16by16_from_int32(L_tmp, code[1], tmp);
+        L_tmp = mul_16by16_to_int32(amr_wb_round(L_tmp), gain_code);
+        L_tmp = shl_int32(L_tmp, 5);
+        L_tmp = mac_16by16_to_int32(L_tmp, exc2[0], gain_pit);
+        L_tmp = shl_int32(L_tmp, 1);       /* saturation can occur here */
+        exc2[0] = amr_wb_round(L_tmp);
+
+
+        for (i = 1; i < L_SUBFR - 1; i++)
+        {
+            L_tmp = (int32)(code[i] << 16);
+            L_tmp = msu_16by16_from_int32(L_tmp, (code[i + 1] + code[i - 1]), tmp);
+            L_tmp = mul_16by16_to_int32(amr_wb_round(L_tmp), gain_code);
+            L_tmp = shl_int32(L_tmp, 5);
+            L_tmp = mac_16by16_to_int32(L_tmp, exc2[i], gain_pit);
+            L_tmp = shl_int32(L_tmp, 1);       /* saturation can occur here */
+            exc2[i] = amr_wb_round(L_tmp);
+        }
+
+        L_tmp = (int32)(code[L_SUBFR - 1] << 16);
+        L_tmp = msu_16by16_from_int32(L_tmp, code[L_SUBFR - 2], tmp);
+        L_tmp = mul_16by16_to_int32(amr_wb_round(L_tmp), gain_code);
+        L_tmp = shl_int32(L_tmp, 5);
+        L_tmp = mac_16by16_to_int32(L_tmp, exc2[L_SUBFR - 1], gain_pit);
+        L_tmp = shl_int32(L_tmp, 1);       /* saturation can occur here */
+        exc2[L_SUBFR - 1] = amr_wb_round(L_tmp);
+
+
+
+        if (nb_bits <= NBBITS_9k)
+        {
+            if (pit_sharp > 16384)
+            {
+                for (i = 0; i < L_SUBFR; i++)
+                {
+                    excp[i] = add_int16(excp[i], exc2[i]);
+                }
+                agc2_amr_wb(exc2, excp, L_SUBFR);
+                pv_memcpy((void *)exc2, (void *)excp, L_SUBFR*sizeof(*exc2));
+
+            }
+        }
+        if (nb_bits <= NBBITS_7k)
+        {
+            j = i_subfr >> 6;
+            for (i = 0; i < M; i++)
+            {
+                L_tmp = mul_16by16_to_int32(isf_tmp[i], sub_int16(32767, interpol_frac[j]));
+                L_tmp = mac_16by16_to_int32(L_tmp, isf[i], interpol_frac[j]);
+                HfIsf[i] = amr_wb_round(L_tmp);
+            }
+        }
+        else
+        {
+            pv_memset((void *)st->mem_syn_hf,
+                      0,
+                      (M16k - M)*sizeof(*st->mem_syn_hf));
+        }
+
+        if (nb_bits >= NBBITS_24k)
+        {
+            corr_gain = Serial_parm(4, &prms);
+        }
+        else
+        {
+            corr_gain = 0;
+        }
+
+        synthesis_amr_wb(p_Aq,
+                         exc2,
+                         Q_new,
+                         &synth16k[i_subfr + (i_subfr>>2)],
+                         corr_gain,
+                         HfIsf,
+                         nb_bits,
+                         newDTXState,
+                         st,
+                         bfi,
+                         ScratchMem);
+
+        p_Aq += (M + 1);                   /* interpolated LPC parameters for next subframe */
+    }
+
+    /*
+     *   Update signal for next frame.
+     *   -> save past of exc[]
+     *   -> save pitch parameters
+     */
+
+    pv_memcpy((void *)st->old_exc,
+              (void *)&old_exc[L_FRAME],
+              (PIT_MAX + L_INTERPOL)*sizeof(*old_exc));
+
+    scale_signal(exc, L_FRAME, (int16)(-Q_new));
+
+    dtx_dec_amr_wb_activity_update(&(st->dtx_decSt), isf, exc);
+
+    st->dtx_decSt.dtxGlobalState = newDTXState;
+
+    st->prev_bfi = bfi;
+
+    return 0;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.h
new file mode 100644
index 0000000..433fc92
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder.h
@@ -0,0 +1,158 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Name: pvamrwbdecoder.h
+
+     Date: 05/02/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Main header file for the Packet Video AMR Wide  Band  decoder library. The
+ constants, structures, and functions defined within this file, along with
+ a basic data types header file, is all that is needed to use and communicate
+ with the library. The internal data structures within the library are
+ purposely hidden.
+
+ ---* Need description of the input buffering. *-------
+
+ ---* Need an example of calling the library here *----
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (Normally header files do not have a reference section)
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef _PVAMRWBDECODER_H
+#define _PVAMRWBDECODER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_amr_wb_type_defs.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
+    ----------------------------------------------------------------------------*/
+
+typedef struct
+{
+    int16 prev_ft;
+    int16 prev_mode;
+} RX_State;
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    void pvDecoder_AmrWb_Init(void **spd_state, void *st, int16 ** ScratchMem);
+
+    int32 pvDecoder_AmrWb(
+        int16 mode,                          /* input : used mode             */
+        int16 prms[],                        /* input : parameter vector      */
+        int16 synth16k[],                    /* output: synthesis speech      */
+        int16 * frame_length,                /* output:  lenght of the frame  */
+        void *spd_state,                     /* i/o   : State structure       */
+        int16 frame_type,                    /* input : received frame type   */
+        int16 ScratchMem[]
+    );
+
+    void pvDecoder_AmrWb_Reset(void *st, int16 reset_all);
+
+    int16 pvDecoder_AmrWb_homing_frame_test(int16 input_frame[], int16 mode);
+
+    int16 pvDecoder_AmrWb_homing_frame_test_first(int16 input_frame[], int16 mode);
+
+    int32 pvDecoder_AmrWbMemRequirements();
+
+    void mime_unsorting(uint8 packet[],
+                        int16 compressed_data[],
+                        int16 *frame_type,
+                        int16 *mode,
+                        uint8 q,
+                        RX_State *st);
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* PVMP4AUDIODECODER_API_H */
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_acelp.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_acelp.h
new file mode 100644
index 0000000..5967115
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_acelp.h
@@ -0,0 +1,329 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/pvamrwbdecoder_acelp.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVAMRWBDECODER_ACELP_H
+#define PVAMRWBDECODER_ACELP_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*-----------------------------------------------------------------*
+     *                        LPC prototypes                           *
+     *-----------------------------------------------------------------*/
+
+    void isf_extrapolation(int16 HfIsf[]);
+
+    void Init_Lagconc(int16 lag_hist[]);
+    void lagconceal(
+        int16 gain_hist[],                   /* (i) : Gain history     */
+        int16 lag_hist[],                    /* (i) : Subframe size         */
+        int16 * T0,
+        int16 * old_T0,
+        int16 * seed,
+        int16 unusable_frame
+    );
+
+    void agc2_amr_wb(
+        int16 * sig_in,                      /* input : postfilter input signal  */
+        int16 * sig_out,                     /* in/out: postfilter output signal */
+        int16 l_trm                          /* input : subframe size            */
+    );
+
+    void low_pass_filt_7k_init(int16 mem[]);
+    void low_pass_filt_7k(
+        int16 signal[],                      /* input:  signal                  */
+        int16 lg,                            /* input:  length of input         */
+        int16 mem[],                         /* in/out: memory (size=30)        */
+        int16 x[]
+    );
+
+    int16 median5(int16 x[]);
+
+    void Isp_Az(
+        int16 isp[],                         /* (i) Q15 : Immittance spectral pairs            */
+        int16 a[],                           /* (o) Q12 : predictor coefficients (order = M)   */
+        int16 m,
+        int16 adaptive_scaling               /* (i) 0   : adaptive scaling disabled */
+        /*     1   : adaptive scaling enabled  */
+    );
+    void Isf_isp(
+        int16 isf[],                         /* (i) Q15 : isf[m] normalized (range: 0.0<=val<=0.5) */
+        int16 isp[],                         /* (o) Q15 : isp[m] (range: -1<=val<1)                */
+        int16 m                              /* (i)     : LPC order                                */
+    );
+    void interpolate_isp(
+        int16 isp_old[],                     /* input : isps from past frame              */
+        int16 isp_new[],                     /* input : isps from present frame           */
+        const int16 frac[],                  /* input : fraction for 3 first subfr (Q15)  */
+        int16 Az[]                           /* output: LP coefficients in 4 subframes    */
+    );
+    void weight_amrwb_lpc(
+        int16 a[],                           /* (i) Q12 : a[m+1]  LPC coefficients             */
+        int16 ap[],                          /* (o) Q12 : Spectral expanded LPC coefficients   */
+        int16 gamma,                         /* (i) Q15 : Spectral expansion factor.           */
+        int16 m                              /* (i)     : LPC order.                           */
+    );
+
+
+    /*-----------------------------------------------------------------*
+     *                        isf quantizers                           *
+     *-----------------------------------------------------------------*/
+
+    void Disf_ns(
+        int16 * indice,                      /* input:  quantization indices                  */
+        int16 * isf_q                        /* input : ISF in the frequency domain (0..0.5)  */
+    );
+
+    void Dpisf_2s_46b(
+        int16 * indice,                      /* input:  quantization indices                       */
+        int16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        int16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        int16 * isfold,                      /* input : past quantized ISF                    */
+        int16 * isf_buf,                     /* input : isf buffer                                                        */
+        int16 bfi,                           /* input : Bad frame indicator                   */
+        int16 enc_dec
+    );
+    void Dpisf_2s_36b(
+        int16 * indice,                      /* input:  quantization indices                       */
+        int16 * isf_q,                       /* output: quantized ISF in frequency domain (0..0.5) */
+        int16 * past_isfq,                   /* i/0   : past ISF quantizer                    */
+        int16 * isfold,                      /* input : past quantized ISF                    */
+        int16 * isf_buf,                     /* input : isf buffer                                                        */
+        int16 bfi,                           /* input : Bad frame indicator                   */
+        int16 enc_dec
+    );
+
+
+    void Reorder_isf(
+        int16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+        int16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+        int16 n                              /* (i)      : number of ISF                        */
+    );
+
+    /*-----------------------------------------------------------------*
+     *                       filter prototypes                         *
+     *-----------------------------------------------------------------*/
+
+    void oversamp_12k8_to_16k_init(
+        int16 mem[]                          /* output: memory (2*NB_COEF_UP) set to zeros  */
+    );
+    void oversamp_12k8_to_16k(
+        int16 sig12k8[],                     /* input:  signal to oversampling  */
+        int16 lg,                            /* input:  length of input         */
+        int16 sig16k[],                      /* output: oversampled signal      */
+        int16 mem[],                         /* in/out: memory (2*NB_COEF_UP)   */
+        int16 signal[]
+    );
+
+    void highpass_50Hz_at_12k8_init(int16 mem[]);
+    void highpass_50Hz_at_12k8(
+        int16 signal[],                      /* input/output signal */
+        int16 lg,                            /* lenght of signal    */
+        int16 mem[]                          /* filter memory [6]   */
+    );
+    void highpass_400Hz_at_12k8_init(int16 mem[]);
+    void highpass_400Hz_at_12k8(
+        int16 signal[],                      /* input/output signal */
+        int16 lg,                            /* lenght of signal    */
+        int16 mem[]                          /* filter memory [6]   */
+    );
+
+    void band_pass_6k_7k_init(int16 mem[]);
+    void band_pass_6k_7k(
+        int16 signal[],                      /* input:  signal                  */
+        int16 lg,                            /* input:  length of input         */
+        int16 mem[],                         /* in/out: memory (size=30)        */
+        int16 x[]
+    );
+
+
+    void preemph_amrwb_dec(
+        int16 x[],                           /* (i/o)   : input signal overwritten by the output */
+        int16 mu,                            /* (i) Q15 : preemphasis coefficient                */
+        int16 lg                             /* (i)     : lenght of filtering                    */
+    );
+
+    void deemphasis_32(
+        int16 x_hi[],                        /* (i)     : input signal (bit31..16) */
+        int16 x_lo[],                        /* (i)     : input signal (bit15..4)  */
+        int16 y[],                           /* (o)     : output signal (x16)      */
+        int16 mu,                            /* (i) Q15 : deemphasis factor        */
+        int16 L,                             /* (i)     : vector size              */
+        int16 * mem                          /* (i/o)   : memory (y[-1])           */
+    );
+
+
+    void wb_syn_filt(
+        int16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients           */
+        int16 m,                             /* (i)     : order of LP filter                       */
+        int16 x[],                           /* (i)     : input signal                             */
+        int16 y[],                           /* (o)     : output signal                            */
+        int16 lg,                            /* (i)     : size of filtering                        */
+        int16 mem[],                         /* (i/o)   : memory associated with this filtering.   */
+        int16 update,                        /* (i)     : 0=no update, 1=update of memory.         */
+        int16 y_buf[]
+    );
+    void Syn_filt_32(
+        int16 a[],                           /* (i) Q12 : a[m+1] prediction coefficients */
+        int16 m,                             /* (i)     : order of LP filter             */
+        int16 exc[],                         /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+        int16 Qnew,                          /* (i)     : exc scaling = 0(min) to 8(max) */
+        int16 sig_hi[],                      /* (o) /16 : synthesis high                 */
+        int16 sig_lo[],                      /* (o) /16 : synthesis low                  */
+        int16 lg                             /* (i)     : size of filtering              */
+    );
+
+    /*-----------------------------------------------------------------*
+     *                       pitch prototypes                          *
+     *-----------------------------------------------------------------*/
+
+
+    void Pred_lt4(
+        int16 exc[],                         /* in/out: excitation buffer */
+        int16 T0,                            /* input : integer pitch lag */
+        int16 frac,                          /* input : fraction of lag   */
+        int16 L_subfr                        /* input : subframe size     */
+    );
+
+    /*-----------------------------------------------------------------*
+     *                       gain prototypes                           *
+     *-----------------------------------------------------------------*/
+
+
+    void dec_gain2_amr_wb_init(
+        int16 * mem                          /* output  : memory (4 words)      */
+    );
+    void dec_gain2_amr_wb(
+        int16 index,                         /* (i)     :index of quantization.       */
+        int16 nbits,                         /* (i)     : number of bits (6 or 7)     */
+        int16 code[],                        /* (i) Q9  :Innovative vector.           */
+        int16 L_subfr,                       /* (i)     :Subframe lenght.             */
+        int16 * gain_pit,                    /* (o) Q14 :Pitch gain.                  */
+        int32 * gain_cod,                    /* (o) Q16 :Code gain.                   */
+        int16 bfi,                           /* (i)     :bad frame indicator          */
+        int16 prev_bfi,                      /* (i) : Previous BF indicator      */
+        int16 state,                         /* (i) : State of BFH               */
+        int16 unusable_frame,                /* (i) : UF indicator            */
+        int16 vad_hist,                      /* (i)         :number of non-speech frames  */
+        int16 * mem                          /* (i/o)   : memory (4 words)      */
+    );
+
+    /*-----------------------------------------------------------------*
+     *                       acelp prototypes                          *
+     *-----------------------------------------------------------------*/
+
+    void dec_acelp_2p_in_64(
+        int16 index,                         /* (i) :    12 bits index                                  */
+        int16 code[]                         /* (o) :Q9  algebraic (fixed) codebook excitation          */
+    );
+
+    void dec_acelp_4p_in_64(
+        int16 index[],                       /* (i) : index (20): 5+5+5+5 = 20 bits.                 */
+        /* (i) : index (36): 9+9+9+9 = 36 bits.                 */
+        /* (i) : index (44): 13+9+13+9 = 44 bits.               */
+        /* (i) : index (52): 13+13+13+13 = 52 bits.             */
+        /* (i) : index (64): 2+2+2+2+14+14+14+14 = 64 bits.     */
+        /* (i) : index (72): 10+2+10+2+10+14+10+14 = 72 bits.   */
+        /* (i) : index (88): 11+11+11+11+11+11+11+11 = 88 bits. */
+        int16 nbbits,                        /* (i) : 20, 36, 44, 52, 64, 72 or 88 bits              */
+        int16 code[]                         /* (o) Q9: algebraic (fixed) codebook excitation        */
+    );
+    void Pit_shrp(
+        int16 * x,                           /* in/out: impulse response (or algebraic code) */
+        int16 pit_lag,                       /* input : pitch lag                            */
+        int16 sharp,                         /* input : pitch sharpening factor (Q15)        */
+        int16 L_subfr                        /* input : subframe size                        */
+    );
+
+
+    /*-----------------------------------------------------------------*
+     *                        others prototypes                        *
+     *-----------------------------------------------------------------*/
+
+    int16 voice_factor(                       /* (o) Q15 : factor (-1=unvoiced to 1=voiced) */
+        int16 exc[],                         /* (i) Q_exc: pitch excitation                */
+        int16 Q_exc,                         /* (i)     : exc format                       */
+        int16 gain_pit,                      /* (i) Q14 : gain of pitch                    */
+        int16 code[],                        /* (i) Q9  : Fixed codebook excitation        */
+        int16 gain_code,                     /* (i) Q0  : gain of code                     */
+        int16 L_subfr                        /* (i)     : subframe length                  */
+    );
+
+    void scale_signal(
+        int16 x[],                           /* (i/o) : signal to scale               */
+        int16 lg,                            /* (i)   : size of x[]                   */
+        int16 exp                            /* (i)   : exponent: x = round(x << exp) */
+    );
+
+    int16 noise_gen_amrwb(int16 * seed);
+
+
+    void phase_dispersion(
+        int16 gain_code,                     /* (i) Q0  : gain of code             */
+        int16 gain_pit,                      /* (i) Q14 : gain of pitch            */
+        int16 code[],                        /* (i/o)   : code vector              */
+        int16 mode,                          /* (i)     : level, 0=hi, 1=lo, 2=off */
+        int16 disp_mem[],                    /* (i/o)   :  memory (size = 8) */
+        int16 ScratchMem[]
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* ACELP_H */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
new file mode 100644
index 0000000..df239d2
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op.h
@@ -0,0 +1,249 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/pvamrwbdecoder_basic_op.h
+
+     Date: 05/07/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+
+#ifndef PVAMRWBDECODER_BASIC_OP_H
+#define PVAMRWBDECODER_BASIC_OP_H
+
+
+#include "normalize_amr_wb.h"
+
+
+#define MAX_32 (int32)0x7fffffffL
+#define MIN_32 (int32)0x80000000L
+
+#define MAX_16 (int16)+32767    /* 0x7fff */
+#define MIN_16 (int16)-32768    /* 0x8000 */
+
+
+
+
+/*----------------------------------------------------------------------------
+     Function Name : negate_int16
+
+     Negate var1 with saturation, saturate in the case where input is -32768:
+                  negate(var1) = sub(0,var1).
+
+     Inputs :
+      var1
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x8000 <= var1 <= 0x7fff.
+
+     Outputs :
+      none
+
+     Return Value :
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x8000 <= var_out <= 0x7fff.
+ ----------------------------------------------------------------------------*/
+
+__inline int16 negate_int16(int16 var1)
+{
+    return (((var1 == MIN_16) ? MAX_16 : -var1));
+}
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : shl_int16
+
+     Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill
+     the var2 LSB of the result. If var2 is negative, arithmetically shift
+     var1 right by -var2 with sign extension. Saturate the result in case of
+     underflows or overflows.
+
+     Inputs :
+      var1
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x8000 <= var1 <= 0x7fff.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x8000 <= var1 <= 0x7fff.
+
+     Return Value :
+      var_out
+               16 bit short signed integer (int16) whose value falls in the
+               range : 0x8000 <= var_out <= 0x7fff.
+ ----------------------------------------------------------------------------*/
+
+__inline int16 shl_int16(int16 var1, int16 var2)
+{
+    int16 var_out;
+
+    if (var2 < 0)
+    {
+        var2 = (-var2) & (0xf);
+        var_out = var1 >> var2;
+    }
+    else
+    {
+        var2 &= 0xf;
+        var_out = var1 << var2;
+        if (var_out >> var2 != var1)
+        {
+            var_out = (var1 >> 15) ^ MAX_16;
+        }
+    }
+    return (var_out);
+}
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : shl_int32
+
+     Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero
+     fill the var2 LSB of the result. If var2 is negative, arithmetically
+     shift L_var1 right by -var2 with sign extension. Saturate the result in
+     case of underflows or overflows.
+
+     Inputs :
+      L_var1   32 bit long signed integer (int32) whose value falls in the
+               range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range :  8000 <= var2 <= 7fff.
+     Return Value :
+               32 bit long signed integer (int32) whose value falls in the
+               range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+ ----------------------------------------------------------------------------*/
+
+__inline int32 shl_int32(int32 L_var1, int16 var2)
+{
+    int32 L_var_out;
+
+    if (var2 > 0)
+    {
+        L_var_out = L_var1 << var2;
+        if (L_var_out >> var2 != L_var1)
+        {
+            L_var_out = (L_var1 >> 31) ^ MAX_32;
+        }
+    }
+    else
+    {
+        var2 = (-var2) & (0xf);
+        L_var_out = L_var1 >> var2;
+    }
+
+    return (L_var_out);
+}
+
+
+/*----------------------------------------------------------------------------
+
+     Function Name : shr_int32
+
+     Arithmetically shift the 32 bit input L_var1 right var2 positions with
+     sign extension. If var2 is negative, arithmetically shift L_var1 left
+     by -var2 and zero fill the -var2 LSB of the result. Saturate the result
+     in case of underflows or overflows.
+
+     Inputs :
+      L_var1   32 bit long signed integer (int32) whose value falls in the
+               range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+      var2
+               16 bit short signed integer (int16) whose value falls in the
+               range :  8000 <= var2 <= 7fff.
+     Return Value :
+               32 bit long signed integer (int32) whose value falls in the
+               range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+ ----------------------------------------------------------------------------*/
+
+__inline int32 shr_int32(int32 L_var1, int16 var2)
+{
+    int32 L_var_out;
+
+    if (var2 >= 0)
+    {
+        L_var_out = L_var1 >> (var2 & 0x1f);
+    }
+    else
+    {
+        var2 = (int16)(-var2);
+        var2 &= 0x1f;
+        L_var_out = L_var1 << var2;
+        if (L_var_out >> var2 != L_var1)
+        {
+            L_var_out = (L_var1 >> 31) ^ MAX_32;
+        }
+
+    }
+    return (L_var_out);
+}
+
+
+
+
+
+
+#if defined(PV_ARM_V5)
+
+#include "pvamrwbdecoder_basic_op_armv5.h"
+
+#elif defined(PV_ARM_GCC_V5)
+
+#include "pvamrwbdecoder_basic_op_gcc_armv5.h"
+
+#else
+
+#ifndef C_EQUIVALENT
+#define C_EQUIVALENT        // default to C_EQUIVALENT
+#endif
+
+#include "pvamrwbdecoder_basic_op_cequivalent.h"
+
+#endif
+
+
+#endif   /*  PVAMRWBDECODER_BASIC_OP_H  */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_armv5.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_armv5.h
new file mode 100644
index 0000000..c800a2e
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_armv5.h
@@ -0,0 +1,253 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/pvamrwbdecoder_basic_op_armv5.h
+
+     Date: 05/07/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVAMRWBDECODER_BASIC_OP_ARMV5_H
+#define PVAMRWBDECODER_BASIC_OP_ARMV5_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+
+
+
+#if defined(PV_ARM_V5)
+
+    __inline int16 add_int16(int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+        int32 L_var_aux;
+
+        __asm
+        {
+            mov L_var_out, var1, lsl #16
+            mov L_var_aux, var2, lsl #16
+            qadd L_var_out, L_var_out, L_var_aux
+            mov L_var_out, L_var_out, asr #16
+
+        }
+        return L_var_out;
+    }
+
+
+    __inline int16 sub_int16(int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+        int32 L_var_aux;
+
+        __asm
+        {
+            mov L_var_out, var1, lsl #16
+            mov L_var_aux, var2, lsl #16
+            qsub L_var_out, L_var_out, L_var_aux
+            mov L_var_out, L_var_out, asr #16
+
+        }
+        return L_var_out;
+    }
+
+
+    __inline int32 add_int32(int32 L_var1, int32 L_var2)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            qadd L_var_out, L_var1, L_var2
+        }
+        return L_var_out;
+    }
+
+
+    __inline int32 mac_16by16_to_int32(int32 L_var3, int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+
+
+        __asm
+        {
+            smulbb L_var_out, var1, var2
+            qdadd L_var_out, L_var3, L_var_out
+        }
+        return L_var_out;
+    }
+
+    __inline int32 sub_int32(int32 L_var1, int32 L_var2)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            qsub L_var_out, L_var1, L_var2
+        }
+        return L_var_out;
+    }
+
+    __inline int32 msu_16by16_from_int32(int32 L_var3, int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+
+
+        __asm
+        {
+            smulbb L_var_out, var1, var2
+            qdsub L_var_out, L_var3, L_var_out
+        }
+        return L_var_out;
+    }
+
+    __inline int32 mul_16by16_to_int32(int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            smulbb L_var_out, var1, var2
+            qadd L_var_out, L_var_out, L_var_out
+        }
+        return L_var_out;
+    }
+
+    __inline int16 mult_int16(int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            smulbb L_var_out, var1, var2
+            mov L_var_out, L_var_out, asr #15
+        }
+        return L_var_out;
+    }
+
+
+    __inline int16 amr_wb_round(int32 L_var1)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            qadd L_var_out, L_var1, (int32) 0x00008000L
+            mov L_var_out, L_var_out, asr #16
+        }
+        return L_var_out;
+    }
+
+
+
+    __inline int16 amr_wb_shl1_round(int32 L_var1)
+    {
+        int32 L_var_out;
+
+        __asm
+        {
+            qadd L_var_out, L_var1, L_var1
+            qadd L_var_out, L_var_out, (int32) 0x00008000L
+            mov L_var_out, L_var_out, asr #16
+        }
+        return L_var_out;
+    }
+
+    __inline int32 mul_32by16(int16 hi, int16 lo, int16 n)
+    {
+        int32 H_32;
+        int32 L_32;
+        __asm
+        {
+            smulbb H_32, hi, n
+            smulbb L_32, lo, n
+            add H_32, H_32, L_32, asr #15
+            qadd H_32, H_32, H_32
+        }
+
+        return (H_32);
+    }
+
+    __inline  int32 fxp_mac_16by16(const int16 var1, const int16 var2, int32 L_add)
+    {
+        __asm
+        {
+            smlabb L_add, var1, var2, L_add
+        }
+        return (L_add);
+    }
+
+    __inline  int32 fxp_mul_16by16(int16 var1, const int16 var2)
+    {
+        int32 L_mult;
+        __asm
+        {
+            smulbb L_mult, var1, var2
+        }
+        return (L_mult);
+    }
+
+    __inline  int32 fxp_mul32_by_16b(int32 L_var1, const int32 L_var2)
+    {
+        int32 L_mult;
+        __asm
+        {
+            smulwb L_mult, L_var1, L_var2
+        }
+
+        return L_mult;
+    }
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+#endif   /*  PVAMRWBDECODER_BASIC_OP_ARMV5_H  */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_cequivalent.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_cequivalent.h
new file mode 100644
index 0000000..7fd680d
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_cequivalent.h
@@ -0,0 +1,545 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/pvamrwbdecoder_basic_op_cequivalent.h
+
+     Date: 05/07/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+#ifndef PVAMRWBDECODER_BASIC_OP_CEQUIVALENT_H
+#define PVAMRWBDECODER_BASIC_OP_CEQUIVALENT_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "normalize_amr_wb.h"
+
+#if defined(C_EQUIVALENT)
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : add_int16
+
+         Purpose :
+
+          Performs the addition (var1+var2) with overflow control and saturation;
+          the 16 bit result is set at +32767 when overflow occurs or at -32768
+          when underflow occurs.
+
+         Inputs :
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+         Outputs :
+          none
+
+         Return Value :
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+
+     ----------------------------------------------------------------------------*/
+    __inline int16 add_int16(int16 var1, int16 var2)
+    {
+        int32 L_sum;
+
+        L_sum = (int32) var1 + var2;
+        if ((L_sum >> 15) != (L_sum >> 31))
+        {
+            L_sum = (L_sum >> 31) ^ MAX_16;
+        }
+        return ((int16)(L_sum));
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : sub_int16
+
+          Performs the subtraction (var1+var2) with overflow control and satu-
+          ration; the 16 bit result is set at +32767 when overflow occurs or at
+          -32768 when underflow occurs.
+
+         Inputs :
+
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+         Outputs :
+          none
+
+         Return Value :
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+
+     ----------------------------------------------------------------------------*/
+    __inline int16 sub_int16(int16 var1, int16 var2)
+    {
+        int32 L_diff;
+
+        L_diff = (int32) var1 - var2;
+        if ((L_diff >> 15) != (L_diff >> 31))
+        {
+            L_diff = (L_diff >> 31) ^ MAX_16;
+        }
+        return ((int16)(L_diff));
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : mult_int16
+
+          Performs the multiplication of var1 by var2 and gives a 16 bit result
+          which is scaled i.e.:
+                   mult_int16(var1,var2) = extract_l(L_shr((var1 times var2),15)) and
+                   mult_int16(-32768,-32768) = 32767.
+
+         Inputs :
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+
+         Return Value :
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+
+     ----------------------------------------------------------------------------*/
+
+    __inline int16 mult_int16(int16 var1, int16 var2)
+    {
+        int32 L_product;
+
+        L_product = ((int32) var1 * (int32) var2) >> 15;
+
+        if ((L_product >> 15) != (L_product >> 31))
+        {
+            L_product = (L_product >> 31) ^ MAX_16;
+        }
+
+        return ((int16)L_product);
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : add_int32
+
+         32 bits addition of the two 32 bits variables (L_var1+L_var2) with
+         overflow control and saturation; the result is set at +2147483647 when
+         overflow occurs or at -2147483648 when underflow occurs.
+
+         Inputs :
+
+          L_var1   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+          L_var2   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+
+         Return Value :
+          L_var_out
+                   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+
+    __inline  int32 add_int32(int32 L_var1, int32 L_var2)
+    {
+        int32 L_var_out;
+
+        L_var_out = L_var1 + L_var2;
+
+        if (((L_var1 ^ L_var2) & MIN_32) == 0)  /* same sign ? */
+        {
+            if ((L_var_out ^ L_var1) & MIN_32)  /* addition matches sign ? */
+            {
+                L_var_out = (L_var1 >> 31) ^ MAX_32;
+            }
+        }
+        return (L_var_out);
+    }
+
+
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : sub_int32
+
+         32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with
+         overflow control and saturation; the result is set at +2147483647 when
+         overflow occurs or at -2147483648 when underflow occurs.
+
+         Inputs :
+
+          L_var1   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+          L_var2   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+
+         Return Value :
+          L_var_out
+                   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+
+    __inline  int32 sub_int32(int32 L_var1, int32 L_var2)
+    {
+        int32 L_var_out;
+
+        L_var_out = L_var1 - L_var2;
+
+        if (((L_var1 ^ L_var2) & MIN_32) != 0)  /* different sign ? */
+        {
+            if ((L_var_out ^ L_var1) & MIN_32)  /* difference matches sign ? */
+            {
+                L_var_out = (L_var1 >> 31) ^ MAX_32;
+            }
+        }
+        return (L_var_out);
+    }
+
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : mac_16by16_to_int32
+
+         Multiply var1 by var2 and shift the result left by 1. Add the 32 bit
+         result to L_var3 with saturation, return a 32 bit result:
+              L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)).
+
+         Inputs :
+
+          L_var3   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+
+         Return Value :
+                   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+
+    __inline  int32 mac_16by16_to_int32(int32 L_var3, int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+        int32 L_mul;
+
+        L_mul  = ((int32) var1 * (int32) var2);
+
+        if (L_mul != 0x40000000)
+        {
+            L_mul <<= 1;
+        }
+        else
+        {
+            L_mul = MAX_32;     /* saturation */
+        }
+
+        L_var_out = L_var3 + L_mul;
+
+        if (((L_mul ^ L_var3) & MIN_32) == 0)  /* same sign ? */
+        {
+            if ((L_var_out ^ L_var3) & MIN_32)  /* addition matches sign ? */
+            {
+                L_var_out = (L_var3 >> 31) ^ MAX_32;
+            }
+        }
+
+        return (L_var_out);
+    }
+
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : msu_16by16_from_int32
+
+         Multiply var1 by var2 and shift the result left by 1. Subtract the 32 bit
+         result to L_var3 with saturation, return a 32 bit result:
+              L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)).
+
+         Inputs :
+
+          L_var3   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var3 <= 0x7fff ffff.
+
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+
+         Return Value :
+                   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+    __inline  int32 msu_16by16_from_int32(int32 L_var3, int16 var1, int16 var2)
+    {
+        int32 L_var_out;
+        int32 L_mul;
+
+        L_mul  = ((int32) var1 * (int32) var2);
+
+        if (L_mul != 0x40000000)
+        {
+            L_mul <<= 1;
+        }
+        else
+        {
+            L_mul = MAX_32;     /* saturation */
+        }
+
+        L_var_out = L_var3 - L_mul;
+
+        if (((L_mul ^ L_var3) & MIN_32) != 0)  /* different sign ? */
+        {
+            if ((L_var_out ^ L_var3) & MIN_32)  /* difference matches sign ? */
+            {
+                L_var_out = (L_var3 >> 31) ^ MAX_32;
+            }
+        }
+
+        return (L_var_out);
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : mul_16by16_to_int32
+
+         mul_16by16_to_int32 is the 32 bit result of the multiplication of var1
+         times var2 with one shift left i.e.:
+              L_mult(var1,var2) = L_shl((var1 times var2),1) and
+              L_mult(-32768,-32768) = 2147483647.
+
+         Inputs :
+          var1
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+          var2
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var1 <= 0x0000 7fff.
+
+         Return Value :
+                   32 bit long signed integer (int32) whose value falls in the
+                   range : 0x8000 0000 <= L_var_out <= 0x7fff ffff.
+
+     ----------------------------------------------------------------------------*/
+
+
+    __inline  int32 mul_16by16_to_int32(int16 var1, int16 var2)
+    {
+        int32 L_mul;
+
+        L_mul  = ((int32) var1 * (int32) var2);
+
+        if (L_mul != 0x40000000)
+        {
+            L_mul <<= 1;
+        }
+        else
+        {
+            L_mul = MAX_32;     /* saturation */
+        }
+
+        return (L_mul);
+
+    }
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : amr_wb_round
+
+         Round the lower 16 bits of the 32 bit input number into the MS 16 bits
+         with saturation. Shift the resulting bits right by 16 and return the 16
+         bit number:
+                     round(L_var1) = extract_h(L_add(L_var1,32768))
+
+         Inputs :
+          L_var1
+                   32 bit long signed integer (int32 ) whose value falls in the
+                   range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+         Return Value :
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+
+     ----------------------------------------------------------------------------*/
+    __inline int16 amr_wb_round(int32 L_var1)
+    {
+        if (L_var1 != MAX_32)
+        {
+            L_var1 +=  0x00008000L;
+        }
+        return ((int16)(L_var1 >> 16));
+    }
+
+
+    /*----------------------------------------------------------------------------
+
+         Function Name : amr_wb_shl1_round
+
+         Shift the 32 bit input number to the left by 1, round up the result and
+         shift down by 16
+                     amr_wb_shl1_round(L_var1) = round(L_shl(L_var1,1))
+
+         Inputs :
+          L_var1
+                   32 bit long signed integer (int32 ) whose value falls in the
+                   range : 0x8000 0000 <= L_var1 <= 0x7fff ffff.
+
+         Return Value :
+                   16 bit short signed integer (int16) whose value falls in the
+                   range : 0xffff 8000 <= var_out <= 0x0000 7fff.
+
+     ----------------------------------------------------------------------------*/
+    __inline int16 amr_wb_shl1_round(int32 L_var1)
+    {
+        int16 var_out;
+
+        if ((L_var1 << 1) >> 1 == L_var1)
+        {
+            var_out = (int16)((L_var1 + 0x00004000) >> 15);
+        }
+        else
+        {
+            var_out = (int16)(((L_var1 >> 31) ^ MAX_32) >> 16);
+        }
+
+        return (var_out);
+    }
+
+    /*----------------------------------------------------------------------------
+             Function Name : mul_32by16
+
+             Multiply a 16 bit integer by a 32 bit (DPF). The result is divided
+             by 2^15
+
+                    L_32 = (hi1*lo2)<<1 + ((lo1*lo2)>>15)<<1
+
+             Inputs :
+
+             hi          hi part of 32 bit number.
+             lo          lo part of 32 bit number.
+             n           16 bit number.
+
+         ----------------------------------------------------------------------------*/
+
+
+    __inline int32 mul_32by16(int16 hi, int16 lo, int16 n)
+    {
+        return (((((int32)hi*n)) + ((((int32)lo*n) >> 15))) << 1);
+    }
+
+    __inline  int32 fxp_mac_16by16(int16 var1,  int16 var2, int32 L_add)
+    {
+
+        L_add += (int32)var1 * var2;
+
+        return L_add;
+    }
+
+    __inline  int32 fxp_mul_16by16(int16 var1, const int16 var2)
+    {
+        int32 L_mul = (int32)var1 * var2;
+
+        return L_mul;
+    }
+
+    __inline  int32 fxp_mul32_by_16b(int32 L_var1, const int32 L_var2)
+    {
+
+        int32 L_mul = (int32)(((int64)L_var1 * (L_var2 << 16)) >> 32);
+
+        return L_mul;
+    }
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+#endif   /*  PVAMRWBDECODER_BASIC_OP_CEQUIVALENT_H  */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_gcc_armv5.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_gcc_armv5.h
new file mode 100644
index 0000000..741b584
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_basic_op_gcc_armv5.h
@@ -0,0 +1,319 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./src/pvamrwbdecoder_basic_op_gcc_armv5.h
+
+     Date: 05/07/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVAMRWBDECODER_BASIC_OP_GCC_ARMV5_H
+#define PVAMRWBDECODER_BASIC_OP_GCC_ARMV5_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#if (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+    static inline int16 sub_int16(int16 var1, int16 var2)
+    {
+        register int32 L_var_out;
+        register int32 L_var_aux;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+
+        asm volatile(
+            "mov  %0, %2, lsl #16\n"
+            "mov  %1, %3, lsl #16\n"
+            "qsub %0, %0, %1\n"
+            "mov  %0, %0, asr #16"
+    : "=&r*i"(L_var_out),
+            "=&r*i"(L_var_aux)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (int16)L_var_out;
+
+    }
+
+    static inline int16 add_int16(int16 var1, int16 var2)
+{
+        register int32 L_var_out;
+        register int32 L_var_aux;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+
+        asm volatile(
+            "mov  %0, %2, lsl #16\n"
+            "mov  %1, %3, lsl #16\n"
+            "qadd %0, %0, %1\n"
+            "mov  %0, %0, asr #16"
+    : "=&r*i"(L_var_out),
+            "=&r*i"(L_var_aux)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (int16)L_var_out;
+
+    }
+
+    static inline  int32 mul_32by16(int16 hi, int16 lo, int16 n)
+{
+        register int32 H_32;
+        register int32 L_32;
+        register int32 ra = (int32)hi;
+        register int32 rb = (int32)lo;
+        register int32 rc = (int32)n;
+
+
+        asm volatile(
+            "smulbb %0, %2, %4\n"
+            "smulbb %1, %3, %4\n"
+            "add    %0, %0, %1, asr #15\n"
+            "qadd   %0, %0, %0"
+    : "=&r*i"(H_32),
+            "=&r*i"(L_32)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return H_32;
+    }
+
+
+    static inline int32 sub_int32(int32 L_var1, int32 L_var2)
+{
+        register int32 L_var_out;
+        register int32 ra = L_var1;
+        register int32 rb = L_var2;
+
+        asm volatile(
+            "qsub %0, %1, %2"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return L_var_out;
+    }
+
+    static inline int32 add_int32(int32 L_var1, int32 L_var2)
+{
+        register int32 L_var_out;
+        register int32 ra = L_var1;
+        register int32 rb = L_var2;
+
+        asm volatile(
+            "qadd %0, %1, %2"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return L_var_out;
+    }
+
+    static inline int32 msu_16by16_from_int32(int32 L_var3, int16 var1, int16 var2)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+        register int32 rc = L_var3;
+
+        asm volatile(
+            "smulbb %0, %1, %2\n"
+            "qdsub %0, %3, %0"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return L_var_out;
+    }
+
+
+    static inline int32 mac_16by16_to_int32(int32 L_var3, int16 var1, int16 var2)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+        register int32 rc = L_var3;
+
+        asm volatile(
+            "smulbb %0, %1, %2\n"
+            "qdadd %0, %3, %0"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+
+        return L_var_out;
+    }
+
+
+    static inline  int32 mul_16by16_to_int32(int16 var1, int16 var2)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+
+        asm volatile(
+            "smulbb %0, %1, %2\n"
+            "qadd %0, %0, %0"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return L_var_out;
+    }
+
+
+    static inline int16 mult_int16(int16 var1, int16 var2)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)var1;
+        register int32 rb = (int32)var2;
+
+        asm volatile(
+            "smulbb %0, %1, %2\n"
+            "mov %0, %0, asr #15"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (int16)L_var_out;
+    }
+
+    static inline int16 amr_wb_round(int32 L_var1)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)L_var1;
+        register int32 rb = (int32)0x00008000L;
+
+        asm volatile(
+            "qadd %0, %1, %2\n"
+            "mov %0, %0, asr #16"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+        return (int16)L_var_out;
+    }
+
+    static inline int16 amr_wb_shl1_round(int32 L_var1)
+{
+        register int32 L_var_out;
+        register int32 ra = (int32)L_var1;
+        register int32 rb = (int32)0x00008000L;
+
+        asm volatile(
+            "qadd %0, %1, %1\n"
+            "qadd %0, %0, %2\n"
+            "mov %0, %0, asr #16"
+    : "=&r*i"(L_var_out)
+                    : "r"(ra),
+                    "r"(rb));
+        return (int16)L_var_out;
+    }
+
+
+    static inline int32 fxp_mac_16by16(const int16 L_var1, const int16 L_var2, int32 L_add)
+{
+        register int32 tmp;
+        register int32 ra = (int32)L_var1;
+        register int32 rb = (int32)L_var2;
+        register int32 rc = (int32)L_add;
+
+        asm volatile(
+            "smlabb %0, %1, %2, %3"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb),
+                    "r"(rc));
+        return (tmp);
+    }
+
+    static inline int32 fxp_mul_16by16bb(int16 L_var1, const int16 L_var2)
+{
+        register int32 tmp;
+        register int32 ra = (int32)L_var1;
+        register int32 rb = (int32)L_var2;
+
+        asm volatile(
+            "smulbb %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+        return (tmp);
+    }
+
+
+#define fxp_mul_16by16(a, b)  fxp_mul_16by16bb(  a, b)
+
+
+    static inline int32 fxp_mul32_by_16(int32 L_var1, const int32 L_var2)
+{
+        register int32 tmp;
+        register int32 ra = (int32)L_var1;
+        register int32 rb = (int32)L_var2;
+
+        asm volatile(
+            "smulwb %0, %1, %2"
+    : "=&r*i"(tmp)
+                    : "r"(ra),
+                    "r"(rb));
+        return (tmp);
+    }
+
+#define fxp_mul32_by_16b( a, b)   fxp_mul32_by_16( a, b)
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+#endif   /*  PVAMRWBDECODER_BASIC_OP_GCC_ARMV5_H  */
+
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
new file mode 100644
index 0000000..ecf1bf3
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_cnst.h
@@ -0,0 +1,142 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*
+------------------------------------------------------------------------------
+
+ Name: pvamrwbdecoder_cnst.h
+
+     Date: 05/02/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ Main header file for the Packet Video AMR Wide  Band  decoder library. The
+ constants, structures, and functions defined within this file, along with
+ a basic data types header file, is all that is needed to use and communicate
+ with the library. The internal data structures within the library are
+ purposely hidden.
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+  (Normally header files do not have a reference section)
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef PVAMRWBDECODER_CNST_H
+#define PVAMRWBDECODER_CNST_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+
+#define L_FRAME      256                   /* Frame size                                 */
+#define L_SUBFR16k   80                    /* Subframe size at 16kHz                     */
+
+#define L_SUBFR      64                    /* Subframe size                              */
+#define NB_SUBFR     4                     /* Number of subframe per frame               */
+
+#define L_NEXT       64                    /* Overhead in LP analysis                    */
+#define L_WINDOW     384                   /* window size in LP analysis                 */
+#define L_TOTAL      384                   /* Total size of speech buffer.               */
+#define M            16                    /* Order of LP filter                         */
+#define M16k             20
+
+#define L_FILT16k    15                    /* Delay of down-sampling filter              */
+#define L_FILT       12                    /* Delay of up-sampling filter                */
+
+#define GP_CLIP      15565                 /* Pitch gain clipping = 0.95 Q14             */
+#define PIT_SHARP    27853                 /* pitch sharpening factor = 0.85 Q15         */
+
+#define PIT_MIN      34                    /* Minimum pitch lag with resolution 1/4      */
+#define PIT_FR2      128                   /* Minimum pitch lag with resolution 1/2      */
+#define PIT_FR1_9b   160                   /* Minimum pitch lag with resolution 1        */
+#define PIT_FR1_8b   92                    /* Minimum pitch lag with resolution 1        */
+#define PIT_MAX      231                   /* Maximum pitch lag                          */
+#define L_INTERPOL   (16+1)                /* Length of filter for interpolation         */
+
+#define OPL_DECIM    2                     /* Decimation in open-loop pitch analysis     */
+
+#define PREEMPH_FAC  22282                 /* preemphasis factor (0.68 in Q15)           */
+#define GAMMA1       30147                 /* Weighting factor (numerator) (0.92 in Q15) */
+#define TILT_FAC     22282                 /* tilt factor (denominator) (0.68 in Q15)    */
+
+#define Q_MAX        8                     /* scaling max for signal (see syn_filt_32)   */
+
+#define RANDOM_INITSEED  21845             /* own random init value                      */
+
+#define L_MEANBUF        3
+#define ONE_PER_MEANBUF 10923
+
+#define MODE_7k       0
+#define MODE_9k       1
+#define MODE_12k      2
+#define MODE_14k      3
+#define MODE_16k      4
+#define MODE_18k      5
+#define MODE_20k      6
+#define MODE_23k      7
+#define MODE_24k      8
+#define MRDTX         9
+//#define NUM_OF_MODES  10                   /* see bits.h for bits definition             */
+
+#define EHF_MASK (int16)0x0008            /* homing frame pattern                       */
+
+#define BIT_0     (int16)-127
+#define BIT_1     (int16)127
+#define BIT_0_ITU (int16)0x007F
+#define BIT_1_ITU (int16)0x0081
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
diff --git a/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_mem_funcs.h b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_mem_funcs.h
new file mode 100644
index 0000000..e348916
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/pvamrwbdecoder_mem_funcs.h
@@ -0,0 +1,67 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: pvamrwbdecoder_mem_funcs.h
+ Funtions:
+
+
+     Date: 05/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef PVAMRWBDECODER_MEM_FUNCS_H
+#define PVAMRWBDECODER_MEM_FUNCS_H
+
+#include <string.h>
+
+
+#define pv_memset(to, c, n)         memset(to, c, n)
+
+
+#define pv_memcpy(to, from, n)      memcpy(to, from, n)
+#define pv_memmove(to, from, n)     memmove(to, from, n)
+#define pv_memcmp(p, q, n)          memcmp(p, q, n)
+
+
+
+#endif
diff --git a/media/libstagefright/codecs/amrwb/src/q_gain2_tab.cpp b/media/libstagefright/codecs/amrwb/src/q_gain2_tab.cpp
new file mode 100644
index 0000000..92c235f
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/q_gain2_tab.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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 "qisf_ns.h"
+
+
+/*
+ * Tables for function q_gain2()
+ *
+ *  g_pitch(Q14),  g_code(Q11)
+ *
+ * pitch gain are ordered in table to reduce complexity
+ * during quantization of gains.
+ */
+
+
+
+
+const int16 t_qua_gain6b[NB_QUA_GAIN6B*2] =
+{
+    1566,  1332,
+    1577,  3557,
+    3071,  6490,
+    4193, 10163,
+    4496,  2534,
+    5019,  4488,
+    5586, 15614,
+    5725,  1422,
+    6453,   580,
+    6724,  6831,
+    7657,  3527,
+    8072,  2099,
+    8232,  5319,
+    8827,  8775,
+    9740,  2868,
+    9856,  1465,
+    10087, 12488,
+    10241,  4453,
+    10859,  6618,
+    11321,  3587,
+    11417,  1800,
+    11643,  2428,
+    11718,   988,
+    12312,  5093,
+    12523,  8413,
+    12574, 26214,
+    12601,  3396,
+    13172,  1623,
+    13285,  2423,
+    13418,  6087,
+    13459, 12810,
+    13656,  3607,
+    14111,  4521,
+    14144,  1229,
+    14425,  1871,
+    14431,  7234,
+    14445,  2834,
+    14628, 10036,
+    14860, 17496,
+    15161,  3629,
+    15209,  5819,
+    15299,  2256,
+    15518,  4722,
+    15663,  1060,
+    15759,  7972,
+    15939, 11964,
+    16020,  2996,
+    16086,  1707,
+    16521,  4254,
+    16576,  6224,
+    16894,  2380,
+    16906,   681,
+    17213,  8406,
+    17610,  3418,
+    17895,  5269,
+    18168, 11748,
+    18230,  1575,
+    18607, 32767,
+    18728, 21684,
+    19137,  2543,
+    19422,  6577,
+    19446,  4097,
+    19450,  9056,
+    20371, 14885
+};
+
+const int16 t_qua_gain7b[NB_QUA_GAIN7B*2] =
+{
+    204,   441,
+    464,  1977,
+    869,  1077,
+    1072,  3062,
+    1281,  4759,
+    1647,  1539,
+    1845,  7020,
+    1853,   634,
+    1995,  2336,
+    2351, 15400,
+    2661,  1165,
+    2702,  3900,
+    2710, 10133,
+    3195,  1752,
+    3498,  2624,
+    3663,   849,
+    3984,  5697,
+    4214,  3399,
+    4415,  1304,
+    4695,  2056,
+    5376,  4558,
+    5386,   676,
+    5518, 23554,
+    5567,  7794,
+    5644,  3061,
+    5672,  1513,
+    5957,  2338,
+    6533,  1060,
+    6804,  5998,
+    6820,  1767,
+    6937,  3837,
+    7277,   414,
+    7305,  2665,
+    7466, 11304,
+    7942,   794,
+    8007,  1982,
+    8007,  1366,
+    8326,  3105,
+    8336,  4810,
+    8708,  7954,
+    8989,  2279,
+    9031,  1055,
+    9247,  3568,
+    9283,  1631,
+    9654,  6311,
+    9811,  2605,
+    10120,   683,
+    10143,  4179,
+    10245,  1946,
+    10335,  1218,
+    10468,  9960,
+    10651,  3000,
+    10951,  1530,
+    10969,  5290,
+    11203,  2305,
+    11325,  3562,
+    11771,  6754,
+    11839,  1849,
+    11941,  4495,
+    11954,  1298,
+    11975, 15223,
+    11977,   883,
+    11986,  2842,
+    12438,  2141,
+    12593,  3665,
+    12636,  8367,
+    12658,  1594,
+    12886,  2628,
+    12984,  4942,
+    13146,  1115,
+    13224,   524,
+    13341,  3163,
+    13399,  1923,
+    13549,  5961,
+    13606,  1401,
+    13655,  2399,
+    13782,  3909,
+    13868, 10923,
+    14226,  1723,
+    14232,  2939,
+    14278,  7528,
+    14439,  4598,
+    14451,   984,
+    14458,  2265,
+    14792,  1403,
+    14818,  3445,
+    14899,  5709,
+    15017, 15362,
+    15048,  1946,
+    15069,  2655,
+    15405,  9591,
+    15405,  4079,
+    15570,  7183,
+    15687,  2286,
+    15691,  1624,
+    15699,  3068,
+    15772,  5149,
+    15868,  1205,
+    15970,   696,
+    16249,  3584,
+    16338,  1917,
+    16424,  2560,
+    16483,  4438,
+    16529,  6410,
+    16620, 11966,
+    16839,  8780,
+    17030,  3050,
+    17033, 18325,
+    17092,  1568,
+    17123,  5197,
+    17351,  2113,
+    17374,   980,
+    17566, 26214,
+    17609,  3912,
+    17639, 32767,
+    18151,  7871,
+    18197,  2516,
+    18202,  5649,
+    18679,  3283,
+    18930,  1370,
+    19271, 13757,
+    19317,  4120,
+    19460,  1973,
+    19654, 10018,
+    19764,  6792,
+    19912,  5135,
+    20040,  2841,
+    21234, 19833
+};
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/q_pulse.h b/media/libstagefright/codecs/amrwb/src/q_pulse.h
new file mode 100644
index 0000000..0ac52b3
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/q_pulse.h
@@ -0,0 +1,79 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/q_pulse.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+  Coding and decoding of algebraic codebook
+------------------------------------------------------------------------------
+*/
+
+#ifndef Q_PULSE_H
+#define Q_PULSE_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void dec_1p_N1(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_2p_2N1(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_3p_3N1(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_4p_4N1(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_4p_4N(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_5p_5N(int32 index, int16 N, int16 offset, int16 pos[]);
+    void dec_6p_6N_2(int32 index, int16 N, int16 offset, int16 pos[]);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif  /* Q_PULSE_H */
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns.cpp b/media/libstagefright/codecs/amrwb/src/qisf_ns.cpp
new file mode 100644
index 0000000..07e342b
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qisf_ns.cpp
@@ -0,0 +1,145 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: qisf_ns.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 indice[] : indices of the selected codebook entries
+     int16 isf[]    : quantized ISFs (in frequency domain)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Coding/Decoding of ISF parameters for background noise.
+
+   The ISF vector is quantized using VQ with split-by-5
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "qisf_ns.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 Disf_ns(
+    int16 * indice,   /* input:  quantization indices               */
+    int16 * isf_q     /* input: ISF in the frequency domain (0..0.5)*/
+)
+{
+    int16 i;
+
+    isf_q[0] = dico1_isf_noise[(indice[0] << 1)];
+    isf_q[1] = dico1_isf_noise[(indice[0] << 1) + 1];
+
+    for (i = 0; i < 3; i++)
+    {
+        isf_q[i + 2] = dico2_isf_noise[(indice[1] << 1) + indice[1] + i];
+        isf_q[i + 5] = dico3_isf_noise[(indice[2] << 1) + indice[2] + i];
+    }
+
+    for (i = 0; i < 4; i++)
+    {
+        isf_q[i +  8] = dico4_isf_noise[(indice[3] << 2) + i];
+        isf_q[i + 12] = dico5_isf_noise[(indice[4] << 2) + i];
+    }
+
+    for (i = 0; i < ORDER; i++)
+    {
+        isf_q[i] = add_int16(isf_q[i], mean_isf_noise[i]);
+    }
+
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
+
+}
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns.h b/media/libstagefright/codecs/amrwb/src/qisf_ns.h
new file mode 100644
index 0000000..4e9f67e
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qisf_ns.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/qisf_ns.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef QISF_NS_H
+#define QISF_NS_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; DEFINES
+----------------------------------------------------------------------------*/
+
+
+#define ORDER   16            /* order of linear prediction filter */
+#define ISF_GAP 128
+
+#define SIZE_BK_NOISE1  64
+#define SIZE_BK_NOISE2  64
+#define SIZE_BK_NOISE3  64
+#define SIZE_BK_NOISE4  32
+#define SIZE_BK_NOISE5  32
+
+#define NB_QUA_GAIN6B  64     /* Number of quantization level */
+#define NB_QUA_GAIN7B  128    /* Number of quantization level */
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+extern const int16 mean_isf_noise[ORDER];
+extern const int16 dico1_isf_noise[SIZE_BK_NOISE1*2];
+extern const int16 dico2_isf_noise[SIZE_BK_NOISE2*3];
+extern const int16 dico3_isf_noise[SIZE_BK_NOISE3*3];
+extern const int16 dico4_isf_noise[SIZE_BK_NOISE4*4];
+extern const int16 dico5_isf_noise[SIZE_BK_NOISE5*4];
+
+extern const int16 t_qua_gain6b[NB_QUA_GAIN6B*2];
+extern const int16 t_qua_gain7b[NB_QUA_GAIN7B*2];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+#endif  /* QISF_NS_H */
diff --git a/media/libstagefright/codecs/amrwb/src/qisf_ns_tab.cpp b/media/libstagefright/codecs/amrwb/src/qisf_ns_tab.cpp
new file mode 100644
index 0000000..e5630e8
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qisf_ns_tab.cpp
@@ -0,0 +1,367 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*
+ *                         qisf_ns_tab.cpp
+ *
+ * Quantization tables for split by 5 VQ of ISFs for a background
+ * noise database
+ * Version whith no prediction
+ */
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "qisf_ns.h"
+
+
+/* means of ISFs */
+const int16 mean_isf_noise[ORDER] =
+{
+
+    478,  1100,  2213,  3267,  4219,  5222,  6198,  7240,
+    8229,  9153, 10098, 11108, 12144, 13184, 14165,  3803
+};
+
+
+/* 28 bits */
+/*
+ *  isf codebooks:  split-by-5 VQ
+ *
+ *  codebook   vector dimension    number of vectors
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~
+ *     1            2                  64
+ *     2            3                  64
+ *     3            3                  64
+ *     4            4                  32
+ *     5            4                  32
+ */
+
+/*
+ * 1st split:   isf0 to isf1
+ */
+
+
+const int16 dico1_isf_noise[SIZE_BK_NOISE1*2] =
+{
+
+    -269,  -673,
+    -222,  -537,
+    -233,  -430,
+    -138,  -451,
+    -212,  -331,
+    -192,  -241,
+    -87,  -231,
+    -191,  -128,
+    -70,  -106,
+    -164,    -6,
+    74,  -179,
+    27,   -33,
+    -102,    74,
+    -162,   115,
+    -94,   172,
+    -6,   130,
+    -143,   234,
+    14,   218,
+    -65,   270,
+    88,   182,
+    -124,   341,
+    -44,   381,
+    38,   335,
+    117,   274,
+    -112,   454,
+    74,   431,
+    -5,   488,
+    175,   384,
+    -83,   561,
+    122,   529,
+    21,   601,
+    229,   481,
+    231,   303,
+    226,   608,
+    300,   372,
+    210,   187,
+    306,   265,
+    328,   473,
+    382,   331,
+    371,   132,
+    139,    58,
+    365,    21,
+    250,   -82,
+    443,   218,
+    483,   110,
+    426,   415,
+    579,   222,
+    518,   333,
+    573,   448,
+    455,   529,
+    685,   329,
+    332,   580,
+    595,   593,
+    468,   645,
+    762,   517,
+    326,   709,
+    485,   793,
+    130,   684,
+    671,   737,
+    354,   876,
+    88,   806,
+    -65,   706,
+    -35,  1016,
+    266,  1123
+};
+
+
+/*
+ * 2nd split:   isf2 to isf4
+ */
+
+const int16 dico2_isf_noise[SIZE_BK_NOISE2*3] =
+{
+
+    -824,  -884,  -949,
+    -805,  -456,  -418,
+    -442,  -438,  -541,
+    -217,  -578,  -793,
+    -168,  -444,  -582,
+    -287,  -492,  -274,
+    -552,  -297,  -300,
+    -163,  -333,  -358,
+    -370,  -232,  -232,
+    -175,  -358,  -159,
+    -381,   -21,  -357,
+    -184,  -159,  -162,
+    -53,  -191,  -280,
+    18,  -267,  -215,
+    -138,    61,  -283,
+    71,   -95,  -294,
+    13,  -156,  -546,
+    0,   -83,   -79,
+    44,    97,  -316,
+    178,   -52,  -213,
+    222,  -261,  -422,
+    237,  -118,   -44,
+    141,   145,  -132,
+    363,    81,  -287,
+    213,    65,    34,
+    -107,    94,    -5,
+    91,   -29,   126,
+    -355,    51,   -41,
+    -219,   -76,   145,
+    -63,   100,   244,
+    -719,    44,    27,
+    -572,  -124,   155,
+    -423,   133,   315,
+    -917,    71,   224,
+    -268,   318,   131,
+    -93,  -190,   420,
+    -97,   122,   491,
+    -79,   317,   355,
+    130,   100,   325,
+    86,  -293,   210,
+    133,   258,   161,
+    176,   -73,   465,
+    195,   300,   384,
+    348,    22,   221,
+    376,   183,   409,
+    377,   286,   202,
+    242,   213,   659,
+    257,   565,   248,
+    344,   408,   -76,
+    405,   440,   509,
+    612,   385,   379,
+    536,   607,   216,
+    -56,   582,   192,
+    100,   517,   567,
+    -365,   448,   445,
+    728,   347,    10,
+    505,   357,   759,
+    636,   582,   658,
+    335,   517,   852,
+    378,   809,   572,
+    -195,   878,   829,
+    529,   707,   987,
+    918,   726,   392,
+    1250,   997,  1063
+};
+
+/*
+ * 3rd split:   isf5 to isf7
+ */
+
+const int16 dico3_isf_noise[SIZE_BK_NOISE3*3] =
+{
+
+    -805,  -838,  -774,
+    -522,  -627,  -828,
+    -477,  -486,  -603,
+    -295,  -481,  -634,
+    -366,  -384,  -393,
+    -186,  -414,  -396,
+    -237,  -394,  -106,
+    -252,  -202,  -275,
+    -61,  -177,  -442,
+    -84,  -198,  -199,
+    -179,  -125,   -31,
+    -72,   -47,  -163,
+    -298,  -220,   215,
+    -64,  -168,   251,
+    -133,   156,   -59,
+    -30,    -2,   127,
+    54,    66,   -61,
+    -233,    21,   251,
+    209,   -50,    32,
+    33,   194,   136,
+    -117,   -18,   475,
+    202,    46,   309,
+    256,   185,    53,
+    35,   200,   390,
+    200,   263,   242,
+    -216,   302,   294,
+    128,   358,     0,
+    19,   431,   287,
+    224,   447,   280,
+    367,   165,   213,
+    397,   314,   319,
+    383,   379,    75,
+    277,   325,   462,
+    394,   505,   334,
+    251,    98,  -213,
+    450,   153,   448,
+    565,   226,    76,
+    470,   383,   502,
+    635,   390,   278,
+    237,   135,   620,
+    342,   401,   649,
+    331,   551,   518,
+    130,   418,   592,
+    531,   306,   737,
+    729,   389,   580,
+    497,   557,   699,
+    296,   383,   874,
+    283,   624,   759,
+    126,   622,   476,
+    559,   595,   472,
+    382,   770,   616,
+    719,   613,   745,
+    540,   639,   928,
+    517,   826,   801,
+    684,   811,   604,
+    752,   786,   857,
+    933,   661,   350,
+    694,   450,  1061,
+    562,   911,  1051,
+    824,   813,  1104,
+    758,  1047,   882,
+    1140,   917,   889,
+    1039,  1246,  1426,
+    1483,  1666,  1876
+};
+
+/*
+ * 4th split:   isf8 to isf11
+ */
+
+const int16 dico4_isf_noise[SIZE_BK_NOISE4*4] =
+{
+
+    -776,  -854,  -891,  -920,
+    -552,  -610,  -663,  -741,
+    -321,  -370,  -476,  -565,
+    274,  -160,  -456,   201,
+    265,    67,  -160,  -306,
+    -8,  -210,    79,   272,
+    163,   236,   307,   308,
+    578,   317,    64,   298,
+    -9,   197,   342,   620,
+    343,   232,   314,   622,
+    173,   149,   548,   527,
+    356,   370,   481,   376,
+    135,   444,   488,   556,
+    391,   471,   487,   653,
+    228,   424,   576,   835,
+    422,   372,   722,   682,
+    295,   673,   693,   635,
+    539,   596,   590,   449,
+    475,   618,   659,   818,
+    735,   517,   491,   673,
+    602,   346,   257,   877,
+    625,   635,   849,   720,
+    727,   818,   698,   595,
+    653,   481,   690,  1139,
+    814,   762,   704,   908,
+    507,   747,   898,   936,
+    848,   855,   924,   785,
+    646,  1037,   882,   795,
+    772,   845,  1024,  1151,
+    1133,   983,   818,   921,
+    940,  1068,  1252,  1302,
+    1588,  1767,  1718,  1513
+};
+
+/*
+ * 5th split:   isf12 to isf15
+ */
+
+const int16 dico5_isf_noise[SIZE_BK_NOISE5*4] =
+{
+    -810,  -879,  -945,  -254,
+    248,   184,   671,   128,
+    288,   703,   918,    99,
+    658,   558,   662,   219,
+    552,   585,   910,   208,
+    559,   804,   759,   119,
+    606,   774,   921,  -139,
+    782,   761,   748,   208,
+    756,   708,   983,    56,
+    544,   864,  1010,   152,
+    737,   698,   987,   299,
+    771,   924,   879,   103,
+    536,   785,   961,   405,
+    667,   916,   801,   328,
+    738,   705,   773,   439,
+    823,   871,   992,   355,
+    640,  1004,  1052,   369,
+    724,   822,   949,   597,
+    415,   655,   729,   482,
+    1009,   896,   793,   363,
+    908,   803,   687,   -25,
+    1016,   838,  1011,   189,
+    947,  1112,   942,   222,
+    914,  1049,   981,   527,
+    956,   987,  1011,  -120,
+    781,  1049,  1121,    92,
+    1178,  1053,   884,    47,
+    1123,  1059,  1182,   118,
+    933,   972,  1277,   357,
+    1109,   918,  1101,   503,
+    1039,  1286,  1220,   317,
+    1351,  1207,  1010,   326
+};
+
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s.cpp b/media/libstagefright/codecs/amrwb/src/qpisf_2s.cpp
new file mode 100644
index 0000000..0d465c6
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qpisf_2s.cpp
@@ -0,0 +1,350 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: qpisf_2s.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    int16 * seed          seed for the random ng
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Coding/Decoding of ISF parameters  with prediction.
+
+   The ISF vector is quantized using two-stage VQ with split-by-2
+   in 1st stage and split-by-5 (or 3)in the second stage.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+#include "qisf_ns.h"
+#include "qpisf_2s.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define MU         10923           /* Prediction factor   (1.0/3.0) in Q15 */
+#define N_SURV_MAX 4               /* 4 survivors max */
+#define ALPHA      29491           /* 0. 9 in Q15     */
+#define ONE_ALPHA (32768-ALPHA)    /* (1.0 - ALPHA) in Q15 */
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/*-------------------------------------------------------------------*
+ * routine:   Disf_2s_46b()                                          *
+ *            ~~~~~~~~~                                              *
+ * Decoding of ISF parameters                                        *
+ *-------------------------------------------------------------------*/
+
+void Dpisf_2s_46b(
+    int16 * indice,   /* input:  quantization indices                       */
+    int16 * isf_q,    /* output: quantized ISF in frequency domain (0..0.5) */
+    int16 * past_isfq,/* i/0   : past ISF quantizer                    */
+    int16 * isfold,   /* input : past quantized ISF                    */
+    int16 * isf_buf,  /* input : isf buffer                            */
+    int16 bfi,        /* input : Bad frame indicator                   */
+    int16 enc_dec
+)
+{
+    int16 ref_isf[M];
+    int16 i, j, tmp;
+    int32 L_tmp;
+
+
+    if (bfi == 0)                          /* Good frame */
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_q[i] = dico1_isf[(indice[0] << 3) + indice[0] + i];
+        }
+        for (i = 0; i < 7; i++)
+        {
+            isf_q[i + 9] = dico2_isf[(indice[1] << 3) - indice[1] + i];
+        }
+
+        for (i = 0; i < 3; i++)
+        {
+            isf_q[i]      += dico21_isf[indice[2] * 3 + i];
+            isf_q[i + 3]  += dico22_isf[indice[3] * 3 + i];
+            isf_q[i + 6]  += dico23_isf[indice[4] * 3 + i];
+            isf_q[i + 9]  += dico24_isf[indice[5] * 3 + i];
+            isf_q[i + 12] += dico25_isf[(indice[6] << 2) + i];
+        }
+
+        isf_q[i + 12] += dico25_isf[(indice[6] << 2) + i];
+
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = isf_q[i];
+            isf_q[i] += mean_isf[i];
+            isf_q[i] += ((int32)MU * past_isfq[i]) >> 15;
+            past_isfq[i] = tmp;
+        }
+
+
+        if (enc_dec)
+        {
+            for (i = 0; i < M; i++)
+            {
+                for (j = (L_MEANBUF - 1); j > 0; j--)
+                {
+                    isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+                }
+                isf_buf[i] = isf_q[i];
+            }
+        }
+    }
+    else
+    {                                      /* bad frame */
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = mul_16by16_to_int32(mean_isf[i], 8192);
+            for (j = 0; j < L_MEANBUF; j++)
+            {
+                L_tmp = mac_16by16_to_int32(L_tmp, isf_buf[j * M + i], 8192);
+            }
+            ref_isf[i] = amr_wb_round(L_tmp);
+        }
+
+        /* use the past ISFs slightly shifted towards their mean */
+        for (i = 0; i < ORDER; i++)
+        {
+            isf_q[i] = add_int16(mult_int16(ALPHA, isfold[i]), mult_int16(ONE_ALPHA, ref_isf[i]));
+        }
+
+        /* estimate past quantized residual to be used in next frame */
+
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = add_int16(ref_isf[i], mult_int16(past_isfq[i], MU));      /* predicted ISF */
+            past_isfq[i] = sub_int16(isf_q[i], tmp);
+            past_isfq[i] >>= 1;           /* past_isfq[i] *= 0.5 */
+        }
+
+    }
+
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
+}
+
+/*
+ * routine:   Disf_2s_36b()
+ *            ~~~~~~~~~
+ * Decoding of ISF parameters
+ */
+
+void Dpisf_2s_36b(
+    int16 * indice,    /* input:  quantization indices                       */
+    int16 * isf_q,     /* output: quantized ISF in frequency domain (0..0.5) */
+    int16 * past_isfq, /* i/0   : past ISF quantizer                    */
+    int16 * isfold,    /* input : past quantized ISF                    */
+    int16 * isf_buf,   /* input : isf buffer                            */
+    int16 bfi,         /* input : Bad frame indicator                   */
+    int16 enc_dec
+)
+{
+    int16 ref_isf[M];
+    int16 i, j, tmp;
+    int32 L_tmp;
+
+
+    if (bfi == 0)                          /* Good frame */
+    {
+        for (i = 0; i < 9; i++)
+        {
+            isf_q[i] = dico1_isf[indice[0] * 9 + i];
+        }
+        for (i = 0; i < 7; i++)
+        {
+            isf_q[i + 9] = add_int16(dico2_isf[indice[1] * 7 + i], dico23_isf_36b[indice[4] * 7 + i]);
+        }
+
+        for (i = 0; i < 5; i++)
+        {
+            isf_q[i] = add_int16(isf_q[i], dico21_isf_36b[indice[2] * 5 + i]);
+        }
+        for (i = 0; i < 4; i++)
+        {
+            isf_q[i + 5] = add_int16(isf_q[i + 5], dico22_isf_36b[(indice[3] << 2) + i]);
+        }
+
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = isf_q[i];
+            isf_q[i] = add_int16(tmp, mean_isf[i]);
+            isf_q[i] = add_int16(isf_q[i], mult_int16(MU, past_isfq[i]));
+            past_isfq[i] = tmp;
+        }
+
+
+        if (enc_dec)
+        {
+            for (i = 0; i < M; i++)
+            {
+                for (j = (L_MEANBUF - 1); j > 0; j--)
+                {
+                    isf_buf[j * M + i] = isf_buf[(j - 1) * M + i];
+                }
+                isf_buf[i] = isf_q[i];
+            }
+        }
+    }
+    else
+    {                                      /* bad frame */
+        for (i = 0; i < M; i++)
+        {
+            L_tmp = mul_16by16_to_int32(mean_isf[i], 8192);
+            for (j = 0; j < L_MEANBUF; j++)
+            {
+                L_tmp = mac_16by16_to_int32(L_tmp, isf_buf[j * M + i], 8192);
+            }
+
+            ref_isf[i] = amr_wb_round(L_tmp);
+        }
+
+        /* use the past ISFs slightly shifted towards their mean */
+        for (i = 0; i < ORDER; i++)
+        {
+            isf_q[i] = add_int16(mult_int16(ALPHA, isfold[i]), mult_int16(ONE_ALPHA, ref_isf[i]));
+        }
+
+        /* estimate past quantized residual to be used in next frame */
+
+        for (i = 0; i < ORDER; i++)
+        {
+            tmp = add_int16(ref_isf[i], mult_int16(past_isfq[i], MU));      /* predicted ISF */
+            past_isfq[i] = sub_int16(isf_q[i], tmp);
+            past_isfq[i] >>=  1;           /* past_isfq[i] *= 0.5 */
+        }
+    }
+
+    Reorder_isf(isf_q, ISF_GAP, ORDER);
+
+    return;
+}
+
+/*
+ * procedure  Reorder_isf()
+ *            ~~~~~~~~~~~~~
+ * To make sure that the  isfs are properly order and to keep a certain
+ * minimum distance between consecutive isfs.
+ *
+ *    Argument         description                     in/out
+ *    ~~~~~~~~         ~~~~~~~~~~~                     ~~~~~~
+ *     isf[]           vector of isfs                    i/o
+ *     min_dist        minimum required distance         i
+ *     n               LPC order                         i
+ */
+
+void Reorder_isf(
+    int16 * isf,                         /* (i/o) Q15: ISF in the frequency domain (0..0.5) */
+    int16 min_dist,                      /* (i) Q15  : minimum distance to keep             */
+    int16 n                              /* (i)      : number of ISF                        */
+)
+{
+    int16 i, isf_min;
+
+    isf_min = min_dist;
+
+    for (i = 0; i < n - 1; i++)
+    {
+        if (isf[i] < isf_min)
+        {
+            isf[i] = isf_min;
+        }
+        isf_min = add_int16(isf[i], min_dist);
+    }
+
+    return;
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s.h b/media/libstagefright/codecs/amrwb/src/qpisf_2s.h
new file mode 100644
index 0000000..61f8c06
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qpisf_2s.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/qpisf_2s.h
+
+     Date: 01/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef QPISF_2S_H
+#define QPISF_2S_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "qisf_ns.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+----------------------------------------------------------------------------*/
+
+#define N_SURV  4
+
+#define SIZE_BK1  256
+#define SIZE_BK2  256
+#define SIZE_BK21 64
+#define SIZE_BK22 128
+#define SIZE_BK23 128
+#define SIZE_BK24 32
+#define SIZE_BK25 32
+
+#define SIZE_BK21_36b 128
+#define SIZE_BK22_36b 128
+#define SIZE_BK23_36b 64
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+extern const int16 mean_isf[ORDER];
+extern const int16 dico1_isf[SIZE_BK1*9];
+extern const int16 dico2_isf[SIZE_BK2*7];
+extern const int16 dico21_isf[SIZE_BK21*3];
+extern const int16 dico22_isf[SIZE_BK22*3];
+extern const int16 dico23_isf[SIZE_BK23*3];
+extern const int16 dico24_isf[SIZE_BK24*3];
+extern const int16 dico25_isf[SIZE_BK25*4];
+extern const int16 dico21_isf_36b[SIZE_BK21_36b*5];
+extern const int16 dico22_isf_36b[SIZE_BK22_36b*4];
+extern const int16 dico23_isf_36b[SIZE_BK23_36b*7];
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+#endif  /* QPISF_2S_H */
diff --git a/media/libstagefright/codecs/amrwb/src/qpisf_2s_tab.cpp b/media/libstagefright/codecs/amrwb/src/qpisf_2s_tab.cpp
new file mode 100644
index 0000000..d57522e
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/qpisf_2s_tab.cpp
@@ -0,0 +1,1383 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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.
+****************************************************************************************/
+/*-------------------------------------------------------------------*
+ *                         qpisf_2s_tab.cpp
+ *-------------------------------------------------------------------*
+ * Quantization tables for two-stage of ISFs (split by 2 in 1st stage)
+ * Version whith prediction MU = 0.25
+ *-------------------------------------------------------------------*/
+
+#include "qisf_ns.h"
+#include "qpisf_2s.h"
+
+
+
+
+/* means of ISFs */
+const int16 mean_isf[ORDER] =
+{
+
+    738,  1326,  2336,  3578,  4596,  5662,  6711,  7730,
+    8750,  9753, 10705, 11728, 12833, 13971, 15043,  4037
+};
+
+/* 46 bits */
+/*
+ *  isf codebooks:  two-stage VQ with split-by-5 in 2nd stage
+ *
+ *  codebook   vector dimension    number of vectors
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~
+ *     1_1            9                  256
+ *     1_2            7                  256
+ *     2_1            3                  64
+ *     2_2            3                  128
+ *     2_3            3                  128
+ *     2_4            3                  32
+ *     2_5            4                  32
+ */
+
+/*
+ * 1st stage codebook; 1st split:   isf0 to isf8
+ */
+
+const int16 dico1_isf[SIZE_BK1*9] =
+{
+
+    579,  1081,  1035,   390,     3,  -263,  -198,   -82,    38,
+    18,   -68,   -12,   313,   761,   405,   249,   111,   -76,
+    740,  1263,  1292,  1006,   997,  1019,  1017,   976,   923,
+    -91,   827,   948,   648,   613,   535,   522,   490,   421,
+    41,   -44,  -281,  -472,   652,   534,   193,   135,   -90,
+    41,  -121,  -356,   -60,   663,   307,    61,   -48,  -344,
+    557,   946,  1049,   867,   846,   990,  1112,  1262,  1241,
+    -118,  -204,   328,   512,   870,   793,   610,   402,   186,
+    156,   293,    74,  -338,  -475,  -897,  -594,  -161,  -497,
+    226,   131,  -138,   307,   169,  -271,  -164,  -387,  -624,
+    62,   -32,   -61,  -252,  -541,  -828, -1027,  -523,  -662,
+    102,   -61,   141,   112,  -270,  -251,  -541,    25,  -150,
+    6,  -132,  -356,  -686,   -96,  -322,  -522,   -31,  -326,
+    -36,  -209,  -521,  -229,   307,  -132,    -5,   -99,  -384,
+    60,   -51,  -237,  -668,  -973,  -407,  -708,   -75,  -172,
+    26,  -138,  -266,   111,  -302,    43,  -278,  -356,  -359,
+    570,   822,   496,  -154,  -312,   -92,   137,   279,   371,
+    -146,   368,   409,    68,     6,    77,   167,   202,   162,
+    633,   898,   996,   756,   662,   683,   783,   909,   996,
+    -103,   294,   607,   415,   483,   462,   480,   431,   408,
+    -120,  -338,  -612,  -524,   584,   331,    92,   433,   276,
+    -178,  -293,  -154,   -41,   269,   100,    -9,   213,   160,
+    830,   736,   278,   820,  1254,   686,   712,  1039,   473,
+    -218,  -304,   463,   454,   397,   273,   202,   286,   273,
+    -232,     7,     6,  -388,  -472,  -427,  -378,  -167,  -100,
+    -294,  -183,   134,   -47,   101,   -88,   -84,  -117,    -3,
+    57,    17,  -202,  -634,  -989, -1119,  -533,   176,   -36,
+    120,   -28,    23,   111,  -319,   318,   -22,   -77,   266,
+    -271,  -464,  -434,  -658,  -640,  -385,  -385,   -99,   -69,
+    -198,  -259,  -266,   -44,   -39,  -139,  -137,   171,    66,
+    9,  -145,  -377,  -846, -1000,  -111,  -325,   342,   135,
+    -81,  -286,  -380,   192,   -57,   307,    76,   -24,  -140,
+    677,   702,   247,    56,   249,   141,  -105,  -236,   -99,
+    36,   -39,   -69,   348,   198,   -93,   322,    91,   -72,
+    503,   885,  1508,  1307,  1282,  1172,  1119,  1209,  1061,
+    416,   719,   989,  1227,  1001,  1052,   954,   741,  1044,
+    -127,  -376,  -657,   139,   623,   223,   501,   306,   220,
+    -113,  -384,  -796,   504,   438,    85,   213,   -83,  -194,
+    585,  1132,  1233,  1091,  1247,  1433,  1512,  1448,  1314,
+    -174,  -422,     7,  1155,  1089,  1182,  1003,   945,   806,
+    8,  -126,  -317,  -103,  -351,  -695,   -98,  -268,  -537,
+    33,  -103,  -290,   167,   -39,  -407,    44,  -208,  -375,
+    104,   -23,   -64,  -291,  -637,  -851, -1084,   -61,  -112,
+    -75,  -306,  -434,   218,  -148,  -354,  -680,  -133,  -216,
+    -121,  -377,  -718,   -97,  -130,  -361,  -156,  -379,  -599,
+    -56,  -254,  -586,   235,   157,  -214,    11,  -260,  -149,
+    -124,  -267,  -397,  -580,  -593,  -527,  -805,  -385,   346,
+    -193,  -440,  -708,  -351,  -141,  -255,  -499,  -147,  -185,
+    448,   660,   494,   208,   509,   461,   338,   291,   149,
+    -223,    88,   335,   159,   212,   191,   286,   308,   205,
+    -31,   469,   803,   659,   619,   658,   843,   987,  1113,
+    -171,  -242,   514,   362,   295,   524,   552,   694,   585,
+    -64,  -308,  -448,   -21,   284,   786,   446,   289,    92,
+    -218,  -390,    -7,   169,   206,   330,   352,   408,   358,
+    -36,   702,   959,   859,   861,  1115,  1269,  1357,  1305,
+    -133,  -341,   -65,   678,   417,   440,   486,   518,   780,
+    33,   -44,  -191,  -344,  -461,  -755,  -201,   217,   -31,
+    -353,  -547,   -44,   123,   -61,   -68,   -79,    29,    60,
+    73,   -57,  -406,  -766, -1243, -1203,   240,   400,   165,
+    -73,  -282,  -601,  -213,  -171,  -375,   332,    35,  -103,
+    -29,  -207,  -553,  -476,  -638,  -908,   172,   -22,  -135,
+    -192,  -239,  -164,  -103,  -111,   -47,   153,   125,   110,
+    -1,  -203,  -570, -1030, -1424,  -535,   155,     1,   147,
+    -333,  -653,  -865,  -197,  -158,   -21,   -44,    95,   108,
+    389,   588,   490,    33,  -237,  -524,  -628,  -136,  -260,
+    40,  -177,  -462,   453,   862,   380,   131,  -130,  -405,
+    842,  1678,  1841,  1549,  1474,  1256,  1082,   905,   742,
+    370,  1216,  1768,  1633,  1212,   636,    22,  -330,    71,
+    -76,  -281,  -741,  -742,   898,   619,   277,    71,  -222,
+    -32,  -265,  -556,   -25,   994,   682,   305,   126,  -165,
+    73,   738,   893,   968,   993,  1768,  2273,  1840,  1391,
+    -69,  -349,  -585,   234,  1158,   903,   626,   510,   251,
+    -1,   -99,  -272,  -210,  -603,  -351,  -540,  -811,  -383,
+    -16,  -230,  -504,   410,   149,  -205,  -343,  -651,  -639,
+    103,    -9,  -227,  -205,  -562,  -781, -1079, -1208,  -156,
+    143,    63,  -135,   -67,  -317,  -602,  -784, -1154,  -640,
+    -144,  -391,  -674,  -622,  -200,  -254,  -660,  -947,  -395,
+    -40,  -250,  -625,    27,   543,    94,  -131,  -386,  -673,
+    -123,  -371,  -757,  -451,  -564,  -614,  -415,  -711,   -35,
+    -116,  -309,  -593,  -268,   239,   -33,  -338,  -650,  -135,
+    94,   251,   554,    57,  -312,  -423,  -154,   -57,   235,
+    -268,   -71,   381,   114,   -44,   -87,   125,   173,   133,
+    1513,  1714,  1238,   534,   276,   315,   461,   459,   508,
+    -131,   -19,  1149,   670,   486,   356,   309,   369,   296,
+    -223,  -501,  -899,  -722,   -70,     6,   131,   310,   394,
+    -99,  -303,  -517,   249,    64,   -53,   135,   -11,   453,
+    -147,  -399,  -730,  -401,   817,   738,   802,   749,   575,
+    -154,  -435,  -739,   800,   593,   366,   529,   318,   326,
+    -224,    45,   -39,  -387,  -515,  -518,  -608,  -384,  -321,
+    -315,  -377,   143,  -101,  -113,  -377,  -177,  -144,   -12,
+    117,    40,  -239,  -651, -1051,  -581,  -737,  -990,  -328,
+    26,   -50,  -157,   -23,  -453,  -283,  -531,  -546,   192,
+    -252,  -501,  -743,  -589,  -627,  -499,  -328,  -118,   -72,
+    -324,  -494,  -244,  -306,  -144,  -177,  -262,  -135,   -78,
+    -36,  -234,  -519,  -961, -1290,  -314,  -479,  -371,   -45,
+    -95,  -292,  -535,    -8,  -300,   112,  -164,  -277,   198,
+    -99,  -128,   880,   836,   579,   351,    23,   -95,  -217,
+    -27,  -258,   124,  1011,   597,   425,   144,     7,   -73,
+    421,  1293,  1640,  1623,  1742,  1617,  1499,  1284,  1006,
+    -95,   752,  1680,  1569,  1618,  1436,  1200,   980,   712,
+    -69,  -300,  -683,  -435,  1132,   899,   504,   332,   109,
+    -74,  -323,  -637,   563,  1074,   608,   371,   105,   -49,
+    -78,   831,  1194,  1110,  1378,  1481,  1492,  1365,  1217,
+    -259,  -121,  1440,  1334,  1628,  1490,  1438,  1223,   933,
+    -82,  -306,  -613,  -222,  -378,  -675,  -545,  -671,  -845,
+    53,  -124,  -347,   422,    52,  -125,  -270,  -529,     9,
+    79,   -89,  -320,  -662,  -999, -1199, -1243,  -676,  -297,
+    -68,  -273,  -611,   137,  -146,  -397,  -627,  -845,  -220,
+    -112,  -346,  -797,  -826,   234,  -132,  -188,  -278,  -522,
+    -159,  -405,  -734,  -419,   293,    74,  -167,  -167,   184,
+    -153,  -437,  -833, -1080,  -336,  -472,  -561,  -340,  -253,
+    -169,  -423,  -820,  -904,  -131,   -19,  -346,  -604,    31,
+    33,   -31,   312,    62,  -148,    49,   -59,   564,   486,
+    -306,  -333,   194,   -44,    67,    72,   147,   205,   243,
+    -207,   -49,  1360,   983,   969,   991,  1014,  1110,   973,
+    -211,  -172,   883,   627,   711,   674,   705,   798,   746,
+    -88,  -325,  -763,  -974,   687,   908,   514,   382,   172,
+    -292,  -612,  -805,    63,   131,   270,   259,   352,   348,
+    -235,   -84,   955,   818,  1120,  1289,  1559,  1480,  1285,
+    -180,  -461,  -614,   657,   691,   745,   854,   783,   713,
+    -97,  -309,  -477,  -614,  -777,  -734,  -768,  -526,  -472,
+    -344,  -476,   -35,  -169,    49,   -77,  -150,  -240,  -141,
+    -52,  -268,  -639,  -919, -1278, -1113,  -342,  -333,  -151,
+    -68,  -242,  -585,   -73,  -209,  -478,  -159,  -429,   133,
+    -197,  -499, -1005, -1268,  -272,  -224,  -105,   -67,    17,
+    -363,  -618,  -414,  -116,   -62,    20,    10,   116,   108,
+    -195,  -475,  -906, -1260,  -891,  -441,  -277,  -142,   -28,
+    -226,  -519,  -950,  -700,  -275,  -266,  -116,  -105,    82,
+    404,   511,   520,   327,    17,  -194,  -333,  -536,  -586,
+    -114,  -130,   276,   237,   204,   342,   135,   -16,  -111,
+    670,  1208,  1168,   860,   742,   601,   528,   403,   309,
+    397,   621,   966,   752,   579,   398,   400,   329,   252,
+    191,   180,  -137,  -467,   272,   106,   -95,    17,  -192,
+    -80,  -290,  -626,   194,   598,   196,    21,  -281,    77,
+    510,   864,  1108,   807,   939,   902,   925,   717,   481,
+    137,   367,   534,   764,   670,   382,   296,   153,    84,
+    303,   497,   144,   -85,  -125,  -539,  -482,  -464,  -764,
+    233,   347,    68,  -147,   169,  -210,  -242,  -226,  -482,
+    307,   422,   154,  -175,  -386,  -722,  -724,  -904, -1015,
+    309,   308,   160,   -60,  -470,  -420,  -598,  -791,  -219,
+    68,   121,  -137,  -560,  -146,  -446,  -515,  -494,  -729,
+    130,    53,  -227,    46,   474,    32,  -161,  -192,  -490,
+    213,   164,   -71,  -465,  -876,  -161,  -456,  -587,   -48,
+    218,   117,    39,   177,  -194,   -88,  -226,  -418,    50,
+    210,   547,   569,   279,   121,   -44,   -50,    10,   -84,
+    58,   140,   182,    -5,   267,   117,   106,   211,   198,
+    539,   835,   913,   719,   617,   544,   591,   565,   642,
+    153,   559,   872,   460,   222,   108,   188,   180,   183,
+    158,   119,   284,  -153,  -271,   229,    87,   110,   -57,
+    -183,    82,   118,    21,    13,    40,   118,   191,   185,
+    162,   889,   654,   108,   -34,   244,   488,   561,   532,
+    163,    56,   609,   341,    50,   329,    68,   266,   218,
+    100,   206,    18,  -304,  -107,  -436,  -487,   -65,  -306,
+    -86,   154,   134,   -30,   -45,   -73,  -104,   -80,   -96,
+    245,   330,    10,  -440,  -849, -1082,    79,    40,  -265,
+    196,   372,   272,  -181,  -493,  -389,   275,    80,   -59,
+    2,   -12,  -246,  -505,  -100,  -436,    21,  -187,  -431,
+    -221,   -48,    36,  -271,  -186,  -147,  -109,    26,    71,
+    213,   140,    72,  -351,  -620,   -84,  -363,    69,    46,
+    91,   167,    -3,   -95,   -99,  -105,   -48,   114,   147,
+    259,   249,   172,   607,   406,    52,    59,  -189,  -320,
+    115,   -85,   -54,   574,   128,   226,   -59,  -253,   130,
+    -62,  1033,  1308,  1035,  1127,  1098,  1029,   961,   823,
+    39,   364,   757,   940,   728,   660,   659,   583,   770,
+    -115,  -338,  -760,  -471,   394,    37,   441,   178,     6,
+    -57,  -305,  -525,   796,   453,   188,    -4,  -114,   248,
+    71,   444,   797,   731,  1096,  1157,  1222,  1029,   811,
+    135,   359,   551,   425,   749,   815,   874,   704,   502,
+    132,   247,     0,  -206,  -449,  -750,  -258,  -514,  -633,
+    248,   249,    91,   121,  -195,  -499,   -90,  -282,  -435,
+    78,    20,  -277,  -623,  -983, -1224,  -415,  -458,  -639,
+    347,   509,   208,  -179,  -464,  -728,   -76,  -237,  -486,
+    -103,  -343,  -756,  -713,  -265,  -609,  -191,  -398,  -636,
+    -121,  -383,  -749,   567,   252,   -36,  -354,  -417,   -50,
+    204,   100,  -149,  -650, -1081,   -47,    -7,  -263,   111,
+    -46,  -180,  -267,  -324,  -562,  -394,  -692,   398,   292,
+    482,   670,   683,   624,   442,   165,   116,    36,  -149,
+    108,   247,   291,   247,   355,   122,   109,   224,   296,
+    -14,   945,   990,   801,   755,   815,   847,   913,   892,
+    292,   349,   725,   482,   388,   329,   429,   620,   667,
+    -34,   197,   213,  -127,    84,   494,   620,   575,   375,
+    126,   207,   172,   167,   362,   202,   296,   395,   455,
+    -6,   250,   539,   467,   636,   801,  1149,  1287,  1118,
+    27,   240,   369,   280,   440,   411,   634,   892,   953,
+    159,   170,   -58,  -395,  -797,  -690,    77,  -211,  -334,
+    -5,   -28,   -13,   -74,  -335,  -603,   300,    88,  -205,
+    82,   -33,  -364,  -698, -1203, -1153,   110,  -146,  -289,
+    113,     1,  -243,  -588,  -994,  -496,   414,   160,    42,
+    -56,  -247,  -440,  -693,  -996,  -479,    11,  -178,  -357,
+    -151,  -353,  -327,  -211,  -340,   141,    65,   425,   453,
+    34,  -169,  -455,  -932, -1215,   138,   499,   256,   324,
+    68,   139,   -15,  -547,  -478,    17,   306,   502,   481,
+    -32,  -134,   445,   129,  -143,  -244,  -503,  -507,  -599,
+    61,  -140,  -345,   496,   458,    -2,    20,  -227,  -514,
+    394,  1765,  1666,  1339,  1117,   806,   642,   479,   380,
+    215,   519,   920,  1053,  1090,   791,   528,   290,   155,
+    -54,  -233,  -647,  -602,   639,   294,    -2,  -167,  -442,
+    -78,  -315,  -791,  -113,   820,   403,   158,  -116,  -356,
+    529,  1851,  2003,  1228,   622,   -41,  -416,   344,   819,
+    -105,  -379,  -236,  1224,   893,   749,   568,   356,   214,
+    -17,  -199,  -144,    50,  -283,  -247,  -578,  -846, -1087,
+    69,   -11,  -381,  -206,   209,  -284,  -387,  -416,  -716,
+    39,    -5,  -145,  -374,  -682,  -909, -1074, -1169, -1066,
+    287,   226,    67,  -221,  -662,  -171,  -421,  -642,  -707,
+    -132,  -348,  -538,  -448,   -20,    -4,  -354,  -748,  -933,
+    4,   -75,  -289,  -598,   317,    52,  -208,  -297,  -559,
+    -88,  -264,  -358,  -589,  -631,  -248,  -523,  -822, -1071,
+    70,    -8,    54,  -314,  -515,    92,  -146,  -274,  -493,
+    199,    62,   391,   158,  -141,    71,  -219,  -203,  -207,
+    152,    40,   329,   162,   -29,    48,  -149,   108,   127,
+    635,  1058,   883,   492,   372,   312,   317,   274,   241,
+    267,   722,  1256,   882,   625,   248,     8,   -81,   -60,
+    -58,  -138,  -291,  -600,   -12,    -2,   -39,   147,   117,
+    -107,  -345,  -513,   459,    76,    92,  -272,   388,   262,
+    362,   516,   203,  -409,  -716,  -831,  -331,   185,   209,
+    -117,  -391,  -298,   671,   292,   538,   257,   166,   -38,
+    -102,  -319,  -194,  -283,  -573,  -262,  -579,  -219,  -444,
+    -235,    78,    11,  -168,  -101,  -229,  -263,  -321,  -123,
+    70,    50,  -170,  -599,  -996,  -588,  -263,  -516,  -455,
+    394,   363,   229,  -136,  -538,    21,  -183,  -348,  -201,
+    -124,  -368,  -640,  -879,  -847,  -209,  -409,  -494,  -515,
+    -127,  -341,  -541,  -425,  -510,   -10,  -252,  -473,  -291,
+    84,   -69,  -201,  -676,  -868,   103,  -311,  -132,  -320,
+    5,  -173,  -188,  -297,  -628,   197,   -57,     7,   -11,
+    49,  -160,    56,   558,   111,    33,  -311,  -440,  -463,
+    -1,  -246,  -307,   862,   453,   139,  -170,  -355,  -232,
+    279,   966,  1642,  1478,  1463,  1123,   795,   525,   339,
+    -197,   -38,  1702,  1331,  1252,   950,   692,   504,   426,
+    -108,  -344,  -861, -1172,   444,   354,    88,   -46,  -220,
+    -53,  -321,  -494,  1113,   744,   364,   198,   -34,   -75,
+    457,   955,  1177,  1214,  1427,  1457,  1345,   917,   539,
+    -69,   199,   897,  1140,  1343,  1183,   977,   742,   522,
+    122,    44,  -269,    27,  -155,  -562,  -307,  -590,  -773,
+    154,    42,  -160,   252,  -129,  -305,  -471,  -733,  -371,
+    135,   185,   -82,  -416,  -722,  -913,  -504,  -743,  -880,
+    149,   214,   -84,  -329,  -680,  -835,  -426,  -661,   -81,
+    -128,  -380,  -735,  -998,  -337,    17,  -182,  -467,  -697,
+    -84,  -290,  -510,  -592,    13,   440,   154,   -38,  -279,
+    70,   -61,  -246,  -727, -1047,   -80,  -381,  -535,  -704,
+    178,    -2,  -146,  -670,  -938,   482,   138,    63,    65,
+    -11,    15,   772,   443,   142,   -20,  -209,  -126,  -161,
+    -32,  -249,    95,   552,   124,    30,  -343,    82,   -86,
+    148,   751,  1515,  1105,   867,   606,   474,   448,   399,
+    -163,  -257,   899,  1097,   906,   751,   502,   390,   294,
+    -51,  -258,  -447,  -806,  -368,   763,   464,   364,   183,
+    -166,  -374,  -367,    87,    35,   399,   418,   856,   833,
+    -205,  -310,   588,   778,   785,  1065,  1118,  1245,  1157,
+    -173,  -312,   107,   345,   400,   790,   870,  1113,  1001,
+    -7,  -120,  -387,  -410,  -614,  -943,  -226,  -384,  -491,
+    -203,  -288,   -51,  -331,   -90,  -178,  -408,  -573,  -338,
+    56,   -29,  -273,  -627, -1041,  -798,  -247,  -467,   148,
+    66,    -2,  -205,  -205,  -575,  -349,   -57,  -352,   -58,
+    -45,  -225,  -471,  -924,  -497,    77,   -32,    44,  -135,
+    -277,  -491,  -497,  -502,  -424,  -202,  -137,    77,    96,
+    26,  -179,  -469, -1008, -1260,   262,   -35,  -132,  -259,
+    -66,  -232,  -447,  -533,  -789,  -191,  -100,  -267,   364
+};
+
+/*------------------------------------------------*
+ * 1st stage codebook; 2nd split:   isf9 to isf15
+ *------------------------------------------------*/
+
+const int16 dico2_isf[SIZE_BK2*7] =
+{
+
+    1357,  1313,  1136,   784,   438,   181,   145,
+    636,   648,   667,   568,   442,   217,   362,
+    427,   440,   674,   524,   332,   117,  -417,
+    121,   295,   468,   465,   230,    44,  -221,
+    -147,  -240,   149,    80,   390,   278,   106,
+    -418,  -556,   552,   511,   235,   144,   -95,
+    43,   193,   274,   150,    67,    34,  -273,
+    -43,  -126,   171,   416,   282,    63,  -354,
+    -372,   -86,  -344,  -108,   -94,  -182,   -89,
+    -600,  -840,  -200,   465,   258,   -11,  -253,
+    -48,   329,    97,  -290,  -543,  -795,  -354,
+    -570,  -117,   187,    10,  -133,  -416,   -76,
+    -618,  -129,  -247,  -371,    45,   -76,   277,
+    -1022, -1079,   126,   474,   254,   127,    52,
+    -281,    76,  -167,  -361,  -283,  -551,  -283,
+    -119,   -52,    -1,   134,   -32,  -204,  -415,
+    1064,   827,   637,   684,   464,   209,    12,
+    482,   416,   449,   371,   335,   294,   194,
+    719,   576,   365,   135,   113,    91,  -199,
+    298,   176,   493,   366,   194,   163,    36,
+    -35,  -236,  -259,   -36,    -4,    99,   152,
+    -98,  -306,   -27,   228,    90,   111,   -86,
+    91,    13,  -211,  -258,  -106,    86,   -64,
+    73,   -35,   -57,   -31,   162,    35,  -192,
+    -109,  -335,  -629,   -66,   -61,  -128,   322,
+    -495,  -669,  -728,   193,    31,  -220,   122,
+    324,    95,   -89,   -91,  -409,  -710,  -154,
+    0,  -234,    92,    33,  -343,  -609,  -220,
+    -343,  -408,  -476,  -655,  -153,    82,   222,
+    -490,  -745,  -255,    49,   -48,   135,  -127,
+    119,   -67,  -328,  -390,  -272,  -545,   -56,
+    -57,  -130,   -10,    -7,  -164,   -47,   -22,
+    984,  1064,   961,   568,   210,   -27,    16,
+    811,   691,   754,   514,   224,   -35,   166,
+    662,   704,   618,   386,    57,  -211,  -257,
+    510,   359,   418,   393,    91,  -144,   -18,
+    -193,   -31,   -27,   223,    89,  -143,    24,
+    -112,   -98,   471,   319,   185,     3,   175,
+    252,   146,   -47,   272,    48,  -211,  -234,
+    146,    69,   203,   364,    68,   -52,    51,
+    -259,  -478,  -697,  -349,  -758,  -501,    63,
+    -501,  -769,  -289,    79,  -311,  -497,  -106,
+    251,    53,  -235,  -469,  -895,  -884,   145,
+    -416,  -551,   140,  -133,  -523,  -775,    44,
+    -326,  -423,  -713,  -497,   -86,  -431,    99,
+    -757,  -772,  -160,   -76,   -46,   -32,   379,
+    85,   -35,  -200,  -401,  -663, -1040,  -247,
+    -180,  -330,   -92,  -376,    27,  -183,  -110,
+    1279,  1086,   781,   502,   324,   164,   157,
+    682,   466,   449,   277,   146,    28,   409,
+    635,   472,   390,   107,  -232,  -538,  -139,
+    196,   396,   332,   213,   209,   -29,   -81,
+    150,   -95,  -312,    76,   -77,  -320,   -50,
+    46,     9,    47,   175,   139,    30,   384,
+    218,   206,   -24,  -250,   -96,  -276,  -183,
+    26,   119,    38,    14,    -4,  -133,   -52,
+    -477,  -614,  -987,  -715,  -631,  -813,   200,
+    -744, -1009, -1065,  -745,  -631,  -171,    18,
+    -137,  -251,  -483,  -613,  -980, -1203,    12,
+    -605,  -767,  -562,  -686, -1088,  -515,    58,
+    -202,  -428,  -782, -1072,   -96,  -234,  -179,
+    -480,  -709, -1070,  -897,  -131,   -92,   321,
+    -145,  -193,  -512,  -729,  -572,  -765,  -210,
+    -331,  -585,  -525,  -631,  -281,  -208,  -303,
+    1165,  1104,   939,   828,   716,   426,   155,
+    6,  -109,   820,   778,   415,   113,   -27,
+    381,   339,   314,   265,   121,    -9,  -474,
+    -373,    47,   584,   442,    99,  -231,  -113,
+    -496,   -38,  -285,   262,   305,   170,     4,
+    -587,  -556,    69,    66,   471,   354,    13,
+    -138,    70,   -18,   106,    67,   167,  -302,
+    -445,  -141,   185,   191,   151,    83,  -133,
+    -257,  -521,  -720,  -198,   134,   -46,  -182,
+    -819, -1168,  -777,   512,   359,    95,  -113,
+    137,    -2,   -74,  -138,  -401,  -114,  -371,
+    -242,  -466,   204,   223,   -31,  -212,  -192,
+    -532,  -637,  -466,  -686,   256,   277,  -139,
+    -1141, -1244,  -381,   -75,   -54,    14,    88,
+    -311,   115,  -143,  -499,  -343,   124,  -416,
+    -616,  -147,  -135,    43,    -4,   121,  -369,
+    835,   783,   641,   390,   355,   350,    64,
+    72,   194,   443,   467,   436,   219,   372,
+    464,   369,   192,     4,  -156,   -72,  -226,
+    57,   206,   303,   205,   188,   101,   265,
+    -40,  -205,  -488,  -184,   276,    64,   -26,
+    -217,  -433,  -297,   137,   328,   308,  -289,
+    378,    81,  -308,  -465,    57,   -37,   227,
+    -100,    24,   -36,  -151,   199,     8,   143,
+    -426,  -697, -1059,  -133,   388,   161,   321,
+    -644, -1023, -1271,    39,    66,  -123,    70,
+    372,   177,  -173,  -556,  -553,  -304,  -189,
+    -117,  -369,  -425,  -122,  -462,  -152,   -73,
+    -649,  -850, -1189,  -767,   497,   360,   222,
+    -798, -1139, -1455,  -190,   430,   234,   179,
+    42,   -94,  -405,  -692,    38,  -202,  -246,
+    -169,  -366,  -290,   -88,   -64,    32,  -292,
+    1010,   923,   938,   710,   465,   230,   342,
+    217,   300,  1054,   675,    68,  -458,  -179,
+    78,   453,   316,    18,  -237,  -496,  -243,
+    167,    21,   424,   215,   -91,  -303,  -170,
+    -290,   -81,   -70,   -67,    40,    54,   -59,
+    -353,  -427,   -90,    53,    94,     9,    54,
+    -28,   318,   283,    15,  -240,   -58,    79,
+    -75,  -121,   229,    35,    58,     6,  -133,
+    -351,  -514,  -744,  -834,  -705,  -137,   164,
+    -1124, -1388, -1055,  -230,   -73,    40,    36,
+    -163,  -233,  -532,  -785, -1170,  -697,    96,
+    -788,  -959,  -246,  -430,  -624,  -165,    -8,
+    -856,  -540,  -630,  -907,  -337,   -70,    76,
+    -937, -1042,  -659,  -733,  -208,   199,   -26,
+    -523,    78,   -98,  -501,  -869,  -890,   -81,
+    -624,  -703,   -45,  -348,   -25,    87,  -186,
+    1005,   823,   546,   249,    90,   -22,   207,
+    298,   397,   381,   319,   200,    62,   303,
+    473,   379,   133,  -247,  -632,  -441,    75,
+    284,   208,   391,   115,   -25,    44,    95,
+    -72,    79,   -95,   -63,  -129,  -293,   203,
+    -164,  -349,   115,   122,    69,    -1,   378,
+    348,   170,    99,    58,  -179,  -302,   188,
+    -190,    -2,   150,    23,   -51,   -11,   216,
+    -615,  -863, -1090, -1427,  -802,   -48,    -6,
+    -961, -1276, -1548,  -727,   -58,    56,   223,
+    -124,  -255,  -561,  -988, -1277,  -148,   -82,
+    -480,  -660,  -891, -1191, -1339,  -325,    20,
+    -621,  -917, -1296, -1350,   264,   289,    50,
+    -844, -1022, -1345, -1329,  -293,    46,   278,
+    -260,  -468,  -829, -1176,  -533,  -560,   -78,
+    -215,  -484,  -822, -1233,  -791,    15,  -138,
+    1301,  1317,  1262,  1048,   716,   357,   -64,
+    578,   824,   925,   802,   630,   362,   102,
+    470,   925,   767,   514,   327,   190,  -112,
+    225,   492,   495,   437,   598,   384,   -45,
+    43,    82,   -42,   175,   519,   342,   -64,
+    -304,  -154,   159,   576,   403,   221,   327,
+    214,   244,   122,   -62,   312,    92,  -160,
+    218,   208,   310,   268,   306,   323,  -199,
+    -285,  -269,   -79,  -124,  -143,  -153,   236,
+    -205,  -384,  -426,   344,    59,  -185,  -184,
+    -272,   247,   126,  -210,  -518,  -468,    78,
+    -99,  -120,   502,   160,  -280,  -557,   304,
+    -423,   -17,  -283,  -443,   215,   212,  -140,
+    -564,  -684,  -228,   510,   361,   130,   323,
+    -428,   335,    98,   -65,    36,  -215,  -246,
+    -362,    51,   364,   -16,  -234,   150,  -165,
+    914,   883,   751,   653,   676,   464,  -153,
+    631,   545,   535,   720,   596,   360,   -81,
+    783,   712,   512,   439,   341,   251,  -391,
+    497,   417,   249,   372,   295,   173,  -193,
+    128,  -110,  -385,    93,    39,   173,  -231,
+    216,   -59,  -253,   462,   389,   154,    69,
+    455,   270,    -4,  -337,   -49,   233,  -322,
+    307,   143,    53,   218,   128,   236,  -156,
+    -37,  -186,  -240,  -411,  -110,     9,   399,
+    -140,  -365,  -628,   258,   380,   214,   277,
+    131,   454,   177,  -285,  -520,   108,  -214,
+    77,  -141,   201,  -123,  -490,  -131,    60,
+    -14,  -194,  -521,  -741,   273,   362,   -33,
+    -362,  -566,  -287,  -228,   161,   237,   317,
+    -269,   195,   -75,  -375,  -204,    11,    77,
+    -128,  -264,  -156,  -223,  -475,   265,    27,
+    1238,  1147,   916,   689,   432,   210,  -280,
+    800,   664,   879,   726,   411,   160,  -164,
+    454,   686,   536,   275,   147,    46,   111,
+    303,   486,   512,   355,   241,   181,   -69,
+    79,    92,    29,   147,   233,    52,    17,
+    -171,   289,   131,   439,   271,     3,   -10,
+    413,   241,   144,   174,   155,    -2,    14,
+    58,   217,   247,   219,   149,   175,   -18,
+    228,    -8,  -240,  -206,  -513,  -191,   202,
+    -96,  -272,  -454,    33,  -300,  -575,    46,
+    -10,  -108,  -246,  -347,  -770,  -535,     9,
+    -326,  -430,   -61,  -321,  -704,  -299,   201,
+    -1,  -280,  -603,  -419,  -185,    18,   -36,
+    -516,  -522,  -379,  -291,  -181,   -97,    27,
+    -159,  -313,  -525,  -224,  -510,  -831,  -197,
+    -292,  -459,   -59,  -310,  -562,  -143,  -351,
+    1066,   912,   631,   389,   207,    86,  -224,
+    596,   512,   596,   505,   314,   122,   -48,
+    787,   861,   441,   -93,  -303,    33,  -190,
+    257,   469,   337,    51,    15,   298,   -93,
+    295,    73,  -119,    25,    36,    23,   108,
+    -28,    -3,   -32,   114,    21,   185,   107,
+    482,   305,    15,  -279,  -319,    52,    96,
+    226,    46,   115,    72,  -136,   133,  -125,
+    18,  -207,  -559,  -590,  -503,  -482,   321,
+    -571,  -789,  -951,  -172,  -441,  -538,   113,
+    181,    14,  -310,  -641, -1001,  -202,   159,
+    -136,  -393,  -433,  -513,  -911,  -144,   -22,
+    72,  -265,  -706,  -954,  -159,    53,   332,
+    -338,  -591,  -852,  -383,  -395,    56,    44,
+    43,  -158,  -464,  -897,  -631,  -157,  -294,
+    -161,  -128,  -328,  -573,  -483,  -125,    11,
+    1017,   906,  1051,  1005,   679,   341,  -102,
+    359,   334,  1567,  1314,   723,   105,    10,
+    -65,   726,   529,   301,   220,    43,  -273,
+    -510,   436,   719,   566,   358,   179,   114,
+    -560,   298,   133,  -120,   342,   225,    14,
+    -899,  -101,   217,   617,   400,   146,   -58,
+    -41,   352,    82,  -196,    39,   121,  -167,
+    -212,    59,   447,   284,   423,   250,  -169,
+    -371,  -484,  -596,    30,   -41,   249,    22,
+    -372,  -650,  -794,   477,   445,   216,   -79,
+    -352,   275,    17,  -443,  -929,    92,    19,
+    -699,  -696,   431,   264,   -49,  -310,   182,
+    -978,  -217,  -430,  -400,   101,   261,    72,
+    -929,  -889,  -357,   -13,   463,   378,   236,
+    -826,    56,    30,  -299,  -360,  -128,   -51,
+    -878,  -299,  -111,    75,    65,    36,     3,
+    817,   368,   -25,   354,   697,   591,  -173,
+    309,   212,   222,   751,   484,   140,   -56,
+    593,   379,    70,    -8,   258,   180,   110,
+    165,   -46,   255,   297,   219,   273,   105,
+    160,   -70,  -358,  -181,   379,   330,   319,
+    -238,  -369,  -198,   740,   580,   319,  -143,
+    201,   109,  -202,  -456,   328,   276,  -141,
+    203,   170,   111,    42,   207,   360,   188,
+    -345,  -399,  -513,  -233,   650,   422,    81,
+    -635,  -961, -1220,   463,   539,   204,   209,
+    202,   -25,  -194,  -498,  -787,   193,  -143,
+    -449,  -538,   195,  -106,  -331,    68,    62,
+    -228,  -477,  -840,  -576,   317,   128,   283,
+    -671,  -937,  -807,  -114,   391,   335,   -62,
+    246,     2,  -314,  -679,  -303,   180,   -88,
+    -107,  -272,    90,  -198,   -28,   290,  -112,
+    885,  1149,  1021,   712,   496,   281,   -83,
+    269,   492,   787,   643,   347,    70,   124,
+    336,   636,   499,    92,  -229,  -179,   191,
+    26,   402,   564,   340,   149,   -11,   135,
+    -440,   561,   470,   204,   -72,  -186,   140,
+    -720,    14,   355,   229,    68,  -133,   465,
+    110,   310,   103,    12,   106,    29,   158,
+    -178,   113,   161,   142,   121,   115,    27,
+    -651,  -414,  -645,  -152,  -164,   -13,  -429,
+    -639,  -944,  -681,  -104,   -81,    52,  -189,
+    -663,  -164,  -316,  -683,  -954,  -205,   -83,
+    -609,  -669,  -172,  -517,  -694,   283,   -80,
+    -646,  -152,  -383,  -678,  -246,   -40,  -143,
+    -747,  -796,  -745,  -390,   -98,    43,   275,
+    -599,  -199,  -398,  -433,  -436,  -538,    31,
+    -1107,  -568,  -376,  -265,  -126,   -21,     1,
+    847,   573,   308,   392,   305,   101,    55,
+    273,   293,   201,   267,   346,   201,   123,
+    727,   480,   226,     2,   -65,  -138,   164,
+    273,   208,   173,   292,    12,   253,   174,
+    340,   207,   180,    88,   116,    46,   475,
+    -460,  -166,   -30,    13,   110,   173,   396,
+    137,    88,    43,  -137,   -94,    34,   284,
+    96,   -14,   226,    40,    63,    70,   130,
+    -467,  -735, -1012, -1174,  -307,   305,   -67,
+    -612,  -920, -1146,  -567,    -8,    92,   -25,
+    -182,  -271,  -492,  -754,  -857,   287,   -75,
+    -494,  -787,  -689,  -683,  -709,   137,  -326,
+    -288,  -550,  -903, -1105,   334,   321,   -62,
+    -354,  -653,  -834,  -445,     1,   377,  -152,
+    -162,  -306,  -608,  -937,  -297,   247,  -192,
+    -234,  -477,  -244,  -488,  -266,   342,  -332
+};
+
+/*
+ * 2nd stage codebook; 1st split:   isf2_0 to isf2_2
+ */
+
+
+const int16 dico21_isf[SIZE_BK21*3] =
+{
+
+    329,   409,   249,
+    -33,   505,   160,
+    -29,   -14,   582,
+    -262,   127,   354,
+    145,   237,   175,
+    -152,   245,   122,
+    27,    42,   340,
+    -84,   -93,   311,
+    285,   222,  -156,
+    47,   -43,  -504,
+    234,   121,   385,
+    104,  -317,    45,
+    176,   195,     8,
+    104,   -59,   -94,
+    177,    53,   192,
+    -34,  -127,   152,
+    570,   277,   -34,
+    -67,  -329,  -639,
+    -157,  -272,   462,
+    -177,  -462,   198,
+    322,   179,   115,
+    -386,   171,    19,
+    19,   -12,   195,
+    -120,  -252,   201,
+    304,    36,  -336,
+    -128,  -221,  -380,
+    171,  -185,   296,
+    -242,  -312,    23,
+    198,    39,    16,
+    -3,  -177,  -111,
+    111,   -93,    76,
+    -92,  -223,     4,
+    177,   406,   -44,
+    -168,   380,  -149,
+    -4,   273,   331,
+    -420,   513,   277,
+    21,   247,    47,
+    -58,   131,    -2,
+    -3,   134,   180,
+    -145,    40,   175,
+    189,    74,  -145,
+    -27,   -45,  -325,
+    370,  -114,   -21,
+    -83,  -415,  -173,
+    77,    95,   -51,
+    -40,   -30,   -67,
+    71,    88,    86,
+    -35,   -98,    14,
+    69,   197,  -334,
+    -196,    79,  -231,
+    -348,  -137,   218,
+    -352,   -89,   -85,
+    47,   201,  -130,
+    -165,    37,   -15,
+    -43,     3,    86,
+    -161,  -108,    79,
+    83,    21,  -237,
+    -81,  -149,  -238,
+    150,  -186,  -251,
+    -186,  -249,  -162,
+    -19,    66,  -139,
+    -26,   -50,  -181,
+    24,    11,     0,
+    -130,  -105,   -98
+};
+
+
+
+/*
+ * 2nd stage codebook; 2nd split:   isf2_3 to isf2_5
+ */
+
+
+const int16 dico22_isf[SIZE_BK22*3] =
+{
+
+    -127,   310,    42,
+    -242,   197,     5,
+    -151,    84,   -17,
+    -214,   127,  -149,
+    -247,  -131,   159,
+    -268,  -267,   -95,
+    -217,     1,   -79,
+    -271,   -80,  -185,
+    -45,   436,   159,
+    165,   199,   391,
+    -33,    81,   187,
+    -66,   -42,   355,
+    -298,   -57,   343,
+    -108,  -537,   226,
+    -144,   -23,   193,
+    176,  -402,    87,
+    53,   296,    25,
+    -84,   253,  -104,
+    -58,   105,  -126,
+    -169,   174,  -314,
+    -48,    44,  -294,
+    -164,  -417,  -242,
+    -139,     3,  -194,
+    -155,  -207,  -211,
+    119,   322,   213,
+    333,    50,   380,
+    237,   247,    -2,
+    466,   -16,   201,
+    238,  -255,  -107,
+    67,  -440,  -149,
+    122,   -88,  -139,
+    88,  -247,   -73,
+    -41,   231,   167,
+    -62,   155,    16,
+    -65,    16,    77,
+    -68,    -2,   -63,
+    -151,  -300,   160,
+    -18,  -333,    54,
+    -56,   -94,     5,
+    2,  -190,    14,
+    92,   148,   209,
+    108,     9,   272,
+    108,    35,   110,
+    142,   -85,   145,
+    47,  -157,   279,
+    3,  -320,   246,
+    43,   -72,    68,
+    86,  -217,   135,
+    36,   140,    79,
+    56,   175,   -49,
+    26,    45,     3,
+    73,    55,  -101,
+    109,  -183,  -242,
+    -4,  -283,  -242,
+    48,   -68,   -48,
+    -6,  -153,  -122,
+    161,   196,    96,
+    232,    80,   190,
+    165,    97,    11,
+    258,   -31,    71,
+    267,   -77,   -91,
+    311,  -209,    87,
+    152,   -14,   -22,
+    150,  -149,     9,
+    -324,   557,   187,
+    -384,   307,    46,
+    -251,    27,    77,
+    -365,    77,   -52,
+    -482,   -84,   160,
+    -424,  -515,   -64,
+    -294,  -120,    -4,
+    -476,  -116,  -109,
+    -97,   318,   365,
+    106,   627,   445,
+    -190,   120,   287,
+    -146,    65,   619,
+    -427,   242,   363,
+    -361,  -371,   432,
+    -347,   102,   168,
+    -629,   195,   -14,
+    -65,   476,   -47,
+    -297,   320,  -168,
+    -55,   356,  -264,
+    -391,    82,  -286,
+    -51,   -31,  -556,
+    -178,  -399,  -586,
+    -205,   -49,  -360,
+    -343,  -238,  -337,
+    220,   457,    58,
+    561,   467,   259,
+    340,   270,  -168,
+    450,    77,  -280,
+    60,   167,  -413,
+    133,  -252,  -492,
+    216,   157,  -290,
+    282,     0,  -495,
+    -226,   293,   183,
+    -157,   135,   122,
+    -158,   -59,    39,
+    -133,  -118,   -97,
+    -332,  -309,   113,
+    -160,  -425,    -6,
+    -149,  -211,    24,
+    -80,  -277,   -90,
+    -11,   125,   338,
+    130,   -71,   465,
+    5,   -45,   184,
+    237,   -95,   253,
+    -139,  -197,   297,
+    -19,  -300,   511,
+    -63,  -152,   139,
+    250,  -289,   336,
+    124,   339,  -150,
+    34,   176,  -208,
+    171,   166,  -116,
+    94,    38,  -229,
+    75,   -65,  -339,
+    -78,  -205,  -385,
+    0,   -30,  -163,
+    -56,  -110,  -242,
+    321,   244,   194,
+    505,   238,    -1,
+    317,   116,    65,
+    309,    88,   -74,
+    452,   -51,   -50,
+    334,  -217,  -290,
+    211,    41,  -152,
+    238,   -55,  -260
+};
+
+
+/*
+ * 2nd stage codebook; 3rd split:   isf2_6 to isf2_8
+ */
+
+
+const int16 dico23_isf[SIZE_BK23*3] =
+{
+
+    -10,   151,   359,
+    136,   298,   223,
+    255,  -104,   290,
+    423,     6,   183,
+    -270,  -269,   -98,
+    -52,   -82,    13,
+    -82,  -274,   -97,
+    90,  -246,   -72,
+    -299,   -70,   421,
+    -88,   365,   430,
+    187,  -318,   381,
+    380,    37,   488,
+    -373,  -316,    79,
+    -308,  -101,     5,
+    -135,  -451,     8,
+    72,  -421,  -154,
+    180,   170,  -121,
+    62,   177,   -40,
+    326,    80,  -105,
+    248,   263,    -5,
+    -168,  -181,  -221,
+    -2,   -23,  -158,
+    -14,  -149,  -121,
+    119,   -91,  -147,
+    119,   332,  -153,
+    49,   303,    34,
+    442,   -55,   -69,
+    217,   454,    58,
+    -359,  -187,  -375,
+    -42,    50,  -274,
+    -8,  -267,  -249,
+    85,   -86,  -346,
+    -77,   -40,   345,
+    89,   134,   219,
+    156,   -80,   160,
+    108,    40,   116,
+    -158,  -206,    29,
+    5,   -32,   175,
+    -65,  -158,   146,
+    55,   -78,    73,
+    -114,  -222,   353,
+    -47,    81,   211,
+    49,  -151,   268,
+    105,     4,   302,
+    -263,  -132,   183,
+    -151,   -28,   201,
+    -177,  -307,   166,
+    101,  -221,   130,
+    74,    58,   -98,
+    32,    44,    13,
+    194,    30,  -142,
+    170,    96,     8,
+    -136,  -119,   -91,
+    -65,     8,   -55,
+    3,  -188,    12,
+    45,   -63,   -49,
+    149,   -21,   -19,
+    24,   144,    95,
+    254,   -22,    60,
+    161,   196,    96,
+    -158,   -61,    48,
+    -70,    33,    82,
+    -23,  -321,    58,
+    155,  -147,     5,
+    -364,   328,    77,
+    -21,   453,   173,
+    -108,    82,   630,
+    367,   263,   208,
+    -300,   -62,  -176,
+    -205,   143,  -158,
+    -169,  -410,  -264,
+    257,  -269,  -100,
+    -636,   289,    -2,
+    -292,   627,   173,
+    -382,  -363,   387,
+    248,   524,   447,
+    -521,  -111,  -107,
+    -395,   118,  -274,
+    -343,  -680,  -125,
+    -172,  -447,  -663,
+    75,   148,  -367,
+    -79,   263,   -94,
+    249,   148,  -286,
+    380,   271,  -162,
+    -142,    -4,  -186,
+    -57,   111,  -125,
+    -35,  -108,  -254,
+    100,    29,  -242,
+    -80,   303,  -264,
+    -78,   464,   -57,
+    248,   -22,  -494,
+    661,   662,    44,
+    -193,   -40,  -330,
+    -178,   145,  -337,
+    -90,  -199,  -400,
+    -40,   -23,  -498,
+    -192,   114,   315,
+    -41,   244,   190,
+    88,   -97,   485,
+    241,    80,   212,
+    -246,    40,    87,
+    -156,   147,   134,
+    -2,  -334,   239,
+    308,  -203,   110,
+    -459,   251,   422,
+    -218,   310,   228,
+    -86,  -346,   654,
+    184,   175,   425,
+    -481,   -63,   169,
+    -349,   117,   188,
+    -125,  -560,   310,
+    158,  -416,    94,
+    46,   171,  -192,
+    -63,   157,    14,
+    256,   -35,  -271,
+    322,   123,    53,
+    -214,     4,   -76,
+    -156,    86,   -18,
+    128,  -197,  -232,
+    265,   -90,   -98,
+    -308,   332,  -145,
+    -131,   308,    58,
+    509,    59,  -339,
+    562,   196,   -14,
+    -378,   100,   -47,
+    -234,   202,     1,
+    104,  -270,  -493,
+    319,  -210,  -325
+};
+
+
+/*
+ * 2nd stage codebook; 4th split:   isf2_9 to isf2_11
+ */
+
+const int16 dico24_isf[SIZE_BK24*3] =
+{
+
+    -79,   -89,    -4,
+    -171,    77,  -211,
+    160,  -193,    98,
+    120,  -103,   323,
+    32,   -22,  -129,
+    72,    78,  -268,
+    182,   -76,   -66,
+    309,    99,  -145,
+    -229,  -157,   -84,
+    -383,    98,   -71,
+    -90,  -352,    12,
+    -284,  -178,   178,
+    -65,  -125,  -166,
+    -87,  -175,  -351,
+    42,  -198,   -48,
+    154,  -140,  -243,
+    -77,    18,   108,
+    -39,   355,    91,
+    87,     8,   155,
+    -4,   158,   239,
+    128,    95,   -54,
+    7,   246,  -124,
+    258,    15,    89,
+    206,   216,    98,
+    -201,     9,    18,
+    -312,   233,   204,
+    -39,  -174,   155,
+    -144,    -9,   284,
+    -57,    70,   -69,
+    -157,   187,    18,
+    54,   -30,    23,
+    24,   135,    55
+};
+
+
+/*
+ * 2nd stage codebook; 5th split:   isf2_12 to isf2_15
+ */
+
+const int16 dico25_isf[SIZE_BK25*4] =
+{
+
+    169,   142,  -119,   115,
+    206,   -20,    94,   226,
+    -106,   313,   -21,    16,
+    -62,   161,    71,   255,
+    -89,   101,  -185,   125,
+    72,   -30,  -201,   344,
+    -258,    33,    -8,    81,
+    -104,  -154,    72,   296,
+    144,   -68,  -268,   -25,
+    81,   -78,   -87,   106,
+    22,   155,  -186,  -119,
+    -46,   -28,    27,    91,
+    -114,   -37,  -175,   -33,
+    -94,  -222,  -189,   122,
+    -132,  -119,  -191,  -270,
+    -172,  -173,    18,   -43,
+    279,   135,   -42,  -128,
+    187,   -86,   229,  -138,
+    159,   240,   140,    46,
+    69,    25,   227,    77,
+    21,   115,    13,     8,
+    68,  -248,   126,    81,
+    -150,   137,   207,    -9,
+    -154,  -133,   289,    67,
+    143,   -37,   -86,  -326,
+    180,   -32,    19,   -23,
+    26,   168,   116,  -233,
+    -32,   -26,   118,   -78,
+    3,    -8,   -45,  -115,
+    57,  -215,   -54,   -83,
+    -209,   112,   -22,  -167,
+    -91,  -151,   168,  -262
+};
+
+
+
+/* 36 bit */
+/*
+ *  isf codebooks:  two-stage VQ with split-by-3 in 2nd stage
+ *                1st stage is kept the same as the 46 bit quantizer
+ *
+ *  codebook   vector dimension    number of vectors
+ *  ~~~~~~~~   ~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~~~~
+ *     1_1            9                  256
+ *     1_2            7                  256
+ *     2_1            5                  128
+ *     2_2            4                  128
+ *     2_3            7                  64
+ */
+
+const int16 dico21_isf_36b[SIZE_BK21_36b*5] =
+{
+
+    -52,   -96,   212,   315,   -73,
+    82,  -204,   363,   136,  -197,
+    -126,  -331,   183,   218,   143,
+    -49,   -41,   557,   230,    72,
+    2,   -73,   163,   377,   221,
+    133,   111,   278,   215,  -110,
+    -102,   -20,   284,   113,   273,
+    84,   319,   290,    18,    85,
+    -25,    -5,   125,   132,  -204,
+    -38,    -5,   286,    -9,  -356,
+    -140,  -256,    92,   117,  -189,
+    -144,   191,   313,    51,   -98,
+    167,   -10,    44,   247,    36,
+    381,   197,   238,    74,     6,
+    38,  -408,    29,    -3,   -85,
+    92,   266,   157,   -25,  -200,
+    161,  -121,    70,    84,  -140,
+    -16,   -86,   112,   -94,  -189,
+    -269,  -270,   351,   107,   -24,
+    -68,   -67,   492,  -103,  -155,
+    -53,  -131,    62,   122,    10,
+    135,    84,   283,   -55,  -120,
+    -12,  -219,   331,   -81,   167,
+    220,  -136,   147,  -172,   -42,
+    140,   -95,  -109,   -88,  -194,
+    0,    -2,    -4,   -33,  -381,
+    -66,  -217,   152,  -186,  -402,
+    244,   108,   156,  -140,  -395,
+    113,  -136,  -196,   110,   -24,
+    214,   118,    11,   -64,  -131,
+    -110,  -286,    -6,  -332,    16,
+    94,    97,    79,  -291,  -205,
+    -5,   -39,   -20,   252,   -96,
+    76,   174,   101,   163,    61,
+    -69,  -239,   -55,   399,     6,
+    -115,   319,   164,   275,   196,
+    -15,    36,   -47,   331,   121,
+    226,   209,   271,   325,   184,
+    13,   -80,  -218,   471,   353,
+    288,   378,    16,   -51,   251,
+    174,   116,    52,   149,  -279,
+    235,   276,    39,   120,   -48,
+    0,  -108,  -108,   241,  -339,
+    -93,   534,    45,    33,   -87,
+    194,   149,   -71,   405,   -44,
+    409,   370,    81,  -186,  -154,
+    25,  -102,  -448,   124,  -173,
+    22,   408,  -110,  -310,  -214,
+    -26,    23,   -83,   114,    14,
+    -110,   164,    52,   223,   -82,
+    37,   -25,  -263,   306,   -15,
+    -466,   415,   292,   165,   -18,
+    29,   -19,  -171,   155,   182,
+    179,   144,   -27,   231,   258,
+    -103,  -247,  -396,   238,   113,
+    375,  -154,  -109,    -4,   156,
+    98,    85,  -292,    -5,  -124,
+    116,   139,  -116,   -98,  -294,
+    -14,   -83,  -278,  -117,  -378,
+    106,    33,  -106,  -344,  -484,
+    119,    17,  -412,   138,   166,
+    384,   101,  -204,    88,  -156,
+    -121,  -284,  -300,    -1,  -166,
+    280,    33,  -152,  -313,   -81,
+    -37,    22,   229,   153,    37,
+    -60,   -83,   236,    -8,   -41,
+    -169,  -228,   126,   -20,   363,
+    -235,    17,   364,  -156,   156,
+    -25,   -30,    72,   144,   156,
+    153,   -26,   256,    97,   144,
+    -21,   -37,    48,   -65,   250,
+    63,    77,   273,  -128,   124,
+    -129,   -26,    40,     9,  -115,
+    -6,    82,    38,   -90,  -182,
+    -336,   -13,    28,   158,    91,
+    -30,   241,   137,  -170,   -17,
+    146,    14,   -11,    33,    61,
+    192,   197,    54,   -84,    85,
+    23,  -200,   -78,   -29,   140,
+    122,   237,   106,  -341,   136,
+    -57,  -142,   -85,   -16,   -74,
+    -59,   -90,    -8,  -187,   -20,
+    -211,  -267,   216,  -179,  -110,
+    -50,    -7,   220,  -267,   -70,
+    -57,   -42,   -17,   -15,    71,
+    32,    21,    63,  -137,    33,
+    -137,  -175,   104,   -68,    97,
+    -67,   -43,   133,  -301,   221,
+    -116,  -200,   -81,   -92,  -272,
+    -64,   -41,   -54,  -244,  -220,
+    -287,  -242,   -50,   -87,   -89,
+    -245,   236,   102,  -166,  -295,
+    66,    24,  -162,   -71,    95,
+    66,   136,   -90,  -220,   -36,
+    -98,  -161,  -222,  -188,    29,
+    -18,    18,   -19,  -415,     9,
+    49,    61,   100,    39,   -56,
+    -111,    82,   135,   -31,    52,
+    -90,  -153,   -93,   189,   182,
+    -214,   295,   119,   -74,   284,
+    2,   137,    37,    47,   182,
+    92,   117,   184,   -53,   373,
+    -21,   -14,   -35,   136,   391,
+    146,   129,  -164,   -28,   333,
+    92,    80,   -84,   100,  -134,
+    -8,   217,   -32,     3,   -47,
+    -151,   251,  -215,   142,    92,
+    -224,   310,  -172,  -275,    98,
+    159,   155,  -177,   112,    53,
+    205,    27,     8,  -240,   192,
+    169,   120,  -319,  -201,   106,
+    11,    36,   -86,  -237,   455,
+    -109,  -154,  -163,   174,   -55,
+    -38,    32,  -101,   -78,   -59,
+    -205,  -321,   -97,    69,    79,
+    -310,    44,    18,  -185,    34,
+    -115,   -20,  -148,   -39,   203,
+    -29,   154,   -30,  -158,   166,
+    -45,  -131,  -317,   -24,   363,
+    -165,  -205,  -112,  -222,   265,
+    -32,   -44,  -150,    54,  -193,
+    -6,   -38,  -255,  -169,  -115,
+    -266,    87,  -189,   -36,  -169,
+    -60,   -87,  -266,  -436,  -170,
+    -68,   -81,  -278,    24,    38,
+    -23,   -19,  -155,  -256,   141,
+    -61,  -226,  -565,  -175,    71,
+    9,   -29,  -237,  -515,   263
+};
+
+const int16 dico22_isf_36b[SIZE_BK22_36b*4] =
+{
+
+    -298,    -6,    95,    31,
+    -213,   -87,  -122,   261,
+    4,   -49,   208,    14,
+    -129,  -110,    30,   118,
+    -214,   258,   110,  -235,
+    -41,   -18,  -126,   120,
+    103,    65,   127,   -37,
+    126,   -36,   -24,    25,
+    -138,   -67,  -278,  -186,
+    -164,  -194,  -201,    78,
+    -211,   -87,   -51,  -221,
+    -174,   -79,   -94,   -39,
+    23,    -6,  -157,  -240,
+    22,  -110,  -153,   -68,
+    148,    -5,    -2,  -149,
+    -1,  -135,   -39,  -179,
+    68,   360,  -117,   -15,
+    137,    47,  -278,   146,
+    136,   260,   135,    65,
+    61,   116,   -45,    97,
+    231,   379,    87,  -120,
+    338,   177,  -272,     3,
+    266,   156,    28,   -69,
+    260,    84,   -85,    86,
+    -266,   154,  -256,  -182,
+    -17,   -65,  -304,    -6,
+    -40,   175,  -151,  -180,
+    -27,    27,   -87,   -63,
+    121,   114,  -166,  -469,
+    159,   -66,  -323,  -231,
+    214,   152,  -141,  -212,
+    137,    36,  -184,   -51,
+    -282,  -237,    40,    10,
+    -48,  -235,   -37,   251,
+    -54,  -323,   136,    29,
+    -88,  -174,   213,   198,
+    -390,    99,   -63,  -375,
+    107,  -169,  -164,   424,
+    69,  -111,   141,  -167,
+    74,  -129,    65,   144,
+    -353,  -207,  -205,  -109,
+    -160,  -386,  -355,    98,
+    -176,  -493,   -20,  -143,
+    -252,  -432,    -2,   216,
+    -90,  -174,  -168,  -411,
+    13,  -284,  -229,  -160,
+    -87,  -279,    34,  -251,
+    -75,  -263,   -58,   -42,
+    420,    53,  -211,  -358,
+    384,   -35,  -374,   396,
+    68,  -228,   323,    -2,
+    167,  -307,   192,   194,
+    459,   329,    -5,  -332,
+    375,    79,    -7,   313,
+    282,  -124,   200,   -92,
+    271,  -162,   -70,   180,
+    -157,  -298,  -514,  -309,
+    58,  -163,  -546,    18,
+    124,  -364,   167,  -238,
+    83,  -411,  -117,    96,
+    140,  -112,  -388,  -624,
+    259,  -133,  -317,    41,
+    163,  -130,   -64,  -334,
+    226,  -165,  -124,  -110,
+    -466,   -61,     6,   229,
+    -153,   205,  -145,   242,
+    -159,    48,   195,   148,
+    -58,    28,    31,   279,
+    -303,   185,   279,    -4,
+    -61,   197,    59,    86,
+    -114,   123,   168,   -52,
+    35,    36,   100,   126,
+    -407,   102,   -77,   -40,
+    -338,    -1,  -342,   156,
+    -179,   105,   -34,   -97,
+    -185,    84,   -35,   108,
+    -133,   107,   -91,  -357,
+    -180,    54,  -229,    24,
+    -44,    47,    47,  -182,
+    -66,    13,    45,     4,
+    -339,   251,    64,   226,
+    -42,   101,  -350,   275,
+    -99,   398,   142,   121,
+    111,    12,  -102,   260,
+    0,   505,   260,   -94,
+    161,   285,   -96,   224,
+    -4,   206,   314,    33,
+    167,   139,    88,   204,
+    -235,   316,   -60,   -25,
+    -8,  -150,  -312,   201,
+    -36,   292,    61,  -104,
+    -40,   174,  -162,    42,
+    -21,   402,   -29,  -351,
+    21,   152,  -360,   -93,
+    57,   191,   212,  -196,
+    76,   158,   -21,   -69,
+    -328,  -185,   331,   119,
+    -53,   285,    56,   337,
+    -107,   -24,   405,    29,
+    -18,   137,   272,   277,
+    -255,    22,   173,  -191,
+    295,   322,   325,   302,
+    21,   -27,   332,  -178,
+    119,    13,   271,   129,
+    -455,  -180,   116,  -191,
+    -227,    62,  -148,   524,
+    -176,  -287,   282,  -157,
+    -243,    13,   199,   430,
+    -59,   -49,   115,  -365,
+    72,  -172,  -137,    93,
+    -138,  -126,   141,   -84,
+    5,  -124,    38,   -20,
+    -258,   311,   601,   213,
+    94,   130,   -61,   502,
+    -1,  -157,   485,   313,
+    146,   -74,   158,   345,
+    276,   135,   280,   -57,
+    490,   252,    99,    43,
+    267,   -74,   429,   105,
+    278,   -23,   119,    94,
+    -542,   488,   257,  -115,
+    -84,  -244,  -438,   478,
+    -113,  -545,   387,   101,
+    -95,  -306,   111,   498,
+    95,   166,    22,  -301,
+    420,   -15,   -58,   -78,
+    270,    29,   122,  -282,
+    160,  -240,    50,   -38
+};
+
+const int16 dico23_isf_36b[SIZE_BK23_36b*7] =
+{
+
+    81,   -18,    68,   -27,  -122,  -280,    -4,
+    45,  -177,   209,   -30,  -136,   -74,   131,
+    -44,   101,   -75,   -88,   -48,  -137,   -54,
+    -245,   -28,    63,   -18,  -112,  -103,    58,
+    -79,    -6,   220,   -65,   114,   -35,   -50,
+    109,   -65,   143,  -114,   129,    76,   125,
+    166,    90,   -61,  -242,   186,   -74,   -43,
+    -46,   -92,    49,  -227,    24,  -155,    39,
+    67,    85,    99,   -42,    53,  -184,  -281,
+    142,  -122,     0,    21,  -142,   -15,   -17,
+    223,    92,   -21,   -48,   -82,   -14,  -167,
+    51,   -37,  -243,   -30,   -90,    18,   -56,
+    54,   105,    74,    86,    69,    13,  -101,
+    196,    72,   -89,    43,    65,    19,    39,
+    121,    34,   131,   -82,    25,   213,  -156,
+    101,  -102,  -136,   -21,    57,   214,    22,
+    36,  -124,   205,   204,    58,  -156,   -83,
+    83,  -117,   137,   137,    85,   116,    44,
+    -92,  -148,   -68,    11,  -102,  -197,  -220,
+    -76,  -185,   -58,   132,   -26,  -183,    85,
+    -7,   -31,    -2,    23,   205,  -151,    10,
+    -27,   -37,    -5,   -18,   292,   131,     1,
+    117,  -168,     9,   -93,    80,   -59,  -125,
+    -182,  -244,    98,   -24,   135,   -22,    94,
+    221,    97,   106,    42,    43,  -160,    83,
+    25,   -64,   -21,     6,    14,   -15,   154,
+    126,    15,  -140,   150,   -10,  -207,  -114,
+    79,   -63,  -211,   -70,   -28,  -217,   165,
+    46,    38,   -22,   281,   132,   -62,   109,
+    112,    54,  -112,   -93,   208,    27,   296,
+    115,    10,  -147,    41,   216,    42,  -276,
+    50,  -115,  -254,   167,   117,    -2,    61,
+    17,   144,    34,   -72,  -186,  -150,   272,
+    -29,   -66,   -89,   -95,  -149,   129,   251,
+    122,     0,   -50,  -234,   -91,    36,    26,
+    -105,  -102,   -88,  -121,  -236,    -7,   -11,
+    -204,   109,     5,  -191,   105,   -15,   163,
+    -80,    32,   -24,  -209,    41,   294,    70,
+    -106,   -94,  -204,  -118,   120,   -50,   -37,
+    -82,  -241,    46,  -131,   -29,   150,   -55,
+    33,   155,   120,   -89,    -8,     7,    62,
+    213,    82,    61,    18,  -161,   144,   152,
+    30,   131,    65,   -87,  -255,   -17,  -107,
+    -8,    85,   -64,    51,  -162,   223,   -53,
+    -134,   261,    69,   -56,   218,    72,  -111,
+    2,   155,  -113,   -87,    49,    85,   -28,
+    -163,    42,    -1,  -196,     7,    39,  -245,
+    14,  -137,   -79,    11,  -160,   202,  -293,
+    -94,    33,   208,   100,    56,   -44,   326,
+    -78,   -41,   232,    13,  -142,   227,    80,
+    -16,   -87,   201,    33,  -133,    15,  -183,
+    -58,  -192,   -47,   184,  -128,   133,    99,
+    -205,    11,  -155,    78,    52,    72,   141,
+    -246,    26,    99,   151,    59,   115,   -64,
+    -79,   -47,   -16,   -14,     6,    47,   -43,
+    -72,  -178,   -27,   162,   112,    43,  -174,
+    -175,   238,   186,    71,   -54,  -188,   -76,
+    -225,   233,    39,   -39,  -158,   122,    44,
+    -26,    43,    84,   130,   -93,   -51,    22,
+    3,    92,  -150,   136,  -182,   -57,    97,
+    -131,   179,   -78,    80,    91,  -165,    90,
+    -2,   148,    15,   130,    65,   175,   117,
+    -138,   114,  -137,   132,     3,   -10,  -186,
+    140,    -4,   -37,   254,   -62,    92,  -109
+};
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/scale_signal.cpp b/media/libstagefright/codecs/amrwb/src/scale_signal.cpp
new file mode 100644
index 0000000..b2b02b1
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/scale_signal.cpp
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: scale_signal.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 signal[],             (i/o) : signal to scale
+     int16 lg,                   (i)   : size of x[]
+     int16 exp                   (i)   : exponent: x = round(x << exp)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Scale signal to get maximum of dynamic range
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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 scale_signal(
+    int16 x[],              /* (i/o) : signal to scale               */
+    int16 lg,               /* (i)   : size of x[]                   */
+    int16 exp               /* (i)   : exponent: x = round(x << exp) */
+)
+{
+    int16 i;
+    int16 tmp;
+    int16 *pt_x;
+
+
+    int32 L_tmp;
+
+
+    if (exp > 0)
+    {
+        for (i = 0; i < lg; i++)
+        {
+            L_tmp = shl_int32(((int32)x[i] << 16), exp);       /* saturation can occur here */
+            x[i] = amr_wb_round(L_tmp);
+        }
+    }
+    else if (exp < 0)
+    {
+        exp = -exp;
+        exp &= 0xf;
+        tmp = (int16)(0x00008000 >> (16 - exp));
+        pt_x = x;
+
+        for (i = lg >> 1; i != 0; i--)
+        {
+            *(pt_x)   = add_int16(*(pt_x), tmp) >> exp;
+            pt_x++;
+            *(pt_x)   = add_int16(*(pt_x), tmp) >> exp;
+            pt_x++;
+        }
+
+    }
+    return;
+}
diff --git a/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.cpp b/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.cpp
new file mode 100644
index 0000000..c3aa887
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.cpp
@@ -0,0 +1,440 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: synthesis_amr_wb.cpp
+
+     Date: 05/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 Aq[],                           A(z)  : quantized Az
+     int16 exc[],                          (i)   : excitation at 12kHz
+     int16 Q_new,                          (i)   : scaling performed on exc
+     int16 synth16k[],                     (o)   : 16kHz synthesis signal
+     int16 prms,                           (i)   : compressed amr wb
+     int16 HfIsf[],
+     int16 nb_bits,
+     int16 newDTXState,
+     Decoder_State * st,                   (i/o) : State structure
+     int16 bfi,                            (i)   : bad frame indicator
+     int16 *ScratchMem
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Synthesis of signal at 16kHz with HF extension
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+#include "e_pv_amrwbdec.h"
+#include "get_amr_wb_bits.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_api.h"
+#include "synthesis_amr_wb.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
+----------------------------------------------------------------------------*/
+/* High Band encoding */
+const int16 HP_gain[16] =
+{
+    3624, 4673, 5597, 6479, 7425, 8378, 9324, 10264,
+    11210, 12206, 13391, 14844, 16770, 19655, 24289, 32728
+};
+
+/*----------------------------------------------------------------------------
+; 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 synthesis_amr_wb(
+    int16 Aq[],              /* A(z)  : quantized Az               */
+    int16 exc[],             /* (i)   : excitation at 12kHz        */
+    int16 Q_new,             /* (i)   : scaling performed on exc   */
+    int16 synth16k[],        /* (o)   : 16kHz synthesis signal     */
+    int16 prms,              /* (i)   : parameter                  */
+    int16 HfIsf[],
+    int16 nb_bits,
+    int16 newDTXState,
+    Decoder_State * st,      /* (i/o) : State structure            */
+    int16 bfi,               /* (i)   : bad frame indicator        */
+    int16 *ScratchMem
+)
+{
+    int16 i, fac, exp;
+    int16 tmp;
+    int16 ener, exp_ener;
+    int32 L_tmp;
+    int32 L_tmp2;
+
+    int16 HF_corr_gain;
+    int16 HF_gain_ind;
+    int16 gain1, gain2;
+
+    int16 *pt_synth;
+    int16 *pt_HF;
+    int16 *synth_hi =  ScratchMem;
+    int16 *synth_lo = &ScratchMem[M + L_SUBFR];
+    int16 *synth    = &synth_lo[M + L_SUBFR];
+    int16 *HF       = &synth[L_SUBFR];
+    int16 *Ap       = &HF[L_SUBFR16k];       /* High Frequency vector   */
+    int16 *HfA      = &Ap[M16k + 1];
+    int16 *pt_tmp;
+
+    /*------------------------------------------------------------*
+     * speech synthesis                                           *
+     * ~~~~~~~~~~~~~~~~                                           *
+     * - Find synthesis speech corresponding to exc2[].           *
+     * - Perform fixed deemphasis and hp 50hz filtering.          *
+     * - Oversampling from 12.8kHz to 16kHz.                      *
+     *------------------------------------------------------------*/
+
+    pv_memcpy((void *)synth_hi,
+              (void *)st->mem_syn_hi,
+              M*sizeof(*synth_hi));
+
+    pv_memcpy((void *)synth_lo,
+              (void *)st->mem_syn_lo,
+              M*sizeof(*synth_lo));
+
+    Syn_filt_32(Aq, M, exc, Q_new, synth_hi + M, synth_lo + M, L_SUBFR);
+
+    pv_memcpy((void *)st->mem_syn_hi,
+              (void *)(synth_hi + L_SUBFR),
+              M*sizeof(*st->mem_syn_hi));
+
+    pv_memcpy((void *)st->mem_syn_lo,
+              (void *)(synth_lo + L_SUBFR),
+              M*sizeof(*st->mem_syn_lo));
+
+    deemphasis_32(synth_hi + M,
+                  synth_lo + M,
+                  synth,
+                  PREEMPH_FAC,
+                  L_SUBFR,
+                  &(st->mem_deemph));
+
+    highpass_50Hz_at_12k8(synth,
+                          L_SUBFR,
+                          st->mem_sig_out);
+
+    oversamp_12k8_to_16k(synth,
+                         L_SUBFR,
+                         synth16k,
+                         st->mem_oversamp,
+                         ScratchMem);
+
+    /*
+     * HF noise synthesis
+     * - Generate HF noise between 5.5 and 7.5 kHz.
+     * - Set energy of noise according to synthesis tilt.
+     *     tilt > 0.8 ==> - 14 dB (voiced)
+     *     tilt   0.5 ==> - 6 dB  (voiced or noise)
+     *     tilt < 0.0 ==>   0 dB  (noise)
+     */
+
+    /* generate white noise vector */
+    pt_tmp = HF;
+    for (i = L_SUBFR16k >> 2; i != 0 ; i--)
+    {
+        *(pt_tmp++) = noise_gen_amrwb(&(st->seed2)) >> 3;
+        *(pt_tmp++) = noise_gen_amrwb(&(st->seed2)) >> 3;
+        *(pt_tmp++) = noise_gen_amrwb(&(st->seed2)) >> 3;
+        *(pt_tmp++) = noise_gen_amrwb(&(st->seed2)) >> 3;
+    }
+    /* energy of excitation */
+
+    pt_tmp = exc;
+
+    for (i = L_SUBFR >> 2; i != 0; i--)
+    {
+        *(pt_tmp) = add_int16(*(pt_tmp), 0x0004) >> 3;
+        pt_tmp++;
+        *(pt_tmp) = add_int16(*(pt_tmp), 0x0004) >> 3;
+        pt_tmp++;
+        *(pt_tmp) = add_int16(*(pt_tmp), 0x0004) >> 3;
+        pt_tmp++;
+        *(pt_tmp) = add_int16(*(pt_tmp), 0x0004) >> 3;
+        pt_tmp++;
+    }
+
+
+    Q_new -= 3;
+
+    ener = extract_h(Dot_product12(exc, exc, L_SUBFR, &exp_ener));
+    exp_ener -= Q_new << 1;
+
+    /* set energy of white noise to energy of excitation */
+
+    tmp = extract_h(Dot_product12(HF, HF, L_SUBFR16k, &exp));
+
+    if (tmp > ener)
+    {
+        tmp >>=  1;                 /* Be sure tmp < ener */
+        exp += 1;
+    }
+    L_tmp = L_deposit_h(div_16by16(tmp, ener)); /* result is normalized */
+    exp -= exp_ener;
+    one_ov_sqrt_norm(&L_tmp, &exp);
+    L_tmp = shl_int32(L_tmp, exp + 1); /* L_tmp x 2, L_tmp in Q31 */
+
+    tmp = (int16)(L_tmp >> 16);    /* tmp = 2 x sqrt(ener_exc/ener_hf) */
+
+
+
+    pt_tmp = HF;
+    for (i = L_SUBFR16k >> 2; i != 0 ; i--)
+    {
+        *(pt_tmp) = (int16)(fxp_mul_16by16(*(pt_tmp), tmp) >> 15);
+        pt_tmp++;
+        *(pt_tmp) = (int16)(fxp_mul_16by16(*(pt_tmp), tmp) >> 15);
+        pt_tmp++;
+        *(pt_tmp) = (int16)(fxp_mul_16by16(*(pt_tmp), tmp) >> 15);
+        pt_tmp++;
+        *(pt_tmp) = (int16)(fxp_mul_16by16(*(pt_tmp), tmp) >> 15);
+        pt_tmp++;
+    }
+
+    /* find tilt of synthesis speech (tilt: 1=voiced, -1=unvoiced) */
+
+    highpass_400Hz_at_12k8(synth, L_SUBFR, st->mem_hp400);
+
+    L_tmp = 1L;
+    L_tmp2 = 1L;
+
+
+    L_tmp = mac_16by16_to_int32(L_tmp, synth[0], synth[0]);
+
+    for (i = 1; i < L_SUBFR; i++)
+    {
+        L_tmp  = mac_16by16_to_int32(L_tmp,  synth[i], synth[i    ]);
+        L_tmp2 = mac_16by16_to_int32(L_tmp2, synth[i], synth[i - 1]);
+    }
+
+
+    exp = normalize_amr_wb(L_tmp);
+
+    ener = (int16)((L_tmp << exp) >> 16);   /* ener = r[0] */
+    tmp  = (int16)((L_tmp2 << exp) >> 16);    /* tmp = r[1] */
+
+    if (tmp > 0)
+    {
+        fac = div_16by16(tmp, ener);
+    }
+    else
+    {
+        fac = 0;
+    }
+
+    /* modify energy of white noise according to synthesis tilt */
+    gain1 = 32767 - fac;
+    gain2 = mult_int16(gain1, 20480);
+    gain2 = shl_int16(gain2, 1);
+
+    if (st->vad_hist > 0)
+    {
+        tmp  = gain2 - 1;
+    }
+    else
+    {
+        tmp  = gain1 - 1;
+    }
+
+
+    if (tmp != 0)
+    {
+        tmp++;
+    }
+
+    if (tmp < 3277)
+    {
+        tmp = 3277;                        /* 0.1 in Q15 */
+
+    }
+
+
+    if ((nb_bits >= NBBITS_24k) && (bfi == 0))
+    {
+        /* HF correction gain */
+        HF_gain_ind = prms;
+        HF_corr_gain = HP_gain[HF_gain_ind];
+
+        pt_tmp = HF;
+        for (i = L_SUBFR16k >> 2; i != 0 ; i--)
+        {
+            *(pt_tmp) = mult_int16(*(pt_tmp), HF_corr_gain) << 1;
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), HF_corr_gain) << 1;
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), HF_corr_gain) << 1;
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), HF_corr_gain) << 1;
+            pt_tmp++;
+        }
+
+        /* HF gain */
+    }
+    else
+    {
+        pt_tmp = HF;
+        for (i = L_SUBFR16k >> 2; i != 0 ; i--)
+        {
+            *(pt_tmp) = mult_int16(*(pt_tmp), tmp);
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), tmp);
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), tmp);
+            pt_tmp++;
+            *(pt_tmp) = mult_int16(*(pt_tmp), tmp);
+            pt_tmp++;
+        }
+    }
+
+
+    if ((nb_bits <= NBBITS_7k) && (newDTXState == SPEECH))
+    {
+        isf_extrapolation(HfIsf);
+        Isp_Az(HfIsf, HfA, M16k, 0);
+
+        weight_amrwb_lpc(HfA, Ap, 29491, M16k);     /* fac=0.9 */
+
+        wb_syn_filt(Ap,
+                    M16k,
+                    HF,
+                    HF,
+                    L_SUBFR16k,
+                    st->mem_syn_hf,
+                    1,
+                    ScratchMem);
+    }
+    else
+    {
+        /* synthesis of noise: 4.8kHz..5.6kHz --> 6kHz..7kHz */
+        weight_amrwb_lpc(Aq, Ap, 19661, M);         /* fac=0.6 */
+
+        wb_syn_filt(Ap,
+                    M,
+                    HF,
+                    HF,
+                    L_SUBFR16k,
+                    st->mem_syn_hf + (M16k - M),
+                    1,
+                    ScratchMem);
+    }
+
+    /* noise Band Pass filtering (1ms of delay) */
+    band_pass_6k_7k(HF,
+                    L_SUBFR16k,
+                    st->mem_hf,
+                    ScratchMem);
+
+
+    if (nb_bits >= NBBITS_24k)
+    {
+        /* Low Pass filtering (7 kHz) */
+        low_pass_filt_7k(HF,
+                         L_SUBFR16k,
+                         st->mem_hf3,
+                         ScratchMem);
+    }
+    /* add filtered HF noise to speech synthesis */
+
+    pt_synth = synth16k;
+    pt_HF = HF;
+
+    for (i = L_SUBFR16k >> 1; i != 0; i--)
+    {
+        *(pt_synth) = add_int16(*(pt_synth), *(pt_HF++)); /* check 16 bit saturation */
+        pt_synth++;
+        *(pt_synth) = add_int16(*(pt_synth), *(pt_HF++));
+        pt_synth++;
+    }
+
+}
+
diff --git a/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.h b/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.h
new file mode 100644
index 0000000..4bfc3c5
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/synthesis_amr_wb.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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: ./cpp/include/synthesis_amr_wb.h
+
+     Date: 05/04/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef SYNTHESIS_AMR_WB_H
+#define SYNTHESIS_AMR_WB_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void synthesis_amr_wb(
+        int16 Aq[],                          /* A(z)  : quantized Az               */
+        int16 exc[],                         /* (i)   : excitation at 12kHz        */
+        int16 Q_new,                         /* (i)   : scaling performed on exc   */
+        int16 synth16k[],                    /* (o)   : 16kHz synthesis signal     */
+        int16 prms,                          /* (i)   : parameter                  */
+        int16 HfIsf[],
+        int16 nb_bits,
+        int16 newDTXState,
+        Decoder_State * st,                   /* (i/o) : State structure            */
+        int16 bfi,                           /* (i)   : bad frame indicator        */
+        int16 * ScratchMemory
+    );
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+#endif  /* PV_NORMALIZE_H */
diff --git a/media/libstagefright/codecs/amrwb/src/voice_factor.cpp b/media/libstagefright/codecs/amrwb/src/voice_factor.cpp
new file mode 100644
index 0000000..6153c67
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/voice_factor.cpp
@@ -0,0 +1,175 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: voice_factor.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 exc[],        (i) Q_exc : pitch excitation
+     int16 Q_exc,        (i)       : exc format
+     int16 gain_pit,     (i) Q14   : gain of pitch
+     int16 code[],       (i) Q9    : Fixed codebook excitation
+     int16 gain_code,    (i) Q0    : gain of code
+     int16 L_subfr       (i)       : subframe length
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Find the voicing factor (1=voice to -1=unvoiced).
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_acelp.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
+----------------------------------------------------------------------------*/
+
+int16 voice_factor(    /* (o) Q15   : factor (-1=unvoiced to 1=voiced) */
+    int16 exc[],      /* (i) Q_exc : pitch excitation                 */
+    int16 Q_exc,      /* (i)       : exc format                       */
+    int16 gain_pit,   /* (i) Q14   : gain of pitch                    */
+    int16 code[],     /* (i) Q9    : Fixed codebook excitation        */
+    int16 gain_code,  /* (i) Q0    : gain of code                     */
+    int16 L_subfr     /* (i)       : subframe length                  */
+)
+{
+    int16 i, tmp, exp, ener1, exp1, ener2, exp2;
+    int32 L_tmp;
+
+    ener1 = extract_h(Dot_product12(exc, exc, L_subfr, &exp1));
+    exp1 = sub_int16(exp1, Q_exc << 1);
+    L_tmp = mul_16by16_to_int32(gain_pit, gain_pit);
+    exp = normalize_amr_wb(L_tmp);
+
+    tmp = (int16)((L_tmp << exp) >> 16);
+    ener1 = mult_int16(ener1, tmp);
+    exp1 -= (exp + 10);        /* 10 -> gain_pit Q14 to Q9 */
+
+    ener2 = extract_h(Dot_product12(code, code, L_subfr, &exp2));
+
+    exp = norm_s(gain_code);
+    tmp = shl_int16(gain_code, exp);
+    tmp = mult_int16(tmp, tmp);
+    ener2 = mult_int16(ener2, tmp);
+    exp2 -= (exp << 1);
+
+    i = exp1 - exp2;
+
+
+    if (i >= 0)
+    {
+        ener1 >>=  1;
+        ener2 >>= (i + 1);
+    }
+    else
+    {
+        ener1 >>= (1 - i);
+        ener2 >>= 1;
+    }
+
+    tmp = ener1 - ener2;
+    ener1 += ener2 + 1;
+
+
+    if (tmp >= 0)
+    {
+        tmp = div_16by16(tmp, ener1);
+    }
+    else
+    {
+        tmp = negate_int16(div_16by16(negate_int16(tmp), ener1));
+    }
+
+    return (tmp);
+}
diff --git a/media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp b/media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp
new file mode 100644
index 0000000..e1af6d4
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/wb_syn_filt.cpp
@@ -0,0 +1,307 @@
+/* ------------------------------------------------------------------
+ * 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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: wb_syn_filt.cpp
+
+     Date: 05/08/2004
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+wb_syn_filt
+
+     int16 a[],               (i) Q12 : a[m+1] prediction coefficients
+     int16 m,                 (i)     : order of LP filter
+     int16 x[],               (i)     : input signal
+     int16 y[],               (o)     : output signal
+     int16 lg,                (i)     : size of filtering
+     int16 mem[],             (i/o)   : memory associated with this filtering.
+     int16 update,            (i)     : 0=no update, 1=update of memory.
+     int16 y_buf[]
+
+Syn_filt_32
+
+     int16 a[],              (i) Q12 : a[m+1] prediction coefficients
+     int16 m,                (i)     : order of LP filter
+     int16 exc[],            (i) Qnew: excitation (exc[i] >> Qnew)
+     int16 Qnew,             (i)     : exc scaling = 0(min) to 8(max)
+     int16 sig_hi[],         (o) /16 : synthesis high
+     int16 sig_lo[],         (o) /16 : synthesis low
+     int16 lg                (i)     : size of filtering
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Do the synthesis filtering 1/A(z)  16 and 32-bits version
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_mem_funcs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwb_math_op.h"
+#include "pvamrwbdecoder_cnst.h"
+#include "pvamrwbdecoder_acelp.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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 wb_syn_filt(
+    int16 a[],       /* (i) Q12 : a[m+1] prediction coefficients           */
+    int16 m,         /* (i)     : order of LP filter                       */
+    int16 x[],       /* (i)     : input signal                             */
+    int16 y[],       /* (o)     : output signal                            */
+    int16 lg,        /* (i)     : size of filtering                        */
+    int16 mem[],     /* (i/o)   : memory associated with this filtering.   */
+    int16 update,    /* (i)     : 0=no update, 1=update of memory.         */
+    int16 y_buf[]
+)
+{
+
+    int16 i, j;
+    int32 L_tmp1;
+    int32 L_tmp2;
+    int32 L_tmp3;
+    int32 L_tmp4;
+    int16 *yy;
+
+    /* copy initial filter states into synthesis buffer */
+    pv_memcpy(y_buf, mem, m*sizeof(*yy));
+
+    yy = &y_buf[m];
+
+    /* Do the filtering. */
+
+    for (i = 0; i < lg >> 2; i++)
+    {
+        L_tmp1 = -((int32)x[(i<<2)] << 11);
+        L_tmp2 = -((int32)x[(i<<2)+1] << 11);
+        L_tmp3 = -((int32)x[(i<<2)+2] << 11);
+        L_tmp4 = -((int32)x[(i<<2)+3] << 11);
+
+        /* a[] uses Q12 and abs(a) =< 1 */
+
+        L_tmp1  = fxp_mac_16by16(yy[(i<<2) -3], a[3], L_tmp1);
+        L_tmp2  = fxp_mac_16by16(yy[(i<<2) -2], a[3], L_tmp2);
+        L_tmp1  = fxp_mac_16by16(yy[(i<<2) -2], a[2], L_tmp1);
+        L_tmp2  = fxp_mac_16by16(yy[(i<<2) -1], a[2], L_tmp2);
+        L_tmp1  = fxp_mac_16by16(yy[(i<<2) -1], a[1], L_tmp1);
+
+        for (j = 4; j < m; j += 2)
+        {
+            L_tmp1  = fxp_mac_16by16(yy[(i<<2)-1  - j], a[j+1], L_tmp1);
+            L_tmp2  = fxp_mac_16by16(yy[(i<<2)    - j], a[j+1], L_tmp2);
+            L_tmp1  = fxp_mac_16by16(yy[(i<<2)    - j], a[j  ], L_tmp1);
+            L_tmp2  = fxp_mac_16by16(yy[(i<<2)+1  - j], a[j  ], L_tmp2);
+            L_tmp3  = fxp_mac_16by16(yy[(i<<2)+1  - j], a[j+1], L_tmp3);
+            L_tmp4  = fxp_mac_16by16(yy[(i<<2)+2  - j], a[j+1], L_tmp4);
+            L_tmp3  = fxp_mac_16by16(yy[(i<<2)+2  - j], a[j  ], L_tmp3);
+            L_tmp4  = fxp_mac_16by16(yy[(i<<2)+3  - j], a[j  ], L_tmp4);
+        }
+
+        L_tmp1  = fxp_mac_16by16(yy[(i<<2)    - j], a[j], L_tmp1);
+        L_tmp2  = fxp_mac_16by16(yy[(i<<2)+1  - j], a[j], L_tmp2);
+        L_tmp3  = fxp_mac_16by16(yy[(i<<2)+2  - j], a[j], L_tmp3);
+        L_tmp4  = fxp_mac_16by16(yy[(i<<2)+3  - j], a[j], L_tmp4);
+
+        L_tmp1 = shl_int32(L_tmp1, 4);
+
+        y[(i<<2)] = yy[(i<<2)] = amr_wb_round(-L_tmp1);
+
+        L_tmp2  = fxp_mac_16by16(yy[(i<<2)], a[1], L_tmp2);
+
+        L_tmp2 = shl_int32(L_tmp2, 4);
+
+        y[(i<<2)+1] = yy[(i<<2)+1] = amr_wb_round(-L_tmp2);
+
+        L_tmp3  = fxp_mac_16by16(yy[(i<<2) - 1], a[3], L_tmp3);
+        L_tmp4  = fxp_mac_16by16(yy[(i<<2)], a[3], L_tmp4);
+        L_tmp3  = fxp_mac_16by16(yy[(i<<2)], a[2], L_tmp3);
+        L_tmp4  = fxp_mac_16by16(yy[(i<<2) + 1], a[2], L_tmp4);
+        L_tmp3  = fxp_mac_16by16(yy[(i<<2) + 1], a[1], L_tmp3);
+
+        L_tmp3 = shl_int32(L_tmp3, 4);
+
+        y[(i<<2)+2] = yy[(i<<2)+2] = amr_wb_round(-L_tmp3);
+
+        L_tmp4  = fxp_mac_16by16(yy[(i<<2)+2], a[1], L_tmp4);
+
+        L_tmp4 = shl_int32(L_tmp4, 4);
+
+        y[(i<<2)+3] = yy[(i<<2)+3] = amr_wb_round(-L_tmp4);
+    }
+
+
+    /* Update memory if required */
+
+    if (update)
+    {
+        pv_memcpy(mem, &y[lg - m], m*sizeof(*y));
+    }
+
+    return;
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void Syn_filt_32(
+    int16 a[],              /* (i) Q12 : a[m+1] prediction coefficients */
+    int16 m,                /* (i)     : order of LP filter             */
+    int16 exc[],            /* (i) Qnew: excitation (exc[i] >> Qnew)    */
+    int16 Qnew,             /* (i)     : exc scaling = 0(min) to 8(max) */
+    int16 sig_hi[],         /* (o) /16 : synthesis high                 */
+    int16 sig_lo[],         /* (o) /16 : synthesis low                  */
+    int16 lg                /* (i)     : size of filtering              */
+)
+{
+    int16 i, k, a0;
+    int32 L_tmp1;
+    int32 L_tmp2;
+    int32 L_tmp3;
+    int32 L_tmp4;
+
+    a0 = 9 - Qnew;        /* input / 16 and >>Qnew */
+
+    /* Do the filtering. */
+
+    for (i = 0; i < lg >> 1; i++)
+    {
+
+        L_tmp3 = 0;
+        L_tmp4 = 0;
+
+        L_tmp1 = fxp_mul_16by16(sig_lo[(i<<1) - 1], a[1]);
+        L_tmp2 = fxp_mul_16by16(sig_hi[(i<<1) - 1], a[1]);
+
+        for (k = 2; k < m; k += 2)
+        {
+
+            L_tmp1 = fxp_mac_16by16(sig_lo[(i<<1)-1 - k], a[k+1], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(sig_hi[(i<<1)-1 - k], a[k+1], L_tmp2);
+            L_tmp1 = fxp_mac_16by16(sig_lo[(i<<1)   - k], a[k  ], L_tmp1);
+            L_tmp2 = fxp_mac_16by16(sig_hi[(i<<1)   - k], a[k  ], L_tmp2);
+            L_tmp3 = fxp_mac_16by16(sig_lo[(i<<1)   - k], a[k+1], L_tmp3);
+            L_tmp4 = fxp_mac_16by16(sig_hi[(i<<1)   - k], a[k+1], L_tmp4);
+            L_tmp3 = fxp_mac_16by16(sig_lo[(i<<1)+1 - k], a[k  ], L_tmp3);
+            L_tmp4 = fxp_mac_16by16(sig_hi[(i<<1)+1 - k], a[k  ], L_tmp4);
+        }
+
+        L_tmp1 = -fxp_mac_16by16(sig_lo[(i<<1)   - k], a[k], L_tmp1);
+        L_tmp3 =  fxp_mac_16by16(sig_lo[(i<<1)+1 - k], a[k], L_tmp3);
+        L_tmp2 =  fxp_mac_16by16(sig_hi[(i<<1)   - k], a[k], L_tmp2);
+        L_tmp4 =  fxp_mac_16by16(sig_hi[(i<<1)+1 - k], a[k], L_tmp4);
+
+
+
+        L_tmp1 >>= 11;      /* -4 : sig_lo[i] << 4 */
+
+        L_tmp1 += (int32)exc[(i<<1)] << a0;
+
+        L_tmp1 -= (L_tmp2 << 1);
+        /* sig_hi = bit16 to bit31 of synthesis */
+        L_tmp1 = shl_int32(L_tmp1, 3);           /* ai in Q12 */
+
+        sig_hi[(i<<1)] = (int16)(L_tmp1 >> 16);
+
+        L_tmp4 = fxp_mac_16by16((int16)(L_tmp1 >> 16), a[1], L_tmp4);
+
+        /* sig_lo = bit4 to bit15 of synthesis */
+        /* L_tmp1 >>= 4 : sig_lo[i] >> 4 */
+        sig_lo[(i<<1)] = (int16)((L_tmp1 >> 4) - ((L_tmp1 >> 16) << 12));
+
+        L_tmp3 = fxp_mac_16by16(sig_lo[(i<<1)], a[1], L_tmp3);
+        L_tmp3 = -L_tmp3 >> 11;
+
+        L_tmp3 += (int32)exc[(i<<1)+1] << a0;
+
+        L_tmp3 -= (L_tmp4 << 1);
+        /* sig_hi = bit16 to bit31 of synthesis */
+        L_tmp3 = shl_int32(L_tmp3, 3);           /* ai in Q12 */
+        sig_hi[(i<<1)+1] = (int16)(L_tmp3 >> 16);
+
+        /* sig_lo = bit4 to bit15 of synthesis */
+        /* L_tmp1 >>= 4 : sig_lo[i] >> 4 */
+        sig_lo[(i<<1)+1] = (int16)((L_tmp3 >> 4) - (sig_hi[(i<<1)+1] << 12));
+    }
+
+}
+
+
diff --git a/media/libstagefright/codecs/amrwb/src/weight_amrwb_lpc.cpp b/media/libstagefright/codecs/amrwb/src/weight_amrwb_lpc.cpp
new file mode 100644
index 0000000..63d2e00
--- /dev/null
+++ b/media/libstagefright/codecs/amrwb/src/weight_amrwb_lpc.cpp
@@ -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.173
+    ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
+    Available from http://www.3gpp.org
+
+(C) 2007, 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: weight_amrwb_lpc.cpp
+
+     Date: 05/08/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+     int16 a[],            (i) Q12 : a[m+1]  LPC coefficients
+     int16 ap[],           (o) Q12 : Spectral expanded LPC coefficients
+     int16 gamma,          (i) Q15 : Spectral expansion factor.
+     int16 m               (i)     : LPC order.
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   Weighting of LPC coefficients.
+     ap[i]  =  a[i]   (gamma    i)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_amr_wb_type_defs.h"
+#include "pvamrwbdecoder_basic_op.h"
+#include "pvamrwbdecoder_acelp.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 weight_amrwb_lpc(
+    int16 a[],          /* (i) Q12 : a[m+1]  LPC coefficients             */
+    int16 ap[],         /* (o) Q12 : Spectral expanded LPC coefficients   */
+    int16 gamma,        /* (i) Q15 : Spectral expansion factor.           */
+    int16 m             /* (i)     : LPC order.                           */
+)
+{
+    int16 i, fac;
+    int32 roundFactor = 0x00004000L;
+    ap[0] = a[0];
+    fac = gamma;
+    for (i = 1; i < m; i++)
+    {
+        ap[i] = (int16)(fxp_mac_16by16(a[i], fac, roundFactor) >> 15);
+        fac   = (int16)(fxp_mac_16by16(fac, gamma, roundFactor) >> 15);
+    }
+    ap[i] = (int16)(fxp_mac_16by16(a[i], fac, roundFactor) >> 15);
+
+    return;
+}
diff --git a/media/libstagefright/codecs/avc/Android.mk b/media/libstagefright/codecs/avc/Android.mk
new file mode 100644
index 0000000..2e43120
--- /dev/null
+++ b/media/libstagefright/codecs/avc/Android.mk
@@ -0,0 +1,4 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codecs/avc/common/Android.mk b/media/libstagefright/codecs/avc/common/Android.mk
new file mode 100644
index 0000000..39c6da8
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/Android.mk
@@ -0,0 +1,21 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	src/deblock.cpp \
+ 	src/dpb.cpp \
+ 	src/fmo.cpp \
+ 	src/mb_access.cpp \
+ 	src/reflist.cpp
+
+LOCAL_MODULE := libstagefright_avc_common
+
+LOCAL_CFLAGS := -DOSCL_EXPORT_REF= -DOSCL_IMPORT_REF=
+
+LOCAL_C_INCLUDES := \
+	$(LOCAL_PATH)/src \
+ 	$(LOCAL_PATH)/include
+
+LOCAL_PRELINK_MODULE:= false
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/codecs/avc/common/include/avc_types.h b/media/libstagefright/codecs/avc/common/include/avc_types.h
new file mode 100644
index 0000000..73cad89
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/include/avc_types.h
@@ -0,0 +1,14 @@
+#ifndef AVC_TYPES_H_
+
+#define AVC_TYPES_H_
+
+#include <stdint.h>
+
+typedef uint8_t uint8;
+typedef uint16_t uint16;
+typedef int16_t int16;
+typedef uint32_t uint32;
+typedef int32_t int32;
+typedef unsigned int uint;
+
+#endif  // AVC_TYPES_H_
diff --git a/media/libstagefright/codecs/avc/common/include/avcapi_common.h b/media/libstagefright/codecs/avc/common/include/avcapi_common.h
new file mode 100644
index 0000000..3331689
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/include/avcapi_common.h
@@ -0,0 +1,274 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains common type definitions and enumerations used by AVC encoder
+and decoder libraries which are exposed to the users.
+@publishedAll
+*/
+
+#ifndef AVCAPI_COMMON_H_INCLUDED
+#define AVCAPI_COMMON_H_INCLUDED
+
+#include "avc_types.h"
+
+#define PV_MEMORY_POOL
+/**
+This is common return status.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_NO_BUFFER = -2,
+    AVC_MEMORY_FAIL = -1,
+    AVC_FAIL = 0,
+    AVC_SUCCESS = 1,
+    AVC_PICTURE_OUTPUT_READY = 2
+} AVCStatus;
+
+/**
+This enumeration is for profiles. The value follows the profile_idc  in sequence
+parameter set rbsp. See Annex A.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_BASELINE = 66,
+    AVC_MAIN = 77,
+    AVC_EXTENDED = 88,
+    AVC_HIGH = 100,
+    AVC_HIGH10 = 110,
+    AVC_HIGH422 = 122,
+    AVC_HIGH444 = 144
+} AVCProfile;
+
+/**
+This enumeration is for levels. The value follows the level_idc in sequence
+parameter set rbsp. See Annex A.
+@published All
+*/
+typedef enum
+{
+    AVC_LEVEL_AUTO = 0,
+    AVC_LEVEL1_B = 9,
+    AVC_LEVEL1 = 10,
+    AVC_LEVEL1_1 = 11,
+    AVC_LEVEL1_2 = 12,
+    AVC_LEVEL1_3 = 13,
+    AVC_LEVEL2 = 20,
+    AVC_LEVEL2_1 = 21,
+    AVC_LEVEL2_2 = 22,
+    AVC_LEVEL3 = 30,
+    AVC_LEVEL3_1 = 31,
+    AVC_LEVEL3_2 = 32,
+    AVC_LEVEL4 = 40,
+    AVC_LEVEL4_1 = 41,
+    AVC_LEVEL4_2 = 42,
+    AVC_LEVEL5 = 50,
+    AVC_LEVEL5_1 = 51
+} AVCLevel;
+
+/**
+This enumeration follows Table 7-1 for NAL unit type codes.
+This may go to avccommon_api.h later (external common).
+@publishedAll
+*/
+typedef enum
+{
+    AVC_NALTYPE_SLICE = 1,  /* non-IDR non-data partition */
+    AVC_NALTYPE_DPA = 2,    /* data partition A */
+    AVC_NALTYPE_DPB = 3,    /* data partition B */
+    AVC_NALTYPE_DPC = 4,    /* data partition C */
+    AVC_NALTYPE_IDR = 5,    /* IDR NAL */
+    AVC_NALTYPE_SEI = 6,    /* supplemental enhancement info */
+    AVC_NALTYPE_SPS = 7,    /* sequence parameter set */
+    AVC_NALTYPE_PPS = 8,    /* picture parameter set */
+    AVC_NALTYPE_AUD = 9,    /* access unit delimiter */
+    AVC_NALTYPE_EOSEQ = 10, /* end of sequence */
+    AVC_NALTYPE_EOSTREAM = 11, /* end of stream */
+    AVC_NALTYPE_FILL = 12   /* filler data */
+} AVCNalUnitType;
+
+/**
+This enumeration specifies debug logging type.
+This may go to avccommon_api.h later (external common).
+@publishedAll
+*/
+typedef enum
+{
+    AVC_LOGTYPE_ERROR = 0,
+    AVC_LOGTYPE_WARNING = 1,
+    AVC_LOGTYPE_INFO = 2
+} AVCLogType;
+
+/**
+This enumerate the status of certain flags.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_OFF = 0,
+    AVC_ON = 1
+} AVCFlag;
+
+/**
+This structure contains input information.
+Note, this structure is identical to AVCDecOutput for now.
+*/
+typedef struct tagAVCFrameIO
+{
+    /** A unique identification number for a particular instance of this structure.
+    To remain unchanged by the application between the time when it is given to the
+    library and the time when the library returns it back. */
+    uint32 id;
+
+    /** Array of pointers to Y,Cb,Cr content in 4:2:0 format. For AVC decoding,
+    this memory is allocated by the AVC decoder library. For AVC encoding, only the
+    memory for original unencoded frame is allocated by the application. Internal
+    memory is also allocated by the AVC encoder library. */
+    uint8 *YCbCr[3];
+
+    /** In/Out: Coded width of the luma component, it has to be multiple of 16. */
+    int pitch;
+
+    /** In/Out: Coded height of the luma component, must be multiple of 16. */
+    int height;
+
+    /** In/Out: Display width, less than picth */
+    int clip_width;
+
+    /** In/Out: Display height, less than height */
+    int clip_height;
+
+    /** Input: Origin of the display area [0]=>row, [1]=>column  */
+    int clip_origin[2];
+
+    /** Output: Frame number in de/encoding order (not necessary)*/
+    uint32 coding_order;
+
+    /** Output: Frame number in displaying order (this may or may not be associated with the POC at all!!!). */
+    uint32 disp_order;
+
+    /** In/Out: Flag for use for reference or not. */
+    uint  is_reference;
+
+    /** In/Out: Coding timestamp in msec (not display timestamp) */
+    uint32 coding_timestamp;
+
+    /* there could be something else here such as format, DON (decoding order number)
+     if available thru SEI, etc. */
+} AVCFrameIO;
+
+
+/** CALLBACK FUNCTION TO BE IMPLEMENTED BY APPLICATION */
+/** In AVCDecControls structure, userData is a pointer to an object with the following
+    member functions.
+*/
+
+
+/** @brief Decoded picture buffers (DPB) must be allocated or re-allocated before an
+    IDR frame is decoded. If PV_MEMORY_POOL is not defined, AVC lib will allocate DPB
+    internally which cannot be shared with the application. In that case, this function
+    will not be called.
+    @param userData  The same value of userData in AVCHandle object.
+    @param frame_size_in_mbs  The size of each frame in number of macroblocks.
+    @param num_frames The number of frames in DPB.
+    @return 1 for success, 0 for fail (cannot allocate DPB)
+*/
+
+typedef int (*FunctionType_DPBAlloc)(void *userData, uint frame_size_in_mbs, uint num_buffers);
+
+/** @brief AVC library calls this function is reserve a memory of one frame from the DPB.
+    Once reserved, this frame shall not be deleted or over-written by the app.
+    @param userData  The same value of userData in AVCHandle object.
+    @param indx      Index of a frame in DPB (AVC library keeps track of the index).
+    @param yuv      The address of the yuv pointer returned to the AVC lib.
+    @return         1 for success, 0 for fail (no frames available to bind).
+    */
+typedef int (*FunctionType_FrameBind)(void *userData, int indx, uint8 **yuv);
+
+/** @brief AVC library calls this function once a bound frame is not needed for decoding
+    operation (falls out of the sliding window, or marked unused for reference).
+    @param userData  The same value of userData in AVCHandle object.
+    @param indx      Index of frame to be unbound (AVC library keeps track of the index).
+    @return  none.
+*/
+typedef void (*FuctionType_FrameUnbind)(void *userData, int);
+
+/** Pointer to malloc function for general memory allocation, so that application can keep track of
+    memory usage.
+\param "size" "Size of requested memory in bytes."
+\param "attribute" "Some value specifying types, priority, etc. of the memory."
+\return "The address of the allocated memory casted to int"
+*/
+typedef int (*FunctionType_Malloc)(void *userData, int32 size, int attribute);
+
+/** Function pointer to free
+\param "mem" "Pointer to the memory to be freed casted to int"
+\return "void"
+*/
+typedef void (*FunctionType_Free)(void *userData, int mem);
+
+/** Debug logging information is returned to the application thru this function.
+\param "type"   "Type of logging message, see definition of AVCLogType."
+\param "string1"    "Logging message."
+\param "string2"    "To be defined."
+*/
+typedef void (*FunctionType_DebugLog)(uint32 *userData, AVCLogType type, char *string1, int val1, int val2);
+
+/**
+This structure has to be allocated and maintained by the user of the library.
+This structure is used as a handle to the library object.
+*/
+typedef struct tagAVCHandle
+{
+    /** A pointer to the internal data structure. Users have to make sure that this value
+        is NULL at the beginning.
+    */
+    void        *AVCObject;
+
+    /** A pointer to user object which has the following member functions used for
+    callback purpose.  !!! */
+    void        *userData;
+
+    /** Pointers to functions implemented by the users of AVC library */
+    FunctionType_DPBAlloc CBAVC_DPBAlloc;
+
+    FunctionType_FrameBind CBAVC_FrameBind;
+
+    FuctionType_FrameUnbind CBAVC_FrameUnbind;
+
+    FunctionType_Malloc CBAVC_Malloc;
+
+    FunctionType_Free  CBAVC_Free;
+
+    FunctionType_DebugLog CBAVC_DebugLog;
+
+    /** Flag to enable debugging */
+    uint32  debugEnable;
+
+} AVCHandle;
+
+
+
+#ifdef PVDEBUGMSG_LOG
+#define DEBUG_LOG(a,b,c,d,e)    CBAVC_DebugLog(a,b,c,d,e)
+#else
+#define DEBUG_LOG(a,b,c,d,e)
+#endif
+
+#endif /* _AVCAPI_COMMON_H_ */
diff --git a/media/libstagefright/codecs/avc/common/include/avcint_common.h b/media/libstagefright/codecs/avc/common/include/avcint_common.h
new file mode 100644
index 0000000..465e604
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/include/avcint_common.h
@@ -0,0 +1,882 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains common code shared between AVC decoder and AVC encoder for
+internal use only.
+@publishedAll
+*/
+
+#ifndef AVCINT_COMMON_H_INCLUDED
+#define AVCINT_COMMON_H_INCLUDED
+
+#ifndef AVCAPI_COMMON_H_INCLUDED
+#include "avcapi_common.h"
+#endif
+
+
+#ifndef TRUE
+#define TRUE  1
+#define FALSE 0
+#endif
+
+
+
+/**
+Mathematic functions defined in subclause 5.7.
+Can be replaced with assembly instructions for speedup.
+@publishedAll
+*/
+#define AVC_ABS(x)   (((x)<0)? -(x) : (x))
+#define AVC_SIGN(x)  (((x)<0)? -1 : 1)
+#define AVC_SIGN0(x) (((x)<0)? -1 : (((x)>0) ? 1 : 0))
+#define AVC_MAX(x,y) ((x)>(y)? (x):(y))
+#define AVC_MIN(x,y) ((x)<(y)? (x):(y))
+#define AVC_MEDIAN(A,B,C) ((A) > (B) ? ((A) < (C) ? (A) : (B) > (C) ? (B) : (C)): (B) < (C) ? (B) : (C) > (A) ? (C) : (A))
+#define AVC_CLIP3(a,b,x) (AVC_MAX(a,AVC_MIN(x,b)))  /* clip x between a and b */
+#define AVC_CLIP(x)  AVC_CLIP3(0,255,x)
+#define AVC_FLOOR(x) ((int)(x))
+#define AVC_RASTER_SCAN(x,y,n)  ((x)+(y)*(n))
+#define AVC_ROUND(x) (AVC_SIGN(x)*AVC_FLOOR(AVC_ABS(x)+0.5))
+#define AVC_INVERSE_RASTER_SCAN(a,b,c,d,e) (((e)==0)? (((a)%((d)/(b)))*(b)): (((a)/((d)/(b)))*(c)))
+/* a:block address, b:block width, c:block height, d:total_width, e:x or y coordinate */
+
+#define DEFAULT_ATTR  0  /* default memory attribute  */
+#define FAST_MEM_ATTR 1  /* fast memory attribute */
+
+
+/* This section is for definition of constants. */
+#define MB_SIZE 16
+#define BLOCK_SIZE 4
+#define EMULATION_PREVENTION_THREE_BYTE 0x3
+#define NUM_PIXELS_IN_MB  (24*16)
+#define NUM_BLKS_IN_MB 24
+
+#define AVCNumI4PredMode  9
+#define AVCNumI16PredMode  4
+#define AVCNumIChromaMode  4
+
+/* constants used in the structures below */
+#define MAXIMUMVALUEOFcpb_cnt   32  /* used in HRDParams */
+#define MAX_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE 255   /* used in SeqParamSet */
+#define MAX_NUM_SLICE_GROUP  8      /* used in PicParamSet */
+#define MAX_REF_PIC_LIST_REORDERING 32  /* 32 is maximum according to Annex A, SliceHeader */
+#define MAX_DEC_REF_PIC_MARKING 64   /* 64 is the maximum possible given the max num ref pictures to 31. */
+#define MAX_FS (16+1)  /* pre-defined size of frame store array */
+#define MAX_LEVEL_IDX  15  /* only 15 levels defined for now */
+#define MAX_REF_PIC_LIST 33 /* max size of the RefPicList0 and RefPicList1 */
+
+
+/**
+Architectural related macros.
+@publishedAll
+*/
+#ifdef USE_PRED_BLOCK
+#define MB_BASED_DEBLOCK
+#endif
+
+/**
+Picture type, PV created.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_FRAME = 3
+} AVCPictureType;
+
+/**
+This slice type follows Table 7-3. The bottom 5 items may not needed.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_P_SLICE = 0,
+    AVC_B_SLICE = 1,
+    AVC_I_SLICE = 2,
+    AVC_SP_SLICE = 3,
+    AVC_SI_SLICE = 4,
+    AVC_P_ALL_SLICE = 5,
+    AVC_B_ALL_SLICE = 6,
+    AVC_I_ALL_SLICE = 7,
+    AVC_SP_ALL_SLICE = 8,
+    AVC_SI_ALL_SLICE = 9
+} AVCSliceType;
+
+/**
+Types of the macroblock and partition. PV Created.
+@publishedAll
+*/
+typedef enum
+{
+    /* intra */
+    AVC_I4,
+    AVC_I16,
+    AVC_I_PCM,
+    AVC_SI4,
+
+    /* inter for both P and B*/
+    AVC_BDirect16,
+    AVC_P16,
+    AVC_P16x8,
+    AVC_P8x16,
+    AVC_P8,
+    AVC_P8ref0,
+    AVC_SKIP
+} AVCMBMode;
+
+/**
+Enumeration for sub-macroblock mode, interpreted from sub_mb_type.
+@publishedAll
+*/
+typedef enum
+{
+    /* for sub-partition mode */
+    AVC_BDirect8,
+    AVC_8x8,
+    AVC_8x4,
+    AVC_4x8,
+    AVC_4x4
+} AVCSubMBMode;
+
+/**
+Mode of prediction of partition or sub-partition. PV Created.
+Do not change the order!!! Used in table look-up mode prediction in
+vlc.c.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_Pred_L0 = 0,
+    AVC_Pred_L1,
+    AVC_BiPred,
+    AVC_Direct
+} AVCPredMode;
+
+
+/**
+Mode of intra 4x4 prediction. Table 8-2
+@publishedAll
+*/
+typedef enum
+{
+    AVC_I4_Vertical = 0,
+    AVC_I4_Horizontal,
+    AVC_I4_DC,
+    AVC_I4_Diagonal_Down_Left,
+    AVC_I4_Diagonal_Down_Right,
+    AVC_I4_Vertical_Right,
+    AVC_I4_Horizontal_Down,
+    AVC_I4_Vertical_Left,
+    AVC_I4_Horizontal_Up
+} AVCIntra4x4PredMode;
+
+/**
+Mode of intra 16x16 prediction. Table 8-3
+@publishedAll
+*/
+typedef enum
+{
+    AVC_I16_Vertical = 0,
+    AVC_I16_Horizontal,
+    AVC_I16_DC,
+    AVC_I16_Plane
+} AVCIntra16x16PredMode;
+
+
+/**
+Mode of intra chroma prediction. Table 8-4
+@publishedAll
+*/
+typedef enum
+{
+    AVC_IC_DC = 0,
+    AVC_IC_Horizontal,
+    AVC_IC_Vertical,
+    AVC_IC_Plane
+} AVCIntraChromaPredMode;
+
+/**
+Type of residual going to residual_block_cavlc function, PV created.
+@publishedAll
+*/
+typedef enum
+{
+    AVC_Luma,
+    AVC_Intra16DC,
+    AVC_Intra16AC,
+    AVC_ChromaDC,
+    AVC_ChromaAC
+} AVCResidualType;
+
+
+/**
+This structure contains VUI parameters as specified in Annex E.
+Some variables may be removed from the structure if they are found to be useless to store.
+@publishedAll
+*/
+typedef struct tagHRDParams
+{
+    uint  cpb_cnt_minus1;                                   /* ue(v), range 0..31 */
+    uint  bit_rate_scale;                          /* u(4) */
+    uint  cpb_size_scale;                          /* u(4) */
+    uint32  bit_rate_value_minus1[MAXIMUMVALUEOFcpb_cnt];/* ue(v), range 0..2^32-2 */
+    uint32  cpb_size_value_minus1[MAXIMUMVALUEOFcpb_cnt]; /* ue(v), range 0..2^32-2 */
+    uint  cbr_flag[MAXIMUMVALUEOFcpb_cnt];         /* u(1) */
+    uint  initial_cpb_removal_delay_length_minus1;   /* u(5), default 23 */
+    uint  cpb_removal_delay_length_minus1;           /* u(5), default 23 */
+    uint  dpb_output_delay_length_minus1;            /* u(5), default 23 */
+    uint  time_offset_length;                        /* u(5), default 24 */
+} AVCHRDParams;
+
+/**
+This structure contains VUI parameters as specified in Annex E.
+Some variables may be removed from the structure if they are found to be useless to store.
+@publishedAll
+*/
+typedef struct tagVUIParam
+{
+    uint      aspect_ratio_info_present_flag;     /* u(1) */
+    uint  aspect_ratio_idc;                     /* u(8), table E-1 */
+    uint  sar_width;                          /* u(16) */
+    uint  sar_height;                         /* u(16) */
+    uint      overscan_info_present_flag;         /* u(1) */
+    uint      overscan_appropriate_flag;        /* u(1) */
+    uint      video_signal_type_present_flag;     /* u(1) */
+    uint  video_format;                         /* u(3), Table E-2, default 5, unspecified */
+    uint      video_full_range_flag;            /* u(1) */
+    uint      colour_description_present_flag;  /* u(1) */
+    uint  colour_primaries;                   /* u(8), Table E-3, default 2, unspecified */
+    uint  transfer_characteristics;           /* u(8), Table E-4, default 2, unspecified */
+    uint  matrix_coefficients;                /* u(8), Table E-5, default 2, unspecified */
+    uint      chroma_location_info_present_flag;  /* u(1) */
+    uint  chroma_sample_loc_type_top_field;                /* ue(v), Fig. E-1range 0..5, default 0 */
+    uint  chroma_sample_loc_type_bottom_field;                /* ue(v) */
+    uint      timing_info_present_flag;           /* u(1) */
+    uint  num_units_in_tick;                    /* u(32), must be > 0 */
+    uint  time_scale;                           /* u(32), must be > 0 */
+    uint      fixed_frame_rate_flag;            /* u(1), Eq. C-13 */
+    uint      nal_hrd_parameters_present_flag;    /* u(1) */
+    AVCHRDParams nal_hrd_parameters;               /* hrd_paramters */
+    uint      vcl_hrd_parameters_present_flag;    /* u(1) */
+    AVCHRDParams vcl_hrd_parameters;               /* hrd_paramters */
+    /* if ((nal_hrd_parameters_present_flag || (vcl_hrd_parameters_present_flag)) */
+    uint      low_delay_hrd_flag;               /* u(1) */
+    uint    pic_struct_present_flag;
+    uint      bitstream_restriction_flag;         /* u(1) */
+    uint      motion_vectors_over_pic_boundaries_flag;    /* u(1) */
+    uint  max_bytes_per_pic_denom;              /* ue(v), default 2 */
+    uint  max_bits_per_mb_denom;                /* ue(v), range 0..16, default 1 */
+    uint  log2_max_mv_length_vertical;          /* ue(v), range 0..16, default 16 */
+    uint  log2_max_mv_length_horizontal;        /* ue(v), range 0..16, default 16 */
+    uint  max_dec_frame_reordering;             /* ue(v) */
+    uint  max_dec_frame_buffering;              /* ue(v) */
+} AVCVUIParams;
+
+
+/**
+This structure contains information in a sequence parameter set NAL.
+Some variables may be removed from the structure if they are found to be useless to store.
+@publishedAll
+*/
+typedef struct tagSeqParamSet
+{
+    uint   Valid;            /* indicates the parameter set is valid */
+
+    uint  profile_idc;              /* u(8) */
+    uint   constrained_set0_flag;  /* u(1) */
+    uint   constrained_set1_flag;  /* u(1) */
+    uint   constrained_set2_flag;  /* u(1) */
+    uint   constrained_set3_flag;  /* u(1) */
+    uint  level_idc;               /* u(8) */
+    uint  seq_parameter_set_id;    /* ue(v), range 0..31 */
+    uint  log2_max_frame_num_minus4; /* ue(v), range 0..12 */
+    uint pic_order_cnt_type;        /* ue(v), range 0..2 */
+    /* if( pic_order_cnt_type == 0 )  */
+    uint log2_max_pic_order_cnt_lsb_minus4; /* ue(v), range 0..12 */
+    /* else if( pic_order_cnt_type == 1 ) */
+    uint delta_pic_order_always_zero_flag;  /* u(1) */
+    int32  offset_for_non_ref_pic;       /* se(v) */
+    int32  offset_for_top_to_bottom_field;  /* se(v) */
+    uint  num_ref_frames_in_pic_order_cnt_cycle;   /* ue(v) , range 0..255 */
+    /* for( i = 0; i < num_ref_frames_in_pic_order_cnt_cycle; i++ ) */
+    int32   offset_for_ref_frame[MAX_NUM_REF_FRAMES_IN_PIC_ORDER_CNT_CYCLE];        /* se(v) */
+    uint  num_ref_frames;                           /* ue(v), range 0..16 */
+    uint   gaps_in_frame_num_value_allowed_flag;    /* u(1) */
+    uint  pic_width_in_mbs_minus1;                  /* ue(v) */
+    uint  pic_height_in_map_units_minus1;           /* ue(v) */
+    uint   frame_mbs_only_flag;                     /* u(1) */
+    /* if( !frame_mbs_only_flag ) */
+    uint   mb_adaptive_frame_field_flag;          /* u(1) */
+    uint   direct_8x8_inference_flag;    /* u(1), must be 1 when frame_mbs_only_flag is 0 */
+    uint   frame_cropping_flag;                     /* u(1) */
+    /* if( frmae_cropping_flag) */
+    uint  frame_crop_left_offset;                /* ue(v) */
+    uint  frame_crop_right_offset;               /* ue(v) */
+    uint  frame_crop_top_offset;                 /* ue(v) */
+    uint  frame_crop_bottom_offset;              /* ue(v) */
+    uint   vui_parameters_present_flag;                      /* u(1) */
+//  uint nal_hrd_parameters_present_flag;
+//  uint vcl_hrd_parameters_present_flag;
+//  AVCHRDParams *nal_hrd_parameters;
+//  AVCHRDParams *vcl_hrd_parameters;
+    AVCVUIParams vui_parameters;                  /* AVCVUIParam */
+} AVCSeqParamSet;
+
+/**
+This structure contains information in a picture parameter set NAL.
+Some variables may be removed from the structure if they are found to be useless to store.
+@publishedAll
+*/
+typedef struct tagPicParamSet
+{
+    uint  pic_parameter_set_id;              /* ue(v), range 0..255 */
+    uint  seq_parameter_set_id;              /* ue(v), range 0..31 */
+    uint  entropy_coding_mode_flag;         /* u(1) */
+    uint  pic_order_present_flag;        /* u(1) */
+    uint  num_slice_groups_minus1;           /* ue(v), range in Annex A */
+    /* if( num_slice_groups_minus1 > 0) */
+    uint  slice_group_map_type;           /* ue(v), range 0..6 */
+    /* if( slice_group_map_type = = 0 ) */
+    /* for(0:1:num_slice_groups_minus1) */
+    uint  run_length_minus1[MAX_NUM_SLICE_GROUP]; /* ue(v) */
+    /* else if( slice_group_map_type = = 2 ) */
+    /* for(0:1:num_slice_groups_minus1-1) */
+    uint  top_left[MAX_NUM_SLICE_GROUP-1];      /* ue(v) */
+    uint  bottom_right[MAX_NUM_SLICE_GROUP-1];  /* ue(v) */
+    /* else if( slice_group_map_type = = 3 || 4 || 5 */
+    uint  slice_group_change_direction_flag;        /* u(1) */
+    uint  slice_group_change_rate_minus1;            /* ue(v) */
+    /* else if( slice_group_map_type = = 6 ) */
+    uint  pic_size_in_map_units_minus1;          /* ue(v) */
+    /* for(0:1:pic_size_in_map_units_minus1) */
+    uint  *slice_group_id;                           /* complete MBAmap u(v) */
+    uint  num_ref_idx_l0_active_minus1;                  /* ue(v), range 0..31 */
+    uint  num_ref_idx_l1_active_minus1;                  /* ue(v), range 0..31 */
+    uint  weighted_pred_flag;                           /* u(1) */
+    uint  weighted_bipred_idc;                          /* u(2), range 0..2 */
+    int   pic_init_qp_minus26;                       /* se(v), range -26..25 */
+    int   pic_init_qs_minus26;                       /* se(v), range -26..25 */
+    int   chroma_qp_index_offset;                    /* se(v), range -12..12 */
+    uint  deblocking_filter_control_present_flag;       /* u(1) */
+    uint  constrained_intra_pred_flag;                  /* u(1) */
+    uint  redundant_pic_cnt_present_flag;               /* u(1) */
+} AVCPicParamSet;
+
+
+/**
+This structure contains slice header information.
+Some variables may be removed from the structure if they are found to be useless to store.
+@publishedAll
+*/
+typedef struct tagSliceHeader
+{
+    uint    first_mb_in_slice;      /* ue(v) */
+    AVCSliceType slice_type;                /* ue(v), Table 7-3, range 0..9 */
+    uint    pic_parameter_set_id;   /* ue(v), range 0..255 */
+    uint    frame_num;              /* u(v), see log2max_frame_num_minus4 */
+    /* if( !frame_mbs_only_flag) */
+    uint    field_pic_flag;         /* u(1) */
+    /* if(field_pic_flag) */
+    uint bottom_field_flag; /* u(1) */
+    /* if(nal_unit_type == 5) */
+    uint    idr_pic_id;         /* ue(v), range 0..65535 */
+    /* if(pic_order_cnt_type==0) */
+    uint    pic_order_cnt_lsb;  /* u(v), range 0..MaxPicOrderCntLsb-1 */
+    /* if(pic_order_present_flag && !field_pic_flag) */
+    int32 delta_pic_order_cnt_bottom;   /* se(v) */
+    /* if(pic_order_cnt_type==1 && !delta_pic_order_always_zero_flag) */
+    /* if(pic_order_present_flag && !field_pic_flag) */
+    int32 delta_pic_order_cnt[2];
+    /* if(redundant_pic_cnt_present_flag) */
+    uint redundant_pic_cnt; /* ue(v), range 0..127 */
+    /* if(slice_type == B) */
+    uint direct_spatial_mv_pred_flag; /* u(1) */
+    /* if(slice_type == P || slice_type==SP || slice_type==B) */
+    uint num_ref_idx_active_override_flag;  /* u(1) */
+    /* if(num_ref_idx_active_override_flag) */
+    uint num_ref_idx_l0_active_minus1;  /* ue(v) */
+    /* if(slie_type == B) */
+    uint num_ref_idx_l1_active_minus1;  /* ue(v) */
+
+    /* ref_pic_list_reordering() */
+    uint ref_pic_list_reordering_flag_l0;   /* u(1) */
+    uint reordering_of_pic_nums_idc_l0[MAX_REF_PIC_LIST_REORDERING];   /* ue(v), range 0..3 */
+    uint abs_diff_pic_num_minus1_l0[MAX_REF_PIC_LIST_REORDERING];   /* ue(v) */
+    uint long_term_pic_num_l0[MAX_REF_PIC_LIST_REORDERING];     /* ue(v) */
+    uint ref_pic_list_reordering_flag_l1;   /* u(1) */
+    uint reordering_of_pic_nums_idc_l1[MAX_REF_PIC_LIST_REORDERING];   /* ue(v), range 0..3 */
+    uint abs_diff_pic_num_minus1_l1[MAX_REF_PIC_LIST_REORDERING];   /* ue(v) */
+    uint long_term_pic_num_l1[MAX_REF_PIC_LIST_REORDERING];     /* ue(v) */
+
+    /* end ref_pic_list_reordering() */
+    /* if(nal_ref_idc!=0) */
+    /* dec_ref_pic_marking() */
+    uint    no_output_of_prior_pics_flag;   /* u(1) */
+    uint long_term_reference_flag;      /* u(1) */
+    uint    adaptive_ref_pic_marking_mode_flag; /* u(1) */
+    uint    memory_management_control_operation[MAX_DEC_REF_PIC_MARKING];   /* ue(v), range 0..6 */
+    uint difference_of_pic_nums_minus1[MAX_DEC_REF_PIC_MARKING];    /* ue(v) */
+    uint    long_term_pic_num[MAX_DEC_REF_PIC_MARKING];             /* ue(v) */
+    uint    long_term_frame_idx[MAX_DEC_REF_PIC_MARKING];           /* ue(v) */
+    uint    max_long_term_frame_idx_plus1[MAX_DEC_REF_PIC_MARKING]; /* ue(v) */
+    /* end dec_ref_pic_marking() */
+    /* if(entropy_coding_mode_flag && slice_type!=I && slice_type!=SI) */
+    uint cabac_init_idc;        /* ue(v), range 0..2 */
+    int slice_qp_delta;     /* se(v), range 0..51 */
+    /* if(slice_type==SP || slice_type==SI) */
+    /* if(slice_type==SP) */
+    uint    sp_for_switch_flag; /* u(1) */
+    int slice_qs_delta;     /* se(v) */
+
+    /* if(deblocking_filter_control_present_flag)*/
+    uint disable_deblocking_filter_idc; /* ue(v), range 0..2 */
+    /* if(disable_deblocking_filter_idc!=1) */
+    int slice_alpha_c0_offset_div2; /* se(v), range -6..6, default 0 */
+    int slice_beta_offset_div_2; /* se(v), range -6..6, default 0 */
+    /* if(num_slice_groups_minus1>0 && slice_group_map_type>=3 && slice_group_map_type<=5)*/
+    uint    slice_group_change_cycle;   /* u(v), use ceil(log2(PicSizeInMapUnits/SliceGroupChangeRate + 1)) bits*/
+
+} AVCSliceHeader;
+
+/**
+This struct contains information about the neighboring pixel.
+@publishedAll
+*/
+typedef struct tagPixPos
+{
+    int available;
+    int mb_addr;    /* macroblock address of the current pixel, see below */
+    int x;      /* x,y positions of current pixel relative to the macroblock mb_addr */
+    int y;
+    int pos_x;  /* x,y positions of current pixel relative to the picture. */
+    int pos_y;
+} AVCPixelPos;
+
+typedef struct tagNeighborAvailability
+{
+    int left;
+    int top;    /* macroblock address of the current pixel, see below */
+    int top_right;      /* x,y positions of current pixel relative to the macroblock mb_addr */
+} AVCNeighborAvailability;
+
+
+/**
+This structure contains picture data and related information necessary to be used as
+reference frame.
+@publishedAll
+*/
+typedef struct tagPictureData
+{
+    uint16 RefIdx;  /* index used for reference frame */
+    uint8 *Sl;   /* derived from base_dpb in AVCFrameStore */
+    uint8 *Scb;  /* for complementary fields, YUV are interlaced */
+    uint8 *Scr;  /* Sl of top_field and bottom_fields will be one line apart and the
+                    stride will be 2 times the width. */
+    /* For non-complementary field, the above still applies. A special
+       output formatting is required. */
+
+    /* Then, necessary variables that need to be stored */
+    AVCPictureType  picType; /* frame, top-field or bot-field */
+    /*bool*/
+    uint    isReference;
+    /*bool*/
+    uint    isLongTerm;
+    int     PicOrderCnt;
+    int     PicNum;
+    int     LongTermPicNum;
+
+    int     width; /* how many pixel per line */
+    int     height;/* how many line */
+    int     pitch; /* how many pixel between the line */
+
+    uint    padded; /* flag for being padded */
+
+} AVCPictureData;
+
+/**
+This structure contains information for frame storage.
+@publishedAll
+*/
+typedef struct tagFrameStore
+{
+    uint8 *base_dpb;    /* base pointer for the YCbCr */
+
+    int     IsReference; /*  0=not used for ref; 1=top used; 2=bottom used; 3=both fields (or frame) used */
+    int     IsLongTerm;  /*  0=not used for ref; 1=top used; 2=bottom used; 3=both fields (or frame) used */
+    /* if IsLongTerm is true, IsReference can be ignored. */
+    /* if IsReference is true, IsLongterm will be checked for short-term or long-term. */
+    /* IsUsed must be true to enable the validity of IsReference and IsLongTerm */
+
+    int     IsOutputted;  /* has it been outputted via AVCDecGetOutput API, then don't output it again,
+                            wait until it is returned. */
+    AVCPictureData frame;
+
+    int     FrameNum;
+    int     FrameNumWrap;
+    int     LongTermFrameIdx;
+    int     PicOrderCnt; /* of the frame, smaller of the 2 fields */
+
+} AVCFrameStore;
+
+/**
+This structure maintains the actual memory for the decoded picture buffer (DPB) which is
+allocated at the beginning according to profile/level.
+Once decoded_picture_buffer is allocated, Sl,Scb,Scr in
+AVCPictureData structure just point to the address in decoded_picture_buffer.
+used_size maintains the used space.
+NOTE:: In order to maintain contiguous memory space, memory equal to a single frame is
+assigned at a time. Two opposite fields reside in the same frame memory.
+
+  |-------|---|---|---|xxx|-------|xxx|---|-------|   decoded_picture_buffer
+    frame  top bot top      frame      bot  frame
+      0     1   1   2         3         4     5
+
+  bot 2 and top 4 do not exist, the memory is not used.
+
+@publishedAll
+*/
+typedef struct tagDecPicBuffer
+{
+    uint8 *decoded_picture_buffer;  /* actual memory */
+    uint32  dpb_size;       /* size of dpb in bytes */
+    uint32  used_size;  /* used size */
+    struct tagFrameStore    *fs[MAX_FS]; /* list of frame stored, actual buffer */
+    int     num_fs;  /* size of fs */
+
+} AVCDecPicBuffer;
+
+
+/**
+This structure contains macroblock related variables.
+@publishedAll
+*/
+typedef struct tagMacroblock
+{
+    AVCIntraChromaPredMode  intra_chroma_pred_mode;  /* ue(v) */
+
+    int32 mvL0[16];  /* motion vectors, 16 bit packed (x,y) per element  */
+    int32 mvL1[16];
+    int16 ref_idx_L0[4];
+    int16 ref_idx_L1[4];
+    uint16 RefIdx[4]; /* ref index, has value of AVCPictureData->RefIdx */
+    /* stored data */
+    /*bool*/
+    uint    mb_intra; /* intra flag */
+    /*bool*/
+    uint    mb_bottom_field;
+
+    AVCMBMode mbMode;   /* type of MB prediction */
+    AVCSubMBMode subMbMode[4]; /* for each 8x8 partition */
+
+    uint    CBP; /* CodeBlockPattern */
+    AVCIntra16x16PredMode i16Mode; /* Intra16x16PredMode */
+    AVCIntra4x4PredMode i4Mode[16]; /* Intra4x4PredMode, in raster scan order */
+    int NumMbPart; /* number of partition */
+    AVCPredMode MBPartPredMode[4][4]; /* prediction mode [MBPartIndx][subMBPartIndx] */
+    int MbPartWidth;
+    int MbPartHeight;
+    int NumSubMbPart[4];  /* for each 8x8 partition */
+    int SubMbPartWidth[4];  /* for each 8x8 partition */
+    int SubMbPartHeight[4]; /* for each 8x8 partition */
+
+    uint8 nz_coeff[NUM_BLKS_IN_MB];  /* [blk_y][blk_x], Chroma is [4..5][0...3], see predict_nnz() function */
+
+    int QPy; /* Luma QP */
+    int QPc; /* Chroma QP */
+    int QSc; /* Chroma QP S-picture */
+
+    int slice_id;           // MC slice
+} AVCMacroblock;
+
+
+/**
+This structure contains common internal variables between the encoder and decoder
+such that some functions can be shared among them.
+@publishedAll
+*/
+typedef struct tagCommonObj
+{
+    /* put these 2 up here to make sure they are word-aligned */
+    int16   block[NUM_PIXELS_IN_MB]; /* for transformed residue coefficient */
+    uint8   *pred_block;    /* pointer to prediction block, could point to a frame */
+#ifdef USE_PRED_BLOCK
+    uint8   pred[688];  /* for prediction */
+    /* Luma [0-399], Cb [400-543], Cr[544-687] */
+#endif
+    int     pred_pitch; /* either equal to 20 or to frame pitch */
+
+    /* temporary buffers for intra prediction */
+    /* these variables should remain inside fast RAM */
+#ifdef MB_BASED_DEBLOCK
+    uint8   *intra_pred_top; /* a row of pixel for intra prediction */
+    uint8   intra_pred_left[17]; /* a column of pixel for intra prediction */
+    uint8   *intra_pred_top_cb;
+    uint8   intra_pred_left_cb[9];
+    uint8   *intra_pred_top_cr;
+    uint8   intra_pred_left_cr[9];
+#endif
+    /* pointer to the prediction area for intra prediction */
+    uint8   *pintra_pred_top;   /* pointer to the top intra prediction value */
+    uint8   *pintra_pred_left;  /* pointer to the left intra prediction value */
+    uint8   intra_pred_topleft; /* the [-1,-1] neighboring pixel */
+    uint8   *pintra_pred_top_cb;
+    uint8   *pintra_pred_left_cb;
+    uint8   intra_pred_topleft_cb;
+    uint8   *pintra_pred_top_cr;
+    uint8   *pintra_pred_left_cr;
+    uint8   intra_pred_topleft_cr;
+
+    int QPy;
+    int QPc;
+    int QPy_div_6;
+    int QPy_mod_6;
+    int QPc_div_6;
+    int QPc_mod_6;
+    /**** nal_unit ******/
+    /* previously in AVCNALUnit format */
+    uint    NumBytesInRBSP;
+    int     forbidden_bit;
+    int     nal_ref_idc;
+    AVCNalUnitType  nal_unit_type;
+    AVCNalUnitType  prev_nal_unit_type;
+    /*bool*/
+    uint    slice_data_partitioning; /* flag when nal_unit_type is between 2 and 4 */
+    /**** ******** ******/
+    AVCSliceType slice_type;
+    AVCDecPicBuffer     *decPicBuf; /* decoded picture buffer */
+
+    AVCSeqParamSet *currSeqParams; /*  the currently used one */
+
+    AVCPicParamSet  *currPicParams; /* the currently used one */
+    uint        seq_parameter_set_id;
+    /* slice header */
+    AVCSliceHeader *sliceHdr;   /* slice header param syntax variables */
+
+    AVCPictureData  *currPic; /* pointer to current picture */
+    AVCFrameStore   *currFS;  /* pointer to current frame store */
+    AVCPictureType  currPicType; /* frame, top-field or bot-field */
+    /*bool*/
+    uint    newPic; /* flag for new picture */
+    uint            newSlice; /* flag for new slice */
+    AVCPictureData  *prevRefPic; /* pointer to previous picture */
+
+    AVCMacroblock   *mblock; /* array of macroblocks covering entire picture */
+    AVCMacroblock   *currMB; /* pointer to current macroblock */
+    uint                    mbNum; /* number of current MB */
+    int                 mb_x;  /* x-coordinate of the current mbNum */
+    int                 mb_y;  /* y-coordinate of the current mbNum */
+
+    /* For internal operation, scratch memory for MV, prediction, transform, etc.*/
+    uint32 cbp4x4; /* each bit represent nonzero 4x4 block in reverse raster scan order */
+    /* starting from luma, Cb and Cr, lsb toward msb */
+    int mvd_l0[4][4][2]; /* [mbPartIdx][subMbPartIdx][compIdx], se(v) */
+    int mvd_l1[4][4][2]; /* [mbPartIdx][subMbPartIdx][compIdx], se(v) */
+
+    int mbAddrA, mbAddrB, mbAddrC, mbAddrD; /* address of neighboring MBs */
+    /*bool*/
+    uint    mbAvailA, mbAvailB, mbAvailC, mbAvailD; /* availability */
+    /*bool*/
+    uint    intraAvailA, intraAvailB, intraAvailC, intraAvailD; /* for intra mode */
+    /***********************************************/
+    /* The following variables are defined in the draft. */
+    /* They may need to be stored in PictureData structure and used for reference. */
+    /* In that case, just move or copy it to AVCDecPictureData structure. */
+
+    int     padded_size;    /* size of extra padding to a frame */
+
+    uint    MaxFrameNum;    /*2^(log2_max_frame_num_minus4+4), range 0.. 2^16-1 */
+    uint    MaxPicOrderCntLsb; /*2^(log2_max_pic_order_cnt_lsb_minus4+4), 0..2^16-1 */
+    uint    PicWidthInMbs;  /*pic_width_in_mbs_minus1+1 */
+    uint    PicWidthInSamplesL; /* PicWidthInMbs*16 */
+    uint    PicWidthInSamplesC; /* PicWIdthInMbs*8 */
+    uint    PicHeightInMapUnits; /* pic_height_in_map_units_minus1+1 */
+    uint    PicSizeInMapUnits;  /* PicWidthInMbs*PicHeightInMapUnits */
+    uint    FrameHeightInMbs;   /*(2-frame_mbs_only_flag)*PicHeightInMapUnits */
+
+    uint    SliceGroupChangeRate; /* slice_group_change_rate_minus1 + 1 */
+
+    /* access unit */
+    uint    primary_pic_type;   /* u(3), Table 7-2, kinda informative only */
+
+    /* slice data partition */
+    uint    slice_id;           /* ue(v) */
+
+    uint    UnusedShortTermFrameNum;
+    uint    PrevRefFrameNum;
+    uint    MbaffFrameFlag; /* (mb_adaptive_frame_field_flag && !field_pic_flag) */
+    uint    PicHeightInMbs; /* FrameHeightInMbs/(1+field_pic_flag) */
+    int     PicHeightInSamplesL; /* PicHeightInMbs*16 */
+    int     PicHeightInSamplesC; /* PicHeightInMbs*8 */
+    uint    PicSizeInMbs;   /* PicWidthInMbs*PicHeightInMbs */
+    uint    level_idc;
+    int     numMBs;
+    uint    MaxPicNum;
+    uint    CurrPicNum;
+    int     QSy;    /* 26+pic_init_qp_minus26+slice_qs_delta */
+    int     FilterOffsetA;
+    int     FilterOffsetB;
+    uint    MapUnitsInSliceGroup0;  /* Min(slie_group_change_cycle*SliceGroupChangeRate,PicSizeInMapUnits) */
+    /* dec_ref_pic_marking */
+    int     MaxLongTermFrameIdx;
+    int     LongTermFrameIdx;
+
+    /* POC related variables */
+    /*bool*/
+    uint    mem_mgr_ctrl_eq_5;  /* if memory_management_control_operation equal to 5 flag */
+    int     PicOrderCnt;
+    int     BottomFieldOrderCnt, TopFieldOrderCnt;
+    /* POC mode 0 */
+    int     prevPicOrderCntMsb;
+    uint    prevPicOrderCntLsb;
+    int     PicOrderCntMsb;
+    /* POC mode 1 */
+    int     prevFrameNumOffset, FrameNumOffset;
+    uint    prevFrameNum;
+    int     absFrameNum;
+    int     picOrderCntCycleCnt, frameNumInPicOrderCntCycle;
+    int     expectedDeltaPerPicOrderCntCycle;
+    int     expectedPicOrderCnt;
+
+    /* FMO */
+    int *MbToSliceGroupMap;  /* to be re-calculate at the beginning */
+
+    /* ref pic list */
+    AVCPictureData  *RefPicList0[MAX_REF_PIC_LIST]; /* list 0 */
+    AVCPictureData  *RefPicList1[MAX_REF_PIC_LIST]; /* list 1 */
+    AVCFrameStore   *refFrameList0ShortTerm[32];
+    AVCFrameStore   *refFrameList1ShortTerm[32];
+    AVCFrameStore   *refFrameListLongTerm[32];
+    int     refList0Size;
+    int     refList1Size;
+
+    /* slice data semantics*/
+    int mb_skip_run;    /* ue(v) */
+    /*uint  mb_skip_flag;*/ /* ae(v) */
+    /* uint end_of_slice_flag;*//* ae(v) */
+    /***********************************************/
+
+    /* function pointers */
+    int (*is_short_ref)(AVCPictureData *s);
+    int (*is_long_ref)(AVCPictureData *s);
+
+} AVCCommonObj;
+
+/**
+Commonly used constant arrays.
+@publishedAll
+*/
+/**
+Zigzag scan from 1-D to 2-D. */
+const static uint8 ZZ_SCAN[16] = {0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15};
+/* Zigzag scan from 1-D to 2-D output to block[24][16]. */
+const static uint8 ZZ_SCAN_BLOCK[16] = {0, 1, 16, 32, 17, 2, 3, 18, 33, 48, 49, 34, 19, 35, 50, 51};
+
+/**
+From zigzag to raster for luma DC value */
+const static uint8 ZIGZAG2RASTERDC[16] = {0, 4, 64, 128, 68, 8, 12, 72, 132, 192, 196, 136, 76, 140, 200, 204};
+
+
+/**
+Mapping from coding scan block indx to raster scan block index */
+const static int blkIdx2blkX[16] = {0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3};
+const static int blkIdx2blkY[16] = {0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3};
+/** from [blk8indx][blk4indx] to raster scan index */
+const static int blkIdx2blkXY[4][4] = {{0, 1, 4, 5}, {2, 3, 6, 7}, {8, 9, 12, 13}, {10, 11, 14, 15}};
+
+/*
+Availability of the neighboring top-right block relative to the current block. */
+const static int BlkTopRight[16] = {2, 2, 2, 3, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0};
+
+/**
+Table 8-13 Specification of QPc as a function of qPI. */
+const static uint8 mapQPi2QPc[52] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
+                                     21, 22, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36,
+                                     37, 37, 37, 38, 38, 38, 39, 39, 39, 39
+                                    };
+
+/**
+See 8.5.5 equation (8-252 and 8-253) the definition of v matrix. */
+/* in zigzag scan */
+const static int dequant_coefres[6][16] =
+{
+    {10, 13, 13, 10, 16, 10, 13, 13, 13, 13, 16, 10, 16, 13, 13, 16},
+    {11, 14, 14, 11, 18, 11, 14, 14, 14, 14, 18, 11, 18, 14, 14, 18},
+    {13, 16, 16, 13, 20, 13, 16, 16, 16, 16, 20, 13, 20, 16, 16, 20},
+    {14, 18, 18, 14, 23, 14, 18, 18, 18, 18, 23, 14, 23, 18, 18, 23},
+    {16, 20, 20, 16, 25, 16, 20, 20, 20, 20, 25, 16, 25, 20, 20, 25},
+    {18, 23, 23, 18, 29, 18, 23, 23, 23, 23, 29, 18, 29, 23, 23, 29}
+};
+
+/**
+From jm7.6 block.c. (in zigzag scan) */
+const static int quant_coef[6][16] =
+{
+    {13107, 8066,   8066,   13107,  5243,   13107,  8066,   8066,   8066,   8066,   5243,   13107,  5243,   8066,   8066,   5243},
+    {11916, 7490,   7490,   11916,  4660,   11916,  7490,   7490,   7490,   7490,   4660,   11916,  4660,   7490,   7490,   4660},
+    {10082, 6554,   6554,   10082,  4194,   10082,  6554,   6554,   6554,   6554,   4194,   10082,  4194,   6554,   6554,   4194},
+    {9362,  5825,   5825,   9362,   3647,   9362,   5825,   5825,   5825,   5825,   3647,   9362,   3647,   5825,   5825,   3647},
+    {8192,  5243,   5243,   8192,   3355,   8192,   5243,   5243,   5243,   5243,   3355,   8192,   3355,   5243,   5243,   3355},
+    {7282,  4559,   4559,   7282,   2893,   7282,   4559,   4559,   4559,   4559,   2893,   7282,   2893,   4559,   4559,   2893}
+};
+
+/**
+Convert scan from raster scan order to block decoding order and
+from block decoding order to raster scan order. Same table!!!
+*/
+const static uint8 ras2dec[16] = {0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15};
+
+/* mapping from level_idc to index map */
+const static uint8 mapLev2Idx[61] = {255, 255, 255, 255, 255, 255, 255, 255, 255, 1,
+                                     0, 1, 2, 3, 255, 255, 255, 255, 255, 255,
+                                     4, 5, 6, 255, 255, 255, 255, 255, 255, 255,
+                                     7, 8, 9, 255, 255, 255, 255, 255, 255, 255,
+                                     10, 11, 12, 255, 255, 255, 255, 255, 255, 255,
+                                     13, 14, 255, 255, 255, 255, 255, 255, 255, 255
+                                    };
+/* map back from index to Level IDC */
+const static uint8 mapIdx2Lev[MAX_LEVEL_IDX] = {10, 11, 12, 13, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51};
+
+/**
+from the index map to the MaxDPB value times 2 */
+const static int32 MaxDPBX2[MAX_LEVEL_IDX] = {297, 675, 1782, 1782, 1782, 3564, 6075, 6075,
+        13500, 15360, 24576, 24576, 24576, 82620, 138240
+                                             };
+
+/* map index to the max frame size */
+const static int MaxFS[MAX_LEVEL_IDX] = {99, 396, 396, 396, 396, 792, 1620, 1620, 3600, 5120,
+                                        8192, 8192, 8192, 22080, 36864
+                                        };
+
+/* map index to max MB processing rate */
+const static int32 MaxMBPS[MAX_LEVEL_IDX] = {1485, 3000, 6000, 11880, 11880, 19800, 20250, 40500,
+        108000, 216000, 245760, 245760, 491520, 589824, 983040
+                                            };
+
+/* map index to max video bit rate */
+const static uint32 MaxBR[MAX_LEVEL_IDX] = {64, 192, 384, 768, 2000, 4000, 4000, 10000, 14000, 20000,
+        20000, 50000, 50000, 135000, 240000
+                                           };
+
+/* map index to max CPB size */
+const static uint32 MaxCPB[MAX_LEVEL_IDX] = {175, 500, 1000, 2000, 2000, 4000, 4000, 10000, 14000,
+        20000, 25000, 62500, 62500, 135000, 240000
+                                            };
+
+/* map index to max vertical MV range */
+const static int MaxVmvR[MAX_LEVEL_IDX] = {64, 128, 128, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512, 512, 512};
+
+#endif /*  _AVCINT_COMMON_H_ */
diff --git a/media/libstagefright/codecs/avc/common/include/avclib_common.h b/media/libstagefright/codecs/avc/common/include/avclib_common.h
new file mode 100644
index 0000000..cbbf0c6
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/include/avclib_common.h
@@ -0,0 +1,557 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains declarations of internal functions for common encoder/decoder library.
+@publishedAll
+*/
+#ifndef AVCCOMMON_LIB_H_INCLUDED
+#define AVCCOMMON_LIB_H_INCLUDED
+
+#include <stdlib.h>
+
+#ifndef AVCINT_COMMON_H_INCLUDED
+#include "avcint_common.h"
+#endif
+
+/*----------- deblock.c --------------*/
+/**
+This function performs conditional deblocking on a complete picture.
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS for success and AVC_FAIL otherwise."
+*/
+OSCL_IMPORT_REF AVCStatus DeblockPicture(AVCCommonObj *video);
+
+/**
+This function performs MB-based deblocking when MB_BASED_DEBLOCK
+is defined at compile time.
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS for success and AVC_FAIL otherwise."
+*/
+void MBInLoopDeblock(AVCCommonObj *video);
+
+
+/*---------- dpb.c --------------------*/
+/**
+This function is called everytime a new sequence is detected.
+\param "avcHandle"  "Pointer to AVCHandle."
+\param "video" "Pointer to AVCCommonObj."
+\param "padding"    "Flag specifying whether padding in luma component is needed (used for encoding)."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+OSCL_IMPORT_REF AVCStatus AVCConfigureSequence(AVCHandle *avcHandle, AVCCommonObj *video, bool padding);
+
+/**
+This function allocates and initializes the decoded picture buffer structure based on
+the profile and level for the first sequence parameter set. Currently,
+it does not allow changing in profile/level for subsequent SPS.
+\param "avcHandle"  "Pointer to AVCHandle."
+\param "video" "Pointer to AVCCommonObj."
+\param "FrameHeightInMbs"   "Height of the frame in the unit of MBs."
+\param "PicWidthInMbs"  "Width of the picture in the unit of MBs."
+\param "padding"    "Flag specifying whether padding in luma component is needed (used for encoding)."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+AVCStatus InitDPB(AVCHandle *avcHandle, AVCCommonObj *video, int FrameHeightInMbs, int PicWidthInMbs, bool padding);
+
+/**
+This function frees the DPB memory.
+\param "avcHandle"  "Pointer to AVCHandle."
+\param "video" "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+OSCL_IMPORT_REF AVCStatus CleanUpDPB(AVCHandle *avcHandle, AVCCommonObj *video);
+
+/**
+This function finds empty frame in the decoded picture buffer to be used for the
+current picture, initializes the corresponding picture structure with Sl, Scb, Scr,
+width, height and pitch.
+\param "avcHandle" "Pointer to the main handle object."
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+OSCL_IMPORT_REF AVCStatus DPBInitBuffer(AVCHandle *avcHandle, AVCCommonObj *video);
+/**
+This function finds empty frame in the decoded picture buffer to be used for the
+current picture, initializes the corresponding picture structure with Sl, Scb, Scr,
+width, height and pitch.
+\param "video"  "Pointer to AVCCommonObj."
+\param "CurrPicNum" "Current picture number (only used in decoder)."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+
+OSCL_IMPORT_REF void DPBInitPic(AVCCommonObj *video, int CurrPicNum);
+
+/**
+This function releases the current frame back to the available pool for skipped frame after encoding.
+\param "avcHandle" "Pointer to the main handle object."
+\param "video" "Pointer to the AVCCommonObj."
+\return "void."
+*/
+OSCL_IMPORT_REF void DPBReleaseCurrentFrame(AVCHandle *avcHandle, AVCCommonObj *video);
+
+/**
+This function performs decoded reference picture marking process and store the current picture to the
+corresponding frame storage in the decoded picture buffer.
+\param "avcHandle" "Pointer to the main handle object."
+\param "video" "Pointer to the AVCCommonObj."
+\return "AVC_SUCCESS or AVC_FAIL."
+*/
+OSCL_IMPORT_REF AVCStatus StorePictureInDPB(AVCHandle *avcHandle, AVCCommonObj *video);
+
+/**
+This function perform sliding window operation on the reference picture lists, see subclause 8.2.5.3.
+It removes short-term ref frames with smallest FrameNumWrap from the reference list.
+\param "avcHandle" "Pointer to the main handle object."
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\return "AVC_SUCCESS or AVC_FAIL (contradicting values or scenario as in the Note in the draft)."
+*/
+AVCStatus sliding_window_process(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb);
+
+
+/**
+This function perform adaptive memory marking operation on the reference picture lists,
+see subclause 8.2.5.4. It calls other functions for specific operations.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "sliceHdr"   "Pointer to the AVCSliceHeader."
+\return "AVC_SUCCESS or AVC_FAIL (contradicting values or scenario as in the Note in the draft)."
+*/
+AVCStatus adaptive_memory_marking(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, AVCSliceHeader *sliceHdr);
+
+/**
+This function performs memory management control operation 1, marking a short-term picture
+as unused for reference. See subclause 8.2.5.4.1.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "difference_of_pic_nums_minus1"  "From the syntax in dec_ref_pic_marking()."
+*/
+void MemMgrCtrlOp1(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, int difference_of_pic_nums_minus1);
+
+/**
+This function performs memory management control operation 2, marking a long-term picture
+as unused for reference. See subclause 8.2.5.4.2.
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "field_pic_flag"  "Flag whether the current picture is field or not."
+\param "long_term_pic_num"  "From the syntax in dec_ref_pic_marking()."
+*/
+void MemMgrCtrlOp2(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, int long_term_pic_num);
+
+/**
+This function performs memory management control operation 3, assigning a LongTermFrameIdx to
+a short-term reference picture. See subclause 8.2.5.4.3.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "difference_of_pic_nums_minus1"  "From the syntax in dec_ref_pic_marking()."
+\param "long_term_pic_num"  "From the syntax in dec_ref_pic_marking()."
+*/
+void MemMgrCtrlOp3(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint difference_of_pic_nums_minus1,
+                   uint long_term_frame_idx);
+
+/**
+This function performs memory management control operation 4, getting new MaxLongTermFrameIdx.
+ See subclause 8.2.5.4.4.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "max_long_term_frame_idx_plus1"  "From the syntax in dec_ref_pic_marking()."
+*/
+void MemMgrCtrlOp4(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint max_long_term_frame_idx_plus1);
+
+/**
+This function performs memory management control operation 5, marking all reference pictures
+as unused for reference and set MaxLongTermFrameIdx to no long-termframe indices.
+ See subclause 8.2.5.4.5.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+*/
+void MemMgrCtrlOp5(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb);
+
+/**
+This function performs memory management control operation 6, assigning a long-term frame index
+to the current picture. See subclause 8.2.5.4.6.
+\param "video" "Pointer to the AVCCommonObj."
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "long_term_frame_idx"  "From the syntax in dec_ref_pic_marking()."
+*/
+void MemMgrCtrlOp6(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint long_term_frame_idx);
+
+/**
+This function mark a long-term ref frame with a specific frame index as unused for reference.
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "long_term_frame_idx"  "To look for"
+*/
+void unmark_long_term_frame_for_reference_by_frame_idx(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, uint long_term_frame_idx);
+
+/**
+This function mark a long-term ref field with a specific frame index as unused for reference except
+a frame that contains a picture with picNumX.
+\param "dpb"  "Pointer to the AVCDecPicBuffer."
+\param "long_term_frame_idx"  "To look for."
+\param "picNumX"    "To look for."
+*/
+void unmark_long_term_field_for_reference_by_frame_idx(AVCCommonObj *video, AVCDecPicBuffer *dpb, uint long_term_frame_indx, int picNumX);
+
+/**
+This function mark a frame to unused for reference.
+\param "fs" "Pointer to AVCFrameStore to be unmarked."
+*/
+void unmark_for_reference(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, uint idx);
+
+void update_ref_list(AVCDecPicBuffer *dpb);
+
+
+/*---------- fmo.c --------------*/
+/**
+This function initializes flexible macroblock reordering.
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS for success and AVC_FAIL otherwise."
+*/
+OSCL_IMPORT_REF AVCStatus FMOInit(AVCCommonObj *video);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following the interleaved slice group map type.
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "run_length_minus1"  "Array of the run-length."
+\param "num_slice_groups_minus_1"   "Number of slice group minus 1."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "Void."
+*/
+void FmoGenerateType0MapUnitMap(int *mapUnitToSliceGroupMap, uint *run_length_minus1, uint num_slice_groups_minus1, uint PicSizeInMapUnits);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following the dispersed slice group map type.
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "PicWidthInMbs"  "Width of the luma picture in macroblock unit."
+\param "num_slice_groups_minus_1"   "Number of slice group minus 1."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "Void."
+*/
+void FmoGenerateType1MapUnitMap(int *mapUnitToSliceGroupMap, int PicWidthInMbs, uint num_slice_groups_minus1, uint PicSizeInMapUnits);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following the foreground with left-over slice group map type.
+\param "pps"    "Pointer to AVCPicParamSets structure."
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "PicWidthInMbs"  "Width of the luma picture in macroblock unit."
+\param "num_slice_groups_minus_1"   "Number of slice group minus 1."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "Void."
+*/
+void FmoGenerateType2MapUnitMap(AVCPicParamSet *pps, int *mapUnitToSliceGroupMap, int PicWidthInMbs,
+                                uint num_slice_groups_minus1, uint PicSizeInMapUnits);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following the box-out slice group map type.
+\param "pps"    "Pointer to AVCPicParamSets structure."
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "PicWidthInMbs"  "Width of the luma picture in macroblock unit."
+\return "Void."
+*/
+void FmoGenerateType3MapUnitMap(AVCCommonObj *video, AVCPicParamSet* pps, int *mapUnitToSliceGroupMap,
+                                int PicWidthInMbs);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following the raster scan slice group map type.
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "MapUnitsInSliceGroup0"  "Derived in subclause 7.4.3."
+\param "slice_group_change_direction_flag"  "A value from the slice header."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "void"
+*/
+void FmoGenerateType4MapUnitMap(int *mapUnitToSliceGroupMap, int MapUnitsInSliceGroup0,
+                                int slice_group_change_direction_flag, uint PicSizeInMapUnits);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following wipe slice group map type.
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "video"  "Pointer to AVCCommonObj structure."
+\param "slice_group_change_direction_flag"  "A value from the slice header."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "void"
+*/
+void FmoGenerateType5MapUnitMap(int *mapUnitsToSliceGroupMap, AVCCommonObj *video,
+                                int slice_group_change_direction_flag, uint PicSizeInMapUnits);
+
+/**
+This function fills up an array that maps Map unit to the slice group
+following wipe slice group map type.
+\param "mapUnitToSliceGroupMap" "Array of slice group mapping."
+\param "slice_group_id" "Array of slice_group_id from AVCPicParamSet structure."
+\param "PicSizeInMapUnit"   "Size of the picture in number Map units."
+\return "void"
+*/
+void FmoGenerateType6MapUnitMap(int *mapUnitsToSliceGroupMap, int *slice_group_id, uint PicSizeInMapUnits);
+
+/*------------- itrans.c --------------*/
+/**
+This function performs transformation of the Intra16x16DC value according to
+subclause 8.5.6.
+\param "block"  "Pointer to the video->block[0][0][0]."
+\param "QPy"    "Quantization parameter."
+\return "void."
+*/
+void Intra16DCTrans(int16 *block, int Qq, int Rq);
+
+/**
+This function performs transformation of a 4x4 block according to
+subclause 8.5.8.
+\param "block"  "Pointer to the origin of transform coefficient area."
+\param "pred"   "Pointer to the origin of predicted area."
+\param "cur"    "Pointer to the origin of the output area."
+\param "width"  "Pitch of cur."
+\return "void."
+*/
+void itrans(int16 *block, uint8 *pred, uint8 *cur, int width);
+
+/*
+This function is the same one as itrans except for chroma.
+\param "block"  "Pointer to the origin of transform coefficient area."
+\param "pred"   "Pointer to the origin of predicted area."
+\param "cur"    "Pointer to the origin of the output area."
+\param "width"  "Pitch of cur."
+\return "void."
+*/
+void ictrans(int16 *block, uint8 *pred, uint8 *cur, int width);
+
+/**
+This function performs transformation of the DCChroma value according to
+subclause 8.5.7.
+\param "block"  "Pointer to the video->block[0][0][0]."
+\param "QPc"    "Quantization parameter."
+\return "void."
+*/
+void ChromaDCTrans(int16 *block, int Qq, int Rq);
+
+/**
+This function copies a block from pred to cur.
+\param "pred"   "Pointer to prediction block."
+\param "cur"    "Pointer to the current YUV block."
+\param "width"  "Pitch of cur memory."
+\param "pred_pitch" "Pitch for pred memory.
+\return "void."
+*/
+void copy_block(uint8 *pred, uint8 *cur, int width, int pred_pitch);
+
+/*--------- mb_access.c ----------------*/
+/**
+This function initializes the neighboring information before start macroblock decoding.
+\param "video"  "Pointer to AVCCommonObj."
+\param "mbNum"  "The current macroblock index."
+\param "currMB" "Pointer to the current AVCMacroblock structure."
+\return "void"
+*/
+OSCL_IMPORT_REF void InitNeighborAvailability(AVCCommonObj *video, int mbNum);
+
+/**
+This function checks whether the requested neighboring macroblock is available.
+\param "MbToSliceGroupMap"  "Array containing the slice group ID mapping to MB index."
+\param "PicSizeInMbs"   "Size of the picture in number of MBs."
+\param "mbAddr"     "Neighboring macroblock index to check."
+\param "currMbAddr" "Current macroblock index."
+\return "TRUE if the neighboring MB is available, FALSE otherwise."
+*/
+bool mb_is_available(AVCMacroblock *mblock, uint PicSizeInMbs, int mbAddr, int currMbAddr);
+
+/**
+This function performs prediction of the nonzero coefficient for a luma block (i,j).
+\param "video"  "Pointer to AVCCommonObj."
+\param "i"  "Block index, horizontal."
+\param "j"  "Block index, vertical."
+\return "Predicted number of nonzero coefficient."
+*/
+OSCL_IMPORT_REF int predict_nnz(AVCCommonObj *video, int i, int j);
+
+/**
+This function performs prediction of the nonzero coefficient for a chroma block (i,j).
+\param "video"  "Pointer to AVCCommonObj."
+\param "i"  "Block index, horizontal."
+\param "j"  "Block index, vertical."
+\return "Predicted number of nonzero coefficient."
+*/
+OSCL_IMPORT_REF int predict_nnz_chroma(AVCCommonObj *video, int i, int j);
+
+/**
+This function calculates the predicted motion vectors for the current macroblock.
+\param "video" "Pointer to AVCCommonObj."
+\param "encFlag"    "Boolean whether this function is used by encoder or decoder."
+\return "void."
+*/
+OSCL_IMPORT_REF void GetMotionVectorPredictor(AVCCommonObj *video, int encFlag);
+
+/*---------- reflist.c -----------------*/
+/**
+This function initializes reference picture list used in INTER prediction
+at the beginning of each slice decoding. See subclause 8.2.4.
+\param "video"  "Pointer to AVCCommonObj."
+\return "void"
+Output is video->RefPicList0, video->RefPicList1, video->refList0Size and video->refList1Size.
+*/
+OSCL_IMPORT_REF void RefListInit(AVCCommonObj *video);
+
+/**
+This function generates picture list from frame list. Used when current picture is field.
+see subclause 8.2.4.2.5.
+\param "video"  "Pointer to AVCCommonObj."
+\param "IsL1"   "Is L1 list?"
+\param "long_term"  "Is long-term prediction?"
+\return "void"
+*/
+void    GenPicListFromFrameList(AVCCommonObj *video, int IsL1, int long_term);
+
+/**
+This function performs reference picture list reordering according to the
+ref_pic_list_reordering() syntax. See subclause 8.2.4.3.
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVC_SUCCESS or AVC_FAIL"
+Output is video->RefPicList0, video->RefPicList1, video->refList0Size and video->refList1Size.
+*/
+OSCL_IMPORT_REF AVCStatus ReOrderList(AVCCommonObj *video);
+
+/**
+This function performs reference picture list reordering according to the
+ref_pic_list_reordering() syntax regardless of list 0 or list 1. See subclause 8.2.4.3.
+\param "video"  "Pointer to AVCCommonObj."
+\param "isL1"   "Is list 1 or not."
+\return "AVC_SUCCESS or AVC_FAIL"
+Output is video->RefPicList0 and video->refList0Size or video->RefPicList1 and video->refList1Size.
+*/
+AVCStatus ReorderRefPicList(AVCCommonObj *video, int isL1);
+
+/**
+This function performs reordering process of reference picture list for short-term pictures.
+See subclause 8.2.4.3.1.
+\param "video"  "Pointer to AVCCommonObj."
+\param "picNumLX"   "picNumLX of an entry in the reference list."
+\param "refIdxLX"   "Pointer to the current entry index in the reference."
+\param "isL1"       "Is list 1 or not."
+\return "AVC_SUCCESS or AVC_FAIL"
+*/
+AVCStatus ReorderShortTerm(AVCCommonObj *video, int picNumLX, int *refIdxLX, int isL1);
+
+/**
+This function performs reordering process of reference picture list for long-term pictures.
+See subclause 8.2.4.3.2.
+\param "video"  "Pointer to AVCCommonObj."
+\param "LongTermPicNum" "LongTermPicNum of an entry in the reference list."
+\param "refIdxLX"   "Pointer to the current entry index in the reference."
+\param "isL1"       "Is list 1 or not."
+\return "AVC_SUCCESS or AVC_FAIL"
+*/
+AVCStatus ReorderLongTerm(AVCCommonObj *video, int LongTermPicNum, int *refIdxLX, int isL1);
+
+/**
+This function gets the pictures in DPB according to the PicNum.
+\param "video"  "Pointer to AVCCommonObj."
+\param "picNum" "PicNum of the picture we are looking for."
+\return "Pointer to the AVCPictureData or NULL if not found"
+*/
+AVCPictureData*  GetShortTermPic(AVCCommonObj *video, int picNum);
+
+/**
+This function gets the pictures in DPB according to the LongtermPicNum.
+\param "video"  "Pointer to AVCCommonObj."
+\param "LongtermPicNum" "LongtermPicNum of the picture we are looking for."
+\return "Pointer to the AVCPictureData."
+*/
+AVCPictureData*  GetLongTermPic(AVCCommonObj *video, int LongtermPicNum);
+
+/**
+This function indicates whether the picture is used for short-term reference or not.
+\param "s"  "Pointer to AVCPictureData."
+\return "1 if it is used for short-term, 0 otherwise."
+*/
+int is_short_ref(AVCPictureData *s);
+
+/**
+This function indicates whether the picture is used for long-term reference or not.
+\param "s"  "Pointer to AVCPictureData."
+\return "1 if it is used for long-term, 0 otherwise."
+*/
+int is_long_ref(AVCPictureData *s);
+
+/**
+This function sorts array of pointers to AVCPictureData in descending order of
+the PicNum value.
+\param "data"   "Array of pointers to AVCPictureData."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortPicByPicNum(AVCPictureData *data[], int num);
+
+/**
+This function sorts array of pointers to AVCPictureData in ascending order of
+the PicNum value.
+\param "data"   "Array of pointers to AVCPictureData."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortPicByPicNumLongTerm(AVCPictureData *data[], int num);
+
+/**
+This function sorts array of pointers to AVCFrameStore in descending order of
+the FrameNumWrap value.
+\param "data"   "Array of pointers to AVCFrameStore."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortFrameByFrameNumWrap(AVCFrameStore *data[], int num);
+
+/**
+This function sorts array of pointers to AVCFrameStore in ascending order of
+the LongTermFrameIdx value.
+\param "data"   "Array of pointers to AVCFrameStore."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortFrameByLTFrameIdx(AVCFrameStore *data[], int num);
+
+/**
+This function sorts array of pointers to AVCPictureData in descending order of
+the PicOrderCnt value.
+\param "data"   "Array of pointers to AVCPictureData."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortPicByPOC(AVCPictureData *data[], int num, int descending);
+
+/**
+This function sorts array of pointers to AVCPictureData in ascending order of
+the LongTermPicNum value.
+\param "data"   "Array of pointers to AVCPictureData."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortPicByLTPicNum(AVCPictureData *data[], int num);
+
+/**
+This function sorts array of pointers to AVCFrameStore in descending order of
+the PicOrderCnt value.
+\param "data"   "Array of pointers to AVCFrameStore."
+\param "num"    "Size of the array."
+\return "void"
+*/
+void SortFrameByPOC(AVCFrameStore *data[], int num, int descending);
+
+
+#endif /* _AVCCOMMON_LIB_H_ */
diff --git a/media/libstagefright/codecs/avc/common/src/deblock.cpp b/media/libstagefright/codecs/avc/common/src/deblock.cpp
new file mode 100644
index 0000000..5ed4c82
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/src/deblock.cpp
@@ -0,0 +1,1666 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#include <string.h>
+
+#include "avclib_common.h"
+
+#define MAX_QP 51
+#define MB_BLOCK_SIZE 16
+
+// NOTE: these 3 tables are for funtion GetStrength() only
+const static int ININT_STRENGTH[4] = {0x04040404, 0x03030303, 0x03030303, 0x03030303};
+
+
+// NOTE: these 3 tables are for funtion EdgeLoop() only
+// NOTE: to change the tables below for instance when the QP doubling is changed from 6 to 8 values
+
+const static int ALPHA_TABLE[52]  = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6,  7, 8, 9, 10, 12, 13, 15, 17,  20, 22, 25, 28, 32, 36, 40, 45,  50, 56, 63, 71, 80, 90, 101, 113,  127, 144, 162, 182, 203, 226, 255, 255} ;
+const static int BETA_TABLE[52]   = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3,  3, 3, 3, 4, 4, 4, 6, 6,   7, 7, 8, 8, 9, 9, 10, 10,  11, 11, 12, 12, 13, 13, 14, 14,   15, 15, 16, 16, 17, 17, 18, 18} ;
+const static int CLIP_TAB[52][5]  =
+{
+    { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0},
+    { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0},
+    { 0, 0, 0, 0, 0}, { 0, 0, 0, 1, 1}, { 0, 0, 0, 1, 1}, { 0, 0, 0, 1, 1}, { 0, 0, 0, 1, 1}, { 0, 0, 1, 1, 1}, { 0, 0, 1, 1, 1}, { 0, 1, 1, 1, 1},
+    { 0, 1, 1, 1, 1}, { 0, 1, 1, 1, 1}, { 0, 1, 1, 1, 1}, { 0, 1, 1, 2, 2}, { 0, 1, 1, 2, 2}, { 0, 1, 1, 2, 2}, { 0, 1, 1, 2, 2}, { 0, 1, 2, 3, 3},
+    { 0, 1, 2, 3, 3}, { 0, 2, 2, 3, 3}, { 0, 2, 2, 4, 4}, { 0, 2, 3, 4, 4}, { 0, 2, 3, 4, 4}, { 0, 3, 3, 5, 5}, { 0, 3, 4, 6, 6}, { 0, 3, 4, 6, 6},
+    { 0, 4, 5, 7, 7}, { 0, 4, 5, 8, 8}, { 0, 4, 6, 9, 9}, { 0, 5, 7, 10, 10}, { 0, 6, 8, 11, 11}, { 0, 6, 8, 13, 13}, { 0, 7, 10, 14, 14}, { 0, 8, 11, 16, 16},
+    { 0, 9, 12, 18, 18}, { 0, 10, 13, 20, 20}, { 0, 11, 15, 23, 23}, { 0, 13, 17, 25, 25}
+};
+
+// NOTE: this table is only QP clipping, index = QP + video->FilterOffsetA/B, clipped to [0, 51]
+//       video->FilterOffsetA/B is in {-12, 12]
+const static int QP_CLIP_TAB[76] =
+{
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,              // [-12, 0]
+    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+    13, 14, 15, 16, 17, 18, 19, 20, 21,
+    22, 23, 24, 25, 26, 27, 28, 29, 30,
+    31, 32, 33, 34, 35, 36, 37, 38, 39,
+    40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // [1, 51]
+    51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51      // [52,63]
+};
+
+static void DeblockMb(AVCCommonObj *video, int mb_x, int mb_y, uint8 *SrcY, uint8 *SrcU, uint8 *SrcV);
+//static void GetStrength(AVCCommonObj *video, uint8 *Strength, AVCMacroblock* MbP, AVCMacroblock* MbQ, int dir, int edge);
+static void GetStrength_Edge0(uint8 *Strength, AVCMacroblock* MbP, AVCMacroblock* MbQ, int dir);
+static void GetStrength_VerticalEdges(uint8 *Strength, AVCMacroblock* MbQ);
+static void GetStrength_HorizontalEdges(uint8 Strength[12], AVCMacroblock* MbQ);
+static void EdgeLoop_Luma_vertical(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch);
+static void EdgeLoop_Luma_horizontal(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch);
+static void EdgeLoop_Chroma_vertical(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch);
+static void EdgeLoop_Chroma_horizontal(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch);
+
+/*
+ *****************************************************************************************
+ * \brief Filter all macroblocks in order of increasing macroblock address.
+ *****************************************************************************************
+*/
+
+OSCL_EXPORT_REF AVCStatus DeblockPicture(AVCCommonObj *video)
+{
+    uint   i, j;
+    int   pitch = video->currPic->pitch, pitch_c, width;
+    uint8 *SrcY, *SrcU, *SrcV;
+
+    SrcY = video->currPic->Sl;      // pointers to source
+    SrcU = video->currPic->Scb;
+    SrcV = video->currPic->Scr;
+    pitch_c = pitch >> 1;
+    width = video->currPic->width;
+
+    for (i = 0; i < video->PicHeightInMbs; i++)
+    {
+        for (j = 0; j < video->PicWidthInMbs; j++)
+        {
+            DeblockMb(video, j, i, SrcY, SrcU, SrcV);
+            // update SrcY, SrcU, SrcV
+            SrcY += MB_BLOCK_SIZE;
+            SrcU += (MB_BLOCK_SIZE >> 1);
+            SrcV += (MB_BLOCK_SIZE >> 1);
+        }
+
+        SrcY += ((pitch << 4) - width);
+        SrcU += ((pitch_c << 3) - (width >> 1));
+        SrcV += ((pitch_c << 3) - (width >> 1));
+    }
+
+    return AVC_SUCCESS;
+}
+
+#ifdef MB_BASED_DEBLOCK
+/*
+ *****************************************************************************************
+ * \brief Filter one macroblocks in a fast macroblock memory and copy it to frame
+ *****************************************************************************************
+*/
+void MBInLoopDeblock(AVCCommonObj *video)
+{
+    AVCPictureData *currPic = video->currPic;
+#ifdef USE_PRED_BLOCK
+    uint8 *predCb, *predCr, *pred_block;
+    int i, j, dst_width, dst_height, dst_widthc, dst_heightc;
+#endif
+    int pitch = currPic->pitch;
+    int x_pos = video->mb_x;
+    int y_pos = video->mb_y;
+    uint8 *curL, *curCb, *curCr;
+    int offset;
+
+    offset = (y_pos << 4) * pitch;
+
+    curL = currPic->Sl + offset + (x_pos << 4);
+
+    offset >>= 2;
+    offset += (x_pos << 3);
+
+    curCb = currPic->Scb + offset;
+    curCr = currPic->Scr + offset;
+
+#ifdef USE_PRED_BLOCK
+    pred_block = video->pred;
+
+    /* 1. copy neighboring pixels from frame to the video->pred_block */
+    if (y_pos) /* not the 0th row */
+    {
+        /* copy to the top 4 lines of the macroblock */
+        curL -= (pitch << 2); /* go back 4 lines */
+
+        memcpy(pred_block + 4, curL, 16);
+        curL += pitch;
+        memcpy(pred_block + 24, curL, 16);
+        curL += pitch;
+        memcpy(pred_block + 44, curL, 16);
+        curL += pitch;
+        memcpy(pred_block + 64, curL, 16);
+        curL += pitch;
+
+        curCb -= (pitch << 1); /* go back 4 lines chroma */
+        curCr -= (pitch << 1);
+
+        pred_block += 400;
+
+        memcpy(pred_block + 4, curCb, 8);
+        curCb += (pitch >> 1);
+        memcpy(pred_block + 16, curCb, 8);
+        curCb += (pitch >> 1);
+        memcpy(pred_block + 28, curCb, 8);
+        curCb += (pitch >> 1);
+        memcpy(pred_block + 40, curCb, 8);
+        curCb += (pitch >> 1);
+
+        pred_block += 144;
+        memcpy(pred_block + 4, curCr, 8);
+        curCr += (pitch >> 1);
+        memcpy(pred_block + 16, curCr, 8);
+        curCr += (pitch >> 1);
+        memcpy(pred_block + 28, curCr, 8);
+        curCr += (pitch >> 1);
+        memcpy(pred_block + 40, curCr, 8);
+        curCr += (pitch >> 1);
+
+        pred_block = video->pred;
+    }
+
+    /* 2. perform deblocking. */
+    DeblockMb(video, x_pos, y_pos, pred_block + 84, pred_block + 452, pred_block + 596);
+
+    /* 3. copy it back to the frame and update pred_block */
+    predCb = pred_block + 400;
+    predCr = predCb + 144;
+
+    /* find the range of the block inside pred_block to be copied back */
+    if (y_pos)  /* the first row */
+    {
+        curL -= (pitch << 2);
+        curCb -= (pitch << 1);
+        curCr -= (pitch << 1);
+
+        dst_height = 20;
+        dst_heightc = 12;
+    }
+    else
+    {
+        pred_block += 80;
+        predCb += 48;
+        predCr += 48;
+        dst_height = 16;
+        dst_heightc = 8;
+    }
+
+    if (x_pos) /* find the width */
+    {
+        curL -= 4;
+        curCb -= 4;
+        curCr -= 4;
+        if (x_pos == (int)(video->PicWidthInMbs - 1))
+        {
+            dst_width = 20;
+            dst_widthc = 12;
+        }
+        else
+        {
+            dst_width = 16;
+            dst_widthc = 8;
+        }
+    }
+    else
+    {
+        pred_block += 4;
+        predCb += 4;
+        predCr += 4;
+        dst_width = 12;
+        dst_widthc = 4;
+    }
+
+    /* perform copy */
+    for (j = 0; j < dst_height; j++)
+    {
+        memcpy(curL, pred_block, dst_width);
+        curL += pitch;
+        pred_block += 20;
+    }
+    for (j = 0; j < dst_heightc; j++)
+    {
+        memcpy(curCb, predCb, dst_widthc);
+        memcpy(curCr, predCr, dst_widthc);
+        curCb += (pitch >> 1);
+        curCr += (pitch >> 1);
+        predCb += 12;
+        predCr += 12;
+    }
+
+    if (x_pos != (int)(video->PicWidthInMbs - 1)) /* now copy from the right-most 4 columns to the left-most 4 columns */
+    {
+        pred_block = video->pred;
+        for (i = 0; i < 20; i += 4)
+        {
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 16));
+            pred_block += 20;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 16));
+            pred_block += 20;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 16));
+            pred_block += 20;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 16));
+            pred_block += 20;
+        }
+
+        for (i = 0; i < 24; i += 4)
+        {
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 8));
+            pred_block += 12;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 8));
+            pred_block += 12;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 8));
+            pred_block += 12;
+            *((uint32*)pred_block) = *((uint32*)(pred_block + 8));
+            pred_block += 12;
+        }
+
+    }
+#else
+    DeblockMb(video, x_pos, y_pos, curL, curCb, curCr);
+#endif
+
+    return ;
+}
+#endif
+
+/*
+ *****************************************************************************************
+ * \brief Deblocking filter for one macroblock.
+ *****************************************************************************************
+ */
+
+void DeblockMb(AVCCommonObj *video, int mb_x, int mb_y, uint8 *SrcY, uint8 *SrcU, uint8 *SrcV)
+{
+    AVCMacroblock *MbP, *MbQ;
+    int     edge, QP, QPC;
+    int     filterLeftMbEdgeFlag = (mb_x != 0);
+    int     filterTopMbEdgeFlag  = (mb_y != 0);
+    int     pitch = video->currPic->pitch;
+    int     indexA, indexB, tmp;
+    int     Alpha, Beta, Alpha_c, Beta_c;
+    int     mbNum = mb_y * video->PicWidthInMbs + mb_x;
+    int     *clipTable, *clipTable_c, *qp_clip_tab;
+    uint8   Strength[16];
+    void*     str;
+
+    MbQ = &(video->mblock[mbNum]);      // current Mb
+
+
+    // If filter is disabled, return
+    if (video->sliceHdr->disable_deblocking_filter_idc == 1) return;
+
+    if (video->sliceHdr->disable_deblocking_filter_idc == 2)
+    {
+        // don't filter at slice boundaries
+        filterLeftMbEdgeFlag = mb_is_available(video->mblock, video->PicSizeInMbs, mbNum - 1, mbNum);
+        filterTopMbEdgeFlag  = mb_is_available(video->mblock, video->PicSizeInMbs, mbNum - video->PicWidthInMbs, mbNum);
+    }
+
+    /* NOTE: edge=0 and edge=1~3 are separate cases because of the difference of MbP, index A and indexB calculation */
+    /*       for edge = 1~3, MbP, indexA and indexB remain the same, and thus there is no need to re-calculate them for each edge */
+
+    qp_clip_tab = (int *)QP_CLIP_TAB + 12;
+
+    /* 1.VERTICAL EDGE + MB BOUNDARY (edge = 0) */
+    if (filterLeftMbEdgeFlag)
+    {
+        MbP = MbQ - 1;
+        //GetStrength(video, Strength, MbP, MbQ, 0, 0); // Strength for 4 blks in 1 stripe, 0 => vertical edge
+        GetStrength_Edge0(Strength, MbP, MbQ, 0);
+
+        str = (void*)Strength; //de-ref type-punned pointer fix
+        if (*((uint32*)str))    // only if one of the 4 Strength bytes is != 0
+        {
+            QP = (MbP->QPy + MbQ->QPy + 1) >> 1; // Average QP of the two blocks;
+            indexA = QP + video->FilterOffsetA;
+            indexB = QP + video->FilterOffsetB;
+            indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+            indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+            Alpha  = ALPHA_TABLE[indexA];
+            Beta = BETA_TABLE[indexB];
+            clipTable = (int *) CLIP_TAB[indexA];
+
+            if (Alpha > 0 && Beta > 0)
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Luma_vertical(SrcY, Strength,  Alpha, Beta, clipTable, 20);
+#else
+                EdgeLoop_Luma_vertical(SrcY, Strength,  Alpha, Beta, clipTable, pitch);
+#endif
+
+            QPC = (MbP->QPc + MbQ->QPc + 1) >> 1;
+            indexA = QPC + video->FilterOffsetA;
+            indexB = QPC + video->FilterOffsetB;
+            indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+            indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+            Alpha  = ALPHA_TABLE[indexA];
+            Beta = BETA_TABLE[indexB];
+            clipTable = (int *) CLIP_TAB[indexA];
+            if (Alpha > 0 && Beta > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Chroma_vertical(SrcU, Strength, Alpha, Beta, clipTable, 12);
+                EdgeLoop_Chroma_vertical(SrcV, Strength, Alpha, Beta, clipTable, 12);
+#else
+                EdgeLoop_Chroma_vertical(SrcU, Strength, Alpha, Beta, clipTable, pitch >> 1);
+                EdgeLoop_Chroma_vertical(SrcV, Strength, Alpha, Beta, clipTable, pitch >> 1);
+#endif
+            }
+        }
+
+    } /* end of: if(filterLeftMbEdgeFlag) */
+
+    /* 2.VERTICAL EDGE (no boundary), the edges are all inside a MB */
+    /* First calculate the necesary parameters all at once, outside the loop */
+    MbP = MbQ;
+
+    indexA = MbQ->QPy + video->FilterOffsetA;
+    indexB = MbQ->QPy + video->FilterOffsetB;
+    //  index
+    indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+    indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+    Alpha = ALPHA_TABLE[indexA];
+    Beta = BETA_TABLE[indexB];
+    clipTable = (int *)CLIP_TAB[indexA];
+
+    /* Save Alpha,  Beta and clipTable for future use, with the obselete variables filterLeftMbEdgeFlag, mbNum amd tmp */
+    filterLeftMbEdgeFlag = Alpha;
+    mbNum = Beta;
+    tmp = (int)clipTable;
+
+    indexA = MbQ->QPc + video->FilterOffsetA;
+    indexB = MbQ->QPc + video->FilterOffsetB;
+    indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+    indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+    Alpha_c  = ALPHA_TABLE[indexA];
+    Beta_c = BETA_TABLE[indexB];
+    clipTable_c = (int *)CLIP_TAB[indexA];
+
+    GetStrength_VerticalEdges(Strength + 4, MbQ); // Strength for 4 blks in 1 stripe, 0 => vertical edge
+
+    for (edge = 1; edge < 4; edge++)  // 4 vertical strips of 16 pel
+    {
+        //GetStrength_VerticalEdges(video, Strength, MbP, MbQ, 0, edge); // Strength for 4 blks in 1 stripe, 0 => vertical edge
+        if (*((int*)(Strength + (edge << 2))))   // only if one of the 4 Strength bytes is != 0
+        {
+            if (Alpha > 0 && Beta > 0)
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Luma_vertical(SrcY + (edge << 2), Strength + (edge << 2),  Alpha, Beta, clipTable, 20);
+#else
+                EdgeLoop_Luma_vertical(SrcY + (edge << 2), Strength + (edge << 2),  Alpha, Beta, clipTable, pitch);
+#endif
+
+            if (!(edge & 1) && Alpha_c > 0 && Beta_c > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Chroma_vertical(SrcU + (edge << 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, 12);
+                EdgeLoop_Chroma_vertical(SrcV + (edge << 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, 12);
+#else
+                EdgeLoop_Chroma_vertical(SrcU + (edge << 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, pitch >> 1);
+                EdgeLoop_Chroma_vertical(SrcV + (edge << 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, pitch >> 1);
+#endif
+            }
+        }
+
+    } //end edge
+
+
+
+    /* 3.HORIZONTAL EDGE + MB BOUNDARY (edge = 0) */
+    if (filterTopMbEdgeFlag)
+    {
+        MbP = MbQ - video->PicWidthInMbs;
+        //GetStrength(video, Strength, MbP, MbQ, 1, 0); // Strength for 4 blks in 1 stripe, 0 => vertical edge
+        GetStrength_Edge0(Strength, MbP, MbQ, 1);
+        str = (void*)Strength; //de-ref type-punned pointer fix
+        if (*((uint32*)str))    // only if one of the 4 Strength bytes is != 0
+        {
+            QP = (MbP->QPy + MbQ->QPy + 1) >> 1; // Average QP of the two blocks;
+            indexA = QP + video->FilterOffsetA;
+            indexB = QP + video->FilterOffsetB;
+            indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+            indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+            Alpha  = ALPHA_TABLE[indexA];
+            Beta = BETA_TABLE[indexB];
+            clipTable = (int *)CLIP_TAB[indexA];
+
+            if (Alpha > 0 && Beta > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Luma_horizontal(SrcY, Strength,  Alpha, Beta, clipTable, 20);
+#else
+                EdgeLoop_Luma_horizontal(SrcY, Strength,  Alpha, Beta, clipTable, pitch);
+#endif
+            }
+
+            QPC = (MbP->QPc + MbQ->QPc + 1) >> 1;
+            indexA = QPC + video->FilterOffsetA;
+            indexB = QPC + video->FilterOffsetB;
+            indexA = qp_clip_tab[indexA]; // IClip(0, MAX_QP, QP+video->FilterOffsetA)
+            indexB = qp_clip_tab[indexB]; // IClip(0, MAX_QP, QP+video->FilterOffsetB)
+
+            Alpha  = ALPHA_TABLE[indexA];
+            Beta = BETA_TABLE[indexB];
+            clipTable = (int *)CLIP_TAB[indexA];
+            if (Alpha > 0 && Beta > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Chroma_horizontal(SrcU, Strength, Alpha, Beta, clipTable, 12);
+                EdgeLoop_Chroma_horizontal(SrcV, Strength, Alpha, Beta, clipTable, 12);
+#else
+                EdgeLoop_Chroma_horizontal(SrcU, Strength, Alpha, Beta, clipTable, pitch >> 1);
+                EdgeLoop_Chroma_horizontal(SrcV, Strength, Alpha, Beta, clipTable, pitch >> 1);
+#endif
+            }
+        }
+
+    } /* end of: if(filterTopMbEdgeFlag) */
+
+
+    /* 4.HORIZONTAL EDGE (no boundary), the edges are inside a MB */
+    MbP = MbQ;
+
+    /* Recover Alpha,  Beta and clipTable for edge!=0 with the variables filterLeftMbEdgeFlag, mbNum and tmp */
+    /* Note that Alpha_c, Beta_c and clipTable_c for chroma is already calculated */
+    Alpha = filterLeftMbEdgeFlag;
+    Beta = mbNum;
+    clipTable = (int *)tmp;
+
+    GetStrength_HorizontalEdges(Strength + 4, MbQ); // Strength for 4 blks in 1 stripe, 0 => vertical edge
+
+    for (edge = 1; edge < 4; edge++)  // 4 horicontal strips of 16 pel
+    {
+        //GetStrength(video, Strength, MbP, MbQ, 1, edge); // Strength for 4 blks in 1 stripe   1 => horizontal edge
+        if (*((int*)(Strength + (edge << 2)))) // only if one of the 4 Strength bytes is != 0
+        {
+            if (Alpha > 0 && Beta > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Luma_horizontal(SrcY + (edge << 2)*20, Strength + (edge << 2),  Alpha, Beta, clipTable, 20);
+#else
+                EdgeLoop_Luma_horizontal(SrcY + (edge << 2)*pitch, Strength + (edge << 2),  Alpha, Beta, clipTable, pitch);
+#endif
+            }
+
+            if (!(edge & 1) && Alpha_c > 0 && Beta_c > 0)
+            {
+#ifdef USE_PRED_BLOCK
+                EdgeLoop_Chroma_horizontal(SrcU + (edge << 1)*12, Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, 12);
+                EdgeLoop_Chroma_horizontal(SrcV + (edge << 1)*12, Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, 12);
+#else
+                EdgeLoop_Chroma_horizontal(SrcU + (edge << 1)*(pitch >> 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, pitch >> 1);
+                EdgeLoop_Chroma_horizontal(SrcV + (edge << 1)*(pitch >> 1), Strength + (edge << 2), Alpha_c, Beta_c, clipTable_c, pitch >> 1);
+#endif
+            }
+        }
+
+    } //end edge
+
+    return;
+}
+
+/*
+ *****************************************************************************************************
+ * \brief   returns a buffer of 4 Strength values for one stripe in a mb (for different Frame types)
+ *****************************************************************************************************
+*/
+
+void GetStrength_Edge0(uint8 *Strength, AVCMacroblock* MbP, AVCMacroblock* MbQ, int dir)
+{
+    int tmp;
+    int16 *ptrQ, *ptrP;
+    void* vptr;
+    uint8 *pStrength;
+    void* refIdx;
+
+    if (MbP->mbMode == AVC_I4 || MbP->mbMode == AVC_I16 ||
+            MbQ->mbMode == AVC_I4 || MbQ->mbMode == AVC_I16)
+    {
+
+        *((int*)Strength) = ININT_STRENGTH[0];      // Start with Strength=3. or Strength=4 for Mb-edge
+
+    }
+    else // if not intra or SP-frame
+    {
+        *((int*)Strength) = 0;
+
+        if (dir == 0)  // Vertical Edge 0
+        {
+
+            //1. Check the ref_frame_id
+            refIdx = (void*) MbQ->RefIdx; //de-ref type-punned pointer fix
+            ptrQ = (int16*)refIdx;
+            refIdx = (void*)MbP->RefIdx; //de-ref type-punned pointer fix
+            ptrP = (int16*)refIdx;
+            pStrength = Strength;
+            if (ptrQ[0] != ptrP[1]) pStrength[0] = 1;
+            if (ptrQ[2] != ptrP[3]) pStrength[2] = 1;
+            pStrength[1] = pStrength[0];
+            pStrength[3] = pStrength[2];
+
+            //2. Check the non-zero coeff blocks (4x4)
+            if (MbQ->nz_coeff[0] != 0 || MbP->nz_coeff[3] != 0) pStrength[0] = 2;
+            if (MbQ->nz_coeff[4] != 0 || MbP->nz_coeff[7] != 0) pStrength[1] = 2;
+            if (MbQ->nz_coeff[8] != 0 || MbP->nz_coeff[11] != 0) pStrength[2] = 2;
+            if (MbQ->nz_coeff[12] != 0 || MbP->nz_coeff[15] != 0) pStrength[3] = 2;
+
+            //3. Only need to check the mv difference
+            vptr = (void*)MbQ->mvL0;  // for deref type-punned pointer
+            ptrQ = (int16*)vptr;
+            ptrP = (int16*)(MbP->mvL0 + 3); // points to 4x4 block #3 (the 4th column)
+
+            // 1st blk
+            if (*pStrength == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 8;
+            ptrP += 8;
+
+            // 2nd blk
+            if (*pStrength == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 8;
+            ptrP += 8;
+
+            // 3rd blk
+            if (*pStrength == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 8;
+            ptrP += 8;
+
+            // 4th blk
+            if (*pStrength == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+        }
+        else   // Horizontal Edge 0
+        {
+
+            //1. Check the ref_frame_id
+            refIdx = (void*)MbQ->RefIdx;  //de-ref type-punned pointer
+            ptrQ = (int16*)refIdx;
+            refIdx = (void*)MbP->RefIdx;  //de-ref type-punned pointer
+            ptrP = (int16*)refIdx;
+            pStrength = Strength;
+            if (ptrQ[0] != ptrP[2]) pStrength[0] = 1;
+            if (ptrQ[1] != ptrP[3]) pStrength[2] = 1;
+            pStrength[1] = pStrength[0];
+            pStrength[3] = pStrength[2];
+
+            //2. Check the non-zero coeff blocks (4x4)
+            if (MbQ->nz_coeff[0] != 0 || MbP->nz_coeff[12] != 0) pStrength[0] = 2;
+            if (MbQ->nz_coeff[1] != 0 || MbP->nz_coeff[13] != 0) pStrength[1] = 2;
+            if (MbQ->nz_coeff[2] != 0 || MbP->nz_coeff[14] != 0) pStrength[2] = 2;
+            if (MbQ->nz_coeff[3] != 0 || MbP->nz_coeff[15] != 0) pStrength[3] = 2;
+
+            //3. Only need to check the mv difference
+            vptr = (void*)MbQ->mvL0;
+            ptrQ = (int16*)vptr;
+            ptrP = (int16*)(MbP->mvL0 + 12); // points to 4x4 block #12 (the 4th row)
+
+            // 1st blk
+            if (*pStrength == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 2;
+            ptrP += 2;
+
+            // 2nd blk
+            if (*pStrength  == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 2;
+            ptrP += 2;
+
+            // 3rd blk
+            if (*pStrength  == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pStrength++;
+            ptrQ += 2;
+            ptrP += 2;
+
+            // 4th blk
+            if (*pStrength  == 0)
+            {
+                // check |mv difference| >= 4
+                tmp = *ptrQ++ - *ptrP++;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *ptrQ-- - *ptrP--;
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+        } /* end of: else if(dir == 0) */
+
+    } /* end of: if( !(MbP->mbMode == AVC_I4 ...) */
+}
+
+
+void GetStrength_VerticalEdges(uint8 *Strength, AVCMacroblock* MbQ)
+{
+    int     idx, tmp;
+    int16   *ptr, *pmvx, *pmvy;
+    uint8   *pnz;
+    uint8   *pStrength, *pStr;
+    void* refIdx;
+
+    if (MbQ->mbMode == AVC_I4 || MbQ->mbMode == AVC_I16)
+    {
+        *((int*)Strength)     = ININT_STRENGTH[1];      // Start with Strength=3. or Strength=4 for Mb-edge
+        *((int*)(Strength + 4)) = ININT_STRENGTH[2];
+        *((int*)(Strength + 8)) = ININT_STRENGTH[3];
+    }
+    else   // Not intra or SP-frame
+    {
+
+        *((int*)Strength)     = 0; // for non-intra MB, strength = 0, 1 or 2.
+        *((int*)(Strength + 4)) = 0;
+        *((int*)(Strength + 8)) = 0;
+
+        //1. Check the ref_frame_id
+        refIdx = (void*)MbQ->RefIdx;  //de-ref type-punned pointer fix
+        ptr = (int16*)refIdx;
+        pStrength = Strength;
+        if (ptr[0] != ptr[1]) pStrength[4] = 1;
+        if (ptr[2] != ptr[3]) pStrength[6] = 1;
+        pStrength[5] = pStrength[4];
+        pStrength[7] = pStrength[6];
+
+        //2. Check the nz_coeff block and mv difference
+        pmvx = (int16*)(MbQ->mvL0 + 1); // points to 4x4 block #1,not #0
+        pmvy = pmvx + 1;
+        for (idx = 0; idx < 4; idx += 2) // unroll the loop, make 4 iterations to 2
+        {
+            // first/third row : 1,2,3 or 9,10,12
+            // Strength = 2 for a whole row
+            pnz = MbQ->nz_coeff + (idx << 2);
+            if (*pnz++ != 0) *pStrength = 2;
+            if (*pnz++ != 0)
+            {
+                *pStrength = 2;
+                *(pStrength + 4) = 2;
+            }
+            if (*pnz++ != 0)
+            {
+                *(pStrength + 4) = 2;
+                *(pStrength + 8) = 2;
+            }
+            if (*pnz != 0) *(pStrength + 8) = 2;
+
+            // Then Strength = 1
+            if (*pStrength == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pmvx += 2;
+            pmvy += 2;
+            pStr = pStrength + 4;
+
+            if (*pStr == 0)
+            {
+                //check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 2;
+            pmvy += 2;
+            pStr = pStrength + 8;
+
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            // Second/fourth row: 5,6,7 or 14,15,16
+            // Strength = 2 for a whole row
+            pnz = MbQ->nz_coeff + ((idx + 1) << 2);
+            if (*pnz++ != 0) *(pStrength + 1) = 2;
+            if (*pnz++ != 0)
+            {
+                *(pStrength + 1) = 2;
+                *(pStrength + 5) = 2;
+            }
+            if (*pnz++ != 0)
+            {
+                *(pStrength + 5) = 2;
+                *(pStrength + 9) = 2;
+            }
+            if (*pnz != 0) *(pStrength + 9) = 2;
+
+            // Then Strength = 1
+            pmvx += 4;
+            pmvy += 4;
+            pStr = pStrength + 1;
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 2;
+            pmvy += 2;
+            pStr = pStrength + 5;
+
+            if (*pStr == 0)
+            {
+                //check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 2;
+            pmvy += 2;
+            pStr = pStrength + 9;
+
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 2);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            // update some variables for the next two rows
+            pmvx += 4;
+            pmvy += 4;
+            pStrength += 2;
+
+        } /* end of: for(idx=0; idx<2; idx++) */
+
+    } /* end of: else if( MbQ->mbMode == AVC_I4 ...) */
+}
+
+
+void GetStrength_HorizontalEdges(uint8 Strength[12], AVCMacroblock* MbQ)
+{
+    int     idx, tmp;
+    int16   *ptr, *pmvx, *pmvy;
+    uint8   *pStrength, *pStr;
+    void* refIdx;
+
+    if (MbQ->mbMode == AVC_I4 || MbQ->mbMode == AVC_I16)
+    {
+        *((int*)Strength)     = ININT_STRENGTH[1];      // Start with Strength=3. or Strength=4 for Mb-edge
+        *((int*)(Strength + 4)) = ININT_STRENGTH[2];
+        *((int*)(Strength + 8)) = ININT_STRENGTH[3];
+    }
+    else   // Not intra or SP-frame
+    {
+
+        *((int*)Strength)     = 0; // for non-intra MB, strength = 0, 1 or 2.
+        *((int*)(Strength + 4)) = 0; // for non-intra MB, strength = 0, 1 or 2.
+        *((int*)(Strength + 8)) = 0; // for non-intra MB, strength = 0, 1 or 2.
+
+
+        //1. Check the ref_frame_id
+        refIdx = (void*) MbQ->RefIdx; // de-ref type-punned fix
+        ptr = (int16*) refIdx;
+        pStrength = Strength;
+        if (ptr[0] != ptr[2]) pStrength[4] = 1;
+        if (ptr[1] != ptr[3]) pStrength[6] = 1;
+        pStrength[5] = pStrength[4];
+        pStrength[7] = pStrength[6];
+
+        //2. Check the nz_coeff block and mv difference
+        pmvx = (int16*)(MbQ->mvL0 + 4); // points to 4x4 block #4,not #0
+        pmvy = pmvx + 1;
+        for (idx = 0; idx < 4; idx += 2) // unroll the loop, make 4 iterations to 2
+        {
+            // first/third row : 1,2,3 or 9,10,12
+            // Strength = 2 for a whole row
+            if (MbQ->nz_coeff[idx] != 0) *pStrength = 2;
+            if (MbQ->nz_coeff[4+idx] != 0)
+            {
+                *pStrength = 2;
+                *(pStrength + 4) = 2;
+            }
+            if (MbQ->nz_coeff[8+idx] != 0)
+            {
+                *(pStrength + 4) = 2;
+                *(pStrength + 8) = 2;
+            }
+            if (MbQ->nz_coeff[12+idx] != 0) *(pStrength + 8) = 2;
+
+            // Then Strength = 1
+            if (*pStrength == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStrength = 1;
+            }
+
+            pmvx += 8;
+            pmvy += 8;
+            pStr = pStrength + 4;
+
+            if (*pStr == 0)
+            {
+                //check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 8;
+            pmvy += 8;
+            pStr = pStrength + 8;
+
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            // Second/fourth row: 5,6,7 or 14,15,16
+            // Strength = 2 for a whole row
+            if (MbQ->nz_coeff[idx+1] != 0) *(pStrength + 1) = 2;
+            if (MbQ->nz_coeff[4+idx+1] != 0)
+            {
+                *(pStrength + 1) = 2;
+                *(pStrength + 5) = 2;
+            }
+            if (MbQ->nz_coeff[8+idx+1] != 0)
+            {
+                *(pStrength + 5) = 2;
+                *(pStrength + 9) = 2;
+            }
+            if (MbQ->nz_coeff[12+idx+1] != 0) *(pStrength + 9) = 2;
+
+            // Then Strength = 1
+            pmvx -= 14;
+            pmvy -= 14; // -14 = -16 + 2
+            pStr = pStrength + 1;
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 8;
+            pmvy += 8;
+            pStr = pStrength + 5;
+
+            if (*pStr == 0)
+            {
+                //check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            pmvx += 8;
+            pmvy += 8;
+            pStr = pStrength + 9;
+
+            if (*pStr == 0)
+            {
+                //within the same 8x8 block, no need to check the reference id
+                //only need to check the |mv difference| >= 4
+                tmp = *pmvx - *(pmvx - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+
+                tmp = *pmvy - *(pmvy - 8);
+                if (tmp < 0) tmp = -tmp;
+                if (tmp >= 4) *pStr = 1;
+            }
+
+            // update some variables for the next two rows
+            pmvx -= 14;
+            pmvy -= 14; // -14 = -16 + 2
+            pStrength += 2;
+
+        } /* end of: for(idx=0; idx<2; idx++) */
+
+    } /* end of: else if( MbQ->mbMode == AVC_I4 ...) */
+}
+
+/*
+ *****************************************************************************************
+ * \brief  Filters one edge of 16 (luma) or 8 (chroma) pel
+ *****************************************************************************************
+*/
+
+void EdgeLoop_Luma_horizontal(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch)
+{
+    int  pel, ap = 0, aq = 0, Strng;
+    int  C0, c0, dif, AbsDelta, tmp, tmp1;
+    int  L2 = 0, L1, L0, R0, R1, R2 = 0, RL0;
+
+
+    if (Strength[0] == 4)  /* INTRA strong filtering */
+    {
+        for (pel = 0; pel < 16; pel++)
+        {
+            R0  = SrcPtr[0];
+            R1  = SrcPtr[pitch];
+            L0  = SrcPtr[-pitch];
+            L1  = SrcPtr[-(pitch<<1)];
+
+            // |R0 - R1| < Beta
+            tmp1 = R0 - R1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp = (tmp1 - Beta);
+
+            //|L0 - L1| < Beta
+            tmp1 = L0 - L1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Beta);
+
+            //|R0 - L0| < Alpha
+            AbsDelta = R0 - L0;
+            if (AbsDelta < 0) AbsDelta = -AbsDelta;
+            tmp &= (AbsDelta - Alpha);
+
+            if (tmp < 0)
+            {
+                AbsDelta -= ((Alpha >> 2) + 2);
+                R2 = SrcPtr[pitch<<1]; //inc2
+                L2 = SrcPtr[-(pitch+(pitch<<1))]; // -inc3
+
+                // |R0 - R2| < Beta && |R0 - L0| < (Alpha/4 + 2)
+                tmp = R0 - R2;
+                if (tmp < 0) tmp = -tmp;
+                aq = AbsDelta & (tmp - Beta);
+
+                // |L0 - L2| < Beta && |R0 - L0| < (Alpha/4 + 2)
+                tmp = L0 - L2;
+                if (tmp < 0) tmp = -tmp;
+                ap = AbsDelta & (tmp - Beta);
+
+                if (aq < 0)
+                {
+                    tmp = R1 + R0 + L0;
+                    SrcPtr[0] = (L1 + (tmp << 1) +  R2 + 4) >> 3;
+                    tmp += R2;
+                    SrcPtr[pitch]  = (tmp + 2) >> 2;
+                    SrcPtr[pitch<<1] = (((SrcPtr[(pitch+(pitch<<1))] + R2) << 1) + tmp + 4) >> 3;
+                }
+                else
+                    SrcPtr[0] = ((R1 << 1) + R0 + L1 + 2) >> 2;
+
+                if (ap < 0)
+                {
+                    tmp = L1 + R0 + L0;
+                    SrcPtr[-pitch]  = (R1 + (tmp << 1) +  L2 + 4) >> 3;
+                    tmp += L2;
+                    SrcPtr[-(pitch<<1)] = (tmp + 2) >> 2;
+                    SrcPtr[-(pitch+(pitch<<1))] = (((SrcPtr[-(pitch<<2)] + L2) << 1) + tmp + 4) >> 3;
+                }
+                else
+                    SrcPtr[-pitch] = ((L1 << 1) + L0 + R1 + 2) >> 2;
+
+            } /* if(tmp < 0) */
+
+            SrcPtr ++; // Increment to next set of pixel
+
+        } /* end of: for(pel=0; pel<16; pel++) */
+
+    } /* if(Strength[0] == 4) */
+
+    else   /* Normal filtering */
+    {
+        for (pel = 0; pel < 16; pel++)
+        {
+            Strng = Strength[pel >> 2];
+            if (Strng)
+            {
+                R0  = SrcPtr[0];
+                R1  = SrcPtr[pitch];
+                L0  = SrcPtr[-pitch];
+                L1  = SrcPtr[-(pitch<<1)]; // inc2
+
+                //|R0 - L0| < Alpha
+                tmp1 = R0 - L0;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                tmp = (tmp1 - Alpha);
+
+                // |R0 - R1| < Beta
+                tmp1 = R0 - R1;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                tmp &= (tmp1 - Beta);
+
+                //|L0 - L1| < Beta
+                tmp1 = L0 - L1;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                tmp &= (tmp1 - Beta);
+
+                if (tmp < 0)
+                {
+                    R2 = SrcPtr[pitch<<1]; //inc2
+                    L2 = SrcPtr[-(pitch+(pitch<<1))]; // -inc3
+
+                    // |R0 - R2| < Beta
+                    tmp = R0 - R2;
+                    if (tmp < 0) tmp = -tmp;
+                    aq = tmp - Beta;
+
+                    // |L0 - L2| < Beta
+                    tmp = L0 - L2;
+                    if (tmp < 0) tmp = -tmp;
+                    ap = tmp - Beta;
+
+
+                    c0 = C0 = clipTable[Strng];
+                    if (ap < 0) c0++;
+                    if (aq < 0) c0++;
+
+                    //dif = IClip(-c0, c0, ((Delta << 2) + (L1 - R1) + 4) >> 3);
+                    dif = (((R0 - L0) << 2) + (L1 - R1) + 4) >> 3;
+                    tmp = dif + c0;
+                    if ((uint)tmp > (uint)c0 << 1)
+                    {
+                        tmp = ~(tmp >> 31);
+                        dif = (tmp & (c0 << 1)) - c0;
+                    }
+
+                    //SrcPtr[0]    = (uint8)IClip(0, 255, R0 - dif);
+                    //SrcPtr[-inc] = (uint8)IClip(0, 255, L0 + dif);
+                    RL0 = R0 + L0;
+                    R0 -= dif;
+                    L0 += dif;
+                    if ((uint)R0 > 255)
+                    {
+                        tmp = ~(R0 >> 31);
+                        R0 = tmp & 255;
+                    }
+                    if ((uint)L0 > 255)
+                    {
+                        tmp = ~(L0 >> 31);
+                        L0 = tmp & 255;
+                    }
+                    SrcPtr[-pitch] = L0;
+                    SrcPtr[0] = R0;
+
+                    if (C0 != 0) /* Multiple zeros in the clip tables */
+                    {
+                        if (aq < 0)  // SrcPtr[inc]   += IClip(-C0, C0,(R2 + ((RL0 + 1) >> 1) - (R1<<1)) >> 1);
+                        {
+                            R2 = (R2 + ((RL0 + 1) >> 1) - (R1 << 1)) >> 1;
+                            tmp = R2 + C0;
+                            if ((uint)tmp > (uint)C0 << 1)
+                            {
+                                tmp = ~(tmp >> 31);
+                                R2 = (tmp & (C0 << 1)) - C0;
+                            }
+                            SrcPtr[pitch] += R2;
+                        }
+
+                        if (ap < 0)  //SrcPtr[-inc2] += IClip(-C0, C0,(L2 + ((RL0 + 1) >> 1) - (L1<<1)) >> 1);
+                        {
+                            L2 = (L2 + ((RL0 + 1) >> 1) - (L1 << 1)) >> 1;
+                            tmp = L2 + C0;
+                            if ((uint)tmp > (uint)C0 << 1)
+                            {
+                                tmp = ~(tmp >> 31);
+                                L2 = (tmp & (C0 << 1)) - C0;
+                            }
+                            SrcPtr[-(pitch<<1)] += L2;
+                        }
+                    }
+
+                } /* if(tmp < 0) */
+
+            } /* end of:  if((Strng = Strength[pel >> 2])) */
+
+            SrcPtr ++; // Increment to next set of pixel
+
+        } /* for(pel=0; pel<16; pel++) */
+
+    } /* else if(Strength[0] == 4) */
+}
+
+void EdgeLoop_Luma_vertical(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch)
+{
+    int  pel, ap = 1, aq = 1;
+    int  C0, c0, dif, AbsDelta, Strng, tmp, tmp1;
+    int  L2 = 0, L1, L0, R0, R1, R2 = 0;
+    uint8 *ptr, *ptr1;
+    register uint R_in, L_in;
+    uint R_out, L_out;
+
+
+    if (Strength[0] == 4)  /* INTRA strong filtering */
+    {
+
+        for (pel = 0; pel < 16; pel++)
+        {
+
+            // Read 8 pels
+            R_in = *((uint *)SrcPtr);       // R_in = {R3, R2, R1, R0}
+            L_in = *((uint *)(SrcPtr - 4)); // L_in = {L0, L1, L2, L3}
+            R1   = (R_in >> 8) & 0xff;
+            R0   = R_in & 0xff;
+            L0   = L_in >> 24;
+            L1   = (L_in >> 16) & 0xff;
+
+            // |R0 - R1| < Beta
+            tmp1 = (R_in & 0xff) - R1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp = (tmp1 - Beta);
+
+
+            //|L0 - L1| < Beta
+            tmp1 = (L_in >> 24) - L1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Beta);
+
+            //|R0 - L0| < Alpha
+            AbsDelta = (R_in & 0xff) - (L_in >> 24);
+            if (AbsDelta < 0) AbsDelta = -AbsDelta;
+            tmp &= (AbsDelta - Alpha);
+
+            if (tmp < 0)
+            {
+                AbsDelta -= ((Alpha >> 2) + 2);
+                R2   = (R_in >> 16) & 0xff;
+                L2   = (L_in >> 8) & 0xff;
+
+                // |R0 - R2| < Beta && |R0 - L0| < (Alpha/4 + 2)
+                tmp1 = (R_in & 0xff) - R2;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                aq = AbsDelta & (tmp1 - Beta);
+
+                // |L0 - L2| < Beta && |R0 - L0| < (Alpha/4 + 2)
+                tmp1 = (L_in >> 24) - L2;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                ap = AbsDelta & (tmp1 - Beta);
+
+
+                ptr = SrcPtr;
+                if (aq < 0)
+                {
+                    R_out = (R_in >> 24) << 24; // Keep R3 at the fourth byte
+
+                    tmp  = R0 + L0 + R1;
+                    R_out |= (((tmp << 1) +  L1 + R2 + 4) >> 3);
+                    tmp += R2;
+                    R_out |= (((tmp + 2) >> 2) << 8);
+                    tmp1 = ((R_in >> 24) + R2) << 1;
+                    R_out |= (((tmp1 + tmp + 4) >> 3) << 16);
+
+                    *((uint *)SrcPtr) = R_out;
+                }
+                else
+                    *ptr = ((R1 << 1) + R0 + L1 + 2) >> 2;
+
+
+                if (ap < 0)
+                {
+                    L_out = (L_in << 24) >> 24; // Keep L3 at the first byte
+
+                    tmp  = R0 + L0 + L1;
+                    L_out |= ((((tmp << 1) + R1 + L2 + 4) >> 3) << 24);
+                    tmp += L2;
+                    L_out |= (((tmp + 2) >> 2) << 16);
+                    tmp1 = ((L_in & 0xff) + L2) << 1;
+                    L_out |= (((tmp1 + tmp + 4) >> 3) << 8);
+
+                    *((uint *)(SrcPtr - 4)) = L_out;
+                }
+                else
+                    *(--ptr) = ((L1 << 1) + L0 + R1 + 2) >> 2;
+
+            } /* if(tmp < 0) */
+
+            SrcPtr += pitch;    // Increment to next set of pixel
+
+        } /* end of: for(pel=0; pel<16; pel++) */
+
+    } /* if(Strength[0] == 4) */
+
+    else   /* Normal filtering */
+    {
+
+        for (pel = 0; pel < 16; pel++)
+        {
+            Strng = Strength[pel >> 2];
+            if (Strng)
+            {
+                // Read 8 pels
+                R_in = *((uint *)SrcPtr);       // R_in = {R3, R2, R1, R0}
+                L_in = *((uint *)(SrcPtr - 4)); // L_in = {L0, L1, L2, L3}
+                R1   = (R_in >> 8) & 0xff;
+                R0   = R_in & 0xff;
+                L0   = L_in >> 24;
+                L1   = (L_in >> 16) & 0xff;
+
+                //|R0 - L0| < Alpha
+                tmp = R0 - L0;
+                if (tmp < 0) tmp = -tmp;
+                tmp -= Alpha;
+
+                // |R0 - R1| < Beta
+                tmp1 = R0 - R1;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                tmp &= (tmp1 - Beta);
+
+                //|L0 - L1| < Beta
+                tmp1 = L0 - L1;
+                if (tmp1 < 0) tmp1 = -tmp1;
+                tmp &= (tmp1 - Beta);
+
+                if (tmp < 0)
+                {
+                    L2 = SrcPtr[-3];
+                    R2 = SrcPtr[2];
+
+                    // |R0 - R2| < Beta
+                    tmp = R0 - R2;
+                    if (tmp < 0) tmp = -tmp;
+                    aq = tmp - Beta;
+
+                    // |L0 - L2| < Beta
+                    tmp = L0 - L2;
+                    if (tmp < 0) tmp = -tmp;
+                    ap = tmp - Beta;
+
+
+                    c0 = C0 = clipTable[Strng];
+                    if (ap < 0) c0++;
+                    if (aq < 0) c0++;
+
+                    //dif = IClip(-c0, c0, ((Delta << 2) + (L1 - R1) + 4) >> 3);
+                    dif = (((R0 - L0) << 2) + (L1 - R1) + 4) >> 3;
+                    tmp = dif + c0;
+                    if ((uint)tmp > (uint)c0 << 1)
+                    {
+                        tmp = ~(tmp >> 31);
+                        dif = (tmp & (c0 << 1)) - c0;
+                    }
+
+                    ptr = SrcPtr;
+                    ptr1 = SrcPtr - 1;
+                    //SrcPtr[0]    = (uint8)IClip(0, 255, R0 - dif);
+                    //SrcPtr[-inc] = (uint8)IClip(0, 255, L0 + dif);
+                    R_in = R0 - dif;
+                    L_in = L0 + dif; /* cannot re-use R0 and L0 here */
+                    if ((uint)R_in > 255)
+                    {
+                        tmp = ~((int)R_in >> 31);
+                        R_in = tmp & 255;
+                    }
+                    if ((uint)L_in > 255)
+                    {
+                        tmp = ~((int)L_in >> 31);
+                        L_in = tmp & 255;
+                    }
+                    *ptr1-- = L_in;
+                    *ptr++  = R_in;
+
+                    if (C0 != 0) // Multiple zeros in the clip tables
+                    {
+                        if (ap < 0)  //SrcPtr[-inc2] += IClip(-C0, C0,(L2 + ((RL0 + 1) >> 1) - (L1<<1)) >> 1);
+                        {
+                            L2 = (L2 + ((R0 + L0 + 1) >> 1) - (L1 << 1)) >> 1;
+                            tmp = L2 + C0;
+                            if ((uint)tmp > (uint)C0 << 1)
+                            {
+                                tmp = ~(tmp >> 31);
+                                L2 = (tmp & (C0 << 1)) - C0;
+                            }
+                            *ptr1 += L2;
+                        }
+
+                        if (aq < 0)  // SrcPtr[inc] += IClip(-C0, C0,(R2 + ((RL0 + 1) >> 1) - (R1<<1)) >> 1);
+                        {
+                            R2 = (R2 + ((R0 + L0 + 1) >> 1) - (R1 << 1)) >> 1;
+                            tmp = R2 + C0;
+                            if ((uint)tmp > (uint)C0 << 1)
+                            {
+                                tmp = ~(tmp >> 31);
+                                R2 = (tmp & (C0 << 1)) - C0;
+                            }
+                            *ptr += R2;
+                        }
+                    }
+
+                } /* if(tmp < 0) */
+
+            } /* end of:  if((Strng = Strength[pel >> 2])) */
+
+            SrcPtr += pitch;    // Increment to next set of pixel
+
+        } /* for(pel=0; pel<16; pel++) */
+
+    } /* else if(Strength[0] == 4) */
+
+}
+
+void EdgeLoop_Chroma_vertical(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch)
+{
+    int     pel, Strng;
+    int     c0, dif;
+    int     L1, L0, R0, R1, tmp, tmp1;
+    uint8   *ptr;
+    uint    R_in, L_in;
+
+
+    for (pel = 0; pel < 16; pel++)
+    {
+        Strng = Strength[pel>>2];
+        if (Strng)
+        {
+            // Read 8 pels
+            R_in = *((uint *)SrcPtr);       // R_in = {R3, R2, R1, R0}
+            L_in = *((uint *)(SrcPtr - 4)); // L_in = {L0, L1, L2, L3}
+            R1   = (R_in >> 8) & 0xff;
+            R0   = R_in & 0xff;
+            L0   = L_in >> 24;
+            L1   = (L_in >> 16) & 0xff;
+
+            // |R0 - R1| < Beta
+            tmp1 = R0 - R1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp = (tmp1 - Beta);
+
+            //|L0 - L1| < Beta
+            tmp1 = L0 - L1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Beta);
+
+            //|R0 - L0| < Alpha
+            tmp1 = R0 - L0;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Alpha);
+
+            if (tmp < 0)
+            {
+                ptr = SrcPtr;
+                if (Strng == 4) /* INTRA strong filtering */
+                {
+                    *ptr-- = ((R1 << 1) + R0 + L1 + 2) >> 2;
+                    *ptr   = ((L1 << 1) + L0 + R1 + 2) >> 2;
+                }
+                else  /* normal filtering */
+                {
+                    c0  = clipTable[Strng] + 1;
+                    //dif = IClip(-c0, c0, ((Delta << 2) + (L1 - R1) + 4) >> 3);
+                    dif = (((R0 - L0) << 2) + (L1 - R1) + 4) >> 3;
+                    tmp = dif + c0;
+                    if ((uint)tmp > (uint)c0 << 1)
+                    {
+                        tmp = ~(tmp >> 31);
+                        dif = (tmp & (c0 << 1)) - c0;
+                    }
+
+                    //SrcPtr[0]    = (uint8)IClip(0, 255, R0 - dif);
+                    //SrcPtr[-inc] = (uint8)IClip(0, 255, L0 + dif);
+                    L0 += dif;
+                    R0 -= dif;
+                    if ((uint)L0 > 255)
+                    {
+                        tmp = ~(L0 >> 31);
+                        L0 = tmp & 255;
+                    }
+                    if ((uint)R0 > 255)
+                    {
+                        tmp = ~(R0 >> 31);
+                        R0 = tmp & 255;
+                    }
+
+                    *ptr-- = R0;
+                    *ptr = L0;
+                }
+            }
+            pel ++;
+            SrcPtr += pitch;   // Increment to next set of pixel
+
+        } /* end of: if((Strng = Strength[pel >> 2])) */
+        else
+        {
+            pel += 3;
+            SrcPtr += (pitch << 1); //PtrInc << 1;
+        }
+
+    } /* end of: for(pel=0; pel<16; pel++) */
+}
+
+
+void EdgeLoop_Chroma_horizontal(uint8* SrcPtr, uint8 *Strength, int Alpha, int Beta, int *clipTable, int pitch)
+{
+    int  pel, Strng;
+    int  c0, dif;
+    int  L1, L0, R0, R1, tmp, tmp1;
+
+    for (pel = 0; pel < 16; pel++)
+    {
+        Strng = Strength[pel>>2];
+        if (Strng)
+        {
+            R0  = SrcPtr[0];
+            L0  = SrcPtr[-pitch];
+            L1  = SrcPtr[-(pitch<<1)]; //inc2
+            R1  = SrcPtr[pitch];
+
+            // |R0 - R1| < Beta
+            tmp1 = R0 - R1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp = (tmp1 - Beta);
+
+            //|L0 - L1| < Beta
+            tmp1 = L0 - L1;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Beta);
+
+            //|R0 - L0| < Alpha
+            tmp1 = R0 - L0;
+            if (tmp1 < 0) tmp1 = -tmp1;
+            tmp &= (tmp1 - Alpha);
+
+            if (tmp < 0)
+            {
+                if (Strng == 4) /* INTRA strong filtering */
+                {
+                    SrcPtr[0]      = ((R1 << 1) + R0 + L1 + 2) >> 2;
+                    SrcPtr[-pitch] = ((L1 << 1) + L0 + R1 + 2) >> 2;
+                }
+                else  /* normal filtering */
+                {
+                    c0  = clipTable[Strng] + 1;
+                    //dif = IClip(-c0, c0, ((Delta << 2) + (L1 - R1) + 4) >> 3);
+                    dif = (((R0 - L0) << 2) + (L1 - R1) + 4) >> 3;
+                    tmp = dif + c0;
+                    if ((uint)tmp > (uint)c0 << 1)
+                    {
+                        tmp = ~(tmp >> 31);
+                        dif = (tmp & (c0 << 1)) - c0;
+                    }
+
+                    //SrcPtr[-inc] = (uint8)IClip(0, 255, L0 + dif);
+                    //SrcPtr[0]    = (uint8)IClip(0, 255, R0 - dif);
+                    L0 += dif;
+                    R0 -= dif;
+                    if ((uint)L0 > 255)
+                    {
+                        tmp = ~(L0 >> 31);
+                        L0 = tmp & 255;
+                    }
+                    if ((uint)R0 > 255)
+                    {
+                        tmp = ~(R0 >> 31);
+                        R0 = tmp & 255;
+                    }
+                    SrcPtr[0] = R0;
+                    SrcPtr[-pitch] = L0;
+                }
+            }
+
+            pel ++;
+            SrcPtr ++; // Increment to next set of pixel
+
+        } /* end of: if((Strng = Strength[pel >> 2])) */
+        else
+        {
+            pel += 3;
+            SrcPtr += 2;
+        }
+
+    } /* end of: for(pel=0; pel<16; pel++) */
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/avc/common/src/dpb.cpp b/media/libstagefright/codecs/avc/common/src/dpb.cpp
new file mode 100644
index 0000000..2c4c7da
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/src/dpb.cpp
@@ -0,0 +1,724 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avclib_common.h"
+
+#define DPB_MEM_ATTR 0
+
+AVCStatus InitDPB(AVCHandle *avcHandle, AVCCommonObj *video, int FrameHeightInMbs, int PicWidthInMbs, bool padding)
+{
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int level, framesize, num_fs;
+    void *userData = avcHandle->userData;
+#ifndef PV_MEMORY_POOL
+    uint32 addr;
+#endif
+    uint16 refIdx = 0;
+    level = video->currSeqParams->level_idc;
+
+    for (num_fs = 0; num_fs < MAX_FS; num_fs++)
+    {
+        dpb->fs[num_fs] = NULL;
+    }
+
+    framesize = (int)(((FrameHeightInMbs * PicWidthInMbs) << 7) * 3);
+    if (padding)
+    {
+        video->padded_size = (int)((((FrameHeightInMbs + 2) * (PicWidthInMbs + 2)) << 7) * 3) - framesize;
+    }
+    else
+    {
+        video->padded_size = 0;
+    }
+
+#ifndef PV_MEMORY_POOL
+    if (dpb->decoded_picture_buffer)
+    {
+        avcHandle->CBAVC_Free(userData, (int)dpb->decoded_picture_buffer);
+        dpb->decoded_picture_buffer = NULL;
+    }
+#endif
+    /* need to allocate one extra frame for current frame, DPB only defines for reference frames */
+
+    dpb->num_fs = (uint32)(MaxDPBX2[mapLev2Idx[level]] << 2) / (3 * FrameHeightInMbs * PicWidthInMbs) + 1;
+    if (dpb->num_fs > MAX_FS)
+    {
+        dpb->num_fs = MAX_FS;
+    }
+
+    if (video->currSeqParams->num_ref_frames + 1 > (uint32)dpb->num_fs)
+    {
+        dpb->num_fs = video->currSeqParams->num_ref_frames + 1;
+    }
+
+    dpb->dpb_size = dpb->num_fs * (framesize + video->padded_size);
+//  dpb->dpb_size = (uint32)MaxDPBX2[mapLev2Idx[level]]*512 + framesize;
+
+#ifndef PV_MEMORY_POOL
+    dpb->decoded_picture_buffer = (uint8*) avcHandle->CBAVC_Malloc(userData, dpb->dpb_size, 100/*DPB_MEM_ATTR*/);
+
+    if (dpb->decoded_picture_buffer == NULL || dpb->decoded_picture_buffer&0x3) // not word aligned
+        return AVC_MEMORY_FAIL;
+#endif
+    dpb->used_size = 0;
+    num_fs = 0;
+
+    while (num_fs < dpb->num_fs)
+    {
+        /*  fs is an array pointers to AVCDecPicture */
+        dpb->fs[num_fs] = (AVCFrameStore*) avcHandle->CBAVC_Malloc(userData, sizeof(AVCFrameStore), 101/*DEFAULT_ATTR*/);
+        if (dpb->fs[num_fs] == NULL)
+        {
+            return AVC_MEMORY_FAIL;
+        }
+#ifndef PV_MEMORY_POOL
+        /* assign the actual memory for Sl, Scb, Scr */
+        dpb->fs[num_fs]->base_dpb = dpb->decoded_picture_buffer + dpb->used_size;
+#endif
+        dpb->fs[num_fs]->IsReference = 0;
+        dpb->fs[num_fs]->IsLongTerm = 0;
+        dpb->fs[num_fs]->IsOutputted = 3;
+        dpb->fs[num_fs]->frame.RefIdx = refIdx++; /* this value will remain unchanged through out the encoding session */
+        dpb->fs[num_fs]->frame.picType = AVC_FRAME;
+        dpb->fs[num_fs]->frame.isLongTerm = 0;
+        dpb->fs[num_fs]->frame.isReference = 0;
+        video->RefPicList0[num_fs] = &(dpb->fs[num_fs]->frame);
+        dpb->fs[num_fs]->frame.padded = 0;
+        dpb->used_size += (framesize + video->padded_size);
+        num_fs++;
+    }
+
+    return AVC_SUCCESS;
+}
+
+OSCL_EXPORT_REF AVCStatus AVCConfigureSequence(AVCHandle *avcHandle, AVCCommonObj *video, bool padding)
+{
+    void *userData = avcHandle->userData;
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int framesize, ii; /* size of one frame */
+    uint PicWidthInMbs, PicHeightInMapUnits, FrameHeightInMbs, PicSizeInMapUnits;
+    uint num_fs;
+    /* derived variables from SPS */
+    PicWidthInMbs = video->currSeqParams->pic_width_in_mbs_minus1 + 1;
+    PicHeightInMapUnits = video->currSeqParams->pic_height_in_map_units_minus1 + 1 ;
+    FrameHeightInMbs = (2 - video->currSeqParams->frame_mbs_only_flag) * PicHeightInMapUnits ;
+    PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits ;
+
+    if (video->PicSizeInMapUnits != PicSizeInMapUnits || video->currSeqParams->level_idc != video->level_idc)
+    {
+        /* make sure you mark all the frames as unused for reference for flushing*/
+        for (ii = 0; ii < dpb->num_fs; ii++)
+        {
+            dpb->fs[ii]->IsReference = 0;
+            dpb->fs[ii]->IsOutputted |= 0x02;
+        }
+
+        num_fs = (uint32)(MaxDPBX2[(uint32)mapLev2Idx[video->currSeqParams->level_idc]] << 2) / (3 * PicSizeInMapUnits) + 1;
+        if (num_fs >= MAX_FS)
+        {
+            num_fs = MAX_FS;
+        }
+#ifdef PV_MEMORY_POOL
+        if (padding)
+        {
+            avcHandle->CBAVC_DPBAlloc(avcHandle->userData,
+                                      PicSizeInMapUnits + ((PicWidthInMbs + 2) << 1) + (PicHeightInMapUnits << 1), num_fs);
+        }
+        else
+        {
+            avcHandle->CBAVC_DPBAlloc(avcHandle->userData, PicSizeInMapUnits, num_fs);
+        }
+#endif
+        CleanUpDPB(avcHandle, video);
+        if (InitDPB(avcHandle, video, FrameHeightInMbs, PicWidthInMbs, padding) != AVC_SUCCESS)
+        {
+            return AVC_FAIL;
+        }
+        /*  Allocate video->mblock upto PicSizeInMbs and populate the structure  such as the neighboring MB pointers.   */
+        framesize = (FrameHeightInMbs * PicWidthInMbs);
+        if (video->mblock)
+        {
+            avcHandle->CBAVC_Free(userData, (uint32)video->mblock);
+            video->mblock = NULL;
+        }
+        video->mblock = (AVCMacroblock*) avcHandle->CBAVC_Malloc(userData, sizeof(AVCMacroblock) * framesize, DEFAULT_ATTR);
+        if (video->mblock == NULL)
+        {
+            return AVC_FAIL;
+        }
+        for (ii = 0; ii < framesize; ii++)
+        {
+            video->mblock[ii].slice_id = -1;
+        }
+        /* Allocate memory for intra prediction */
+#ifdef MB_BASED_DEBLOCK
+        video->intra_pred_top = (uint8*) avcHandle->CBAVC_Malloc(userData, PicWidthInMbs << 4, FAST_MEM_ATTR);
+        if (video->intra_pred_top == NULL)
+        {
+            return AVC_FAIL;
+        }
+        video->intra_pred_top_cb = (uint8*) avcHandle->CBAVC_Malloc(userData, PicWidthInMbs << 3, FAST_MEM_ATTR);
+        if (video->intra_pred_top_cb == NULL)
+        {
+            return AVC_FAIL;
+        }
+        video->intra_pred_top_cr = (uint8*) avcHandle->CBAVC_Malloc(userData, PicWidthInMbs << 3, FAST_MEM_ATTR);
+        if (video->intra_pred_top_cr == NULL)
+        {
+            return AVC_FAIL;
+        }
+
+#endif
+        /*  Allocate slice group MAP map */
+
+        if (video->MbToSliceGroupMap)
+        {
+            avcHandle->CBAVC_Free(userData, (uint32)video->MbToSliceGroupMap);
+            video->MbToSliceGroupMap = NULL;
+        }
+        video->MbToSliceGroupMap = (int*) avcHandle->CBAVC_Malloc(userData, sizeof(uint) * PicSizeInMapUnits * 2, 7/*DEFAULT_ATTR*/);
+        if (video->MbToSliceGroupMap == NULL)
+        {
+            return AVC_FAIL;
+        }
+        video->PicSizeInMapUnits = PicSizeInMapUnits;
+        video->level_idc = video->currSeqParams->level_idc;
+
+    }
+    return AVC_SUCCESS;
+}
+
+OSCL_EXPORT_REF AVCStatus CleanUpDPB(AVCHandle *avcHandle, AVCCommonObj *video)
+{
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int ii;
+    void *userData = avcHandle->userData;
+
+    for (ii = 0; ii < MAX_FS; ii++)
+    {
+        if (dpb->fs[ii] != NULL)
+        {
+            avcHandle->CBAVC_Free(userData, (int)dpb->fs[ii]);
+            dpb->fs[ii] = NULL;
+        }
+    }
+#ifndef PV_MEMORY_POOL
+    if (dpb->decoded_picture_buffer)
+    {
+        avcHandle->CBAVC_Free(userData, (int)dpb->decoded_picture_buffer);
+        dpb->decoded_picture_buffer = NULL;
+    }
+#endif
+    dpb->used_size = 0;
+    dpb->dpb_size = 0;
+
+    return AVC_SUCCESS;
+}
+
+OSCL_EXPORT_REF AVCStatus DPBInitBuffer(AVCHandle *avcHandle, AVCCommonObj *video)
+{
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int ii, status;
+
+    /* Before doing any decoding, check if there's a frame memory available */
+    /* look for next unused dpb->fs, or complementary field pair */
+    /* video->currPic is assigned to this */
+
+    /* There's also restriction on the frame_num, see page 59 of JVT-I1010.doc. */
+
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        /* looking for the one not used or not reference and has been outputted */
+        if (dpb->fs[ii]->IsReference == 0 && dpb->fs[ii]->IsOutputted == 3)
+        {
+            video->currFS = dpb->fs[ii];
+#ifdef PV_MEMORY_POOL
+            status = avcHandle->CBAVC_FrameBind(avcHandle->userData, ii, &(video->currFS->base_dpb));
+            if (status == AVC_FAIL)
+            {
+                return AVC_NO_BUFFER; /* this should not happen */
+            }
+#endif
+            break;
+        }
+    }
+    if (ii == dpb->num_fs)
+    {
+        return AVC_PICTURE_OUTPUT_READY; /* no empty frame available */
+    }
+    return AVC_SUCCESS;
+}
+
+OSCL_EXPORT_REF void DPBInitPic(AVCCommonObj *video, int CurrPicNum)
+{
+    int offset = 0;
+    int offsetc = 0;
+    int luma_framesize;
+    /* this part has to be set here, assuming that slice header and POC have been decoded. */
+    /* used in GetOutput API */
+    video->currFS->PicOrderCnt = video->PicOrderCnt;
+    video->currFS->FrameNum = video->sliceHdr->frame_num;
+    video->currFS->FrameNumWrap = CurrPicNum;    // MC_FIX
+    /* initialize everything to zero */
+    video->currFS->IsOutputted = 0;
+    video->currFS->IsReference = 0;
+    video->currFS->IsLongTerm = 0;
+    video->currFS->frame.isReference = FALSE;
+    video->currFS->frame.isLongTerm = FALSE;
+
+    /* initialize the pixel pointer to NULL */
+    video->currFS->frame.Sl = video->currFS->frame.Scb = video->currFS->frame.Scr = NULL;
+
+    /* determine video->currPic */
+    /* assign dbp->base_dpb to fs[i]->frame.Sl, Scb, Scr .*/
+    /* For PicSizeInMbs, see DecodeSliceHeader() */
+
+    video->currPic = &(video->currFS->frame);
+
+    video->currPic->padded = 0; // reset this flag to not-padded
+
+    if (video->padded_size)
+    {
+        offset = ((video->PicWidthInSamplesL + 32) << 4) + 16; // offset to the origin
+        offsetc = (offset >> 2) + 4;
+        luma_framesize = (int)((((video->FrameHeightInMbs + 2) * (video->PicWidthInMbs + 2)) << 8));
+    }
+    else
+        luma_framesize = video->PicSizeInMbs << 8;
+
+
+    video->currPic->Sl = video->currFS->base_dpb + offset;
+    video->currPic->Scb = video->currFS->base_dpb  + luma_framesize + offsetc;
+    video->currPic->Scr = video->currPic->Scb + (luma_framesize >> 2);
+    video->currPic->pitch = video->PicWidthInSamplesL + (video->padded_size == 0 ? 0 : 32);
+
+
+    video->currPic->height = video->PicHeightInSamplesL;
+    video->currPic->width = video->PicWidthInSamplesL;
+    video->currPic->PicNum = CurrPicNum;
+}
+
+/* to release skipped frame after encoding */
+OSCL_EXPORT_REF void DPBReleaseCurrentFrame(AVCHandle *avcHandle, AVCCommonObj *video)
+{
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int ii;
+
+    video->currFS->IsOutputted = 3; // return this buffer.
+
+#ifdef PV_MEMORY_POOL /* for non-memory pool, no need to do anything */
+
+    /* search for current frame index */
+    ii = dpb->num_fs;
+    while (ii--)
+    {
+        if (dpb->fs[ii] == video->currFS)
+        {
+            avcHandle->CBAVC_FrameUnbind(avcHandle->userData, ii);
+            break;
+        }
+    }
+#endif
+
+    return ;
+}
+
+/* see subclause 8.2.5.1 */
+OSCL_EXPORT_REF AVCStatus StorePictureInDPB(AVCHandle *avcHandle, AVCCommonObj *video)
+{
+    AVCStatus status;
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    int ii, num_ref;
+
+    /* number 1 of 8.2.5.1, we handle gaps in frame_num differently without using the memory */
+    /* to be done!!!! */
+
+    /* number 3 of 8.2.5.1 */
+    if (video->nal_unit_type == AVC_NALTYPE_IDR)
+    {
+        for (ii = 0; ii < dpb->num_fs; ii++)
+        {
+            if (dpb->fs[ii] != video->currFS) /* not current frame */
+            {
+                dpb->fs[ii]->IsReference = 0; /* mark as unused for reference */
+                dpb->fs[ii]->IsLongTerm = 0;  /* but still used until output */
+                dpb->fs[ii]->IsOutputted |= 0x02;
+#ifdef PV_MEMORY_POOL
+                if (dpb->fs[ii]->IsOutputted == 3)
+                {
+                    avcHandle->CBAVC_FrameUnbind(avcHandle->userData, ii);
+                }
+#endif
+            }
+        }
+
+        video->currPic->isReference = TRUE;
+        video->currFS->IsReference = 3;
+
+        if (sliceHdr->long_term_reference_flag == 0)
+        {
+            video->currPic->isLongTerm = FALSE;
+            video->currFS->IsLongTerm = 0;
+            video->MaxLongTermFrameIdx = -1;
+        }
+        else
+        {
+            video->currPic->isLongTerm = TRUE;
+            video->currFS->IsLongTerm = 3;
+            video->currFS->LongTermFrameIdx = 0;
+            video->MaxLongTermFrameIdx = 0;
+        }
+        if (sliceHdr->no_output_of_prior_pics_flag)
+        {
+            for (ii = 0; ii < dpb->num_fs; ii++)
+            {
+                if (dpb->fs[ii] != video->currFS) /* not current frame */
+                {
+                    dpb->fs[ii]->IsOutputted = 3;
+#ifdef PV_MEMORY_POOL
+                    avcHandle->CBAVC_FrameUnbind(avcHandle->userData, ii);
+#endif
+                }
+            }
+        }
+        video->mem_mgr_ctrl_eq_5 = TRUE;    /* flush reference frames MC_FIX */
+    }
+    else
+    {
+        if (video->currPic->isReference == TRUE)
+        {
+            if (sliceHdr->adaptive_ref_pic_marking_mode_flag == 0)
+            {
+                status = sliding_window_process(avcHandle, video, dpb); /* we may have to do this after adaptive_memory_marking */
+            }
+            else
+            {
+                status = adaptive_memory_marking(avcHandle, video, dpb, sliceHdr);
+            }
+            if (status != AVC_SUCCESS)
+            {
+                return status;
+            }
+        }
+    }
+    /* number 4 of 8.2.5.1 */
+    /* This basically says every frame must be at least used for short-term ref. */
+    /* Need to be revisited!!! */
+    /* look at insert_picture_in_dpb() */
+
+
+
+    if (video->nal_unit_type != AVC_NALTYPE_IDR && video->currPic->isLongTerm == FALSE)
+    {
+        if (video->currPic->isReference)
+        {
+            video->currFS->IsReference = 3;
+        }
+        else
+        {
+            video->currFS->IsReference = 0;
+        }
+        video->currFS->IsLongTerm = 0;
+    }
+
+    /* check if number of reference frames doesn't exceed num_ref_frames */
+    num_ref = 0;
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii]->IsReference)
+        {
+            num_ref++;
+        }
+    }
+
+    if (num_ref > (int)video->currSeqParams->num_ref_frames)
+    {
+        return AVC_FAIL; /* out of range */
+    }
+
+    return AVC_SUCCESS;
+}
+
+
+AVCStatus sliding_window_process(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb)
+{
+    int ii, numShortTerm, numLongTerm;
+    int32 MinFrameNumWrap;
+    int MinIdx;
+
+
+    numShortTerm = 0;
+    numLongTerm = 0;
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii] != video->currFS) /* do not count the current frame */
+        {
+            if (dpb->fs[ii]->IsLongTerm)
+            {
+                numLongTerm++;
+            }
+            else if (dpb->fs[ii]->IsReference)
+            {
+                numShortTerm++;
+            }
+        }
+    }
+
+    while (numShortTerm + numLongTerm >= (int)video->currSeqParams->num_ref_frames)
+    {
+        /* get short-term ref frame with smallest PicOrderCnt */
+        /* this doesn't work for all I-slice clip since PicOrderCnt will not be initialized */
+
+        MinFrameNumWrap = 0x7FFFFFFF;
+        MinIdx = -1;
+        for (ii = 0; ii < dpb->num_fs; ii++)
+        {
+            if (dpb->fs[ii]->IsReference && !dpb->fs[ii]->IsLongTerm)
+            {
+                if (dpb->fs[ii]->FrameNumWrap < MinFrameNumWrap)
+                {
+                    MinFrameNumWrap = dpb->fs[ii]->FrameNumWrap;
+                    MinIdx = ii;
+                }
+            }
+        }
+        if (MinIdx < 0) /* something wrong, impossible */
+        {
+            return AVC_FAIL;
+        }
+
+        /* mark the frame with smallest PicOrderCnt to be unused for reference */
+        dpb->fs[MinIdx]->IsReference = 0;
+        dpb->fs[MinIdx]->IsLongTerm = 0;
+        dpb->fs[MinIdx]->frame.isReference = FALSE;
+        dpb->fs[MinIdx]->frame.isLongTerm = FALSE;
+        dpb->fs[MinIdx]->IsOutputted |= 0x02;
+#ifdef PV_MEMORY_POOL
+        if (dpb->fs[MinIdx]->IsOutputted == 3)
+        {
+            avcHandle->CBAVC_FrameUnbind(avcHandle->userData, MinIdx);
+        }
+#endif
+        numShortTerm--;
+    }
+    return AVC_SUCCESS;
+}
+
+/* see subclause 8.2.5.4 */
+AVCStatus adaptive_memory_marking(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, AVCSliceHeader *sliceHdr)
+{
+    int ii;
+
+    ii = 0;
+    while (ii < MAX_DEC_REF_PIC_MARKING && sliceHdr->memory_management_control_operation[ii] != 0)
+    {
+        switch (sliceHdr->memory_management_control_operation[ii])
+        {
+            case 1:
+                MemMgrCtrlOp1(avcHandle, video, dpb, sliceHdr->difference_of_pic_nums_minus1[ii]);
+                //      update_ref_list(dpb);
+                break;
+            case 2:
+                MemMgrCtrlOp2(avcHandle, dpb, sliceHdr->long_term_pic_num[ii]);
+                break;
+            case 3:
+                MemMgrCtrlOp3(avcHandle, video, dpb, sliceHdr->difference_of_pic_nums_minus1[ii], sliceHdr->long_term_frame_idx[ii]);
+                break;
+            case 4:
+                MemMgrCtrlOp4(avcHandle, video, dpb, sliceHdr->max_long_term_frame_idx_plus1[ii]);
+                break;
+            case 5:
+                MemMgrCtrlOp5(avcHandle, video, dpb);
+                video->currFS->FrameNum = 0;    //
+                video->currFS->PicOrderCnt = 0;
+                break;
+            case 6:
+                MemMgrCtrlOp6(avcHandle, video, dpb, sliceHdr->long_term_frame_idx[ii]);
+                break;
+        }
+        ii++;
+    }
+
+    if (ii == MAX_DEC_REF_PIC_MARKING)
+    {
+        return AVC_FAIL; /* exceed the limit */
+    }
+
+    return AVC_SUCCESS;
+}
+
+
+/* see subclause 8.2.5.4.1, mark short-term picture as "unused for reference" */
+void MemMgrCtrlOp1(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, int difference_of_pic_nums_minus1)
+{
+    int picNumX, ii;
+
+    picNumX = video->CurrPicNum - (difference_of_pic_nums_minus1 + 1);
+
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii]->IsReference == 3 && dpb->fs[ii]->IsLongTerm == 0)
+        {
+            if (dpb->fs[ii]->frame.PicNum == picNumX)
+            {
+                unmark_for_reference(avcHandle, dpb, ii);
+                return ;
+            }
+        }
+    }
+
+    return ;
+}
+
+/* see subclause 8.2.5.4.2 mark long-term picture as "unused for reference" */
+void MemMgrCtrlOp2(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, int long_term_pic_num)
+{
+    int ii;
+
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii]->IsLongTerm == 3)
+        {
+            if (dpb->fs[ii]->frame.LongTermPicNum == long_term_pic_num)
+            {
+                unmark_for_reference(avcHandle, dpb, ii);
+            }
+        }
+    }
+}
+
+/* see subclause 8.2.5.4.3 assign LongTermFrameIdx to a short-term ref picture */
+void MemMgrCtrlOp3(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint difference_of_pic_nums_minus1,
+                   uint long_term_frame_idx)
+{
+    int picNumX, ii;
+
+    picNumX = video->CurrPicNum - (difference_of_pic_nums_minus1 + 1);
+
+    /* look for fs[i] with long_term_frame_idx */
+
+    unmark_long_term_frame_for_reference_by_frame_idx(avcHandle, dpb, long_term_frame_idx);
+
+
+    /* now mark the picture with picNumX to long term frame idx */
+
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii]->IsReference == 3)
+        {
+            if ((dpb->fs[ii]->frame.isLongTerm == FALSE) && (dpb->fs[ii]->frame.PicNum == picNumX))
+            {
+                dpb->fs[ii]->LongTermFrameIdx = long_term_frame_idx;
+                dpb->fs[ii]->frame.LongTermPicNum = long_term_frame_idx;
+
+                dpb->fs[ii]->frame.isLongTerm = TRUE;
+
+                dpb->fs[ii]->IsLongTerm = 3;
+                return;
+            }
+        }
+    }
+
+}
+
+/* see subclause 8.2.5.4.4, MaxLongTermFrameIdx */
+void MemMgrCtrlOp4(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint max_long_term_frame_idx_plus1)
+{
+    int ii;
+
+    video->MaxLongTermFrameIdx = max_long_term_frame_idx_plus1 - 1;
+
+    /* then mark long term frame with exceeding LongTermFrameIdx to unused for reference. */
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+        if (dpb->fs[ii]->IsLongTerm && dpb->fs[ii] != video->currFS)
+        {
+            if (dpb->fs[ii]->LongTermFrameIdx > video->MaxLongTermFrameIdx)
+            {
+                unmark_for_reference(avcHandle, dpb, ii);
+            }
+        }
+    }
+}
+
+/* see subclause 8.2.5.4.5 mark all reference picture as "unused for reference" and setting
+MaxLongTermFrameIdx to "no long-term frame indices" */
+void MemMgrCtrlOp5(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb)
+{
+    int ii;
+
+    video->MaxLongTermFrameIdx = -1;
+    for (ii = 0; ii < dpb->num_fs; ii++) /* including the current frame ??????*/
+    {
+        if (dpb->fs[ii] != video->currFS) // MC_FIX
+        {
+            unmark_for_reference(avcHandle, dpb, ii);
+        }
+    }
+
+    video->mem_mgr_ctrl_eq_5 = TRUE;
+}
+
+/* see subclause 8.2.5.4.6 assing long-term frame index to the current picture */
+void MemMgrCtrlOp6(AVCHandle *avcHandle, AVCCommonObj *video, AVCDecPicBuffer *dpb, uint long_term_frame_idx)
+{
+
+    unmark_long_term_frame_for_reference_by_frame_idx(avcHandle, dpb, long_term_frame_idx);
+    video->currFS->IsLongTerm = 3;
+    video->currFS->IsReference = 3;
+
+    video->currPic->isLongTerm = TRUE;
+    video->currPic->isReference = TRUE;
+    video->currFS->LongTermFrameIdx = long_term_frame_idx;
+}
+
+
+void unmark_for_reference(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, uint idx)
+{
+
+    AVCFrameStore *fs = dpb->fs[idx];
+    fs->frame.isReference = FALSE;
+    fs->frame.isLongTerm = FALSE;
+
+    fs->IsLongTerm = 0;
+    fs->IsReference = 0;
+    fs->IsOutputted |= 0x02;
+#ifdef PV_MEMORY_POOL
+    if (fs->IsOutputted == 3)
+    {
+        avcHandle->CBAVC_FrameUnbind(avcHandle->userData, idx);
+    }
+#endif
+    return ;
+}
+
+void unmark_long_term_frame_for_reference_by_frame_idx(AVCHandle *avcHandle, AVCDecPicBuffer *dpb, uint long_term_frame_idx)
+{
+    int ii;
+    for (ii = 0; ii < dpb->num_fs; ii++)
+    {
+
+        if (dpb->fs[ii]->IsLongTerm && (dpb->fs[ii]->LongTermFrameIdx == (int)long_term_frame_idx))
+        {
+            unmark_for_reference(avcHandle, dpb, ii);
+        }
+
+    }
+}
+
+
diff --git a/media/libstagefright/codecs/avc/common/src/fmo.cpp b/media/libstagefright/codecs/avc/common/src/fmo.cpp
new file mode 100644
index 0000000..d66eba3
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/src/fmo.cpp
@@ -0,0 +1,249 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include <string.h>
+
+#include "avclib_common.h"
+
+/* see subclause 8.2.2 Decoding process for macroblock to slice group map */
+OSCL_EXPORT_REF AVCStatus FMOInit(AVCCommonObj *video)
+{
+    AVCPicParamSet *currPPS = video->currPicParams;
+    int *MbToSliceGroupMap = video->MbToSliceGroupMap;
+    int PicSizeInMapUnits = video->PicSizeInMapUnits;
+    int PicWidthInMbs = video->PicWidthInMbs;
+
+    if (currPPS->num_slice_groups_minus1 == 0)
+    {
+        memset(video->MbToSliceGroupMap, 0, video->PicSizeInMapUnits*sizeof(uint));
+    }
+    else
+    {
+        switch (currPPS->slice_group_map_type)
+        {
+            case 0:
+                FmoGenerateType0MapUnitMap(MbToSliceGroupMap, currPPS->run_length_minus1, currPPS->num_slice_groups_minus1, PicSizeInMapUnits);
+                break;
+            case 1:
+                FmoGenerateType1MapUnitMap(MbToSliceGroupMap, PicWidthInMbs, currPPS->num_slice_groups_minus1, PicSizeInMapUnits);
+                break;
+            case 2:
+                FmoGenerateType2MapUnitMap(currPPS, MbToSliceGroupMap, PicWidthInMbs, currPPS->num_slice_groups_minus1, PicSizeInMapUnits);
+                break;
+            case 3:
+                FmoGenerateType3MapUnitMap(video, currPPS, MbToSliceGroupMap, PicWidthInMbs);
+                break;
+            case 4:
+                FmoGenerateType4MapUnitMap(MbToSliceGroupMap, video->MapUnitsInSliceGroup0, currPPS->slice_group_change_direction_flag, PicSizeInMapUnits);
+                break;
+            case 5:
+                FmoGenerateType5MapUnitMap(MbToSliceGroupMap, video, currPPS->slice_group_change_direction_flag, PicSizeInMapUnits);
+                break;
+            case 6:
+                FmoGenerateType6MapUnitMap(MbToSliceGroupMap, (int*)currPPS->slice_group_id, PicSizeInMapUnits);
+                break;
+            default:
+                return AVC_FAIL; /* out of range, shouldn't come this far */
+        }
+    }
+
+    return AVC_SUCCESS;
+}
+
+/* see subclause 8.2.2.1 interleaved slice group map type*/
+void FmoGenerateType0MapUnitMap(int *mapUnitToSliceGroupMap, uint *run_length_minus1, uint num_slice_groups_minus1, uint PicSizeInMapUnits)
+{
+    uint iGroup, j;
+    uint i = 0;
+    do
+    {
+        for (iGroup = 0;
+                (iGroup <= num_slice_groups_minus1) && (i < PicSizeInMapUnits);
+                i += run_length_minus1[iGroup++] + 1)
+        {
+            for (j = 0; j <= run_length_minus1[ iGroup ] && i + j < PicSizeInMapUnits; j++)
+                mapUnitToSliceGroupMap[i+j] = iGroup;
+        }
+    }
+    while (i < PicSizeInMapUnits);
+}
+
+/* see subclause 8.2.2.2 dispersed slice group map type*/
+void FmoGenerateType1MapUnitMap(int *mapUnitToSliceGroupMap, int PicWidthInMbs, uint num_slice_groups_minus1, uint PicSizeInMapUnits)
+{
+    uint i;
+    for (i = 0; i < PicSizeInMapUnits; i++)
+    {
+        mapUnitToSliceGroupMap[i] = ((i % PicWidthInMbs) + (((i / PicWidthInMbs) * (num_slice_groups_minus1 + 1)) / 2))
+                                    % (num_slice_groups_minus1 + 1);
+    }
+}
+
+/* see subclause 8.2.2.3 foreground with left-over slice group map type */
+void FmoGenerateType2MapUnitMap(AVCPicParamSet *pps, int *mapUnitToSliceGroupMap, int PicWidthInMbs,
+                                uint num_slice_groups_minus1, uint PicSizeInMapUnits)
+{
+    int iGroup;
+    uint i, x, y;
+    uint yTopLeft, xTopLeft, yBottomRight, xBottomRight;
+
+    for (i = 0; i < PicSizeInMapUnits; i++)
+    {
+        mapUnitToSliceGroupMap[ i ] = num_slice_groups_minus1;
+    }
+
+    for (iGroup = num_slice_groups_minus1 - 1 ; iGroup >= 0; iGroup--)
+    {
+        yTopLeft = pps->top_left[ iGroup ] / PicWidthInMbs;
+        xTopLeft = pps->top_left[ iGroup ] % PicWidthInMbs;
+        yBottomRight = pps->bottom_right[ iGroup ] / PicWidthInMbs;
+        xBottomRight = pps->bottom_right[ iGroup ] % PicWidthInMbs;
+        for (y = yTopLeft; y <= yBottomRight; y++)
+        {
+            for (x = xTopLeft; x <= xBottomRight; x++)
+            {
+                mapUnitToSliceGroupMap[ y * PicWidthInMbs + x ] = iGroup;
+            }
+        }
+    }
+}
+
+
+/* see subclause 8.2.2.4 box-out slice group map type */
+/* follow the text rather than the JM, it's quite different. */
+void FmoGenerateType3MapUnitMap(AVCCommonObj *video, AVCPicParamSet* pps, int *mapUnitToSliceGroupMap,
+                                int PicWidthInMbs)
+{
+    uint i, k;
+    int leftBound, topBound, rightBound, bottomBound;
+    int x, y, xDir, yDir;
+    int mapUnitVacant;
+    uint PicSizeInMapUnits = video->PicSizeInMapUnits;
+    uint MapUnitsInSliceGroup0 = video->MapUnitsInSliceGroup0;
+
+    for (i = 0; i < PicSizeInMapUnits; i++)
+    {
+        mapUnitToSliceGroupMap[ i ] = 1;
+    }
+
+    x = (PicWidthInMbs - pps->slice_group_change_direction_flag) / 2;
+    y = (video->PicHeightInMapUnits - pps->slice_group_change_direction_flag) / 2;
+
+    leftBound   = x;
+    topBound    = y;
+    rightBound  = x;
+    bottomBound = y;
+
+    xDir =  pps->slice_group_change_direction_flag - 1;
+    yDir =  pps->slice_group_change_direction_flag;
+
+    for (k = 0; k < MapUnitsInSliceGroup0; k += mapUnitVacant)
+    {
+        mapUnitVacant = (mapUnitToSliceGroupMap[ y * PicWidthInMbs + x ]  ==  1);
+        if (mapUnitVacant)
+        {
+            mapUnitToSliceGroupMap[ y * PicWidthInMbs + x ] = 0;
+        }
+
+        if (xDir  ==  -1  &&  x  ==  leftBound)
+        {
+            leftBound = AVC_MAX(leftBound - 1, 0);
+            x = leftBound;
+            xDir = 0;
+            yDir = 2 * pps->slice_group_change_direction_flag - 1;
+        }
+        else if (xDir  ==  1  &&  x  ==  rightBound)
+        {
+            rightBound = AVC_MIN(rightBound + 1, (int)PicWidthInMbs - 1);
+            x = rightBound;
+            xDir = 0;
+            yDir = 1 - 2 * pps->slice_group_change_direction_flag;
+        }
+        else if (yDir  ==  -1  &&  y  ==  topBound)
+        {
+            topBound = AVC_MAX(topBound - 1, 0);
+            y = topBound;
+            xDir = 1 - 2 * pps->slice_group_change_direction_flag;
+            yDir = 0;
+        }
+        else  if (yDir  ==  1  &&  y  ==  bottomBound)
+        {
+            bottomBound = AVC_MIN(bottomBound + 1, (int)video->PicHeightInMapUnits - 1);
+            y = bottomBound;
+            xDir = 2 * pps->slice_group_change_direction_flag - 1;
+            yDir = 0;
+        }
+        else
+        {
+            x = x + xDir;
+            y = y + yDir;
+        }
+    }
+}
+
+/* see subclause 8.2.2.5 raster scan slice group map types */
+void FmoGenerateType4MapUnitMap(int *mapUnitToSliceGroupMap, int MapUnitsInSliceGroup0, int slice_group_change_direction_flag, uint PicSizeInMapUnits)
+{
+    uint sizeOfUpperLeftGroup = slice_group_change_direction_flag ? (PicSizeInMapUnits - MapUnitsInSliceGroup0) : MapUnitsInSliceGroup0;
+
+    uint i;
+
+    for (i = 0; i < PicSizeInMapUnits; i++)
+        if (i < sizeOfUpperLeftGroup)
+            mapUnitToSliceGroupMap[ i ] = 1 - slice_group_change_direction_flag;
+        else
+            mapUnitToSliceGroupMap[ i ] = slice_group_change_direction_flag;
+
+}
+
+/* see subclause 8.2.2.6, wipe slice group map type. */
+void FmoGenerateType5MapUnitMap(int *mapUnitToSliceGroupMap, AVCCommonObj *video,
+                                int slice_group_change_direction_flag, uint PicSizeInMapUnits)
+{
+    int PicWidthInMbs = video->PicWidthInMbs;
+    int PicHeightInMapUnits = video->PicHeightInMapUnits;
+    int MapUnitsInSliceGroup0 = video->MapUnitsInSliceGroup0;
+    int sizeOfUpperLeftGroup = slice_group_change_direction_flag ? (PicSizeInMapUnits - MapUnitsInSliceGroup0) : MapUnitsInSliceGroup0;
+    int i, j, k = 0;
+
+    for (j = 0; j < PicWidthInMbs; j++)
+    {
+        for (i = 0; i < PicHeightInMapUnits; i++)
+        {
+            if (k++ < sizeOfUpperLeftGroup)
+            {
+                mapUnitToSliceGroupMap[ i * PicWidthInMbs + j ] = 1 - slice_group_change_direction_flag;
+            }
+            else
+            {
+                mapUnitToSliceGroupMap[ i * PicWidthInMbs + j ] = slice_group_change_direction_flag;
+            }
+        }
+    }
+}
+
+/* see subclause 8.2.2.7, explicit slice group map */
+void FmoGenerateType6MapUnitMap(int *mapUnitToSliceGroupMap, int *slice_group_id, uint PicSizeInMapUnits)
+{
+    uint i;
+    for (i = 0; i < PicSizeInMapUnits; i++)
+    {
+        mapUnitToSliceGroupMap[i] = slice_group_id[i];
+    }
+}
+
+
diff --git a/media/libstagefright/codecs/avc/common/src/mb_access.cpp b/media/libstagefright/codecs/avc/common/src/mb_access.cpp
new file mode 100644
index 0000000..414b8f7
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/src/mb_access.cpp
@@ -0,0 +1,471 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include <string.h>
+
+#include "avclib_common.h"
+
+OSCL_EXPORT_REF void InitNeighborAvailability(AVCCommonObj *video, int mbNum)
+{
+    int PicWidthInMbs = video->PicWidthInMbs;
+
+    // do frame-only and postpone intraAvail calculattion
+    video->mbAddrA = mbNum - 1;
+    video->mbAddrB = mbNum - PicWidthInMbs;
+    video->mbAddrC = mbNum - PicWidthInMbs + 1;
+    video->mbAddrD = mbNum - PicWidthInMbs - 1;
+
+    video->mbAvailA = video->mbAvailB = video->mbAvailC = video->mbAvailD = 0;
+    if (video->mb_x)
+    {
+        video->mbAvailA = (video->mblock[video->mbAddrA].slice_id == video->currMB->slice_id);
+        if (video->mb_y)
+        {
+            video->mbAvailD = (video->mblock[video->mbAddrD].slice_id == video->currMB->slice_id);
+        }
+    }
+
+    if (video->mb_y)
+    {
+        video->mbAvailB = (video->mblock[video->mbAddrB].slice_id == video->currMB->slice_id);
+        if (video->mb_x < (PicWidthInMbs - 1))
+        {
+            video->mbAvailC = (video->mblock[video->mbAddrC].slice_id == video->currMB->slice_id);
+        }
+    }
+    return ;
+}
+
+bool mb_is_available(AVCMacroblock *mblock, uint PicSizeInMbs, int mbAddr, int currMbAddr)
+{
+    if (mbAddr < 0 || mbAddr >= (int)PicSizeInMbs)
+    {
+        return FALSE;
+    }
+
+    if (mblock[mbAddr].slice_id != mblock[currMbAddr].slice_id)
+    {
+        return FALSE;
+    }
+
+    return TRUE;
+}
+
+OSCL_EXPORT_REF int predict_nnz(AVCCommonObj *video, int i, int j)
+{
+    int pred_nnz = 0;
+    int cnt      = 1;
+    AVCMacroblock *tempMB;
+
+    /* left block */
+    /*getLuma4x4Neighbour(video, mb_nr, i, j, -1, 0, &pix);
+    leftMB = video->mblock + pix.mb_addr; */
+    /* replace the above with below (won't work for field decoding),  1/19/04 */
+
+    if (i)
+    {
+        pred_nnz = video->currMB->nz_coeff[(j<<2)+i-1];
+    }
+    else
+    {
+        if (video->mbAvailA)
+        {
+            tempMB = video->mblock + video->mbAddrA;
+            pred_nnz = tempMB->nz_coeff[(j<<2)+3];
+        }
+        else
+        {
+            cnt = 0;
+        }
+    }
+
+
+    /* top block */
+    /*getLuma4x4Neighbour(video, mb_nr, i, j, 0, -1, &pix);
+    topMB = video->mblock + pix.mb_addr;*/
+    /* replace the above with below (won't work for field decoding),  1/19/04 */
+
+    if (j)
+    {
+        pred_nnz += video->currMB->nz_coeff[((j-1)<<2)+i];
+        cnt++;
+    }
+    else
+    {
+        if (video->mbAvailB)
+        {
+            tempMB = video->mblock + video->mbAddrB;
+            pred_nnz += tempMB->nz_coeff[12+i];
+            cnt++;
+        }
+    }
+
+
+    if (cnt == 2)
+    {
+        pred_nnz = (pred_nnz + 1) >> 1;
+    }
+
+    return pred_nnz;
+
+}
+
+
+OSCL_EXPORT_REF int predict_nnz_chroma(AVCCommonObj *video, int i, int j)
+{
+    int pred_nnz = 0;
+    int cnt      = 1;
+    AVCMacroblock *tempMB;
+
+    /* left block */
+    /*getChroma4x4Neighbour(video, mb_nr, i%2, j-4, -1, 0, &pix);
+    leftMB = video->mblock + pix.mb_addr;*/
+    /* replace the above with below (won't work for field decoding),  1/19/04 */
+    if (i&1)
+    {
+        pred_nnz = video->currMB->nz_coeff[(j<<2)+i-1];
+
+    }
+    else
+    {
+        if (video->mbAvailA)
+        {
+            tempMB = video->mblock + video->mbAddrA;
+            pred_nnz = tempMB->nz_coeff[(j<<2)+i+1];
+        }
+        else
+        {
+            cnt = 0;
+        }
+    }
+
+
+    /* top block */
+    /*getChroma4x4Neighbour(video, mb_nr, i%2, j-4, 0, -1, &pix);
+    topMB = video->mblock + pix.mb_addr;*/
+    /* replace the above with below (won't work for field decoding),  1/19/04 */
+
+    if (j&1)
+    {
+        pred_nnz += video->currMB->nz_coeff[((j-1)<<2)+i];
+        cnt++;
+    }
+    else
+    {
+        if (video->mbAvailB)
+        {
+            tempMB = video->mblock + video->mbAddrB;
+            pred_nnz += tempMB->nz_coeff[20+i];
+            cnt++;
+        }
+
+    }
+
+    if (cnt == 2)
+    {
+        pred_nnz = (pred_nnz + 1) >> 1;
+    }
+
+    return pred_nnz;
+}
+
+OSCL_EXPORT_REF void GetMotionVectorPredictor(AVCCommonObj *video, int encFlag)
+{
+    AVCMacroblock *currMB = video->currMB;
+    AVCMacroblock *MB_A, *MB_B, *MB_C, *MB_D;
+    int block_x, block_y, block_x_1, block_y_1, new_block_x;
+    int mbPartIdx, subMbPartIdx, offset_indx;
+    int16 *mv, pmv_x, pmv_y;
+    int nmSubMbHeight, nmSubMbWidth, mbPartIdx_X, mbPartIdx_Y;
+    int avail_a, avail_b, avail_c;
+    const static uint32 C = 0x5750;
+    int i, j, offset_MbPart_indx, refIdxLXA, refIdxLXB, refIdxLXC = 0, curr_ref_idx;
+    int pmv_A_x, pmv_B_x, pmv_C_x = 0, pmv_A_y, pmv_B_y, pmv_C_y = 0;
+
+    /* we have to take care of Intra/skip blocks somewhere, i.e. set MV to  0 and set ref to -1! */
+    /* we have to populate refIdx as well */
+
+
+    MB_A = &video->mblock[video->mbAddrA];
+    MB_B = &video->mblock[video->mbAddrB];
+
+
+    if (currMB->mbMode == AVC_SKIP /* && !encFlag */) /* only for decoder */
+    {
+        currMB->ref_idx_L0[0] = currMB->ref_idx_L0[1] = currMB->ref_idx_L0[2] = currMB->ref_idx_L0[3] = 0;
+        if (video->mbAvailA && video->mbAvailB)
+        {
+            if ((MB_A->ref_idx_L0[1] == 0 && MB_A->mvL0[3] == 0) ||
+                    (MB_B->ref_idx_L0[2] == 0 && MB_B->mvL0[12] == 0))
+            {
+                memset(currMB->mvL0, 0, sizeof(int32)*16);
+                return;
+            }
+        }
+        else
+        {
+            memset(currMB->mvL0, 0, sizeof(int32)*16);
+            return;
+        }
+        video->mvd_l0[0][0][0] = 0;
+        video->mvd_l0[0][0][1] = 0;
+    }
+
+    MB_C = &video->mblock[video->mbAddrC];
+    MB_D = &video->mblock[video->mbAddrD];
+
+    offset_MbPart_indx = 0;
+    for (mbPartIdx = 0; mbPartIdx < currMB->NumMbPart; mbPartIdx++)
+    {
+        offset_indx = 0;
+        nmSubMbHeight = currMB->SubMbPartHeight[mbPartIdx] >> 2;
+        nmSubMbWidth = currMB->SubMbPartWidth[mbPartIdx] >> 2;
+        mbPartIdx_X = ((mbPartIdx + offset_MbPart_indx) & 1) << 1;
+        mbPartIdx_Y = (mbPartIdx + offset_MbPart_indx) & 2;
+
+        for (subMbPartIdx = 0; subMbPartIdx < currMB->NumSubMbPart[mbPartIdx]; subMbPartIdx++)
+        {
+            block_x = mbPartIdx_X + ((subMbPartIdx + offset_indx) & 1);
+            block_y = mbPartIdx_Y + (((subMbPartIdx + offset_indx) >> 1) & 1);
+
+            block_x_1 = block_x - 1;
+            block_y_1 = block_y - 1;
+            refIdxLXA = refIdxLXB = refIdxLXC = -1;
+            pmv_A_x = pmv_A_y = pmv_B_x = pmv_B_y = pmv_C_x = pmv_C_y = 0;
+
+            if (block_x)
+            {
+                avail_a = 1;
+                refIdxLXA = currMB->ref_idx_L0[(block_y & 2) + (block_x_1 >> 1)];
+                mv = (int16*)(currMB->mvL0 + (block_y << 2) + block_x_1);
+                pmv_A_x = *mv++;
+                pmv_A_y = *mv;
+            }
+            else
+            {
+                avail_a = video->mbAvailA;
+                if (avail_a)
+                {
+                    refIdxLXA = MB_A->ref_idx_L0[(block_y & 2) + 1];
+                    mv = (int16*)(MB_A->mvL0 + (block_y << 2) + 3);
+                    pmv_A_x = *mv++;
+                    pmv_A_y = *mv;
+                }
+            }
+
+            if (block_y)
+            {
+                avail_b = 1;
+                refIdxLXB = currMB->ref_idx_L0[(block_y_1 & 2) + (block_x >> 1)];
+                mv = (int16*)(currMB->mvL0 + (block_y_1 << 2) + block_x);
+                pmv_B_x = *mv++;
+                pmv_B_y = *mv;
+            }
+
+            else
+            {
+                avail_b = video->mbAvailB;
+                if (avail_b)
+                {
+                    refIdxLXB = MB_B->ref_idx_L0[2 + (block_x >> 1)];
+                    mv = (int16*)(MB_B->mvL0 + 12 + block_x);
+                    pmv_B_x = *mv++;
+                    pmv_B_y = *mv;
+                }
+            }
+
+            new_block_x = block_x + (currMB->SubMbPartWidth[mbPartIdx] >> 2) - 1;
+            avail_c = (C >> ((block_y << 2) + new_block_x)) & 0x1;
+
+            if (avail_c)
+            {
+                /* it guaranteed that block_y > 0 && new_block_x<3 ) */
+                refIdxLXC = currMB->ref_idx_L0[(block_y_1 & 2) + ((new_block_x+1) >> 1)];
+                mv = (int16*)(currMB->mvL0 + (block_y_1 << 2) + (new_block_x + 1));
+                pmv_C_x = *mv++;
+                pmv_C_y = *mv;
+            }
+            else
+            {
+                if (block_y == 0 && new_block_x < 3)
+                {
+                    avail_c = video->mbAvailB;
+                    if (avail_c)
+                    {
+                        refIdxLXC = MB_B->ref_idx_L0[2 + ((new_block_x+1)>>1)];
+                        mv = (int16*)(MB_B->mvL0 + 12 + (new_block_x + 1));
+                        pmv_C_x = *mv++;
+                        pmv_C_y = *mv;
+                    }
+                }
+                else if (block_y == 0 && new_block_x == 3)
+                {
+                    avail_c = video->mbAvailC;
+                    if (avail_c)
+                    {
+                        refIdxLXC = MB_C->ref_idx_L0[2];
+                        mv = (int16*)(MB_C->mvL0 + 12);
+                        pmv_C_x = *mv++;
+                        pmv_C_y = *mv;
+                    }
+                }
+
+                if (avail_c == 0)
+                {   /* check D */
+                    if (block_x && block_y)
+                    {
+                        avail_c = 1;
+                        refIdxLXC =  currMB->ref_idx_L0[(block_y_1 & 2) + (block_x_1 >> 1)];
+                        mv = (int16*)(currMB->mvL0 + (block_y_1 << 2) + block_x_1);
+                        pmv_C_x = *mv++;
+                        pmv_C_y = *mv;
+                    }
+                    else if (block_y)
+                    {
+                        avail_c = video->mbAvailA;
+                        if (avail_c)
+                        {
+                            refIdxLXC =  MB_A->ref_idx_L0[(block_y_1 & 2) + 1];
+                            mv = (int16*)(MB_A->mvL0 + (block_y_1 << 2) + 3);
+                            pmv_C_x = *mv++;
+                            pmv_C_y = *mv;
+                        }
+                    }
+                    else if (block_x)
+                    {
+                        avail_c = video->mbAvailB;
+                        if (avail_c)
+                        {
+                            refIdxLXC = MB_B->ref_idx_L0[2 + (block_x_1 >> 1)];
+                            mv = (int16*)(MB_B->mvL0 + 12 + block_x_1);
+                            pmv_C_x = *mv++;
+                            pmv_C_y = *mv;
+                        }
+                    }
+                    else
+                    {
+                        avail_c = video->mbAvailD;
+                        if (avail_c)
+                        {
+                            refIdxLXC = MB_D->ref_idx_L0[3];
+                            mv = (int16*)(MB_D->mvL0 + 15);
+                            pmv_C_x = *mv++;
+                            pmv_C_y = *mv;
+                        }
+                    }
+                }
+            }
+
+            offset_indx = currMB->SubMbPartWidth[mbPartIdx] >> 3;
+
+            curr_ref_idx = currMB->ref_idx_L0[(block_y & 2) + (block_x >> 1)];
+
+            if (avail_a && !(avail_b || avail_c))
+            {
+                pmv_x = pmv_A_x;
+                pmv_y = pmv_A_y;
+            }
+            else if (((curr_ref_idx == refIdxLXA) + (curr_ref_idx == refIdxLXB) + (curr_ref_idx == refIdxLXC)) == 1)
+            {
+                if (curr_ref_idx == refIdxLXA)
+                {
+                    pmv_x = pmv_A_x;
+                    pmv_y = pmv_A_y;
+                }
+                else if (curr_ref_idx == refIdxLXB)
+                {
+                    pmv_x = pmv_B_x;
+                    pmv_y = pmv_B_y;
+                }
+                else
+                {
+                    pmv_x = pmv_C_x;
+                    pmv_y = pmv_C_y;
+                }
+            }
+            else
+            {
+                pmv_x = AVC_MEDIAN(pmv_A_x, pmv_B_x, pmv_C_x);
+                pmv_y = AVC_MEDIAN(pmv_A_y, pmv_B_y, pmv_C_y);
+            }
+
+            /* overwrite if special case */
+            if (currMB->NumMbPart == 2)
+            {
+                if (currMB->MbPartWidth == 16)
+                {
+                    if (mbPartIdx == 0)
+                    {
+                        if (refIdxLXB == curr_ref_idx)
+                        {
+                            pmv_x = pmv_B_x;
+                            pmv_y = pmv_B_y;
+                        }
+                    }
+                    else if (refIdxLXA == curr_ref_idx)
+                    {
+                        pmv_x = pmv_A_x;
+                        pmv_y = pmv_A_y;
+                    }
+                }
+                else
+                {
+                    if (mbPartIdx == 0)
+                    {
+                        if (refIdxLXA == curr_ref_idx)
+                        {
+                            pmv_x = pmv_A_x;
+                            pmv_y = pmv_A_y;
+                        }
+                    }
+                    else if (refIdxLXC == curr_ref_idx)
+                    {
+                        pmv_x = pmv_C_x;
+                        pmv_y = pmv_C_y;
+                    }
+                }
+            }
+
+            mv = (int16*)(currMB->mvL0 + block_x + (block_y << 2));
+
+            if (encFlag) /* calculate residual MV video->mvd_l0 */
+            {
+                video->mvd_l0[mbPartIdx][subMbPartIdx][0] = *mv++ - pmv_x;
+                video->mvd_l0[mbPartIdx][subMbPartIdx][1] = *mv++ - pmv_y;
+            }
+            else    /* calculate original MV currMB->mvL0 */
+            {
+                pmv_x += video->mvd_l0[mbPartIdx][subMbPartIdx][0];
+                pmv_y += video->mvd_l0[mbPartIdx][subMbPartIdx][1];
+
+                for (i = 0; i < nmSubMbHeight; i++)
+                {
+                    for (j = 0; j < nmSubMbWidth; j++)
+                    {
+                        *mv++ = pmv_x;
+                        *mv++ = pmv_y;
+                    }
+                    mv += (8 - (j << 1));
+                }
+            }
+        }
+        offset_MbPart_indx = currMB->MbPartWidth >> 4;
+
+    }
+}
+
+
diff --git a/media/libstagefright/codecs/avc/common/src/reflist.cpp b/media/libstagefright/codecs/avc/common/src/reflist.cpp
new file mode 100644
index 0000000..4ddc7dd
--- /dev/null
+++ b/media/libstagefright/codecs/avc/common/src/reflist.cpp
@@ -0,0 +1,596 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avclib_common.h"
+
+/** see subclause 8.2.4 Decoding process for reference picture lists construction. */
+OSCL_EXPORT_REF void RefListInit(AVCCommonObj *video)
+{
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int slice_type = video->slice_type;
+    int i, list0idx;
+
+    AVCPictureData *tmp_s;
+
+    list0idx = 0;
+
+    if (slice_type == AVC_I_SLICE)
+    {
+        video->refList0Size = 0;
+        video->refList1Size = 0;
+
+        /* we still have to calculate FrameNumWrap to make sure that all I-slice clip
+        can perform sliding_window_operation properly. */
+
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if ((dpb->fs[i]->IsReference == 3) && (!dpb->fs[i]->IsLongTerm))
+            {
+                /* subclause 8.2.4.1 Decoding process for picture numbers. */
+                if (dpb->fs[i]->FrameNum > (int)sliceHdr->frame_num)
+                {
+                    dpb->fs[i]->FrameNumWrap = dpb->fs[i]->FrameNum - video->MaxFrameNum;
+                }
+                else
+                {
+                    dpb->fs[i]->FrameNumWrap = dpb->fs[i]->FrameNum;
+                }
+                dpb->fs[i]->frame.PicNum = dpb->fs[i]->FrameNumWrap;
+            }
+        }
+
+
+        return ;
+    }
+    if (slice_type == AVC_P_SLICE)
+    {
+        /* Calculate FrameNumWrap and PicNum */
+
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if ((dpb->fs[i]->IsReference == 3) && (!dpb->fs[i]->IsLongTerm))
+            {
+                /* subclause 8.2.4.1 Decoding process for picture numbers. */
+                if (dpb->fs[i]->FrameNum > (int)sliceHdr->frame_num)
+                {
+                    dpb->fs[i]->FrameNumWrap = dpb->fs[i]->FrameNum - video->MaxFrameNum;
+                }
+                else
+                {
+                    dpb->fs[i]->FrameNumWrap = dpb->fs[i]->FrameNum;
+                }
+                dpb->fs[i]->frame.PicNum = dpb->fs[i]->FrameNumWrap;
+                video->RefPicList0[list0idx++] = &(dpb->fs[i]->frame);
+            }
+        }
+
+        if (list0idx == 0)
+        {
+            dpb->fs[0]->IsReference = 3;
+            video->RefPicList0[0] = &(dpb->fs[0]->frame);
+            list0idx = 1;
+        }
+        /* order list 0 by PicNum from max to min, see subclause 8.2.4.2.1 */
+        SortPicByPicNum(video->RefPicList0, list0idx);
+        video->refList0Size = list0idx;
+
+        /* long term handling */
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if (dpb->fs[i]->IsLongTerm == 3)
+            {
+                /* subclause 8.2.4.1 Decoding process for picture numbers. */
+                dpb->fs[i]->frame.LongTermPicNum = dpb->fs[i]->LongTermFrameIdx;
+                video->RefPicList0[list0idx++] = &(dpb->fs[i]->frame);
+            }
+        }
+
+        /* order PicNum from min to max, see subclause 8.2.4.2.1  */
+        SortPicByPicNumLongTerm(&(video->RefPicList0[video->refList0Size]), list0idx - video->refList0Size);
+        video->refList0Size = list0idx;
+
+
+        video->refList1Size = 0;
+    }
+
+
+    if ((video->refList0Size == video->refList1Size) && (video->refList0Size > 1))
+    {
+        /* check if lists are identical, if yes swap first two elements of listX[1] */
+        /* last paragraph of subclause 8.2.4.2.4 */
+
+        for (i = 0; i < video->refList0Size; i++)
+        {
+            if (video->RefPicList0[i] != video->RefPicList1[i])
+            {
+                break;
+            }
+        }
+        if (i == video->refList0Size)
+        {
+            tmp_s = video->RefPicList1[0];
+            video->RefPicList1[0] = video->RefPicList1[1];
+            video->RefPicList1[1] = tmp_s;
+        }
+    }
+
+    /* set max size */
+    video->refList0Size = AVC_MIN(video->refList0Size, (int)video->sliceHdr->num_ref_idx_l0_active_minus1 + 1);
+    video->refList1Size = AVC_MIN(video->refList1Size, (int)video->sliceHdr->num_ref_idx_l1_active_minus1 + 1);
+
+    return ;
+}
+/* see subclause 8.2.4.3 */
+OSCL_EXPORT_REF AVCStatus ReOrderList(AVCCommonObj *video)
+{
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    AVCStatus status = AVC_SUCCESS;
+    int slice_type = video->slice_type;
+
+    if (slice_type != AVC_I_SLICE)
+    {
+        if (sliceHdr->ref_pic_list_reordering_flag_l0)
+        {
+            status = ReorderRefPicList(video, 0);
+            if (status != AVC_SUCCESS)
+                return status;
+        }
+        if (video->refList0Size == 0)
+        {
+            return AVC_FAIL;
+        }
+    }
+    return status;
+}
+
+AVCStatus ReorderRefPicList(AVCCommonObj *video, int isL1)
+{
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    AVCStatus status;
+
+    int *list_size;
+    int num_ref_idx_lX_active_minus1;
+    uint *remapping_of_pic_nums_idc;
+    int *abs_diff_pic_num_minus1;
+    int *long_term_pic_idx;
+    int i;
+    int maxPicNum, currPicNum, picNumLXNoWrap, picNumLXPred, picNumLX;
+    int refIdxLX = 0;
+    void* tmp;
+
+    if (!isL1) /* list 0 */
+    {
+        list_size = &(video->refList0Size);
+        num_ref_idx_lX_active_minus1 = sliceHdr->num_ref_idx_l0_active_minus1;
+        remapping_of_pic_nums_idc = sliceHdr->reordering_of_pic_nums_idc_l0;
+        tmp = (void*)sliceHdr->abs_diff_pic_num_minus1_l0;
+        abs_diff_pic_num_minus1 = (int*) tmp;
+        tmp = (void*)sliceHdr->long_term_pic_num_l0;
+        long_term_pic_idx = (int*) tmp;
+    }
+    else
+    {
+        list_size = &(video->refList1Size);
+        num_ref_idx_lX_active_minus1 = sliceHdr->num_ref_idx_l1_active_minus1;
+        remapping_of_pic_nums_idc = sliceHdr->reordering_of_pic_nums_idc_l1;
+        tmp = (void*) sliceHdr->abs_diff_pic_num_minus1_l1;
+        abs_diff_pic_num_minus1 = (int*) tmp;
+        tmp = (void*) sliceHdr->long_term_pic_num_l1;
+        long_term_pic_idx = (int*)tmp;
+    }
+
+    maxPicNum = video->MaxPicNum;
+    currPicNum = video->CurrPicNum;
+
+    picNumLXPred = currPicNum; /* initial value */
+
+    for (i = 0; remapping_of_pic_nums_idc[i] != 3; i++)
+    {
+        if ((remapping_of_pic_nums_idc[i] > 3) || (i >= MAX_REF_PIC_LIST_REORDERING))
+        {
+            return AVC_FAIL; /* out of range */
+        }
+        /* see subclause 8.2.4.3.1 */
+        if (remapping_of_pic_nums_idc[i] < 2)
+        {
+            if (remapping_of_pic_nums_idc[i] == 0)
+            {
+                if (picNumLXPred - (abs_diff_pic_num_minus1[i] + 1) < 0)
+                    picNumLXNoWrap = picNumLXPred - (abs_diff_pic_num_minus1[i] + 1) + maxPicNum;
+                else
+                    picNumLXNoWrap = picNumLXPred - (abs_diff_pic_num_minus1[i] + 1);
+            }
+            else /* (remapping_of_pic_nums_idc[i] == 1) */
+            {
+                if (picNumLXPred + (abs_diff_pic_num_minus1[i] + 1)  >=  maxPicNum)
+                    picNumLXNoWrap = picNumLXPred + (abs_diff_pic_num_minus1[i] + 1) - maxPicNum;
+                else
+                    picNumLXNoWrap = picNumLXPred + (abs_diff_pic_num_minus1[i] + 1);
+            }
+            picNumLXPred = picNumLXNoWrap; /* prediction for the next one */
+
+            if (picNumLXNoWrap > currPicNum)
+                picNumLX = picNumLXNoWrap - maxPicNum;
+            else
+                picNumLX = picNumLXNoWrap;
+
+            status = ReorderShortTerm(video, picNumLX, &refIdxLX, isL1);
+            if (status != AVC_SUCCESS)
+            {
+                return status;
+            }
+        }
+        else /* (remapping_of_pic_nums_idc[i] == 2), subclause 8.2.4.3.2 */
+        {
+            status = ReorderLongTerm(video, long_term_pic_idx[i], &refIdxLX, isL1);
+            if (status != AVC_SUCCESS)
+            {
+                return status;
+            }
+        }
+    }
+    /* that's a definition */
+    *list_size = num_ref_idx_lX_active_minus1 + 1;
+
+    return AVC_SUCCESS;
+}
+
+/* see subclause 8.2.4.3.1 */
+AVCStatus ReorderShortTerm(AVCCommonObj *video, int picNumLX, int *refIdxLX, int isL1)
+{
+    int cIdx, nIdx;
+    int num_ref_idx_lX_active_minus1;
+    AVCPictureData *picLX, **RefPicListX;
+
+    if (!isL1) /* list 0 */
+    {
+        RefPicListX = video->RefPicList0;
+        num_ref_idx_lX_active_minus1 = video->sliceHdr->num_ref_idx_l0_active_minus1;
+    }
+    else
+    {
+        RefPicListX = video->RefPicList1;
+        num_ref_idx_lX_active_minus1 = video->sliceHdr->num_ref_idx_l1_active_minus1;
+    }
+
+    picLX = GetShortTermPic(video, picNumLX);
+
+    if (picLX == NULL)
+    {
+        return AVC_FAIL;
+    }
+    /* Note RefPicListX has to access element number num_ref_idx_lX_active */
+    /* There could be access violation here. */
+    if (num_ref_idx_lX_active_minus1 + 1 >= MAX_REF_PIC_LIST)
+    {
+        return AVC_FAIL;
+    }
+
+    for (cIdx = num_ref_idx_lX_active_minus1 + 1; cIdx > *refIdxLX; cIdx--)
+    {
+        RefPicListX[ cIdx ] = RefPicListX[ cIdx - 1];
+    }
+
+    RefPicListX[(*refIdxLX)++ ] = picLX;
+
+    nIdx = *refIdxLX;
+
+    for (cIdx = *refIdxLX; cIdx <= num_ref_idx_lX_active_minus1 + 1; cIdx++)
+    {
+        if (RefPicListX[ cIdx ])
+        {
+            if ((RefPicListX[ cIdx ]->isLongTerm) || ((int)RefPicListX[ cIdx ]->PicNum != picNumLX))
+            {
+                RefPicListX[ nIdx++ ] = RefPicListX[ cIdx ];
+            }
+        }
+    }
+    return AVC_SUCCESS;
+}
+
+/* see subclause 8.2.4.3.2 */
+AVCStatus ReorderLongTerm(AVCCommonObj *video, int LongTermPicNum, int *refIdxLX, int isL1)
+{
+    AVCPictureData **RefPicListX;
+    int num_ref_idx_lX_active_minus1;
+    int cIdx, nIdx;
+    AVCPictureData *picLX;
+
+    if (!isL1) /* list 0 */
+    {
+        RefPicListX = video->RefPicList0;
+        num_ref_idx_lX_active_minus1 = video->sliceHdr->num_ref_idx_l0_active_minus1;
+    }
+    else
+    {
+        RefPicListX = video->RefPicList1;
+        num_ref_idx_lX_active_minus1 = video->sliceHdr->num_ref_idx_l1_active_minus1;
+    }
+
+    picLX = GetLongTermPic(video, LongTermPicNum);
+    if (picLX == NULL)
+    {
+        return AVC_FAIL;
+    }
+    /* Note RefPicListX has to access element number num_ref_idx_lX_active */
+    /* There could be access violation here. */
+    if (num_ref_idx_lX_active_minus1 + 1 >= MAX_REF_PIC_LIST)
+    {
+        return AVC_FAIL;
+    }
+    for (cIdx = num_ref_idx_lX_active_minus1 + 1; cIdx > *refIdxLX; cIdx--)
+        RefPicListX[ cIdx ] = RefPicListX[ cIdx - 1];
+
+    RefPicListX[(*refIdxLX)++ ] = picLX;
+
+    nIdx = *refIdxLX;
+
+    for (cIdx = *refIdxLX; cIdx <= num_ref_idx_lX_active_minus1 + 1; cIdx++)
+    {
+        if ((!RefPicListX[ cIdx ]->isLongTerm) || ((int)RefPicListX[ cIdx ]->LongTermPicNum != LongTermPicNum))
+        {
+            RefPicListX[ nIdx++ ] = RefPicListX[ cIdx ];
+        }
+    }
+    return AVC_SUCCESS;
+}
+
+
+AVCPictureData*  GetShortTermPic(AVCCommonObj *video, int picNum)
+{
+    int i;
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+
+    for (i = 0; i < dpb->num_fs; i++)
+    {
+
+        if (dpb->fs[i]->IsReference == 3)
+        {
+            if ((dpb->fs[i]->frame.isLongTerm == FALSE) && (dpb->fs[i]->frame.PicNum == picNum))
+            {
+                return &(dpb->fs[i]->frame);
+            }
+        }
+
+    }
+
+    return NULL;
+}
+
+AVCPictureData*  GetLongTermPic(AVCCommonObj *video, int LongtermPicNum)
+{
+    AVCDecPicBuffer *dpb = video->decPicBuf;
+    int i;
+
+    for (i = 0; i < dpb->num_fs; i++)
+    {
+
+        if (dpb->fs[i]->IsReference == 3)
+        {
+            if ((dpb->fs[i]->frame.isLongTerm == TRUE) && (dpb->fs[i]->frame.LongTermPicNum == LongtermPicNum))
+            {
+                return &(dpb->fs[i]->frame);
+            }
+        }
+
+    }
+    return NULL;
+}
+
+int is_short_ref(AVCPictureData *s)
+{
+    return ((s->isReference) && !(s->isLongTerm));
+}
+
+int is_long_ref(AVCPictureData *s)
+{
+    return ((s->isReference) && (s->isLongTerm));
+}
+
+
+/* sort by PicNum, descending order */
+void SortPicByPicNum(AVCPictureData *data[], int num)
+{
+    int i, j;
+    AVCPictureData *temp;
+
+    for (i = 0; i < num - 1; i++)
+    {
+        for (j = i + 1; j < num; j++)
+        {
+            if (data[j]->PicNum > data[i]->PicNum)
+            {
+                temp = data[j];
+                data[j] = data[i];
+                data[i] = temp;
+            }
+        }
+    }
+
+    return ;
+}
+
+/* sort by PicNum, ascending order */
+void SortPicByPicNumLongTerm(AVCPictureData *data[], int num)
+{
+    int i, j;
+    AVCPictureData *temp;
+
+    for (i = 0; i < num - 1; i++)
+    {
+        for (j = i + 1; j < num; j++)
+        {
+            if (data[j]->LongTermPicNum < data[i]->LongTermPicNum)
+            {
+                temp = data[j];
+                data[j] = data[i];
+                data[i] = temp;
+            }
+        }
+    }
+
+    return ;
+}
+
+
+/* sort by FrameNumWrap, descending order */
+void SortFrameByFrameNumWrap(AVCFrameStore *data[], int num)
+{
+    int i, j;
+    AVCFrameStore *temp;
+
+    for (i = 0; i < num - 1; i++)
+    {
+        for (j = i + 1; j < num; j++)
+        {
+            if (data[j]->FrameNumWrap > data[i]->FrameNumWrap)
+            {
+                temp = data[j];
+                data[j] = data[i];
+                data[i] = temp;
+            }
+        }
+    }
+
+    return ;
+}
+
+/* sort frames by LongTermFrameIdx, ascending order */
+void SortFrameByLTFrameIdx(AVCFrameStore *data[], int num)
+{
+    int i, j;
+    AVCFrameStore *temp;
+
+    for (i = 0; i < num - 1; i++)
+    {
+        for (j = i + 1; j < num; j++)
+        {
+            if (data[j]->LongTermFrameIdx < data[i]->LongTermFrameIdx)
+            {
+                temp = data[j];
+                data[j] = data[i];
+                data[i] = temp;
+            }
+        }
+    }
+
+    return ;
+}
+
+/* sort PictureData by POC in descending order */
+void SortPicByPOC(AVCPictureData *data[], int num, int descending)
+{
+    int i, j;
+    AVCPictureData *temp;
+
+    if (descending)
+    {
+        for (i = 0; i < num - 1; i++)
+        {
+            for (j = i + 1; j < num; j++)
+            {
+                if (data[j]->PicOrderCnt > data[i]->PicOrderCnt)
+                {
+                    temp = data[j];
+                    data[j] = data[i];
+                    data[i] = temp;
+                }
+            }
+        }
+    }
+    else
+    {
+        for (i = 0; i < num - 1; i++)
+        {
+            for (j = i + 1; j < num; j++)
+            {
+                if (data[j]->PicOrderCnt < data[i]->PicOrderCnt)
+                {
+                    temp = data[j];
+                    data[j] = data[i];
+                    data[i] = temp;
+                }
+            }
+        }
+    }
+    return ;
+}
+
+/* sort PictureData by LongTermPicNum in ascending order */
+void SortPicByLTPicNum(AVCPictureData *data[], int num)
+{
+    int i, j;
+    AVCPictureData *temp;
+
+    for (i = 0; i < num - 1; i++)
+    {
+        for (j = i + 1; j < num; j++)
+        {
+            if (data[j]->LongTermPicNum < data[i]->LongTermPicNum)
+            {
+                temp = data[j];
+                data[j] = data[i];
+                data[i] = temp;
+            }
+        }
+    }
+
+    return ;
+}
+
+/* sort by PicOrderCnt, descending order */
+void SortFrameByPOC(AVCFrameStore *data[], int num, int descending)
+{
+    int i, j;
+    AVCFrameStore *temp;
+
+    if (descending)
+    {
+        for (i = 0; i < num - 1; i++)
+        {
+            for (j = i + 1; j < num; j++)
+            {
+                if (data[j]->PicOrderCnt > data[i]->PicOrderCnt)
+                {
+                    temp = data[j];
+                    data[j] = data[i];
+                    data[i] = temp;
+                }
+            }
+        }
+    }
+    else
+    {
+        for (i = 0; i < num - 1; i++)
+        {
+            for (j = i + 1; j < num; j++)
+            {
+                if (data[j]->PicOrderCnt < data[i]->PicOrderCnt)
+                {
+                    temp = data[j];
+                    data[j] = data[i];
+                    data[i] = temp;
+                }
+            }
+        }
+    }
+
+    return ;
+}
+
+
diff --git a/media/libstagefright/codecs/avc/dec/AVCDecoder.cpp b/media/libstagefright/codecs/avc/dec/AVCDecoder.cpp
new file mode 100644
index 0000000..484c742
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/AVCDecoder.cpp
@@ -0,0 +1,484 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "AVCDecoder"
+#include <utils/Log.h>
+
+#include "AVCDecoder.h"
+
+#include "avcdec_api.h"
+#include "avcdec_int.h"
+
+#include <OMX_Component.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>
+#include <media/stagefright/Utils.h>
+
+namespace android {
+
+static int32_t Malloc(void *userData, int32_t size, int32_t attrs) {
+    return reinterpret_cast<int32_t>(malloc(size));
+}
+
+static void Free(void *userData, int32_t ptr) {
+    free(reinterpret_cast<void *>(ptr));
+}
+
+AVCDecoder::AVCDecoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mHandle(new tagAVCHandle),
+      mInputBuffer(NULL),
+      mAnchorTimeUs(0),
+      mNumSamplesOutput(0),
+      mPendingSeekTimeUs(-1) {
+    memset(mHandle, 0, sizeof(tagAVCHandle));
+    mHandle->AVCObject = NULL;
+    mHandle->userData = this;
+    mHandle->CBAVC_DPBAlloc = ActivateSPSWrapper;
+    mHandle->CBAVC_FrameBind = BindFrameWrapper;
+    mHandle->CBAVC_FrameUnbind = UnbindFrame;
+    mHandle->CBAVC_Malloc = Malloc;
+    mHandle->CBAVC_Free = Free;
+
+    mFormat = new MetaData;
+    mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
+    int32_t width, height;
+    CHECK(mSource->getFormat()->findInt32(kKeyWidth, &width));
+    CHECK(mSource->getFormat()->findInt32(kKeyHeight, &height));
+    mFormat->setInt32(kKeyWidth, width);
+    mFormat->setInt32(kKeyHeight, height);
+    mFormat->setInt32(kKeyColorFormat, OMX_COLOR_FormatYUV420Planar);
+    mFormat->setCString(kKeyDecoderComponent, "AVCDecoder");
+
+    int64_t durationUs;
+    if (mSource->getFormat()->findInt64(kKeyDuration, &durationUs)) {
+        mFormat->setInt64(kKeyDuration, durationUs);
+    }
+}
+
+AVCDecoder::~AVCDecoder() {
+    if (mStarted) {
+        stop();
+    }
+
+    delete mHandle;
+    mHandle = NULL;
+}
+
+status_t AVCDecoder::start(MetaData *) {
+    CHECK(!mStarted);
+
+    uint32_t type;
+    const void *data;
+    size_t size;
+    if (mSource->getFormat()->findData(kKeyAVCC, &type, &data, &size)) {
+        // Parse the AVCDecoderConfigurationRecord
+
+        const uint8_t *ptr = (const uint8_t *)data;
+
+        CHECK(size >= 7);
+        CHECK_EQ(ptr[0], 1);  // configurationVersion == 1
+        uint8_t profile = ptr[1];
+        uint8_t level = ptr[3];
+
+        // There is decodable content out there that fails the following
+        // assertion, let's be lenient for now...
+        // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
+
+        size_t lengthSize = 1 + (ptr[4] & 3);
+
+        // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
+        // violates it...
+        // CHECK((ptr[5] >> 5) == 7);  // reserved
+
+        size_t numSeqParameterSets = ptr[5] & 31;
+
+        ptr += 6;
+        size -= 6;
+
+        for (size_t i = 0; i < numSeqParameterSets; ++i) {
+            CHECK(size >= 2);
+            size_t length = U16_AT(ptr);
+
+            ptr += 2;
+            size -= 2;
+
+            CHECK(size >= length);
+
+            addCodecSpecificData(ptr, length);
+
+            ptr += length;
+            size -= length;
+        }
+
+        CHECK(size >= 1);
+        size_t numPictureParameterSets = *ptr;
+        ++ptr;
+        --size;
+
+        for (size_t i = 0; i < numPictureParameterSets; ++i) {
+            CHECK(size >= 2);
+            size_t length = U16_AT(ptr);
+
+            ptr += 2;
+            size -= 2;
+
+            CHECK(size >= length);
+
+            addCodecSpecificData(ptr, length);
+
+            ptr += length;
+            size -= length;
+        }
+    }
+
+    sp<MetaData> params = new MetaData;
+    params->setInt32(kKeyWantsNALFragments, true);
+    mSource->start(params.get());
+
+    mAnchorTimeUs = 0;
+    mNumSamplesOutput = 0;
+    mPendingSeekTimeUs = -1;
+    mStarted = true;
+
+    return OK;
+}
+
+void AVCDecoder::addCodecSpecificData(const uint8_t *data, size_t size) {
+    MediaBuffer *buffer = new MediaBuffer(size);
+    memcpy(buffer->data(), data, size);
+    buffer->set_range(0, size);
+
+    mCodecSpecificData.push(buffer);
+}
+
+status_t AVCDecoder::stop() {
+    CHECK(mStarted);
+
+    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
+        (*mCodecSpecificData.editItemAt(i)).release();
+    }
+    mCodecSpecificData.clear();
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    mSource->stop();
+
+    releaseFrames();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> AVCDecoder::getFormat() {
+    return mFormat;
+}
+
+status_t AVCDecoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        LOGV("seek requested to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
+
+        CHECK(seekTimeUs >= 0);
+        mPendingSeekTimeUs = seekTimeUs;
+
+        if (mInputBuffer) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+
+        PVAVCDecReset(mHandle);
+    }
+
+    if (mInputBuffer == NULL) {
+        LOGV("fetching new input buffer.");
+
+        if (!mCodecSpecificData.isEmpty()) {
+            mInputBuffer = mCodecSpecificData.editItemAt(0);
+            mCodecSpecificData.removeAt(0);
+        } else {
+            for (;;) {
+                if (mPendingSeekTimeUs >= 0) {
+                    LOGV("reading data from timestamp %lld (%.2f secs)",
+                         mPendingSeekTimeUs, mPendingSeekTimeUs / 1E6);
+                }
+
+                ReadOptions seekOptions;
+                if (mPendingSeekTimeUs >= 0) {
+                    seekOptions.setSeekTo(mPendingSeekTimeUs);
+                    mPendingSeekTimeUs = -1;
+                }
+                status_t err = mSource->read(&mInputBuffer, &seekOptions);
+                seekOptions.clearSeekTo();
+
+                if (err != OK) {
+                    return err;
+                }
+
+                if (mInputBuffer->range_length() > 0) {
+                    break;
+                }
+
+                mInputBuffer->release();
+                mInputBuffer = NULL;
+            }
+        }
+    }
+
+    const uint8_t *inPtr =
+        (const uint8_t *)mInputBuffer->data() + mInputBuffer->range_offset();
+
+    int nalType;
+    int nalRefIdc;
+    AVCDec_Status res =
+        PVAVCDecGetNALType(
+                const_cast<uint8_t *>(inPtr), mInputBuffer->range_length(),
+                &nalType, &nalRefIdc);
+
+    if (res != AVCDEC_SUCCESS) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+
+        return UNKNOWN_ERROR;
+    }
+
+    switch (nalType) {
+        case AVC_NALTYPE_SPS:
+        {
+            res = PVAVCDecSeqParamSet(
+                    mHandle, const_cast<uint8_t *>(inPtr),
+                    mInputBuffer->range_length());
+
+            if (res != AVCDEC_SUCCESS) {
+                mInputBuffer->release();
+                mInputBuffer = NULL;
+
+                return UNKNOWN_ERROR;
+            }
+
+            AVCDecObject *pDecVid = (AVCDecObject *)mHandle->AVCObject;
+
+            int32_t width =
+                (pDecVid->seqParams[0]->pic_width_in_mbs_minus1 + 1) * 16;
+
+            int32_t height =
+                (pDecVid->seqParams[0]->pic_height_in_map_units_minus1 + 1) * 16;
+
+            int32_t crop_left, crop_right, crop_top, crop_bottom;
+            if (pDecVid->seqParams[0]->frame_cropping_flag)
+            {
+                crop_left = 2 * pDecVid->seqParams[0]->frame_crop_left_offset;
+                crop_right =
+                    width - (2 * pDecVid->seqParams[0]->frame_crop_right_offset + 1);
+
+                if (pDecVid->seqParams[0]->frame_mbs_only_flag)
+                {
+                    crop_top = 2 * pDecVid->seqParams[0]->frame_crop_top_offset;
+                    crop_bottom =
+                        height -
+                        (2 * pDecVid->seqParams[0]->frame_crop_bottom_offset + 1);
+                }
+                else
+                {
+                    crop_top = 4 * pDecVid->seqParams[0]->frame_crop_top_offset;
+                    crop_bottom =
+                        height -
+                        (4 * pDecVid->seqParams[0]->frame_crop_bottom_offset + 1);
+                }
+            } else {
+                crop_bottom = height - 1;
+                crop_right = width - 1;
+                crop_top = crop_left = 0;
+            }
+
+            mFormat->setInt32(kKeyWidth, crop_right - crop_left + 1);
+            mFormat->setInt32(kKeyHeight, crop_bottom - crop_top + 1);
+
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+
+            return INFO_FORMAT_CHANGED;
+        }
+
+        case AVC_NALTYPE_PPS:
+        {
+            res = PVAVCDecPicParamSet(
+                    mHandle, const_cast<uint8_t *>(inPtr),
+                    mInputBuffer->range_length());
+
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+
+            if (res != AVCDEC_SUCCESS) {
+                return UNKNOWN_ERROR;
+            }
+
+            *out = new MediaBuffer(0);
+
+            return OK;
+        }
+
+        case AVC_NALTYPE_SLICE:
+        case AVC_NALTYPE_IDR:
+        {
+            res = PVAVCDecodeSlice(
+                    mHandle, const_cast<uint8_t *>(inPtr),
+                    mInputBuffer->range_length());
+
+            if (res == AVCDEC_PICTURE_OUTPUT_READY) {
+                int32_t index;
+                int32_t Release;
+                AVCFrameIO Output;
+                Output.YCbCr[0] = Output.YCbCr[1] = Output.YCbCr[2] = NULL;
+                CHECK_EQ(PVAVCDecGetOutput(
+                            mHandle, &index, &Release, &Output),
+                         AVCDEC_SUCCESS);
+
+                CHECK(index >= 0);
+                CHECK(index < (int32_t)mFrames.size());
+
+                *out = mFrames.editItemAt(index);
+                (*out)->set_range(0, (*out)->size());
+                (*out)->add_ref();
+
+                // Do _not_ release input buffer yet.
+
+                return OK;
+            }
+
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+
+            if (res == AVCDEC_PICTURE_READY) {
+                *out = new MediaBuffer(0);
+
+                return OK;
+            } else {
+                return UNKNOWN_ERROR;
+            }
+        }
+
+        case AVC_NALTYPE_SEI:
+        {
+            res = PVAVCDecodeSlice(
+                    mHandle, const_cast<uint8_t *>(inPtr),
+                    mInputBuffer->range_length());
+
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+
+            if (res != AVCDEC_SUCCESS) {
+                return UNKNOWN_ERROR;
+            }
+
+            *out = new MediaBuffer(0);
+
+            return OK;
+        }
+
+        case AVC_NALTYPE_AUD:
+        {
+            *out = new MediaBuffer(0);
+
+            return OK;
+        }
+
+        default:
+        {
+            LOGE("Should not be here, unknown nalType %d", nalType);
+            CHECK(!"Should not be here");
+            break;
+        }
+    }
+
+    mInputBuffer->release();
+    mInputBuffer = NULL;
+
+    return UNKNOWN_ERROR;
+}
+
+// static
+int32_t AVCDecoder::ActivateSPSWrapper(
+        void *userData, unsigned int sizeInMbs, unsigned int numBuffers) {
+    return static_cast<AVCDecoder *>(userData)->activateSPS(sizeInMbs, numBuffers);
+}
+
+// static
+int32_t AVCDecoder::BindFrameWrapper(
+        void *userData, int32_t index, uint8_t **yuv) {
+    return static_cast<AVCDecoder *>(userData)->bindFrame(index, yuv);
+}
+
+// static
+void AVCDecoder::UnbindFrame(void *userData, int32_t index) {
+}
+
+int32_t AVCDecoder::activateSPS(
+        unsigned int sizeInMbs, unsigned int numBuffers) {
+    CHECK(mFrames.isEmpty());
+
+    size_t frameSize = (sizeInMbs << 7) * 3;
+    for (unsigned int i = 0; i < numBuffers; ++i) {
+        MediaBuffer *buffer = new MediaBuffer(frameSize);
+        buffer->setObserver(this);
+
+        mFrames.push(buffer);
+    }
+
+    return 1;
+}
+
+int32_t AVCDecoder::bindFrame(int32_t index, uint8_t **yuv) {
+    CHECK(index >= 0);
+    CHECK(index < (int32_t)mFrames.size());
+
+    CHECK(mInputBuffer != NULL);
+    int64_t timeUs;
+    CHECK(mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
+    mFrames[index]->meta_data()->setInt64(kKeyTime, timeUs);
+
+    *yuv = (uint8_t *)mFrames[index]->data();
+
+    return 1;
+}
+
+void AVCDecoder::releaseFrames() {
+    for (size_t i = 0; i < mFrames.size(); ++i) {
+        MediaBuffer *buffer = mFrames.editItemAt(i);
+
+        buffer->setObserver(NULL);
+        buffer->release();
+    }
+    mFrames.clear();
+}
+
+void AVCDecoder::signalBufferReturned(MediaBuffer *buffer) {
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/avc/dec/Android.mk b/media/libstagefright/codecs/avc/dec/Android.mk
new file mode 100644
index 0000000..2a1c8e0
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/Android.mk
@@ -0,0 +1,27 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        AVCDecoder.cpp \
+	src/avcdec_api.cpp \
+ 	src/avc_bitstream.cpp \
+ 	src/header.cpp \
+ 	src/itrans.cpp \
+ 	src/pred_inter.cpp \
+ 	src/pred_intra.cpp \
+ 	src/residual.cpp \
+ 	src/slice.cpp \
+ 	src/vlc.cpp
+
+LOCAL_MODULE := libstagefright_avcdec
+
+LOCAL_C_INCLUDES := \
+	$(LOCAL_PATH)/src \
+ 	$(LOCAL_PATH)/include \
+ 	$(LOCAL_PATH)/../common/include \
+        $(TOP)/frameworks/base/media/libstagefright/include \
+        $(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
+
+LOCAL_CFLAGS := -DOSCL_IMPORT_REF= -DOSCL_UNUSED_ARG= -DOSCL_EXPORT_REF=
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/avc/dec/include/avcdec_api.h b/media/libstagefright/codecs/avc/dec/include/avcdec_api.h
new file mode 100644
index 0000000..f6a14b7
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/include/avcdec_api.h
@@ -0,0 +1,200 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains application function interfaces to the AVC decoder library
+and necessary type defitionitions and enumerations.
+@publishedAll
+*/
+
+#ifndef _AVCDEC_API_H_
+#define _AVCDEC_API_H_
+
+#include "avcapi_common.h"
+
+/**
+ This enumeration is used for the status returned from the library interface.
+*/
+typedef enum
+{
+    /**
+    The followings are fail with details. Their values are negative.
+    */
+    AVCDEC_NO_DATA = -4,
+    AVCDEC_PACKET_LOSS = -3,
+    /**
+    Fail information
+    */
+    AVCDEC_NO_BUFFER = -2, /* no output picture buffer available */
+    AVCDEC_MEMORY_FAIL = -1, /* memory allocation failed */
+    AVCDEC_FAIL = 0,
+    /**
+    Generic success value
+    */
+    AVCDEC_SUCCESS = 1,
+    AVCDEC_PICTURE_OUTPUT_READY = 2,
+    AVCDEC_PICTURE_READY = 3,
+
+    /**
+    The followings are success with warnings. Their values are positive integers.
+    */
+    AVCDEC_NO_NEXT_SC = 4,
+    AVCDEC_REDUNDANT_FRAME = 5,
+    AVCDEC_CONCEALED_FRAME = 6  /* detect and conceal the error */
+} AVCDec_Status;
+
+
+/**
+This structure contains sequence parameters information.
+*/
+typedef struct tagAVCDecSPSInfo
+{
+    int FrameWidth;
+    int FrameHeight;
+    uint frame_only_flag;
+    int  frame_crop_left;
+    int  frame_crop_right;
+    int  frame_crop_top;
+    int  frame_crop_bottom;
+
+} AVCDecSPSInfo;
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+    /** THE FOLLOWINGS ARE APIS */
+    /**
+    This function parses one NAL unit from byte stream format input according to Annex B.
+    \param "bitstream"  "Pointer to the bitstream buffer."
+    \param "nal_unit"   "Point to pointer and the location of the start of the first NAL unit
+                         found in bitstream."
+    \param "size"       "As input, the pointer to the size of bitstream in bytes. As output,
+                         the value is changed to be the size of the found NAL unit."
+    \return "AVCDEC_SUCCESS if success, AVCDEC_FAIL if no first start code is found, AVCDEC_NO_NEX_SC if
+            the first start code is found, but the second start code is missing (potential partial NAL)."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCAnnexBGetNALUnit(uint8 *bitstream, uint8 **nal_unit, int *size);
+
+    /**
+    This function sniffs the nal_unit_type such that users can call corresponding APIs.
+    \param "bitstream"  "Pointer to the beginning of a NAL unit (start with forbidden_zero_bit, etc.)."
+    \param "size"       "size of the bitstream (NumBytesInNALunit + 1)."
+    \param "nal_unit_type" "Pointer to the return value of nal unit type."
+    \return "AVCDEC_SUCCESS if success, AVCDEC_FAIL otherwise."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecGetNALType(uint8 *bitstream, int size, int *nal_type, int *nal_ref_idc);
+
+    /**
+    This function decodes the sequence parameters set, initializes related parameters and
+    allocates memory (reference frames list), must also be compliant with Annex A.
+    It is equivalent to decode VOL header of MPEG4.
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    \param "nal_unit"   "Pointer to the buffer containing single NAL unit.
+                        The content will change due to EBSP-to-RBSP conversion."
+    \param "nal_size"       "size of the bitstream NumBytesInNALunit."
+    \return "AVCDEC_SUCCESS if success,
+            AVCDEC_FAIL if profile and level is not supported,
+            AVCDEC_MEMORY_FAIL if memory allocations return null."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecSeqParamSet(AVCHandle *avcHandle, uint8 *nal_unit, int nal_size);
+
+    /**
+    This function returns sequence parameters such as dimension and field flag of the most recently
+    decoded SPS. More can be added later or grouped together into a structure. This API can be called
+    after PVAVCInitSequence. If no sequence parameter has been decoded yet, it will return AVCDEC_FAIL.
+
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    \param "seqInfo"    "Pointer to the AVCDecSeqParamInfo structure."
+    \return "AVCDEC_SUCCESS if success and AVCDEC_FAIL if fail."
+    \note "This API can be combined with PVAVCInitSequence if wanted to be consistent with m4vdec lib."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecGetSeqInfo(AVCHandle *avcHandle, AVCDecSPSInfo *seqInfo);
+
+    /**
+    This function decodes the picture parameters set and initializes related parameters. Note thate
+    the PPS may not be present for every picture.
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    \param "nal_unit"   "Pointer to the buffer containing single NAL unit.
+                        The content will change due to EBSP-to-RBSP conversion."
+    \param "nal_size"       "size of the bitstream NumBytesInNALunit."
+    \return "AVCDEC_SUCCESS if success, AVCDEC_FAIL if profile and level is not supported."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecPicParamSet(AVCHandle *avcHandle, uint8 *nal_unit, int nal_size);
+
+    /**
+    This function decodes one NAL unit of bitstream. The type of nal unit is one of the
+    followings, 1, 5. (for now, no data partitioning, type 2,3,4).
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    \param "nal_unit"   "Pointer to the buffer containing a single or partial NAL unit.
+                        The content will change due to EBSP-to-RBSP conversion."
+    \param "buf_size"   "Size of the buffer (less than or equal nal_size)."
+    \param "nal_size"   "size of the current NAL unit NumBytesInNALunit."
+    \return "AVCDEC_PICTURE_READY for success and an output is ready,
+            AVCDEC_SUCCESS for success but no output is ready,
+            AVCDEC_PACKET_LOSS is GetData returns AVCDEC_PACKET_LOSS,
+            AVCDEC_FAIL if syntax error is detected,
+            AVCDEC_MEMORY_FAIL if memory is corrupted.
+            AVCDEC_NO_PICTURE if no frame memory to write to (users need to get output and/or return picture).
+            AVCDEC_REDUNDANT_PICTURE if error has been detected in the primary picture and redundant picture is available,
+            AVCDEC_CONCEALED_PICTURE if error has been detected and decoder has concealed it."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecSEI(AVCHandle *avcHandle, uint8 *nal_unit, int nal_size);
+
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecodeSlice(AVCHandle *avcHandle, uint8 *buffer, int buf_size);
+
+    /**
+    Check the availability of the decoded picture in decoding order (frame_num).
+    The AVCFrameIO also provide displaying order information such that the application
+    can re-order the frame for display. A picture can be retrieved only once.
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    \param "output"      "Pointer to the AVCOutput structure. Note that decoder library will
+                        not re-used the pixel memory in this structure until it has been returned
+                        thru PVAVCReleaseOutput API."
+    \return "AVCDEC_SUCCESS for success, AVCDEC_FAIL if no picture is available to be displayed,
+            AVCDEC_PICTURE_READY if there is another picture to be displayed."
+    */
+    OSCL_IMPORT_REF AVCDec_Status PVAVCDecGetOutput(AVCHandle *avcHandle, int *indx, int *release_flag, AVCFrameIO *output);
+
+    /**
+    This function resets the decoder and expects to see the next IDR slice.
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    */
+    OSCL_IMPORT_REF void    PVAVCDecReset(AVCHandle *avcHandle);
+
+    /**
+    This function performs clean up operation including memory deallocation.
+    \param "avcHandle"  "Handle to the AVC decoder library object."
+    */
+    OSCL_IMPORT_REF void    PVAVCCleanUpDecoder(AVCHandle *avcHandle);
+//AVCDec_Status EBSPtoRBSP(uint8 *nal_unit,int *size);
+
+
+
+    /** CALLBACK FUNCTION TO BE IMPLEMENTED BY APPLICATION */
+    /** In AVCHandle structure, userData is a pointer to an object with the following
+        member functions.
+    */
+    AVCDec_Status CBAVCDec_GetData(uint32 *userData, unsigned char **buffer, unsigned int *size);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _AVCDEC_API_H_ */
+
diff --git a/media/libstagefright/codecs/avc/dec/include/pvavcdecoder.h b/media/libstagefright/codecs/avc/dec/include/pvavcdecoder.h
new file mode 100644
index 0000000..6b196de
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/include/pvavcdecoder.h
@@ -0,0 +1,49 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef PVAVCDECODER_H_INCLUDED
+#define PVAVCDECODER_H_INCLUDED
+
+#ifndef PVAVCDECODERINTERFACE_H_INCLUDED
+#include "pvavcdecoderinterface.h"
+#endif
+
+// AVC video decoder
+class PVAVCDecoder : public PVAVCDecoderInterface
+{
+    public:
+        virtual ~PVAVCDecoder();
+        static  PVAVCDecoder* New(void);
+        virtual bool    InitAVCDecoder(FunctionType_SPS, FunctionType_Alloc, FunctionType_Unbind,
+                                       FunctionType_Malloc, FunctionType_Free, void *);
+        virtual void    CleanUpAVCDecoder(void);
+        virtual void    ResetAVCDecoder(void);
+        virtual int32   DecodeSPS(uint8 *bitstream, int32 buffer_size);
+        virtual int32   DecodePPS(uint8 *bitstream, int32 buffer_size);
+        virtual int32   DecodeAVCSlice(uint8 *bitstream, int32 *buffer_size);
+        virtual bool    GetDecOutput(int *indx, int *release);
+        virtual void    GetVideoDimensions(int32 *width, int32 *height, int32 *top, int32 *left, int32 *bottom, int32 *right);
+        int     AVC_Malloc(int32 size, int attribute);
+        void    AVC_Free(int mem);
+
+    private:
+        PVAVCDecoder();
+        bool Construct(void);
+        void *iAVCHandle;
+};
+
+#endif
diff --git a/media/libstagefright/codecs/avc/dec/include/pvavcdecoderinterface.h b/media/libstagefright/codecs/avc/dec/include/pvavcdecoderinterface.h
new file mode 100644
index 0000000..027212d
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/include/pvavcdecoderinterface.h
@@ -0,0 +1,48 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef PVAVCDECODERINTERFACE_H_INCLUDED
+#define PVAVCDECODERINTERFACE_H_INCLUDED
+
+typedef void (*FunctionType_Unbind)(void *, int);
+typedef int (*FunctionType_Alloc)(void *, int, uint8 **);
+typedef int (*FunctionType_SPS)(void *, uint, uint);
+typedef int (*FunctionType_Malloc)(void *, int32, int);
+typedef void(*FunctionType_Free)(void *, int);
+
+
+// PVAVCDecoderInterface pure virtual interface class
+class PVAVCDecoderInterface
+{
+    public:
+        virtual ~PVAVCDecoderInterface() {};
+        virtual bool    InitAVCDecoder(FunctionType_SPS, FunctionType_Alloc, FunctionType_Unbind,
+                                       FunctionType_Malloc, FunctionType_Free, void *) = 0;
+        virtual void    CleanUpAVCDecoder(void) = 0;
+        virtual void    ResetAVCDecoder(void) = 0;
+        virtual int32   DecodeSPS(uint8 *bitstream, int32 buffer_size) = 0;
+        virtual int32   DecodePPS(uint8 *bitstream, int32 buffer_size) = 0;
+        virtual int32   DecodeAVCSlice(uint8 *bitstream, int32 *buffer_size) = 0;
+        virtual bool    GetDecOutput(int *indx, int *release) = 0;
+        virtual void    GetVideoDimensions(int32 *width, int32 *height, int32 *top, int32 *left, int32 *bottom, int32 *right) = 0;
+//  virtual int     AVC_Malloc(int32 size, int attribute);
+//  virtual void    AVC_Free(int mem);
+};
+
+#endif // PVAVCDECODERINTERFACE_H_INCLUDED
+
+
diff --git a/media/libstagefright/codecs/avc/dec/src/avc_bitstream.cpp b/media/libstagefright/codecs/avc/dec/src/avc_bitstream.cpp
new file mode 100644
index 0000000..270b664
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/avc_bitstream.cpp
@@ -0,0 +1,276 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avcdec_bitstream.h"
+
+/* Swapping may not be needed anymore since we read one byte at a time and perform
+EBSP to RBSP conversion in bitstream. */
+#ifdef LITTLE_ENDIAN
+#if (WORD_SIZE==32)  /* this can be replaced with assembly instructions */
+#define SWAP_BYTES(x) ((((x)&0xFF)<<24) | (((x)&0xFF00)<<8) | (((x)&0xFF0000)>>8) | (((x)&0xFF000000)>>24))
+#else  /* for 16-bit */
+#define SWAP_BYTES(x) ((((x)&0xFF)<<8) | (((x)&0xFF00)>>8))
+#endif
+#else
+#define SWAP_BYTES(x) (x)
+#endif
+
+
+/* array for trailing bit pattern as function of number of bits */
+/* the first one is unused. */
+const static uint8 trailing_bits[9] = {0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
+
+/* ======================================================================== */
+/*  Function : BitstreamInit()                                              */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Populate bitstream structure with bitstream buffer and size  */
+/*             it also initializes internal data                            */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if successed, AVCDEC_FAIL if failed.              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+/* |--------|--------|----~~~~~-----|---------|---------|---------|
+   ^                                          ^read_pos           ^data_end_pos
+   bitstreamBuffer                  <--------->
+                                    current_word
+
+   |xxxxxxxxxxxxx----|  = current_word 32 or 16 bits
+    <------------>
+     bit_left
+ ======================================================================== */
+
+
+/* ======================================================================== */
+/*  Function : BitstreamNextWord()                                          */
+/*  Date     : 12/4/2003                                                    */
+/*  Purpose  : Read up to machine word.                                     */
+/*  In/out   :                                                              */
+/*  Return   : Next word with emulation prevention code removed. Everything
+    in the bitstream structure got modified except current_word             */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+AVCDec_Status BitstreamInit(AVCDecBitstream *stream, uint8 *buffer, int size)
+{
+    EBSPtoRBSP(buffer, &size);
+
+    stream->incnt = 0;
+    stream->incnt_next = 0;
+    stream->bitcnt = 0;
+    stream->curr_word = stream->next_word = 0;
+    stream->read_pos = 0;
+
+    stream->bitstreamBuffer = buffer;
+
+    stream->data_end_pos = size;
+
+    stream->nal_size = size;
+
+    return AVCDEC_SUCCESS;
+}
+/* ======================================================================== */
+/*  Function : AVC_BitstreamFillCache()                                         */
+/*  Date     : 1/1/2005                                                     */
+/*  Purpose  : Read up to machine word.                                     */
+/*  In/out   :                                                              */
+/*  Return   : Read in 4 bytes of input data                                */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+AVCDec_Status AVC_BitstreamFillCache(AVCDecBitstream *stream)
+{
+    uint8 *bitstreamBuffer = stream->bitstreamBuffer;
+    uint8 *v;
+    int num_bits, i;
+
+    stream->curr_word |= (stream->next_word >> stream->incnt);   // stream->incnt cannot be 32
+    stream->next_word <<= (31 - stream->incnt);
+    stream->next_word <<= 1;
+    num_bits = stream->incnt_next + stream->incnt;
+    if (num_bits >= 32)
+    {
+        stream->incnt_next -= (32 - stream->incnt);
+        stream->incnt = 32;
+        return AVCDEC_SUCCESS;
+    }
+    /* this check can be removed if there is additional extra 4 bytes at the end of the bitstream */
+    v = bitstreamBuffer + stream->read_pos;
+
+    if (stream->read_pos > stream->data_end_pos - 4)
+    {
+        if (stream->data_end_pos <= stream->read_pos)
+        {
+            stream->incnt = num_bits;
+            stream->incnt_next = 0;
+            return AVCDEC_SUCCESS;
+        }
+
+        stream->next_word = 0;
+
+        for (i = 0; i < stream->data_end_pos - stream->read_pos; i++)
+        {
+            stream->next_word |= (v[i] << ((3 - i) << 3));
+        }
+
+        stream->read_pos = stream->data_end_pos;
+        stream->curr_word |= (stream->next_word >> num_bits); // this is safe
+
+        stream->next_word <<= (31 - num_bits);
+        stream->next_word <<= 1;
+        num_bits = i << 3;
+        stream->incnt += stream->incnt_next;
+        stream->incnt_next = num_bits - (32 - stream->incnt);
+        if (stream->incnt_next < 0)
+        {
+            stream->incnt +=  num_bits;
+            stream->incnt_next = 0;
+        }
+        else
+        {
+            stream->incnt = 32;
+        }
+        return AVCDEC_SUCCESS;
+    }
+
+    stream->next_word = ((uint32)v[0] << 24) | (v[1] << 16) | (v[2] << 8) | v[3];
+    stream->read_pos += 4;
+
+    stream->curr_word |= (stream->next_word >> num_bits); // this is safe
+    stream->next_word <<= (31 - num_bits);
+    stream->next_word <<= 1;
+    stream->incnt_next += stream->incnt;
+    stream->incnt = 32;
+    return AVCDEC_SUCCESS;
+
+}
+/* ======================================================================== */
+/*  Function : BitstreamReadBits()                                          */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Read up to machine word.                                     */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits   */
+/*              is greater than the word-size, AVCDEC_PACKET_LOSS or        */
+/*              AVCDEC_NO_DATA if callback to get data fails.               */
+/*  Modified :                                                              */
+/* ======================================================================== */
+AVCDec_Status BitstreamReadBits(AVCDecBitstream *stream, int nBits, uint *code)
+{
+    if (stream->incnt < nBits)
+    {
+        /* frame-based decoding */
+        AVC_BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word >> (32 - nBits);
+    BitstreamFlushBits(stream, nBits);
+    return AVCDEC_SUCCESS;
+}
+
+
+
+/* ======================================================================== */
+/*  Function : BitstreamShowBits()                                          */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Show up to machine word without advancing the pointer.       */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits   */
+/*              is greater than the word-size, AVCDEC_NO_DATA if it needs   */
+/*              to callback to get data.                                    */
+/*  Modified :                                                              */
+/* ======================================================================== */
+AVCDec_Status BitstreamShowBits(AVCDecBitstream *stream, int nBits, uint *code)
+{
+    if (stream->incnt < nBits)
+    {
+        /* frame-based decoding */
+        AVC_BitstreamFillCache(stream);
+    }
+
+    *code = stream->curr_word >> (32 - nBits);
+
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : BitstreamRead1Bit()                                          */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Read 1 bit from the bitstream.                               */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits   */
+/*              is greater than the word-size, AVCDEC_PACKET_LOSS or        */
+/*              AVCDEC_NO_DATA if callback to get data fails.               */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+AVCDec_Status BitstreamRead1Bit(AVCDecBitstream *stream, uint *code)
+{
+    if (stream->incnt < 1)
+    {
+        /* frame-based decoding */
+        AVC_BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word >> 31;
+    BitstreamFlushBits(stream, 1);
+    return AVCDEC_SUCCESS;
+}
+
+
+
+AVCDec_Status BitstreamByteAlign(AVCDecBitstream  *stream)
+{
+    uint n_stuffed;
+
+    n_stuffed = (8 - (stream->bitcnt & 0x7)) & 0x7; /*  07/05/01 */
+
+    stream->bitcnt += n_stuffed;
+    stream->incnt -= n_stuffed;
+
+    if (stream->incnt < 0)
+    {
+        stream->bitcnt += stream->incnt;
+        stream->incnt = 0;
+    }
+    stream->curr_word <<= n_stuffed;
+    return AVCDEC_SUCCESS;
+}
+
+/* check whether there are more RBSP data. */
+/* ignore the emulation prevention code, assume it has been taken out. */
+bool more_rbsp_data(AVCDecBitstream *stream)
+{
+    int total_bit_left;
+    uint code;
+
+    if (stream->read_pos >= stream->nal_size)
+    {
+        total_bit_left = stream->incnt_next + stream->incnt;
+        if (total_bit_left <= 0)
+        {
+            return FALSE;
+        }
+        else if (total_bit_left <= 8)
+        {
+            BitstreamShowBits(stream, total_bit_left, &code);
+            if (code == trailing_bits[total_bit_left])
+            {
+                return FALSE;
+            }
+        }
+    }
+
+    return TRUE;
+}
+
diff --git a/media/libstagefright/codecs/avc/dec/src/avcdec_api.cpp b/media/libstagefright/codecs/avc/dec/src/avcdec_api.cpp
new file mode 100644
index 0000000..0a75f17
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/avcdec_api.cpp
@@ -0,0 +1,1036 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains application function interfaces to the AVC decoder library.
+@publishedAll
+*/
+
+#include <string.h>
+
+#include "avcdec_api.h"
+#include "avcdec_lib.h"
+#include "avcdec_bitstream.h"
+
+/* ======================================================================== */
+/*  Function : EBSPtoRBSP()                                                 */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Convert EBSP to RBSP and overwrite it.                       */
+/*             Assuming that forbidden_zero, nal_ref_idc and nal_unit_type  */
+/*          (first byte), has been taken out of the nal_unit.               */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+/**
+@pseudocode "
+    NumBytesInRBSP = 0;
+    for(i=0:i< *size; i++){
+        if(i+2 < *size && next_bits(24)==0x000003){
+            rbsp_byte[NumBytesInRBSP++];
+            rbsp_byte[NumBytesInRBSP++];
+            i+=2;
+            emulation_prevention_three_byte (0x03)
+        }
+        else
+            rbsp_byte[NumBytesInRBSP++];
+    }"
+*/
+AVCDec_Status EBSPtoRBSP(uint8 *nal_unit, int *size)
+{
+    int i, j;
+    int count = 0;
+
+    /* This code is based on EBSPtoRBSP of JM */
+    j = 0;
+
+    for (i = 0; i < *size; i++)
+    {
+        if (count == 2 && nal_unit[i] == 0x03)
+        {
+            i++;
+            count = 0;
+        }
+        nal_unit[j] = nal_unit[i];
+        if (nal_unit[i] == 0x00)
+            count++;
+        else
+            count = 0;
+        j++;
+    }
+
+    *size = j;
+
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCAnnexBGetNALUnit()                                      */
+/*  Date     : 11/3/2003                                                    */
+/*  Purpose  : Parse a NAL from byte stream format.                         */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if succeed, AVC_FAIL if fail.                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+/**
+@pseudocode "
+    byte_stream_nal_unit(NumBytesInNalunit){
+    while(next_bits(24) != 0x000001)
+        zero_byte
+    if(more_data_in_byte_stream()){
+        start_code_prefix_one_3bytes // equal 0x000001
+        nal_unit(NumBytesInNALunit)
+    }
+   }"
+*/
+OSCL_EXPORT_REF AVCDec_Status PVAVCAnnexBGetNALUnit(uint8 *bitstream, uint8 **nal_unit,
+        int *size)
+{
+    int i, j, FoundStartCode = 0;
+    int end;
+
+    i = 0;
+    while (bitstream[i] == 0 && i < *size)
+    {
+        i++;
+    }
+    if (i >= *size)
+    {
+        *nal_unit = bitstream;
+        return AVCDEC_FAIL; /* cannot find any start_code_prefix. */
+    }
+    else if (bitstream[i] != 0x1)
+    {
+        i = -1;  /* start_code_prefix is not at the beginning, continue */
+    }
+
+    i++;
+    *nal_unit = bitstream + i; /* point to the beginning of the NAL unit */
+
+    j = end = i;
+    while (!FoundStartCode)
+    {
+        while ((j + 1 < *size) && (bitstream[j] != 0 || bitstream[j+1] != 0))  /* see 2 consecutive zero bytes */
+        {
+            j++;
+        }
+        end = j;   /* stop and check for start code */
+        while (j + 2 < *size && bitstream[j+2] == 0) /* keep reading for zero byte */
+        {
+            j++;
+        }
+        if (j + 2 >= *size)
+        {
+            *size -= i;
+            return AVCDEC_NO_NEXT_SC;  /* cannot find the second start_code_prefix */
+        }
+        if (bitstream[j+2] == 0x1)
+        {
+            FoundStartCode = 1;
+        }
+        else
+        {
+            /* could be emulation code 0x3 */
+            j += 2; /* continue the search */
+        }
+    }
+
+    *size = end - i;
+
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCGetNALType()                                            */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Sniff NAL type from the bitstream                            */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if succeed, AVC_FAIL if fail.                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF AVCDec_Status PVAVCDecGetNALType(uint8 *bitstream, int size,
+        int *nal_type, int *nal_ref_idc)
+{
+    int forbidden_zero_bit;
+    if (size > 0)
+    {
+        forbidden_zero_bit = bitstream[0] >> 7;
+        if (forbidden_zero_bit != 0)
+            return AVCDEC_FAIL;
+        *nal_ref_idc = (bitstream[0] & 0x60) >> 5;
+        *nal_type = bitstream[0] & 0x1F;
+        return AVCDEC_SUCCESS;
+    }
+
+    return AVCDEC_FAIL;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCDecSeqParamSet()                                        */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Initialize sequence, memory allocation if necessary.         */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if succeed, AVC_FAIL if fail.                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+OSCL_EXPORT_REF AVCDec_Status   PVAVCDecSeqParamSet(AVCHandle *avcHandle, uint8 *nal_unit,
+        int nal_size)
+{
+    AVCDec_Status status;
+    AVCDecObject *decvid;
+    AVCCommonObj *video;
+    AVCDecBitstream *bitstream;
+    void *userData = avcHandle->userData;
+    bool  first_seq = FALSE;
+    int i;
+
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "PVAVCDecSeqParamSet", -1, -1);
+
+    if (avcHandle->AVCObject == NULL)
+    {
+        first_seq = TRUE;
+
+        //avcHandle->memory_usage = 0;
+        /* allocate AVCDecObject */
+        avcHandle->AVCObject = (void*)avcHandle->CBAVC_Malloc(userData, sizeof(AVCDecObject), 0/*DEFAULT_ATTR*/);
+        if (avcHandle->AVCObject == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+
+        decvid = (AVCDecObject*) avcHandle->AVCObject;
+
+        memset(decvid, 0, sizeof(AVCDecObject));
+
+        decvid->common = (AVCCommonObj*)avcHandle->CBAVC_Malloc(userData, sizeof(AVCCommonObj), 0);
+        if (decvid->common == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+
+        video = decvid->common;
+        memset(video, 0, sizeof(AVCCommonObj));
+
+        video->seq_parameter_set_id = 9999; /* set it to some illegal value */
+
+        decvid->bitstream = (AVCDecBitstream *) avcHandle->CBAVC_Malloc(userData, sizeof(AVCDecBitstream), 1/*DEFAULT_ATTR*/);
+        if (decvid->bitstream == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+
+        decvid->bitstream->userData = avcHandle->userData; /* callback for more data */
+        decvid->avcHandle = avcHandle;
+        decvid->debugEnable = avcHandle->debugEnable;
+    }
+
+    decvid = (AVCDecObject*) avcHandle->AVCObject;
+    video = decvid->common;
+    bitstream = decvid->bitstream;
+
+    /* check if we can reuse the memory without re-allocating it. */
+    /* always check if(first_seq==TRUE) */
+
+    /* Conversion from EBSP to RBSP */
+    video->forbidden_bit = nal_unit[0] >> 7;
+    if (video->forbidden_bit) return AVCDEC_FAIL;
+    video->nal_ref_idc = (nal_unit[0] & 0x60) >> 5;
+    video->nal_unit_type = (AVCNalUnitType)(nal_unit[0] & 0x1F);
+
+    if (video->nal_unit_type != AVC_NALTYPE_SPS) /* not a SPS NAL */
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* Initialize bitstream structure*/
+    BitstreamInit(bitstream, nal_unit + 1, nal_size - 1);
+
+    /* if first_seq == TRUE, allocate the following memory  */
+    if (first_seq == TRUE)
+    {
+        video->currSeqParams = NULL; /* initialize it to NULL */
+        video->currPicParams = NULL;
+
+        /* There are 32 pointers to sequence param set, seqParams.
+                There are 255 pointers to picture param set, picParams.*/
+        for (i = 0; i < 32; i++)
+            decvid->seqParams[i] = NULL;
+
+        for (i = 0; i < 256; i++)
+            decvid->picParams[i] = NULL;
+
+        video->MbToSliceGroupMap = NULL;
+
+        video->mem_mgr_ctrl_eq_5 = FALSE;
+        video->newPic = TRUE;
+        video->newSlice = TRUE;
+        video->currPic = NULL;
+        video->currFS = NULL;
+        video->prevRefPic = NULL;
+
+        video->mbNum = 0; // MC_Conceal
+        /*  Allocate sliceHdr. */
+
+        video->sliceHdr = (AVCSliceHeader*) avcHandle->CBAVC_Malloc(userData, sizeof(AVCSliceHeader), 5/*DEFAULT_ATTR*/);
+        if (video->sliceHdr == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+
+        video->decPicBuf = (AVCDecPicBuffer*) avcHandle->CBAVC_Malloc(userData, sizeof(AVCDecPicBuffer), 3/*DEFAULT_ATTR*/);
+        if (video->decPicBuf == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+        memset(video->decPicBuf, 0, sizeof(AVCDecPicBuffer));
+    }
+
+    /* Decode SPS, allocate video->seqParams[i] and assign video->currSeqParams */
+    status = DecodeSPS(decvid, bitstream);
+
+    if (status != AVCDEC_SUCCESS)
+    {
+        return status;
+    }
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCDecGetSeqInfo()                                         */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Get sequence parameter info. after SPS NAL is decoded.       */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if succeed, AVC_FAIL if fail.                 */
+/*  Modified :                                                              */
+/*  12/20/03:  change input argument, use structure instead.                */
+/* ======================================================================== */
+
+OSCL_EXPORT_REF AVCDec_Status PVAVCDecGetSeqInfo(AVCHandle *avcHandle, AVCDecSPSInfo *seqInfo)
+{
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    int PicWidthInMbs, PicHeightInMapUnits, FrameHeightInMbs;
+
+    if (decvid == NULL || decvid->seqParams[0] == NULL)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    video = decvid->common;
+
+    PicWidthInMbs = decvid->seqParams[0]->pic_width_in_mbs_minus1 + 1;
+    PicHeightInMapUnits = decvid->seqParams[0]->pic_height_in_map_units_minus1 + 1 ;
+    FrameHeightInMbs = (2 - decvid->seqParams[0]->frame_mbs_only_flag) * PicHeightInMapUnits ;
+
+    seqInfo->FrameWidth = PicWidthInMbs << 4;
+    seqInfo->FrameHeight = FrameHeightInMbs << 4;
+
+    seqInfo->frame_only_flag = decvid->seqParams[0]->frame_mbs_only_flag;
+
+    if (decvid->seqParams[0]->frame_cropping_flag)
+    {
+        seqInfo->frame_crop_left = 2 * decvid->seqParams[0]->frame_crop_left_offset;
+        seqInfo->frame_crop_right = seqInfo->FrameWidth - (2 * decvid->seqParams[0]->frame_crop_right_offset + 1);
+
+        if (seqInfo->frame_only_flag)
+        {
+            seqInfo->frame_crop_top = 2 * decvid->seqParams[0]->frame_crop_top_offset;
+            seqInfo->frame_crop_bottom = seqInfo->FrameHeight - (2 * decvid->seqParams[0]->frame_crop_bottom_offset + 1);
+            /* Note in 7.4.2.1, there is a contraint on the value of frame_crop_left and frame_crop_top
+            such that they have to be less than or equal to frame_crop_right/2 and frame_crop_bottom/2, respectively. */
+        }
+        else
+        {
+            seqInfo->frame_crop_top = 4 * decvid->seqParams[0]->frame_crop_top_offset;
+            seqInfo->frame_crop_bottom = seqInfo->FrameHeight - (4 * decvid->seqParams[0]->frame_crop_bottom_offset + 1);
+            /* Note in 7.4.2.1, there is a contraint on the value of frame_crop_left and frame_crop_top
+            such that they have to be less than or equal to frame_crop_right/2 and frame_crop_bottom/4, respectively. */
+        }
+    }
+    else  /* no cropping flag, just give the first and last pixel */
+    {
+        seqInfo->frame_crop_bottom = seqInfo->FrameHeight - 1;
+        seqInfo->frame_crop_right = seqInfo->FrameWidth - 1;
+        seqInfo->frame_crop_top = seqInfo->frame_crop_left = 0;
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCDecPicParamSet()                                        */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Initialize picture                                           */
+/*             create reference picture list.                               */
+/*  In/out   :                                                              */
+/*  Return   : AVCDEC_SUCCESS if succeed, AVC_FAIL if fail.                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+/**
+Since PPS doesn't contain much data, most of the picture initialization will
+be done after decoding the slice header in PVAVCDecodeSlice. */
+OSCL_EXPORT_REF AVCDec_Status   PVAVCDecPicParamSet(AVCHandle *avcHandle, uint8 *nal_unit,
+        int nal_size)
+{
+    AVCDec_Status status;
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    AVCDecBitstream *bitstream;
+
+    if (decvid == NULL)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    video = decvid->common;
+    bitstream = decvid->bitstream;
+    /* 1. Convert EBSP to RBSP. Create bitstream structure */
+    video->forbidden_bit = nal_unit[0] >> 7;
+    video->nal_ref_idc = (nal_unit[0] & 0x60) >> 5;
+    video->nal_unit_type = (AVCNalUnitType)(nal_unit[0] & 0x1F);
+
+    if (video->nal_unit_type != AVC_NALTYPE_PPS) /* not a PPS NAL */
+    {
+        return AVCDEC_FAIL;
+    }
+
+
+    /* 2. Initialize bitstream structure*/
+    BitstreamInit(bitstream, nal_unit + 1, nal_size - 1);
+
+    /* 2. Decode pic_parameter_set_rbsp syntax. Allocate video->picParams[i] and assign to currPicParams */
+    status = DecodePPS(decvid, video, bitstream);
+    if (status != AVCDEC_SUCCESS)
+    {
+        return status;
+    }
+
+    video->SliceGroupChangeRate = video->currPicParams->slice_group_change_rate_minus1 + 1 ;
+
+    return AVCDEC_SUCCESS;
+}
+
+OSCL_EXPORT_REF AVCDec_Status   PVAVCDecSEI(AVCHandle *avcHandle, uint8 *nal_unit,
+        int nal_size)
+{
+    OSCL_UNUSED_ARG(avcHandle);
+    OSCL_UNUSED_ARG(nal_unit);
+    OSCL_UNUSED_ARG(nal_size);
+
+    return AVCDEC_SUCCESS;
+}
+/* ======================================================================== */
+/*  Function : PVAVCDecodeSlice()                                           */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Decode one NAL unit.                                         */
+/*  In/out   :                                                              */
+/*  Return   : See enum AVCDec_Status for return values.                    */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF AVCDec_Status PVAVCDecodeSlice(AVCHandle *avcHandle, uint8 *buffer,
+        int buf_size)
+{
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    AVCDecBitstream *bitstream;
+    AVCDec_Status status;
+
+    if (decvid == NULL)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    video = decvid->common;
+    bitstream = decvid->bitstream;
+
+    if (video->mem_mgr_ctrl_eq_5)
+    {
+        return AVCDEC_PICTURE_OUTPUT_READY;      // to flushout frame buffers
+    }
+
+    if (video->newSlice)
+    {
+        /* 2. Check NAL type  */
+        if (buffer == NULL)
+        {
+            return AVCDEC_FAIL;
+        }
+        video->prev_nal_unit_type = video->nal_unit_type;
+        video->forbidden_bit = buffer[0] >> 7;
+        video->nal_ref_idc = (buffer[0] & 0x60) >> 5;
+        video->nal_unit_type = (AVCNalUnitType)(buffer[0] & 0x1F);
+
+
+        if (video->nal_unit_type == AVC_NALTYPE_AUD)
+        {
+            return AVCDEC_SUCCESS;
+        }
+
+        if (video->nal_unit_type != AVC_NALTYPE_SLICE &&
+                video->nal_unit_type != AVC_NALTYPE_IDR)
+        {
+            return AVCDEC_FAIL; /* not supported */
+        }
+
+
+
+        if (video->nal_unit_type >= 2 && video->nal_unit_type <= 4)
+        {
+            return AVCDEC_FAIL; /* not supported */
+        }
+        else
+        {
+            video->slice_data_partitioning = FALSE;
+        }
+
+        video->newSlice = FALSE;
+        /*  Initialize bitstream structure*/
+        BitstreamInit(bitstream, buffer + 1, buf_size - 1);
+
+
+        /* 2.1 Decode Slice Header (separate function)*/
+        status = DecodeSliceHeader(decvid, video, bitstream);
+        if (status != AVCDEC_SUCCESS)
+        {
+            video->newSlice = TRUE;
+            return status;
+        }
+
+        if (video->sliceHdr->frame_num != video->prevFrameNum || (video->sliceHdr->first_mb_in_slice < (uint)video->mbNum && video->currSeqParams->constrained_set1_flag == 1))
+        {
+            video->newPic = TRUE;
+            if (video->numMBs > 0)
+            {
+                // Conceal missing MBs of previously decoded frame
+                ConcealSlice(decvid, video->PicSizeInMbs - video->numMBs, video->PicSizeInMbs);  // Conceal
+                video->numMBs = 0;
+
+                //              DeblockPicture(video);   // No need to deblock
+
+                /* 3.2 Decoded frame reference marking. */
+                /* 3.3 Put the decoded picture in output buffers */
+                /* set video->mem_mge_ctrl_eq_5 */
+                AVCNalUnitType temp = video->nal_unit_type;
+                video->nal_unit_type = video->prev_nal_unit_type;
+                StorePictureInDPB(avcHandle, video);
+                video->nal_unit_type = temp;
+                video->mbNum = 0; // MC_Conceal
+                return AVCDEC_PICTURE_OUTPUT_READY;
+            }
+        }
+
+        if (video->nal_unit_type == AVC_NALTYPE_IDR)
+        {
+            video->prevFrameNum = 0;
+            video->PrevRefFrameNum = 0;
+        }
+
+        if (!video->currSeqParams->gaps_in_frame_num_value_allowed_flag)
+        {   /* no gaps allowed, frame_num has to increase by one only */
+            /*          if(sliceHdr->frame_num != (video->PrevRefFrameNum + 1)%video->MaxFrameNum) */
+            if (video->sliceHdr->frame_num != video->PrevRefFrameNum && video->sliceHdr->frame_num != (video->PrevRefFrameNum + 1) % video->MaxFrameNum)
+            {
+                // Conceal missing MBs of previously decoded frame
+                video->numMBs = 0;
+                video->newPic = TRUE;
+                video->prevFrameNum++; // FIX
+                video->PrevRefFrameNum++;
+                AVCNalUnitType temp = video->nal_unit_type;
+                video->nal_unit_type = AVC_NALTYPE_SLICE; //video->prev_nal_unit_type;
+                status = (AVCDec_Status)DPBInitBuffer(avcHandle, video);
+                if (status != AVCDEC_SUCCESS)
+                {
+                    return status;
+                }
+                video->currFS->IsOutputted = 0x01;
+                video->currFS->IsReference = 3;
+                video->currFS->IsLongTerm = 0;
+
+                DecodePOC(video);
+                /* find an empty memory from DPB and assigned to currPic */
+                DPBInitPic(video, video->PrevRefFrameNum % video->MaxFrameNum);
+                RefListInit(video);
+                ConcealSlice(decvid, 0, video->PicSizeInMbs);  // Conceal
+                video->currFS->IsOutputted |= 0x02;
+                //conceal frame
+                /* 3.2 Decoded frame reference marking. */
+                /* 3.3 Put the decoded picture in output buffers */
+                /* set video->mem_mge_ctrl_eq_5 */
+                video->mbNum = 0; // Conceal
+                StorePictureInDPB(avcHandle, video);
+                video->nal_unit_type = temp;
+
+                return AVCDEC_PICTURE_OUTPUT_READY;
+            }
+        }
+    }
+
+    if (video->newPic == TRUE)
+    {
+        status = (AVCDec_Status)DPBInitBuffer(avcHandle, video);
+        if (status != AVCDEC_SUCCESS)
+        {
+            return status;
+        }
+    }
+
+    video->newSlice = TRUE;
+
+    /* function pointer setting at slice-level */
+    // OPTIMIZE
+    decvid->residual_block = &residual_block_cavlc;
+
+    /* derive picture order count */
+    if (video->newPic == TRUE)
+    {
+        video->numMBs = video->PicSizeInMbs;
+
+        if (video->nal_unit_type != AVC_NALTYPE_IDR && video->currSeqParams->gaps_in_frame_num_value_allowed_flag)
+        {
+            if (video->sliceHdr->frame_num != (video->PrevRefFrameNum + 1) % video->MaxFrameNum)
+            {
+                status = fill_frame_num_gap(avcHandle, video);
+                if (status != AVCDEC_SUCCESS)
+                {
+                    video->numMBs = 0;
+                    return status;
+                }
+
+                status = (AVCDec_Status)DPBInitBuffer(avcHandle, video);
+                if (status != AVCDEC_SUCCESS)
+                {
+                    video->numMBs = 0;
+                    return status;
+                }
+
+
+            }
+        }
+        /* if there's gap in the frame_num, we have to fill in the gap with
+            imaginary frames that won't get used for short-term ref. */
+        /* see fill_frame_num_gap() in JM */
+
+
+        DecodePOC(video);
+        /* find an empty memory from DPB and assigned to currPic */
+        DPBInitPic(video, video->CurrPicNum);
+
+        video->currPic->isReference = TRUE;  // FIX
+
+        if (video->nal_ref_idc == 0)
+        {
+            video->currPic->isReference = FALSE;
+            video->currFS->IsOutputted |= 0x02;     /* The MASK 0x02 means not needed for reference, or returned */
+            /* node need to check for freeing of this buffer */
+        }
+
+        FMOInit(video);
+
+        if (video->currPic->isReference)
+        {
+            video->PrevRefFrameNum = video->sliceHdr->frame_num;
+        }
+
+
+        video->prevFrameNum = video->sliceHdr->frame_num;
+    }
+
+    video->newPic = FALSE;
+
+
+    /* Initialize refListIdx for this picture */
+    RefListInit(video);
+
+    /* Re-order the reference list according to the ref_pic_list_reordering() */
+    status = (AVCDec_Status)ReOrderList(video);
+    if (status != AVCDEC_SUCCESS)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* 2.2 Decode Slice. */
+    status = (AVCDec_Status)DecodeSlice(decvid);
+
+    video->slice_id++;  //  slice
+
+    if (status == AVCDEC_PICTURE_READY)
+    {
+        /* 3. Check complete picture */
+#ifndef MB_BASED_DEBLOCK
+        /* 3.1 Deblock */
+        DeblockPicture(video);
+#endif
+        /* 3.2 Decoded frame reference marking. */
+        /* 3.3 Put the decoded picture in output buffers */
+        /* set video->mem_mge_ctrl_eq_5 */
+        status = (AVCDec_Status)StorePictureInDPB(avcHandle, video);          // CHECK check the retunr status
+        if (status != AVCDEC_SUCCESS)
+        {
+            return AVCDEC_FAIL;
+        }
+
+        if (video->mem_mgr_ctrl_eq_5)
+        {
+            video->PrevRefFrameNum = 0;
+            video->prevFrameNum = 0;
+            video->prevPicOrderCntMsb = 0;
+            video->prevPicOrderCntLsb = video->TopFieldOrderCnt;
+            video->prevFrameNumOffset = 0;
+        }
+        else
+        {
+            video->prevPicOrderCntMsb = video->PicOrderCntMsb;
+            video->prevPicOrderCntLsb = video->sliceHdr->pic_order_cnt_lsb;
+            video->prevFrameNumOffset = video->FrameNumOffset;
+        }
+
+        return AVCDEC_PICTURE_READY;
+    }
+    else if (status != AVCDEC_SUCCESS)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/* ======================================================================== */
+/*  Function : PVAVCDecGetOutput()                                          */
+/*  Date     : 11/3/2003                                                    */
+/*  Purpose  : Get the next picture according to PicOrderCnt.               */
+/*  In/out   :                                                              */
+/*  Return   : AVCFrameIO structure                                         */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+OSCL_EXPORT_REF AVCDec_Status PVAVCDecGetOutput(AVCHandle *avcHandle, int *indx, int *release, AVCFrameIO *output)
+{
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    AVCDecPicBuffer *dpb;
+    AVCFrameStore *oldestFrame = NULL;
+    int i, first = 1;
+    int count_frame = 0;
+    int index = 0;
+    int min_poc = 0;
+
+    if (decvid == NULL)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    video = decvid->common;
+    dpb = video->decPicBuf;
+
+    if (dpb->num_fs == 0)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* search for the oldest frame_num in dpb */
+    /* extension to field decoding, we have to search for every top_field/bottom_field within
+    each frame in the dpb. This code only works for frame based.*/
+
+    if (video->mem_mgr_ctrl_eq_5 == FALSE)
+    {
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if ((dpb->fs[i]->IsOutputted & 0x01) == 0)
+            {
+                count_frame++;
+                if (first)
+                {
+                    min_poc = dpb->fs[i]->PicOrderCnt;
+                    first = 0;
+                    oldestFrame = dpb->fs[i];
+                    index = i;
+                }
+                if (dpb->fs[i]->PicOrderCnt < min_poc)
+                {
+                    min_poc = dpb->fs[i]->PicOrderCnt;
+                    oldestFrame = dpb->fs[i];
+                    index = i;
+                }
+            }
+        }
+    }
+    else
+    {
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if ((dpb->fs[i]->IsOutputted & 0x01) == 0 && dpb->fs[i] != video->currFS)
+            {
+                count_frame++;
+                if (first)
+                {
+                    min_poc = dpb->fs[i]->PicOrderCnt;
+                    first = 0;
+                    oldestFrame = dpb->fs[i];
+                    index = i;
+                }
+                if (dpb->fs[i]->PicOrderCnt < min_poc)
+                {
+                    min_poc = dpb->fs[i]->PicOrderCnt;
+                    oldestFrame = dpb->fs[i];
+                    index = i;
+                }
+            }
+        }
+
+        if (count_frame < 2 && video->nal_unit_type != AVC_NALTYPE_IDR)
+        {
+            video->mem_mgr_ctrl_eq_5 = FALSE;  // FIX
+        }
+        else if (count_frame < 1 && video->nal_unit_type == AVC_NALTYPE_IDR)
+        {
+            for (i = 0; i < dpb->num_fs; i++)
+            {
+                if (dpb->fs[i] == video->currFS && (dpb->fs[i]->IsOutputted & 0x01) == 0)
+                {
+                    oldestFrame = dpb->fs[i];
+                    index = i;
+                    break;
+                }
+            }
+            video->mem_mgr_ctrl_eq_5 = FALSE;
+        }
+    }
+
+    if (oldestFrame == NULL)
+    {
+
+        /*      Check for Mem_mgmt_operation_5 based forced output */
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            /* looking for the one not used or not reference and has been outputted */
+            if (dpb->fs[i]->IsReference == 0 && dpb->fs[i]->IsOutputted == 3)
+            {
+                break;
+            }
+        }
+        if (i < dpb->num_fs)
+        {
+            /* there are frames available for decoding */
+            return AVCDEC_FAIL; /* no frame to be outputted */
+        }
+
+
+        /* no free frame available, we have to release one to continue decoding */
+        int MinIdx = 0;
+        int32 MinFrameNumWrap = 0x7FFFFFFF;
+
+        for (i = 0; i < dpb->num_fs; i++)
+        {
+            if (dpb->fs[i]->IsReference && !dpb->fs[i]->IsLongTerm)
+            {
+                if (dpb->fs[i]->FrameNumWrap < MinFrameNumWrap)
+                {
+                    MinFrameNumWrap = dpb->fs[i]->FrameNumWrap;
+                    MinIdx = i;
+                }
+            }
+        }
+        /* mark the frame with smallest PicOrderCnt to be unused for reference */
+        dpb->fs[MinIdx]->IsReference = 0;
+        dpb->fs[MinIdx]->IsLongTerm = 0;
+        dpb->fs[MinIdx]->frame.isReference = FALSE;
+        dpb->fs[MinIdx]->frame.isLongTerm = FALSE;
+        dpb->fs[MinIdx]->IsOutputted |= 0x02;
+#ifdef PV_MEMORY_POOL
+        if (dpb->fs[MinIdx]->IsOutputted == 3)
+        {
+            avcHandle->CBAVC_FrameUnbind(avcHandle->userData, MinIdx);
+        }
+#endif
+        return AVCDEC_FAIL;
+    }
+    /* MASK 0x01 means the frame is outputted (for display). A frame gets freed when it is
+    outputted (0x01) and not needed for reference (0x02)   */
+    oldestFrame->IsOutputted |= 0x01;
+
+    if (oldestFrame->IsOutputted == 3)
+    {
+        *release = 1; /* flag to release the buffer */
+    }
+    else
+    {
+        *release = 0;
+    }
+    /* do not release buffer here, release it after it is sent to the sink node */
+
+    output->YCbCr[0] = oldestFrame->frame.Sl;
+    output->YCbCr[1] = oldestFrame->frame.Scb;
+    output->YCbCr[2] = oldestFrame->frame.Scr;
+    output->height = oldestFrame->frame.height;
+    output->pitch = oldestFrame->frame.width;
+    output->disp_order = oldestFrame->PicOrderCnt;
+    output->coding_order = oldestFrame->FrameNum;
+    output->id = (uint32) oldestFrame->base_dpb; /* use the pointer as the id */
+    *indx = index;
+
+
+
+    return AVCDEC_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVAVCDecReset()                                              */
+/*  Date     : 03/04/2004                                                   */
+/*  Purpose  : Reset decoder, prepare it for a new IDR frame.               */
+/*  In/out   :                                                              */
+/*  Return   :  void                                                        */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF void    PVAVCDecReset(AVCHandle *avcHandle)
+{
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    AVCDecPicBuffer *dpb;
+    int i;
+
+    if (decvid == NULL)
+    {
+        return;
+    }
+
+    video = decvid->common;
+    dpb = video->decPicBuf;
+
+    /* reset the DPB */
+
+
+    for (i = 0; i < dpb->num_fs; i++)
+    {
+        dpb->fs[i]->IsLongTerm = 0;
+        dpb->fs[i]->IsReference = 0;
+        dpb->fs[i]->IsOutputted = 3;
+        dpb->fs[i]->frame.isReference = 0;
+        dpb->fs[i]->frame.isLongTerm = 0;
+    }
+
+    video->mem_mgr_ctrl_eq_5 = FALSE;
+    video->newPic = TRUE;
+    video->newSlice = TRUE;
+    video->currPic = NULL;
+    video->currFS = NULL;
+    video->prevRefPic = NULL;
+    video->prevFrameNum = 0;
+    video->PrevRefFrameNum = 0;
+    video->prevFrameNumOffset = 0;
+    video->FrameNumOffset = 0;
+    video->mbNum = 0;
+    video->numMBs = 0;
+
+    return ;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVAVCCleanUpDecoder()                                        */
+/*  Date     : 11/4/2003                                                    */
+/*  Purpose  : Clean up the decoder, free all memories allocated.           */
+/*  In/out   :                                                              */
+/*  Return   :  void                                                        */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+OSCL_EXPORT_REF void PVAVCCleanUpDecoder(AVCHandle *avcHandle)
+{
+    AVCDecObject *decvid = (AVCDecObject*) avcHandle->AVCObject;
+    AVCCommonObj *video;
+    void *userData = avcHandle->userData;
+    int i;
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "PVAVCCleanUpDecoder", -1, -1);
+
+    if (decvid != NULL)
+    {
+        video = decvid->common;
+        if (video != NULL)
+        {
+            if (video->MbToSliceGroupMap != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->MbToSliceGroupMap);
+            }
+
+#ifdef MB_BASED_DEBLOCK
+            if (video->intra_pred_top != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->intra_pred_top);
+            }
+            if (video->intra_pred_top_cb != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->intra_pred_top_cb);
+            }
+            if (video->intra_pred_top_cr != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->intra_pred_top_cr);
+            }
+#endif
+            if (video->mblock != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->mblock);
+            }
+
+            if (video->decPicBuf != NULL)
+            {
+                CleanUpDPB(avcHandle, video);
+                avcHandle->CBAVC_Free(userData, (int)video->decPicBuf);
+            }
+
+            if (video->sliceHdr != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)video->sliceHdr);
+            }
+
+            avcHandle->CBAVC_Free(userData, (int)video); /* last thing to do */
+
+        }
+
+        for (i = 0; i < 256; i++)
+        {
+            if (decvid->picParams[i] != NULL)
+            {
+                if (decvid->picParams[i]->slice_group_id != NULL)
+                {
+                    avcHandle->CBAVC_Free(userData, (int)decvid->picParams[i]->slice_group_id);
+                }
+                avcHandle->CBAVC_Free(userData, (int)decvid->picParams[i]);
+            }
+        }
+        for (i = 0; i < 32; i++)
+        {
+            if (decvid->seqParams[i] != NULL)
+            {
+                avcHandle->CBAVC_Free(userData, (int)decvid->seqParams[i]);
+            }
+        }
+        if (decvid->bitstream != NULL)
+        {
+            avcHandle->CBAVC_Free(userData, (int)decvid->bitstream);
+        }
+
+
+        avcHandle->CBAVC_Free(userData, (int)decvid);
+    }
+
+
+    return ;
+}
diff --git a/media/libstagefright/codecs/avc/dec/src/avcdec_bitstream.h b/media/libstagefright/codecs/avc/dec/src/avcdec_bitstream.h
new file mode 100644
index 0000000..bd1bc59
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/avcdec_bitstream.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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains bitstream related functions.
+@publishedAll
+*/
+
+#ifndef _AVCDEC_BITSTREAM_H_
+#define _AVCDEC_BITSTREAM_H_
+
+#include "avcdec_lib.h"
+
+#define WORD_SIZE   32  /* this can vary, default to 32 bit for now */
+
+#ifndef __cplusplus
+
+#define AVC_GETDATA(x,y)   userData->AVC_GetData(x,y)
+
+#endif
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+#define BitstreamFlushBits(A,B)     {(A)->bitcnt += (B); (A)->incnt -= (B); (A)->curr_word <<= (B);}
+
+    AVCDec_Status AVC_BitstreamFillCache(AVCDecBitstream *stream);
+    /**
+    This function populates bitstream structure.
+    \param "stream" "Pointer to bitstream structure."
+    \param "buffer" "Pointer to the bitstream buffer."
+    \param "size"   "Size of the buffer."
+    \param "nal_size"   "Size of the NAL unit."
+    \param "resetall"   "Flag for reset everything."
+    \return "AVCDEC_SUCCESS for success and AVCDEC_FAIL for fail."
+    */
+    AVCDec_Status BitstreamInit(AVCDecBitstream *stream, uint8 *buffer, int size);
+
+    /**
+    This function reads next aligned word and remove the emulation prevention code
+    if necessary.
+    \param "stream" "Pointer to bitstream structure."
+    \return "Next word."
+    */
+    uint BitstreamNextWord(AVCDecBitstream *stream);
+
+    /**
+    This function reads nBits bits from the current position and advance the pointer.
+    \param "stream" "Pointer to bitstream structure."
+    \param "nBits" "Number of bits to be read."
+    \param "code"   "Point to the read value."
+    \return "AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits
+                is greater than the word-size, AVCDEC_PACKET_LOSS or
+                AVCDEC_NO_DATA if callback to get data fails."
+    */
+    AVCDec_Status BitstreamReadBits(AVCDecBitstream *stream, int nBits, uint *code);
+
+    /**
+    This function shows nBits bits from the current position without advancing the pointer.
+    \param "stream" "Pointer to bitstream structure."
+    \param "nBits" "Number of bits to be read."
+    \param "code"   "Point to the read value."
+    \return "AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits
+                    is greater than the word-size, AVCDEC_NO_DATA if it needs
+                    to callback to get data."
+    */
+    AVCDec_Status BitstreamShowBits(AVCDecBitstream *stream, int nBits, uint *code);
+
+
+    /**
+    This function flushes nBits bits from the current position.
+    \param "stream" "Pointer to bitstream structure."
+    \param "nBits" "Number of bits to be read."
+    \return "AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits
+                    is greater than the word-size It will not call back to get
+                   more data. Users should call BitstreamShowBits to determine
+                   how much they want to flush."
+    */
+
+    /**
+    This function read 1 bit from the current position and advance the pointer.
+    \param "stream" "Pointer to bitstream structure."
+    \param "nBits" "Number of bits to be read."
+    \param "code"   "Point to the read value."
+    \return "AVCDEC_SUCCESS if successed, AVCDEC_FAIL if number of bits
+                is greater than the word-size, AVCDEC_PACKET_LOSS or
+                AVCDEC_NO_DATA if callback to get data fails."
+    */
+    AVCDec_Status BitstreamRead1Bit(AVCDecBitstream *stream, uint *code);
+
+    /**
+    This function checks whether the current bit position is byte-aligned or not.
+    \param "stream" "Pointer to the bitstream structure."
+    \return "TRUE if byte-aligned, FALSE otherwise."
+    */
+    bool byte_aligned(AVCDecBitstream *stream);
+    AVCDec_Status BitstreamByteAlign(AVCDecBitstream  *stream);
+    /**
+    This function checks whether there are more RBSP data before the trailing bits.
+    \param "stream" "Pointer to the bitstream structure."
+    \return "TRUE if yes, FALSE otherwise."
+    */
+    bool more_rbsp_data(AVCDecBitstream *stream);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus  */
+
+#endif /* _AVCDEC_BITSTREAM_H_ */
diff --git a/media/libstagefright/codecs/avc/dec/src/avcdec_int.h b/media/libstagefright/codecs/avc/dec/src/avcdec_int.h
new file mode 100644
index 0000000..878f9b3
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/avcdec_int.h
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains application function interfaces to the AVC decoder library
+and necessary type defitionitions and enumerations.
+Naming convention for variables:
+lower_case_with_under_line  is  syntax element in subclause 7.2 and 7.3
+noUnderLine or NoUnderLine  is  derived variables defined somewhere else in the draft
+                                or introduced by this decoder library.
+@publishedAll
+*/
+
+#ifndef _AVCDEC_INT_H_
+#define _AVCDEC_INT_H_
+
+#include "avcint_common.h"
+#include "avcdec_api.h"
+
+
+/**
+Bitstream structure contains bitstream related parameters such as the pointer
+to the buffer, the current byte position and bit position.
+@publishedAll
+*/
+typedef struct tagDecBitstream
+{
+    uint8 *bitstreamBuffer; /* pointer to buffer memory   */
+    int nal_size;       /* size of the current NAL unit */
+    int data_end_pos;  /* bitstreamBuffer size in bytes */
+    int read_pos;       /* next position to read from bitstreamBuffer  */
+    uint curr_word; /* byte-swapped (MSB left) current word read from buffer */
+    int bit_left;      /* number of bit left in current_word */
+    uint next_word;     /* in case for old data in previous buffer hasn't been flushed. */
+    int incnt;  /* bit left in the prev_word */
+    int incnt_next;
+    int bitcnt;
+    void *userData;
+} AVCDecBitstream;
+
+/**
+This structure is the main object for AVC decoder library providing access to all
+global variables. It is allocated at PVAVCInitDecoder and freed at PVAVCCleanUpDecoder.
+@publishedAll
+*/
+typedef struct tagDecObject
+{
+
+    AVCCommonObj *common;
+
+    AVCDecBitstream     *bitstream; /* for current NAL */
+
+    /* sequence parameter set */
+    AVCSeqParamSet *seqParams[32]; /* Array of pointers, get allocated at arrival of new seq_id */
+
+    /* picture parameter set */
+    AVCPicParamSet *picParams[256]; /* Array of pointers to picture param set structures */
+
+    /* For internal operation, scratch memory for MV, prediction, transform, etc.*/
+    uint    ref_idx_l0[4]; /* [mbPartIdx], te(v) */
+    uint    ref_idx_l1[4];
+
+    /* function pointers */
+    AVCDec_Status(*residual_block)(struct tagDecObject*, int,  int,
+                                   int *, int *, int *);
+    /* Application control data */
+    AVCHandle *avcHandle;
+    void (*AVC_DebugLog)(AVCLogType type, char *string1, char *string2);
+    /*bool*/
+    uint    debugEnable;
+
+} AVCDecObject;
+
+#endif /* _AVCDEC_INT_H_ */
diff --git a/media/libstagefright/codecs/avc/dec/src/avcdec_lib.h b/media/libstagefright/codecs/avc/dec/src/avcdec_lib.h
new file mode 100644
index 0000000..fdead05
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/avcdec_lib.h
@@ -0,0 +1,555 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/**
+This file contains declarations of internal functions for AVC decoder library.
+@publishedAll
+*/
+#ifndef _AVCDEC_LIB_H_
+#define _AVCDEC_LIB_H_
+
+#include "avclib_common.h"
+#include "avcdec_int.h"
+
+/*----------- avcdec_api.c -------------*/
+/**
+This function takes out the emulation prevention bytes from the input to creat RBSP.
+The result is written over the input bitstream.
+\param "nal_unit"   "(I/O) Pointer to the input buffer."
+\param "size"       "(I/O) Pointer to the size of the input/output buffer."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status EBSPtoRBSP(uint8 *nal_unit, int *size);
+
+/*------------- pred_intra.c ---------------*/
+/**
+This function is the main entry point to intra prediction operation on a
+macroblock.
+\param "video"  "Pointer to AVCCommonObj."
+*/
+AVCStatus  IntraMBPrediction(AVCCommonObj *video);
+
+void SaveNeighborForIntraPred(AVCCommonObj *video, int offset);
+
+AVCStatus Intra_4x4(AVCCommonObj *video, int component, int SubBlock_indx, uint8 *comp);
+void Intra_4x4_Vertical(AVCCommonObj *video, int block_offset);
+void Intra_4x4_Horizontal(AVCCommonObj *video, int pitch, int block_offset);
+void Intra_4x4_DC(AVCCommonObj *video, int pitch, int block_offset, AVCNeighborAvailability *availability);
+void Intra_4x4_Down_Left(AVCCommonObj *video, int block_offset, AVCNeighborAvailability *availability);
+void Intra_4x4_Diagonal_Down_Right(AVCCommonObj *video, int pitch, int block_offset);
+void Intra_4x4_Diagonal_Vertical_Right(AVCCommonObj *video, int pitch, int block_offset);
+void Intra_4x4_Diagonal_Horizontal_Down(AVCCommonObj *video, int pitch, int block_offset);
+void Intra_4x4_Vertical_Left(AVCCommonObj *video,  int block_offset, AVCNeighborAvailability *availability);
+void Intra_4x4_Horizontal_Up(AVCCommonObj *video, int pitch, int block_offset);
+void  Intra_16x16_Vertical(AVCCommonObj *video);
+void Intra_16x16_Horizontal(AVCCommonObj *video, int pitch);
+void Intra_16x16_DC(AVCCommonObj *video, int pitch);
+void Intra_16x16_Plane(AVCCommonObj *video, int pitch);
+void Intra_Chroma_DC(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr);
+void  Intra_Chroma_Horizontal(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr);
+void  Intra_Chroma_Vertical(AVCCommonObj *video, uint8 *predCb, uint8 *predCr);
+void  Intra_Chroma_Plane(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr);
+
+/*------------ pred_inter.c ---------------*/
+/**
+This function is the main entrance to inter prediction operation for
+a macroblock. For decoding, this function also calls inverse transform and
+compensation.
+\param "video"  "Pointer to AVCCommonObj."
+\return "void"
+*/
+void InterMBPrediction(AVCCommonObj *video);
+
+/**
+This function is called for luma motion compensation.
+\param "ref"    "Pointer to the origin of a reference luma."
+\param "picwidth"   "Width of the picture."
+\param "picheight"  "Height of the picture."
+\param "x_pos"  "X-coordinate of the predicted block in quarter pel resolution."
+\param "y_pos"  "Y-coordinate of the predicted block in quarter pel resolution."
+\param "pred"   "Pointer to the output predicted block."
+\param "pred_pitch" "Width of pred."
+\param "blkwidth"   "Width of the current partition."
+\param "blkheight"  "Height of the current partition."
+\return "void"
+*/
+void LumaMotionComp(uint8 *ref, int picwidth, int picheight,
+                    int x_pos, int y_pos,
+                    uint8 *pred, int pred_pitch,
+                    int blkwidth, int blkheight);
+
+/**
+Functions below are special cases for luma motion compensation.
+LumaFullPelMC is for full pixel motion compensation.
+LumaBorderMC is for interpolation in only one dimension.
+LumaCrossMC is for interpolation in one dimension and half point in the other dimension.
+LumaDiagonalMC is for interpolation in diagonal direction.
+
+\param "ref"    "Pointer to the origin of a reference luma."
+\param "picwidth"   "Width of the picture."
+\param "picheight"  "Height of the picture."
+\param "x_pos"  "X-coordinate of the predicted block in full pel resolution."
+\param "y_pos"  "Y-coordinate of the predicted block in full pel resolution."
+\param "dx"     "Fraction of x_pos in quarter pel."
+\param "dy"     "Fraction of y_pos in quarter pel."
+\param "curr"   "Pointer to the current partition in the current picture."
+\param "residue"    "Pointer to the current partition for the residue block."
+\param "blkwidth"   "Width of the current partition."
+\param "blkheight"  "Height of the current partition."
+\return "void"
+*/
+void CreatePad(uint8 *ref, int picwidth, int picheight, int x_pos, int y_pos,
+               uint8 *out, int blkwidth, int blkheight);
+
+void FullPelMC(uint8 *in, int inwidth, uint8 *out, int outpitch,
+               int blkwidth, int blkheight);
+
+void HorzInterp1MC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dx);
+
+void HorzInterp2MC(int *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dx);
+
+void HorzInterp3MC(uint8 *in, int inpitch, int *out, int outpitch,
+                   int blkwidth, int blkheight);
+
+void VertInterp1MC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dy);
+
+void VertInterp2MC(uint8 *in, int inpitch, int *out, int outpitch,
+                   int blkwidth, int blkheight);
+
+void VertInterp3MC(int *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dy);
+
+void DiagonalInterpMC(uint8 *in1, uint8 *in2, int inpitch,
+                      uint8 *out, int outpitch,
+                      int blkwidth, int blkheight);
+
+
+void ChromaMotionComp(uint8 *ref, int picwidth, int picheight,
+                      int x_pos, int y_pos, uint8 *pred, int pred_pitch,
+                      int blkwidth, int blkheight);
+
+void ChromaFullPelMC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+                     int blkwidth, int blkheight) ;
+void ChromaBorderMC(uint8 *ref, int picwidth, int dx, int dy,
+                    uint8 *pred, int pred_pitch, int blkwidth, int blkheight);
+void ChromaDiagonalMC(uint8 *ref, int picwidth, int dx, int dy,
+                      uint8 *pred, int pred_pitch, int blkwidth, int blkheight);
+
+void ChromaFullPelMCOutside(uint8 *ref, uint8 *pred, int pred_pitch,
+                            int blkwidth, int blkheight, int x_inc,
+                            int y_inc0, int y_inc1, int x_mid, int y_mid);
+void ChromaBorderMCOutside(uint8 *ref, int picwidth, int dx, int dy,
+                           uint8 *pred, int pred_pitch, int blkwidth, int blkheight,
+                           int x_inc, int z_inc, int y_inc0, int y_inc1, int x_mid, int y_mid);
+void ChromaDiagonalMCOutside(uint8 *ref, int picwidth,
+                             int dx, int dy, uint8 *pred, int pred_pitch,
+                             int blkwidth, int blkheight, int x_inc, int z_inc,
+                             int y_inc0, int y_inc1, int x_mid, int y_mid);
+
+void ChromaDiagonalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                           uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaHorizontalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                             uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaVerticalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                           uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaFullMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                       uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaVerticalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                            uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaHorizontalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                              uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+void ChromaDiagonalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                            uint8 *pOut, int predPitch, int blkwidth, int blkheight);
+
+
+/*----------- slice.c ---------------*/
+/**
+This function performs the main decoding loop for slice data including
+INTRA/INTER prediction, transform and quantization and compensation.
+See decode_frame_slice() in JM.
+\param "video"  "Pointer to AVCDecObject."
+\return "AVCDEC_SUCCESS for success, AVCDEC_PICTURE_READY for end-of-picture and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status DecodeSlice(AVCDecObject *video);
+AVCDec_Status ConcealSlice(AVCDecObject *decvid, int mbnum_start, int mbnum_end);
+/**
+This function performs the decoding of one macroblock.
+\param "video"  "Pointer to AVCDecObject."
+\param "prevMbSkipped"  "A value derived in 7.3.4."
+\return "AVCDEC_SUCCESS for success or AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status DecodeMB(AVCDecObject *video);
+
+/**
+This function performs macroblock prediction type decoding as in subclause 7.3.5.1.
+\param "video" "Pointer to AVCCommonObj."
+\param "currMB" "Pointer to the current macroblock."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS for success or AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status mb_pred(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream);
+
+/**
+This function performs sub-macroblock prediction type decoding as in subclause 7.3.5.2.
+\param "video" "Pointer to AVCCommonObj."
+\param "currMB" "Pointer to the current macroblock."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS for success or AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status sub_mb_pred(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream);
+
+/**
+This function interprets the mb_type and sets necessary information
+when the slice type is AVC_I_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretMBModeI(AVCMacroblock *mblock, uint mb_type);
+
+/**
+This function interprets the mb_type and sets necessary information
+when the slice type is AVC_P_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretMBModeP(AVCMacroblock *mblock, uint mb_type);
+
+/**
+This function interprets the mb_type and sets necessary information
+when the slice type is AVC_B_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretMBModeB(AVCMacroblock *mblock, uint mb_type);
+
+/**
+This function interprets the mb_type and sets necessary information
+when the slice type is AVC_SI_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretMBModeSI(AVCMacroblock *mblock, uint mb_type);
+
+/**
+This function interprets the sub_mb_type and sets necessary information
+when the slice type is AVC_P_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "sub_mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretSubMBModeP(AVCMacroblock *mblock, uint *sub_mb_type);
+
+/**
+This function interprets the sub_mb_type and sets necessary information
+when the slice type is AVC_B_SLICE.
+in the macroblock structure.
+\param "mblock" "Pointer to current AVCMacroblock."
+\param "sub_mb_type" "From the syntax bitstream."
+\return "void"
+*/
+void InterpretSubMBModeB(AVCMacroblock *mblock, uint *sub_mb_type);
+
+/**
+This function decodes the Intra4x4 prediction mode from neighboring information
+and from the decoded syntax.
+\param "video"  "Pointer to AVCCommonObj."
+\param "currMB" "Pointer to current macroblock."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status DecodeIntra4x4Mode(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream);
+
+/*----------- vlc.c -------------------*/
+/**
+This function reads and decodes Exp-Golomb codes.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "codeNum" "Pointer to the value of the codeNum."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status ue_v(AVCDecBitstream *bitstream, uint *codeNum);
+
+/**
+This function reads and decodes signed Exp-Golomb codes.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "value"  "Pointer to syntax element value."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status  se_v(AVCDecBitstream *bitstream, int *value);
+
+/**
+This function reads and decodes signed Exp-Golomb codes for
+32 bit codeword.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "value"  "Pointer to syntax element value."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status  se_v32bit(AVCDecBitstream *bitstream, int32 *value);
+
+/**
+This function reads and decodes truncated Exp-Golomb codes.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "value"  "Pointer to syntax element value."
+\param "range"  "Range of the value as input to determine the algorithm."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status te_v(AVCDecBitstream *bitstream, uint *value, uint range);
+
+/**
+This function parse Exp-Golomb code from the bitstream.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "leadingZeros" "Pointer to the number of leading zeros."
+\param "infobits"   "Pointer to the value after leading zeros and the first one.
+                    The total number of bits read is 2*leadingZeros + 1."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status GetEGBitstring(AVCDecBitstream *bitstream, int *leadingZeros, int *infobits);
+
+/**
+This function parse Exp-Golomb code from the bitstream for 32 bit codewords.
+\param "bitstream" "Pointer to AVCDecBitstream."
+\param "leadingZeros" "Pointer to the number of leading zeros."
+\param "infobits"   "Pointer to the value after leading zeros and the first one.
+                    The total number of bits read is 2*leadingZeros + 1."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status GetEGBitstring32bit(AVCDecBitstream *bitstream, int *leadingZeros, uint32 *infobits);
+
+/**
+This function performs CAVLC decoding of the CBP (coded block pattern) of a macroblock
+by calling ue_v() and then mapping the codeNum to the corresponding CBP value.
+\param "currMB"  "Pointer to the current AVCMacroblock structure."
+\param "stream"  "Pointer to the AVCDecBitstream."
+\return "void"
+*/
+AVCDec_Status DecodeCBP(AVCMacroblock *currMB, AVCDecBitstream *stream);
+
+/**
+This function decodes the syntax for trailing ones and total coefficient.
+Subject to optimization.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "TrailingOnes"   "Pointer to the trailing one variable output."
+\param "TotalCoeff" "Pointer to the total coefficient variable output."
+\param "nC" "Context for number of nonzero coefficient (prediction context)."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_TotalCoeffTrailingOnes(AVCDecBitstream *stream, int *TrailingOnes, int *TotalCoeff, int nC);
+
+/**
+This function decodes the syntax for trailing ones and total coefficient for
+chroma DC block. Subject to optimization.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "TrailingOnes"   "Pointer to the trailing one variable output."
+\param "TotalCoeff" "Pointer to the total coefficient variable output."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_TotalCoeffTrailingOnesChromaDC(AVCDecBitstream *stream, int *TrailingOnes, int *TotalCoeff);
+
+/**
+This function decode a VLC table with 2 output.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "lentab" "Table for code length."
+\param "codtab" "Table for code value."
+\param "tabwidth" "Width of the table or alphabet size of the first output."
+\param "tabheight"  "Height of the table or alphabet size of the second output."
+\param "code1"  "Pointer to the first output."
+\param "code2"  "Pointer to the second output."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status code_from_bitstream_2d(AVCDecBitstream *stream, int *lentab, int *codtab, int tabwidth,
+                                     int tabheight, int *code1, int *code2);
+
+/**
+This function decodes the level_prefix VLC value as in Table 9-6.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "code"   "Pointer to the output."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_LevelPrefix(AVCDecBitstream *stream, uint *code);
+
+/**
+This function decodes total_zeros VLC syntax as in Table 9-7 and 9-8.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "code"   "Pointer to the output."
+\param "TotalCoeff" "Context parameter."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_TotalZeros(AVCDecBitstream *stream, int *code, int TotalCoeff);
+
+/**
+This function decodes total_zeros VLC syntax for chroma DC as in Table 9-9.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "code"   "Pointer to the output."
+\param "TotalCoeff" "Context parameter."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_TotalZerosChromaDC(AVCDecBitstream *stream, int *code, int TotalCoeff);
+
+/**
+This function decodes run_before VLC syntax as in Table 9-10.
+\param "stream" "Pointer to the AVCDecBitstream."
+\param "code"   "Pointer to the output."
+\param "zeroLeft"   "Context parameter."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status ce_RunBefore(AVCDecBitstream *stream, int *code, int zeroLeft);
+
+/*----------- header.c -------------------*/
+/**
+This function parses vui_parameters.
+\param "decvid" "Pointer to AVCDecObject."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status vui_parameters(AVCDecObject *decvid, AVCDecBitstream *stream, AVCSeqParamSet *currSPS);
+AVCDec_Status sei_payload(AVCDecObject *decvid, AVCDecBitstream *stream, uint payloadType, uint payloadSize);
+
+AVCDec_Status buffering_period(AVCDecObject *decvid, AVCDecBitstream *stream);
+AVCDec_Status pic_timing(AVCDecObject *decvid, AVCDecBitstream *stream);
+AVCDec_Status recovery_point(AVCDecObject *decvid, AVCDecBitstream *stream);
+AVCDec_Status dec_ref_pic_marking_repetition(AVCDecObject *decvid, AVCDecBitstream *stream);
+AVCDec_Status motion_constrained_slice_group_set(AVCDecObject *decvid, AVCDecBitstream *stream);
+
+
+/**
+This function parses hrd_parameters.
+\param "decvid" "Pointer to AVCDecObject."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status hrd_parameters(AVCDecObject *decvid, AVCDecBitstream *stream, AVCHRDParams *HRDParam);
+
+/**
+This function decodes the syntax in sequence parameter set slice and fill up the AVCSeqParamSet
+structure.
+\param "decvid" "Pointer to AVCDecObject."
+\param "video" "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status DecodeSPS(AVCDecObject *decvid, AVCDecBitstream *stream);
+
+/**
+This function decodes the syntax in picture parameter set and fill up the AVCPicParamSet
+structure.
+\param "decvid" "Pointer to AVCDecObject."
+\param "video" "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS or AVCDEC_FAIL."
+*/
+AVCDec_Status DecodePPS(AVCDecObject *decvid, AVCCommonObj *video, AVCDecBitstream *stream);
+AVCDec_Status DecodeSEI(AVCDecObject *decvid, AVCDecBitstream *stream);
+
+/**
+This function decodes slice header, calls related functions such as
+reference picture list reordering, prediction weight table, decode ref marking.
+See FirstPartOfSliceHeader() and RestOfSliceHeader() in JM.
+\param "decvid" "Pointer to AVCDecObject."
+\param "video" "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status DecodeSliceHeader(AVCDecObject *decvid, AVCCommonObj *video, AVCDecBitstream *stream);
+
+/**
+This function performes necessary operations to create dummy frames when
+there is a gap in frame_num.
+\param "video"  "Pointer to AVCCommonObj."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status fill_frame_num_gap(AVCHandle *avcHandle, AVCCommonObj *video);
+
+/**
+This function decodes ref_pic_list_reordering related syntax and fill up the AVCSliceHeader
+structure.
+\param "video" "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+\param "sliceHdr" "Pointer to AVCSliceHdr."
+\param "slice_type" "Value of slice_type - 5 if greater than 5."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status ref_pic_list_reordering(AVCCommonObj *video, AVCDecBitstream *stream, AVCSliceHeader *sliceHdr, int slice_type);
+
+/**
+This function decodes dec_ref_pic_marking related syntax  and fill up the AVCSliceHeader
+structure.
+\param "video" "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+\param "sliceHdr" "Pointer to AVCSliceHdr."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+*/
+AVCDec_Status dec_ref_pic_marking(AVCCommonObj *video, AVCDecBitstream *stream, AVCSliceHeader *sliceHdr);
+
+/**
+This function performs POC related operation prior to decoding a picture
+\param "video" "Pointer to AVCCommonObj."
+\return "AVCDEC_SUCCESS for success and AVCDEC_FAIL otherwise."
+See also PostPOC() for initialization of some variables.
+*/
+AVCDec_Status DecodePOC(AVCCommonObj *video);
+
+
+
+/*------------ residual.c ------------------*/
+/**
+This function decodes the intra pcm data and fill it in the corresponding location
+on the current picture.
+\param "video"  "Pointer to AVCCommonObj."
+\param "stream" "Pointer to AVCDecBitstream."
+*/
+AVCDec_Status DecodeIntraPCM(AVCCommonObj *video, AVCDecBitstream *stream);
+
+/**
+This function performs residual syntax decoding as well as quantization and transformation of
+the decoded coefficients. See subclause 7.3.5.3.
+\param "video"  "Pointer to AVCDecObject."
+\param "currMB" "Pointer to current macroblock."
+*/
+AVCDec_Status residual(AVCDecObject *video, AVCMacroblock *currMB);
+
+/**
+This function performs CAVLC syntax decoding to get the run and level information of the coefficients.
+\param "video"  "Pointer to AVCDecObject."
+\param "type"   "One of AVCResidualType for a particular 4x4 block."
+\param "bx"     "Horizontal block index."
+\param "by"     "Vertical block index."
+\param "level"  "Pointer to array of level for output."
+\param "run"    "Pointer to array of run for output."
+\param "numcoeff"   "Pointer to the total number of nonzero coefficients."
+\return "AVCDEC_SUCCESS for success."
+*/
+AVCDec_Status residual_block_cavlc(AVCDecObject *video, int nC, int maxNumCoeff,
+                                   int *level, int *run, int *numcoeff);
+
+#endif /* _AVCDEC_LIB_H_ */
diff --git a/media/libstagefright/codecs/avc/dec/src/header.cpp b/media/libstagefright/codecs/avc/dec/src/header.cpp
new file mode 100644
index 0000000..8681e2b
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/header.cpp
@@ -0,0 +1,1391 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avcdec_lib.h"
+#include "avcdec_bitstream.h"
+#include "avcdec_api.h"
+
+/** see subclause 7.4.2.1 */
+AVCDec_Status DecodeSPS(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    AVCDec_Status status = AVCDEC_SUCCESS;
+    AVCSeqParamSet *seqParam;
+    uint temp;
+    int i;
+    uint profile_idc, constrained_set0_flag, constrained_set1_flag, constrained_set2_flag;
+    uint level_idc, seq_parameter_set_id;
+    void *userData = decvid->avcHandle->userData;
+    AVCHandle *avcHandle = decvid->avcHandle;
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "DecodeSPS", -1, -1);
+
+    BitstreamReadBits(stream, 8, &profile_idc);
+    BitstreamRead1Bit(stream, &constrained_set0_flag);
+//  if (profile_idc != 66 && constrained_set0_flag != 1)
+//  {
+//      return AVCDEC_FAIL;
+//  }
+    BitstreamRead1Bit(stream, &constrained_set1_flag);
+    BitstreamRead1Bit(stream, &constrained_set2_flag);
+    BitstreamReadBits(stream, 5, &temp);
+    BitstreamReadBits(stream, 8, &level_idc);
+    if (level_idc > 51)
+    {
+        return AVCDEC_FAIL;
+    }
+    if (mapLev2Idx[level_idc] == 255)
+    {
+        return AVCDEC_FAIL;
+    }
+    ue_v(stream, &seq_parameter_set_id);
+
+    if (seq_parameter_set_id > 31)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* Allocate sequence param set for seqParams[seq_parameter_set_id]. */
+    if (decvid->seqParams[seq_parameter_set_id] == NULL)  /* allocate seqParams[id] */
+    {
+        decvid->seqParams[seq_parameter_set_id] =
+            (AVCSeqParamSet*) avcHandle->CBAVC_Malloc(userData, sizeof(AVCSeqParamSet), DEFAULT_ATTR);
+
+        if (decvid->seqParams[seq_parameter_set_id] == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+    }
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "done alloc seqParams", -1, -1);
+
+    seqParam = decvid->seqParams[seq_parameter_set_id];
+
+    seqParam->profile_idc = profile_idc;
+    seqParam->constrained_set0_flag = constrained_set0_flag;
+    seqParam->constrained_set1_flag = constrained_set1_flag;
+    seqParam->constrained_set2_flag = constrained_set2_flag;
+    seqParam->level_idc = level_idc;
+    seqParam->seq_parameter_set_id = seq_parameter_set_id;
+
+    /* continue decoding SPS */
+    ue_v(stream, &(seqParam->log2_max_frame_num_minus4));
+
+    if (seqParam->log2_max_frame_num_minus4 > 12)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    ue_v(stream, &(seqParam->pic_order_cnt_type));
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "check point 1", seqParam->log2_max_frame_num_minus4, seqParam->pic_order_cnt_type);
+
+    if (seqParam->pic_order_cnt_type == 0)
+    {
+        ue_v(stream, &(seqParam->log2_max_pic_order_cnt_lsb_minus4));
+    }
+    else if (seqParam->pic_order_cnt_type == 1)
+    {               // MC_CHECK
+        BitstreamRead1Bit(stream, (uint*)&(seqParam->delta_pic_order_always_zero_flag));
+        se_v32bit(stream, &(seqParam->offset_for_non_ref_pic));
+        se_v32bit(stream, &(seqParam->offset_for_top_to_bottom_field));
+        ue_v(stream, &(seqParam->num_ref_frames_in_pic_order_cnt_cycle));
+
+        for (i = 0; i < (int)(seqParam->num_ref_frames_in_pic_order_cnt_cycle); i++)
+        {
+            se_v32bit(stream, &(seqParam->offset_for_ref_frame[i]));
+        }
+    }
+
+    ue_v(stream, &(seqParam->num_ref_frames));
+
+    if (seqParam->num_ref_frames > 16)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "check point 2", seqParam->num_ref_frames, -1);
+
+    BitstreamRead1Bit(stream, (uint*)&(seqParam->gaps_in_frame_num_value_allowed_flag));
+    ue_v(stream, &(seqParam->pic_width_in_mbs_minus1));
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "picwidth", seqParam->pic_width_in_mbs_minus1, -1);
+
+    ue_v(stream, &(seqParam->pic_height_in_map_units_minus1));
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "picwidth", seqParam->pic_height_in_map_units_minus1, -1);
+
+    BitstreamRead1Bit(stream, (uint*)&(seqParam->frame_mbs_only_flag));
+
+    seqParam->mb_adaptive_frame_field_flag = 0; /* default value */
+    if (!seqParam->frame_mbs_only_flag)
+    {
+        BitstreamRead1Bit(stream, (uint*)&(seqParam->mb_adaptive_frame_field_flag));
+    }
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "check point 3", seqParam->frame_mbs_only_flag, -1);
+
+    BitstreamRead1Bit(stream, (uint*)&(seqParam->direct_8x8_inference_flag));
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "check point 4", seqParam->direct_8x8_inference_flag, -1);
+
+    BitstreamRead1Bit(stream, (uint*)&(seqParam->frame_cropping_flag));
+    seqParam->frame_crop_left_offset = 0;  /* default value */
+    seqParam->frame_crop_right_offset = 0;/* default value */
+    seqParam->frame_crop_top_offset = 0;/* default value */
+    seqParam->frame_crop_bottom_offset = 0;/* default value */
+    if (seqParam->frame_cropping_flag)
+    {
+        ue_v(stream, &(seqParam->frame_crop_left_offset));
+        ue_v(stream, &(seqParam->frame_crop_right_offset));
+        ue_v(stream, &(seqParam->frame_crop_top_offset));
+        ue_v(stream, &(seqParam->frame_crop_bottom_offset));
+    }
+
+    DEBUG_LOG(userData, AVC_LOGTYPE_INFO, "check point 5", seqParam->frame_cropping_flag, -1);
+
+    BitstreamRead1Bit(stream, (uint*)&(seqParam->vui_parameters_present_flag));
+    if (seqParam->vui_parameters_present_flag)
+    {
+        status = vui_parameters(decvid, stream, seqParam);
+        if (status != AVCDEC_SUCCESS)
+        {
+            return AVCDEC_FAIL;
+        }
+    }
+
+    return status;
+}
+
+
+AVCDec_Status vui_parameters(AVCDecObject *decvid, AVCDecBitstream *stream, AVCSeqParamSet *currSPS)
+{
+    uint temp;
+    uint temp32;
+    uint aspect_ratio_idc, overscan_appopriate_flag, video_format, video_full_range_flag;
+    /* aspect_ratio_info_present_flag */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        BitstreamReadBits(stream, 8, &aspect_ratio_idc);
+        if (aspect_ratio_idc == 255)
+        {
+            /* sar_width */
+            BitstreamReadBits(stream, 16, &temp);
+            /* sar_height */
+            BitstreamReadBits(stream, 16, &temp);
+        }
+    }
+    /* overscan_info_present */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        BitstreamRead1Bit(stream, &overscan_appopriate_flag);
+    }
+    /* video_signal_type_present_flag */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        BitstreamReadBits(stream, 3, &video_format);
+        BitstreamRead1Bit(stream, &video_full_range_flag);
+        /* colour_description_present_flag */
+        BitstreamRead1Bit(stream, &temp);
+        if (temp)
+        {
+            /* colour_primaries */
+            BitstreamReadBits(stream, 8, &temp);
+            /* transfer_characteristics */
+            BitstreamReadBits(stream, 8, &temp);
+            /* matrix coefficients */
+            BitstreamReadBits(stream, 8, &temp);
+        }
+    }
+    /*  chroma_loc_info_present_flag */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        /*  chroma_sample_loc_type_top_field */
+        ue_v(stream, &temp);
+        /*  chroma_sample_loc_type_bottom_field */
+        ue_v(stream, &temp);
+    }
+
+    /*  timing_info_present_flag*/
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        /*  num_unit_in_tick*/
+        BitstreamReadBits(stream, 32, &temp32);
+        /*  time_scale */
+        BitstreamReadBits(stream, 32, &temp32);
+        /*  fixed_frame_rate_flag */
+        BitstreamRead1Bit(stream, &temp);
+    }
+
+    /*  nal_hrd_parameters_present_flag */
+    BitstreamRead1Bit(stream, &temp);
+    currSPS->vui_parameters.nal_hrd_parameters_present_flag = temp;
+    if (temp)
+    {
+        hrd_parameters(decvid, stream, &(currSPS->vui_parameters.nal_hrd_parameters));
+    }
+    /*  vcl_hrd_parameters_present_flag*/
+    BitstreamRead1Bit(stream, &temp);
+    currSPS->vui_parameters.vcl_hrd_parameters_present_flag = temp;
+    if (temp)
+    {
+        hrd_parameters(decvid, stream, &(currSPS->vui_parameters.vcl_hrd_parameters));
+    }
+    if (currSPS->vui_parameters.nal_hrd_parameters_present_flag || currSPS->vui_parameters.vcl_hrd_parameters_present_flag)
+    {
+        /*  low_delay_hrd_flag */
+        BitstreamRead1Bit(stream, &temp);
+    }
+    /*  pic_struct_present_flag */
+    BitstreamRead1Bit(stream, &temp);
+    currSPS->vui_parameters.pic_struct_present_flag = temp;
+    /*  bitstream_restriction_flag */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        /*  motion_vectors_over_pic_boundaries_flag */
+        BitstreamRead1Bit(stream, &temp);
+        /*  max_bytes_per_pic_denom */
+        ue_v(stream, &temp);
+        /*  max_bits_per_mb_denom */
+        ue_v(stream, &temp);
+        /*  log2_max_mv_length_horizontal */
+        ue_v(stream, &temp);
+        /*  log2_max_mv_length_vertical */
+        ue_v(stream, &temp);
+        /*  num_reorder_frames */
+        ue_v(stream, &temp);
+        /*  max_dec_frame_buffering */
+        ue_v(stream, &temp);
+    }
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status hrd_parameters(AVCDecObject *decvid, AVCDecBitstream *stream, AVCHRDParams *HRDParam)
+{
+    OSCL_UNUSED_ARG(decvid);
+    uint temp;
+    uint cpb_cnt_minus1;
+    uint i;
+    ue_v(stream, &cpb_cnt_minus1);
+    HRDParam->cpb_cnt_minus1 = cpb_cnt_minus1;
+    /*  bit_rate_scale */
+    BitstreamReadBits(stream, 4, &temp);
+    /*  cpb_size_scale */
+    BitstreamReadBits(stream, 4, &temp);
+    for (i = 0; i <= cpb_cnt_minus1; i++)
+    {
+        /*  bit_rate_value_minus1[i] */
+        ue_v(stream, &temp);
+        /*  cpb_size_value_minus1[i] */
+        ue_v(stream, &temp);
+        /*  cbr_flag[i] */
+        ue_v(stream, &temp);
+    }
+    /*  initial_cpb_removal_delay_length_minus1 */
+    BitstreamReadBits(stream, 5, &temp);
+    /*  cpb_removal_delay_length_minus1 */
+    BitstreamReadBits(stream, 5, &temp);
+    HRDParam->cpb_removal_delay_length_minus1 = temp;
+    /*  dpb_output_delay_length_minus1 */
+    BitstreamReadBits(stream, 5, &temp);
+    HRDParam->dpb_output_delay_length_minus1 = temp;
+    /*  time_offset_length  */
+    BitstreamReadBits(stream, 5, &temp);
+    HRDParam->time_offset_length = temp;
+    return AVCDEC_SUCCESS;
+}
+
+
+/** see subclause 7.4.2.2 */
+AVCDec_Status DecodePPS(AVCDecObject *decvid, AVCCommonObj *video, AVCDecBitstream *stream)
+{
+    AVCPicParamSet *picParam;
+    AVCDec_Status status;
+    int i, iGroup, numBits;
+    int PicWidthInMbs, PicHeightInMapUnits, PicSizeInMapUnits;
+    uint pic_parameter_set_id, seq_parameter_set_id;
+    void *userData = decvid->avcHandle->userData;
+    AVCHandle *avcHandle = decvid->avcHandle;
+
+    ue_v(stream, &pic_parameter_set_id);
+    if (pic_parameter_set_id > 255)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    ue_v(stream, &seq_parameter_set_id);
+
+    if (seq_parameter_set_id > 31)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* 2.1 if picParams[pic_param_set_id] is NULL, allocate it. */
+    if (decvid->picParams[pic_parameter_set_id] == NULL)
+    {
+        decvid->picParams[pic_parameter_set_id] =
+            (AVCPicParamSet*)avcHandle->CBAVC_Malloc(userData, sizeof(AVCPicParamSet), DEFAULT_ATTR);
+        if (decvid->picParams[pic_parameter_set_id] == NULL)
+        {
+            return AVCDEC_MEMORY_FAIL;
+        }
+
+        decvid->picParams[pic_parameter_set_id]->slice_group_id = NULL;
+    }
+
+    video->currPicParams = picParam = decvid->picParams[pic_parameter_set_id];
+    picParam->seq_parameter_set_id = seq_parameter_set_id;
+    picParam->pic_parameter_set_id = pic_parameter_set_id;
+
+    BitstreamRead1Bit(stream, (uint*)&(picParam->entropy_coding_mode_flag));
+    if (picParam->entropy_coding_mode_flag)
+    {
+        status = AVCDEC_FAIL;
+        goto clean_up;
+    }
+    BitstreamRead1Bit(stream, (uint*)&(picParam->pic_order_present_flag));
+    ue_v(stream, &(picParam->num_slice_groups_minus1));
+
+    if (picParam->num_slice_groups_minus1 > MAX_NUM_SLICE_GROUP - 1)
+    {
+        status = AVCDEC_FAIL;
+        goto clean_up;
+    }
+
+    picParam->slice_group_change_rate_minus1 = 0; /* default value */
+    if (picParam->num_slice_groups_minus1 > 0)
+    {
+        ue_v(stream, &(picParam->slice_group_map_type));
+        if (picParam->slice_group_map_type == 0)
+        {
+            for (iGroup = 0; iGroup <= (int)picParam->num_slice_groups_minus1; iGroup++)
+            {
+                ue_v(stream, &(picParam->run_length_minus1[iGroup]));
+            }
+        }
+        else if (picParam->slice_group_map_type == 2)
+        {   // MC_CHECK  <= or <
+            for (iGroup = 0; iGroup < (int)picParam->num_slice_groups_minus1; iGroup++)
+            {
+                ue_v(stream, &(picParam->top_left[iGroup]));
+                ue_v(stream, &(picParam->bottom_right[iGroup]));
+            }
+        }
+        else if (picParam->slice_group_map_type == 3 ||
+                 picParam->slice_group_map_type == 4 ||
+                 picParam->slice_group_map_type == 5)
+        {
+            BitstreamRead1Bit(stream, (uint*)&(picParam->slice_group_change_direction_flag));
+            ue_v(stream, &(picParam->slice_group_change_rate_minus1));
+        }
+        else if (picParam->slice_group_map_type == 6)
+        {
+            ue_v(stream, &(picParam->pic_size_in_map_units_minus1));
+
+            numBits = 0;/* ceil(log2(num_slice_groups_minus1+1)) bits */
+            i = picParam->num_slice_groups_minus1;
+            while (i > 0)
+            {
+                numBits++;
+                i >>= 1;
+            }
+
+            i = picParam->seq_parameter_set_id;
+            if (decvid->seqParams[i] == NULL)
+            {
+                status = AVCDEC_FAIL;
+                goto clean_up;
+            }
+
+
+            PicWidthInMbs = decvid->seqParams[i]->pic_width_in_mbs_minus1 + 1;
+            PicHeightInMapUnits = decvid->seqParams[i]->pic_height_in_map_units_minus1 + 1 ;
+            PicSizeInMapUnits = PicWidthInMbs * PicHeightInMapUnits ;
+
+            /* information has to be consistent with the seq_param */
+            if ((int)picParam->pic_size_in_map_units_minus1 != PicSizeInMapUnits - 1)
+            {
+                status = AVCDEC_FAIL;
+                goto clean_up;
+            }
+
+            if (picParam->slice_group_id)
+            {
+                avcHandle->CBAVC_Free(userData, (int)picParam->slice_group_id);
+            }
+            picParam->slice_group_id = (uint*)avcHandle->CBAVC_Malloc(userData, sizeof(uint) * PicSizeInMapUnits, DEFAULT_ATTR);
+            if (picParam->slice_group_id == NULL)
+            {
+                status =  AVCDEC_MEMORY_FAIL;
+                goto clean_up;
+            }
+
+            for (i = 0; i < PicSizeInMapUnits; i++)
+            {
+                BitstreamReadBits(stream, numBits, &(picParam->slice_group_id[i]));
+            }
+        }
+
+    }
+
+    ue_v(stream, &(picParam->num_ref_idx_l0_active_minus1));
+    if (picParam->num_ref_idx_l0_active_minus1 > 31)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    ue_v(stream, &(picParam->num_ref_idx_l1_active_minus1));
+    if (picParam->num_ref_idx_l1_active_minus1 > 31)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    BitstreamRead1Bit(stream, (uint*)&(picParam->weighted_pred_flag));
+    BitstreamReadBits(stream, 2, &(picParam->weighted_bipred_idc));
+    if (picParam->weighted_bipred_idc > 2)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    se_v(stream, &(picParam->pic_init_qp_minus26));
+    if (picParam->pic_init_qp_minus26 < -26 || picParam->pic_init_qp_minus26 > 25)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    se_v(stream, &(picParam->pic_init_qs_minus26));
+    if (picParam->pic_init_qs_minus26 < -26 || picParam->pic_init_qs_minus26 > 25)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    se_v(stream, &(picParam->chroma_qp_index_offset));
+    if (picParam->chroma_qp_index_offset < -12 || picParam->chroma_qp_index_offset > 12)
+    {
+        status = AVCDEC_FAIL; /* out of range */
+        status = AVCDEC_FAIL; /* out of range */
+        goto clean_up;
+    }
+
+    BitstreamReadBits(stream, 3, &pic_parameter_set_id);
+    picParam->deblocking_filter_control_present_flag = pic_parameter_set_id >> 2;
+    picParam->constrained_intra_pred_flag = (pic_parameter_set_id >> 1) & 1;
+    picParam->redundant_pic_cnt_present_flag = pic_parameter_set_id & 1;
+
+    return AVCDEC_SUCCESS;
+clean_up:
+    if (decvid->picParams[pic_parameter_set_id])
+    {
+        if (picParam->slice_group_id)
+        {
+            avcHandle->CBAVC_Free(userData, (int)picParam->slice_group_id);
+        }
+        decvid->picParams[pic_parameter_set_id]->slice_group_id = NULL;
+        avcHandle->CBAVC_Free(userData, (int)decvid->picParams[pic_parameter_set_id]);
+        decvid->picParams[pic_parameter_set_id] = NULL;
+        return status;
+    }
+    return AVCDEC_SUCCESS;
+}
+
+
+/* FirstPartOfSliceHeader();
+    RestOfSliceHeader() */
+/** see subclause 7.4.3 */
+AVCDec_Status DecodeSliceHeader(AVCDecObject *decvid, AVCCommonObj *video, AVCDecBitstream *stream)
+{
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    AVCPicParamSet *currPPS;
+    AVCSeqParamSet *currSPS;
+    AVCDec_Status status;
+    uint idr_pic_id;
+    int slice_type, temp, i;
+
+    ue_v(stream, &(sliceHdr->first_mb_in_slice));
+    ue_v(stream, (uint*)&slice_type);
+
+    if (sliceHdr->first_mb_in_slice != 0)
+    {
+        if ((int)sliceHdr->slice_type >= 5 && slice_type != (int)sliceHdr->slice_type - 5)
+        {
+            return AVCDEC_FAIL; /* slice type doesn't follow the first slice in the picture */
+        }
+    }
+    sliceHdr->slice_type = (AVCSliceType) slice_type;
+    if (slice_type > 4)
+    {
+        slice_type -= 5;
+    }
+
+    if (slice_type == 1 || slice_type > 2)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    video->slice_type = (AVCSliceType) slice_type;
+
+    ue_v(stream, &(sliceHdr->pic_parameter_set_id));
+    /* end FirstPartSliceHeader() */
+    /* begin RestOfSliceHeader() */
+    /* after getting pic_parameter_set_id, we have to load corresponding SPS and PPS */
+    if (sliceHdr->pic_parameter_set_id > 255)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    if (decvid->picParams[sliceHdr->pic_parameter_set_id] == NULL)
+        return AVCDEC_FAIL; /* PPS doesn't exist */
+
+    currPPS = video->currPicParams = decvid->picParams[sliceHdr->pic_parameter_set_id];
+
+    if (decvid->seqParams[currPPS->seq_parameter_set_id] == NULL)
+        return AVCDEC_FAIL; /* SPS doesn't exist */
+
+    currSPS = video->currSeqParams = decvid->seqParams[currPPS->seq_parameter_set_id];
+
+    if (currPPS->seq_parameter_set_id != video->seq_parameter_set_id)
+    {
+        video->seq_parameter_set_id = currPPS->seq_parameter_set_id;
+        status = (AVCDec_Status)AVCConfigureSequence(decvid->avcHandle, video, false);
+        if (status != AVCDEC_SUCCESS)
+            return status;
+        video->level_idc = currSPS->level_idc;
+    }
+
+    /* derived variables from SPS */
+    video->MaxFrameNum = 1 << (currSPS->log2_max_frame_num_minus4 + 4);
+    // MC_OPTIMIZE
+    video->PicWidthInMbs = currSPS->pic_width_in_mbs_minus1 + 1;
+    video->PicWidthInSamplesL = video->PicWidthInMbs * 16 ;
+    video->PicWidthInSamplesC = video->PicWidthInMbs * 8 ;
+    video->PicHeightInMapUnits = currSPS->pic_height_in_map_units_minus1 + 1 ;
+    video->PicSizeInMapUnits = video->PicWidthInMbs * video->PicHeightInMapUnits ;
+    video->FrameHeightInMbs = (2 - currSPS->frame_mbs_only_flag) * video->PicHeightInMapUnits ;
+
+    /* derived from PPS */
+    video->SliceGroupChangeRate = currPPS->slice_group_change_rate_minus1 + 1;
+
+    /* then we can continue decoding slice header */
+
+    BitstreamReadBits(stream, currSPS->log2_max_frame_num_minus4 + 4, &(sliceHdr->frame_num));
+
+    if (video->currFS == NULL && sliceHdr->frame_num != 0)
+    {
+        video->prevFrameNum = video->PrevRefFrameNum = sliceHdr->frame_num - 1;
+    }
+
+    if (!currSPS->frame_mbs_only_flag)
+    {
+        BitstreamRead1Bit(stream, &(sliceHdr->field_pic_flag));
+        if (sliceHdr->field_pic_flag)
+        {
+            return AVCDEC_FAIL;
+        }
+    }
+
+    /* derived variables from slice header*/
+    video->PicHeightInMbs = video->FrameHeightInMbs;
+    video->PicHeightInSamplesL = video->PicHeightInMbs * 16;
+    video->PicHeightInSamplesC = video->PicHeightInMbs * 8;
+    video->PicSizeInMbs = video->PicWidthInMbs * video->PicHeightInMbs;
+
+    if (sliceHdr->first_mb_in_slice >= video->PicSizeInMbs)
+    {
+        return AVCDEC_FAIL;
+    }
+    video->MaxPicNum = video->MaxFrameNum;
+    video->CurrPicNum = sliceHdr->frame_num;
+
+
+    if (video->nal_unit_type == AVC_NALTYPE_IDR)
+    {
+        if (sliceHdr->frame_num != 0)
+        {
+            return AVCDEC_FAIL;
+        }
+        ue_v(stream, &idr_pic_id);
+    }
+
+    sliceHdr->delta_pic_order_cnt_bottom = 0; /* default value */
+    sliceHdr->delta_pic_order_cnt[0] = 0; /* default value */
+    sliceHdr->delta_pic_order_cnt[1] = 0; /* default value */
+    if (currSPS->pic_order_cnt_type == 0)
+    {
+        BitstreamReadBits(stream, currSPS->log2_max_pic_order_cnt_lsb_minus4 + 4,
+                          &(sliceHdr->pic_order_cnt_lsb));
+        video->MaxPicOrderCntLsb =  1 << (currSPS->log2_max_pic_order_cnt_lsb_minus4 + 4);
+        if (sliceHdr->pic_order_cnt_lsb > video->MaxPicOrderCntLsb - 1)
+            return AVCDEC_FAIL; /* out of range */
+
+        if (currPPS->pic_order_present_flag)
+        {
+            se_v32bit(stream, &(sliceHdr->delta_pic_order_cnt_bottom));
+        }
+    }
+    if (currSPS->pic_order_cnt_type == 1 && !currSPS->delta_pic_order_always_zero_flag)
+    {
+        se_v32bit(stream, &(sliceHdr->delta_pic_order_cnt[0]));
+        if (currPPS->pic_order_present_flag)
+        {
+            se_v32bit(stream, &(sliceHdr->delta_pic_order_cnt[1]));
+        }
+    }
+
+    sliceHdr->redundant_pic_cnt = 0; /* default value */
+    if (currPPS->redundant_pic_cnt_present_flag)
+    {
+        // MC_CHECK
+        ue_v(stream, &(sliceHdr->redundant_pic_cnt));
+        if (sliceHdr->redundant_pic_cnt > 127) /* out of range */
+            return AVCDEC_FAIL;
+
+        if (sliceHdr->redundant_pic_cnt > 0) /* redundant picture */
+            return AVCDEC_FAIL; /* not supported */
+    }
+    sliceHdr->num_ref_idx_l0_active_minus1 = currPPS->num_ref_idx_l0_active_minus1;
+    sliceHdr->num_ref_idx_l1_active_minus1 = currPPS->num_ref_idx_l1_active_minus1;
+
+    if (slice_type == AVC_P_SLICE)
+    {
+        BitstreamRead1Bit(stream, &(sliceHdr->num_ref_idx_active_override_flag));
+        if (sliceHdr->num_ref_idx_active_override_flag)
+        {
+            ue_v(stream, &(sliceHdr->num_ref_idx_l0_active_minus1));
+        }
+        else  /* the following condition is not allowed if the flag is zero */
+        {
+            if ((slice_type == AVC_P_SLICE) && currPPS->num_ref_idx_l0_active_minus1 > 15)
+            {
+                return AVCDEC_FAIL; /* not allowed */
+            }
+        }
+    }
+
+
+    if (sliceHdr->num_ref_idx_l0_active_minus1 > 15 ||
+            sliceHdr->num_ref_idx_l1_active_minus1 > 15)
+    {
+        return AVCDEC_FAIL; /* not allowed */
+    }
+    /* if MbaffFrameFlag =1,
+    max value of index is num_ref_idx_l0_active_minus1 for frame MBs and
+    2*sliceHdr->num_ref_idx_l0_active_minus1 + 1 for field MBs */
+
+    /* ref_pic_list_reordering() */
+    status = ref_pic_list_reordering(video, stream, sliceHdr, slice_type);
+    if (status != AVCDEC_SUCCESS)
+    {
+        return status;
+    }
+
+
+    if (video->nal_ref_idc != 0)
+    {
+        dec_ref_pic_marking(video, stream, sliceHdr);
+    }
+    se_v(stream, &(sliceHdr->slice_qp_delta));
+
+    video->QPy = 26 + currPPS->pic_init_qp_minus26 + sliceHdr->slice_qp_delta;
+    if (video->QPy > 51 || video->QPy < 0)
+    {
+        video->QPy = AVC_CLIP3(0, 51, video->QPy);
+//                  return AVCDEC_FAIL;
+    }
+    video->QPc = mapQPi2QPc[AVC_CLIP3(0, 51, video->QPy + video->currPicParams->chroma_qp_index_offset)];
+
+    video->QPy_div_6 = (video->QPy * 43) >> 8;
+    video->QPy_mod_6 = video->QPy - 6 * video->QPy_div_6;
+
+    video->QPc_div_6 = (video->QPc * 43) >> 8;
+    video->QPc_mod_6 = video->QPc - 6 * video->QPc_div_6;
+
+    sliceHdr->slice_alpha_c0_offset_div2 = 0;
+    sliceHdr->slice_beta_offset_div_2 = 0;
+    sliceHdr->disable_deblocking_filter_idc = 0;
+    video->FilterOffsetA = video->FilterOffsetB = 0;
+
+    if (currPPS->deblocking_filter_control_present_flag)
+    {
+        ue_v(stream, &(sliceHdr->disable_deblocking_filter_idc));
+        if (sliceHdr->disable_deblocking_filter_idc > 2)
+        {
+            return AVCDEC_FAIL; /* out of range */
+        }
+        if (sliceHdr->disable_deblocking_filter_idc != 1)
+        {
+            se_v(stream, &(sliceHdr->slice_alpha_c0_offset_div2));
+            if (sliceHdr->slice_alpha_c0_offset_div2 < -6 ||
+                    sliceHdr->slice_alpha_c0_offset_div2 > 6)
+            {
+                return AVCDEC_FAIL;
+            }
+            video->FilterOffsetA = sliceHdr->slice_alpha_c0_offset_div2 << 1;
+
+            se_v(stream, &(sliceHdr->slice_beta_offset_div_2));
+            if (sliceHdr->slice_beta_offset_div_2 < -6 ||
+                    sliceHdr->slice_beta_offset_div_2 > 6)
+            {
+                return AVCDEC_FAIL;
+            }
+            video->FilterOffsetB = sliceHdr->slice_beta_offset_div_2 << 1;
+        }
+    }
+
+    if (currPPS->num_slice_groups_minus1 > 0 && currPPS->slice_group_map_type >= 3
+            && currPPS->slice_group_map_type <= 5)
+    {
+        /* Ceil(Log2(PicSizeInMapUnits/(float)SliceGroupChangeRate + 1)) */
+        temp = video->PicSizeInMapUnits / video->SliceGroupChangeRate;
+        if (video->PicSizeInMapUnits % video->SliceGroupChangeRate)
+        {
+            temp++;
+        }
+        i = 0;
+        temp++;
+        while (temp)
+        {
+            temp >>= 1;
+            i++;
+        }
+
+        BitstreamReadBits(stream, i, &(sliceHdr->slice_group_change_cycle));
+        video->MapUnitsInSliceGroup0 =
+            AVC_MIN(sliceHdr->slice_group_change_cycle * video->SliceGroupChangeRate, video->PicSizeInMapUnits);
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+
+AVCDec_Status fill_frame_num_gap(AVCHandle *avcHandle, AVCCommonObj *video)
+{
+    AVCDec_Status status;
+    int CurrFrameNum;
+    int UnusedShortTermFrameNum;
+    int tmp1 = video->sliceHdr->delta_pic_order_cnt[0];
+    int tmp2 = video->sliceHdr->delta_pic_order_cnt[1];
+    int tmp3 = video->CurrPicNum;
+    int tmp4 = video->sliceHdr->adaptive_ref_pic_marking_mode_flag;
+    UnusedShortTermFrameNum = (video->prevFrameNum + 1) % video->MaxFrameNum;
+    CurrFrameNum = video->sliceHdr->frame_num;
+
+    video->sliceHdr->delta_pic_order_cnt[0] = 0;
+    video->sliceHdr->delta_pic_order_cnt[1] = 0;
+    while (CurrFrameNum != UnusedShortTermFrameNum)
+    {
+        video->CurrPicNum = UnusedShortTermFrameNum;
+        video->sliceHdr->frame_num = UnusedShortTermFrameNum;
+
+        status = (AVCDec_Status)DPBInitBuffer(avcHandle, video);
+        if (status != AVCDEC_SUCCESS)  /* no buffer available */
+        {
+            return status;
+        }
+        DecodePOC(video);
+        DPBInitPic(video, UnusedShortTermFrameNum);
+
+
+        video->currFS->PicOrderCnt = video->PicOrderCnt;
+        video->currFS->FrameNum = video->sliceHdr->frame_num;
+
+        /* initialize everything to zero */
+        video->currFS->IsOutputted = 0x01;
+        video->currFS->IsReference = 3;
+        video->currFS->IsLongTerm = 0;
+        video->currFS->frame.isReference = TRUE;
+        video->currFS->frame.isLongTerm = FALSE;
+
+        video->sliceHdr->adaptive_ref_pic_marking_mode_flag = 0;
+
+        status = (AVCDec_Status)StorePictureInDPB(avcHandle, video);  // MC_CHECK check the return status
+        if (status != AVCDEC_SUCCESS)
+        {
+            return AVCDEC_FAIL;
+        }
+        video->prevFrameNum = UnusedShortTermFrameNum;
+        UnusedShortTermFrameNum = (UnusedShortTermFrameNum + 1) % video->MaxFrameNum;
+    }
+    video->sliceHdr->frame_num = CurrFrameNum;
+    video->CurrPicNum = tmp3;
+    video->sliceHdr->delta_pic_order_cnt[0] = tmp1;
+    video->sliceHdr->delta_pic_order_cnt[1] = tmp2;
+    video->sliceHdr->adaptive_ref_pic_marking_mode_flag = tmp4;
+    return AVCDEC_SUCCESS;
+}
+
+/** see subclause 7.4.3.1 */
+AVCDec_Status ref_pic_list_reordering(AVCCommonObj *video, AVCDecBitstream *stream, AVCSliceHeader *sliceHdr, int slice_type)
+{
+    int i;
+
+    if (slice_type != AVC_I_SLICE)
+    {
+        BitstreamRead1Bit(stream, &(sliceHdr->ref_pic_list_reordering_flag_l0));
+        if (sliceHdr->ref_pic_list_reordering_flag_l0)
+        {
+            i = 0;
+            do
+            {
+                ue_v(stream, &(sliceHdr->reordering_of_pic_nums_idc_l0[i]));
+                if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 0 ||
+                        sliceHdr->reordering_of_pic_nums_idc_l0[i] == 1)
+                {
+                    ue_v(stream, &(sliceHdr->abs_diff_pic_num_minus1_l0[i]));
+                    if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 0 &&
+                            sliceHdr->abs_diff_pic_num_minus1_l0[i] > video->MaxPicNum / 2 - 1)
+                    {
+                        return AVCDEC_FAIL; /* out of range */
+                    }
+                    if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 1 &&
+                            sliceHdr->abs_diff_pic_num_minus1_l0[i] > video->MaxPicNum / 2 - 2)
+                    {
+                        return AVCDEC_FAIL; /* out of range */
+                    }
+                }
+                else if (sliceHdr->reordering_of_pic_nums_idc_l0[i] == 2)
+                {
+                    ue_v(stream, &(sliceHdr->long_term_pic_num_l0[i]));
+                }
+                i++;
+            }
+            while (sliceHdr->reordering_of_pic_nums_idc_l0[i-1] != 3
+                    && i <= (int)sliceHdr->num_ref_idx_l0_active_minus1 + 1) ;
+        }
+    }
+    return AVCDEC_SUCCESS;
+}
+
+/** see subclause 7.4.3.3 */
+AVCDec_Status dec_ref_pic_marking(AVCCommonObj *video, AVCDecBitstream *stream, AVCSliceHeader *sliceHdr)
+{
+    int i;
+    if (video->nal_unit_type == AVC_NALTYPE_IDR)
+    {
+        BitstreamRead1Bit(stream, &(sliceHdr->no_output_of_prior_pics_flag));
+        BitstreamRead1Bit(stream, &(sliceHdr->long_term_reference_flag));
+        if (sliceHdr->long_term_reference_flag == 0) /* used for short-term */
+        {
+            video->MaxLongTermFrameIdx = -1; /* no long-term frame indx */
+        }
+        else /* used for long-term */
+        {
+            video->MaxLongTermFrameIdx = 0;
+            video->LongTermFrameIdx = 0;
+        }
+    }
+    else
+    {
+        BitstreamRead1Bit(stream, &(sliceHdr->adaptive_ref_pic_marking_mode_flag));
+        if (sliceHdr->adaptive_ref_pic_marking_mode_flag)
+        {
+            i = 0;
+            do
+            {
+                ue_v(stream, &(sliceHdr->memory_management_control_operation[i]));
+                if (sliceHdr->memory_management_control_operation[i] == 1 ||
+                        sliceHdr->memory_management_control_operation[i] == 3)
+                {
+                    ue_v(stream, &(sliceHdr->difference_of_pic_nums_minus1[i]));
+                }
+                if (sliceHdr->memory_management_control_operation[i] == 2)
+                {
+                    ue_v(stream, &(sliceHdr->long_term_pic_num[i]));
+                }
+                if (sliceHdr->memory_management_control_operation[i] == 3 ||
+                        sliceHdr->memory_management_control_operation[i] == 6)
+                {
+                    ue_v(stream, &(sliceHdr->long_term_frame_idx[i]));
+                }
+                if (sliceHdr->memory_management_control_operation[i] == 4)
+                {
+                    ue_v(stream, &(sliceHdr->max_long_term_frame_idx_plus1[i]));
+                }
+                i++;
+            }
+            while (sliceHdr->memory_management_control_operation[i-1] != 0 && i < MAX_DEC_REF_PIC_MARKING);
+            if (i >= MAX_DEC_REF_PIC_MARKING)
+            {
+                return AVCDEC_FAIL; /* we're screwed!!, not enough memory */
+            }
+        }
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see subclause 8.2.1 Decoding process for picture order count. */
+AVCDec_Status DecodePOC(AVCCommonObj *video)
+{
+    AVCSeqParamSet *currSPS = video->currSeqParams;
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    int i;
+
+    switch (currSPS->pic_order_cnt_type)
+    {
+        case 0: /* POC MODE 0 , subclause 8.2.1.1 */
+            if (video->nal_unit_type == AVC_NALTYPE_IDR)
+            {
+                video->prevPicOrderCntMsb = 0;
+                video->prevPicOrderCntLsb = 0;
+            }
+
+            /* Calculate the MSBs of current picture */
+            if (sliceHdr->pic_order_cnt_lsb  <  video->prevPicOrderCntLsb  &&
+                    (video->prevPicOrderCntLsb - sliceHdr->pic_order_cnt_lsb)  >= (video->MaxPicOrderCntLsb / 2))
+                video->PicOrderCntMsb = video->prevPicOrderCntMsb + video->MaxPicOrderCntLsb;
+            else if (sliceHdr->pic_order_cnt_lsb  >  video->prevPicOrderCntLsb  &&
+                     (sliceHdr->pic_order_cnt_lsb - video->prevPicOrderCntLsb)  > (video->MaxPicOrderCntLsb / 2))
+                video->PicOrderCntMsb = video->prevPicOrderCntMsb - video->MaxPicOrderCntLsb;
+            else
+                video->PicOrderCntMsb = video->prevPicOrderCntMsb;
+
+            /* JVT-I010 page 81 is different from JM7.3 */
+
+
+            video->PicOrderCnt = video->TopFieldOrderCnt = video->PicOrderCntMsb + sliceHdr->pic_order_cnt_lsb;
+            video->BottomFieldOrderCnt = video->TopFieldOrderCnt + sliceHdr->delta_pic_order_cnt_bottom;
+
+            break;
+
+
+        case 1: /* POC MODE 1, subclause 8.2.1.2 */
+            /* calculate FrameNumOffset */
+            if (video->nal_unit_type == AVC_NALTYPE_IDR)
+            {
+                video->prevFrameNumOffset = 0;
+                video->FrameNumOffset = 0;
+            }
+            else if (video->prevFrameNum > sliceHdr->frame_num)
+            {
+                video->FrameNumOffset = video->prevFrameNumOffset + video->MaxFrameNum;
+            }
+            else
+            {
+                video->FrameNumOffset = video->prevFrameNumOffset;
+            }
+            /* calculate absFrameNum */
+            if (currSPS->num_ref_frames_in_pic_order_cnt_cycle)
+            {
+                video->absFrameNum = video->FrameNumOffset + sliceHdr->frame_num;
+            }
+            else
+            {
+                video->absFrameNum = 0;
+            }
+
+            if (video->absFrameNum > 0 && video->nal_ref_idc == 0)
+            {
+                video->absFrameNum--;
+            }
+
+            /* derive picOrderCntCycleCnt and frameNumInPicOrderCntCycle */
+            if (video->absFrameNum > 0)
+            {
+                video->picOrderCntCycleCnt = (video->absFrameNum - 1) / currSPS->num_ref_frames_in_pic_order_cnt_cycle;
+                video->frameNumInPicOrderCntCycle = (video->absFrameNum - 1) % currSPS->num_ref_frames_in_pic_order_cnt_cycle;
+            }
+            /* derive expectedDeltaPerPicOrderCntCycle */
+            video->expectedDeltaPerPicOrderCntCycle = 0;
+            for (i = 0; i < (int)currSPS->num_ref_frames_in_pic_order_cnt_cycle; i++)
+            {
+                video->expectedDeltaPerPicOrderCntCycle += currSPS->offset_for_ref_frame[i];
+            }
+            /* derive expectedPicOrderCnt */
+            if (video->absFrameNum)
+            {
+                video->expectedPicOrderCnt = video->picOrderCntCycleCnt * video->expectedDeltaPerPicOrderCntCycle;
+                for (i = 0; i <= video->frameNumInPicOrderCntCycle; i++)
+                {
+                    video->expectedPicOrderCnt += currSPS->offset_for_ref_frame[i];
+                }
+            }
+            else
+            {
+                video->expectedPicOrderCnt = 0;
+            }
+
+            if (video->nal_ref_idc == 0)
+            {
+                video->expectedPicOrderCnt += currSPS->offset_for_non_ref_pic;
+            }
+            /* derive TopFieldOrderCnt and BottomFieldOrderCnt */
+
+            video->TopFieldOrderCnt = video->expectedPicOrderCnt + sliceHdr->delta_pic_order_cnt[0];
+            video->BottomFieldOrderCnt = video->TopFieldOrderCnt + currSPS->offset_for_top_to_bottom_field + sliceHdr->delta_pic_order_cnt[1];
+
+            video->PicOrderCnt = AVC_MIN(video->TopFieldOrderCnt, video->BottomFieldOrderCnt);
+
+
+            break;
+
+
+        case 2: /* POC MODE 2, subclause 8.2.1.3 */
+            if (video->nal_unit_type == AVC_NALTYPE_IDR)
+            {
+                video->FrameNumOffset = 0;
+            }
+            else if (video->prevFrameNum > sliceHdr->frame_num)
+            {
+                video->FrameNumOffset = video->prevFrameNumOffset + video->MaxFrameNum;
+            }
+            else
+            {
+                video->FrameNumOffset = video->prevFrameNumOffset;
+            }
+            /* derive tempPicOrderCnt, we just use PicOrderCnt */
+            if (video->nal_unit_type == AVC_NALTYPE_IDR)
+            {
+                video->PicOrderCnt = 0;
+            }
+            else if (video->nal_ref_idc == 0)
+            {
+                video->PicOrderCnt = 2 * (video->FrameNumOffset + sliceHdr->frame_num) - 1;
+            }
+            else
+            {
+                video->PicOrderCnt = 2 * (video->FrameNumOffset + sliceHdr->frame_num);
+            }
+            video->TopFieldOrderCnt = video->BottomFieldOrderCnt = video->PicOrderCnt;
+            break;
+        default:
+            return AVCDEC_FAIL;
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+
+AVCDec_Status DecodeSEI(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    OSCL_UNUSED_ARG(decvid);
+    OSCL_UNUSED_ARG(stream);
+    return AVCDEC_SUCCESS;
+}
+
+AVCDec_Status sei_payload(AVCDecObject *decvid, AVCDecBitstream *stream, uint payloadType, uint payloadSize)
+{
+    AVCDec_Status status = AVCDEC_SUCCESS;
+    uint i;
+    switch (payloadType)
+    {
+        case 0:
+            /*  buffering period SEI */
+            status = buffering_period(decvid, stream);
+            break;
+        case 1:
+            /*  picture timing SEI */
+            status = pic_timing(decvid, stream);
+            break;
+        case 2:
+
+        case 3:
+
+        case 4:
+
+        case 5:
+
+        case 8:
+
+        case 9:
+
+        case 10:
+
+        case 11:
+
+        case 12:
+
+        case 13:
+
+        case 14:
+
+        case 15:
+
+        case 16:
+
+        case 17:
+            for (i = 0; i < payloadSize; i++)
+            {
+                BitstreamFlushBits(stream, 8);
+            }
+            break;
+        case 6:
+            /*      recovery point SEI              */
+            status = recovery_point(decvid, stream);
+            break;
+        case 7:
+            /*      decoded reference picture marking repetition SEI */
+            status = dec_ref_pic_marking_repetition(decvid, stream);
+            break;
+
+        case 18:
+            /*      motion-constrained slice group set SEI */
+            status = motion_constrained_slice_group_set(decvid, stream);
+            break;
+        default:
+            /*          reserved_sei_message */
+            for (i = 0; i < payloadSize; i++)
+            {
+                BitstreamFlushBits(stream, 8);
+            }
+            break;
+    }
+    BitstreamByteAlign(stream);
+    return status;
+}
+
+AVCDec_Status buffering_period(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    AVCSeqParamSet *currSPS;
+    uint seq_parameter_set_id;
+    uint temp;
+    uint i;
+    ue_v(stream, &seq_parameter_set_id);
+    if (seq_parameter_set_id > 31)
+    {
+        return AVCDEC_FAIL;
+    }
+
+//  decvid->common->seq_parameter_set_id = seq_parameter_set_id;
+
+    currSPS = decvid->seqParams[seq_parameter_set_id];
+    if (currSPS->vui_parameters.nal_hrd_parameters_present_flag)
+    {
+        for (i = 0; i <= currSPS->vui_parameters.nal_hrd_parameters.cpb_cnt_minus1; i++)
+        {
+            /* initial_cpb_removal_delay[i] */
+            BitstreamReadBits(stream, currSPS->vui_parameters.nal_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+            /*initial _cpb_removal_delay_offset[i] */
+            BitstreamReadBits(stream, currSPS->vui_parameters.nal_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+        }
+    }
+
+    if (currSPS->vui_parameters.vcl_hrd_parameters_present_flag)
+    {
+        for (i = 0; i <= currSPS->vui_parameters.vcl_hrd_parameters.cpb_cnt_minus1; i++)
+        {
+            /* initial_cpb_removal_delay[i] */
+            BitstreamReadBits(stream, currSPS->vui_parameters.vcl_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+            /*initial _cpb_removal_delay_offset[i] */
+            BitstreamReadBits(stream, currSPS->vui_parameters.vcl_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+        }
+    }
+
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status pic_timing(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    AVCSeqParamSet *currSPS;
+    uint temp, NumClockTs = 0, time_offset_length = 24, full_timestamp_flag;
+    uint i;
+
+    currSPS = decvid->seqParams[decvid->common->seq_parameter_set_id];
+
+    if (currSPS->vui_parameters.nal_hrd_parameters_present_flag)
+    {
+        BitstreamReadBits(stream, currSPS->vui_parameters.nal_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+        BitstreamReadBits(stream, currSPS->vui_parameters.nal_hrd_parameters.dpb_output_delay_length_minus1 + 1, &temp);
+        time_offset_length = currSPS->vui_parameters.nal_hrd_parameters.time_offset_length;
+    }
+    else if (currSPS->vui_parameters.vcl_hrd_parameters_present_flag)
+    {
+        BitstreamReadBits(stream, currSPS->vui_parameters.vcl_hrd_parameters.cpb_removal_delay_length_minus1 + 1, &temp);
+        BitstreamReadBits(stream, currSPS->vui_parameters.vcl_hrd_parameters.dpb_output_delay_length_minus1 + 1, &temp);
+        time_offset_length = currSPS->vui_parameters.vcl_hrd_parameters.time_offset_length;
+    }
+
+    if (currSPS->vui_parameters.pic_struct_present_flag)
+    {
+        /* pic_struct */
+        BitstreamReadBits(stream, 4, &temp);
+
+        switch (temp)
+        {
+            case 0:
+            case 1:
+            case 2:
+                NumClockTs = 1;
+                break;
+            case 3:
+            case 4:
+            case 7:
+                NumClockTs = 2;
+                break;
+            case 5:
+            case 6:
+            case 8:
+                NumClockTs = 3;
+                break;
+            default:
+                NumClockTs = 0;
+                break;
+        }
+
+        for (i = 0; i < NumClockTs; i++)
+        {
+            /* clock_timestamp_flag[i] */
+            BitstreamRead1Bit(stream, &temp);
+            if (temp)
+            {
+                /* ct_type */
+                BitstreamReadBits(stream, 2, &temp);
+                /* nuit_field_based_flag */
+                BitstreamRead1Bit(stream, &temp);
+                /* counting_type        */
+                BitstreamReadBits(stream, 5, &temp);
+                /* full_timestamp_flag */
+                BitstreamRead1Bit(stream, &temp);
+                full_timestamp_flag = temp;
+                /* discontinuity_flag */
+                BitstreamRead1Bit(stream, &temp);
+                /* cnt_dropped_flag */
+                BitstreamRead1Bit(stream, &temp);
+                /* n_frames           */
+                BitstreamReadBits(stream, 8, &temp);
+
+
+                if (full_timestamp_flag)
+                {
+                    /* seconds_value */
+                    BitstreamReadBits(stream, 6, &temp);
+                    /* minutes_value */
+                    BitstreamReadBits(stream, 6, &temp);
+                    /* hours_value */
+                    BitstreamReadBits(stream, 5, &temp);
+                }
+                else
+                {
+                    /* seconds_flag  */
+                    BitstreamRead1Bit(stream, &temp);
+                    if (temp)
+                    {
+                        /* seconds_value */
+                        BitstreamReadBits(stream, 6, &temp);
+                        /* minutes_flag  */
+                        BitstreamRead1Bit(stream, &temp);
+                        if (temp)
+                        {
+                            /* minutes_value */
+                            BitstreamReadBits(stream, 6, &temp);
+
+                            /* hourss_flag  */
+                            BitstreamRead1Bit(stream, &temp);
+
+                            if (temp)
+                            {
+                                /* hours_value */
+                                BitstreamReadBits(stream, 5, &temp);
+                            }
+
+                        }
+                    }
+                }
+
+                if (time_offset_length)
+                {
+                    /* time_offset */
+                    BitstreamReadBits(stream, time_offset_length, &temp);
+                }
+                else
+                {
+                    /* time_offset */
+                    temp = 0;
+                }
+            }
+        }
+    }
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status recovery_point(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    OSCL_UNUSED_ARG(decvid);
+    uint temp;
+    /* recover_frame_cnt */
+    ue_v(stream, &temp);
+    /* exact_match_flag */
+    BitstreamRead1Bit(stream, &temp);
+    /* broken_link_flag */
+    BitstreamRead1Bit(stream, &temp);
+    /* changing slic_group_idc */
+    BitstreamReadBits(stream, 2, &temp);
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status dec_ref_pic_marking_repetition(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    AVCSeqParamSet *currSPS;
+    uint temp;
+    currSPS = decvid->seqParams[decvid->common->seq_parameter_set_id];
+    /* original_idr_flag */
+    BitstreamRead1Bit(stream, &temp);
+    /* original_frame_num */
+    ue_v(stream, &temp);
+    if (currSPS->frame_mbs_only_flag == 0)
+    {
+        /* original_field_pic_flag */
+        BitstreamRead1Bit(stream, &temp);
+        if (temp)
+        {
+            /* original_bottom_field_flag */
+            BitstreamRead1Bit(stream, &temp);
+        }
+    }
+
+    /*  dec_ref_pic_marking(video,stream,sliceHdr); */
+
+
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status motion_constrained_slice_group_set(AVCDecObject *decvid, AVCDecBitstream *stream)
+{
+    OSCL_UNUSED_ARG(decvid);
+    uint temp, i, numBits;
+    /* num_slice_groups_in_set_minus1 */
+    ue_v(stream, &temp);
+
+    numBits = 0;/* ceil(log2(num_slice_groups_minus1+1)) bits */
+    i = temp;
+    while (i > 0)
+    {
+        numBits++;
+        i >>= 1;
+    }
+    for (i = 0; i <= temp; i++)
+    {
+        /* slice_group_id */
+        BitstreamReadBits(stream, numBits, &temp);
+    }
+    /* exact_sample_value_match_flag */
+    BitstreamRead1Bit(stream, &temp);
+    /* pan_scan_rect_flag */
+    BitstreamRead1Bit(stream, &temp);
+    if (temp)
+    {
+        /* pan_scan_rect_id */
+        ue_v(stream, &temp);
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
diff --git a/media/libstagefright/codecs/avc/dec/src/itrans.cpp b/media/libstagefright/codecs/avc/dec/src/itrans.cpp
new file mode 100644
index 0000000..02c550d
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/itrans.cpp
@@ -0,0 +1,307 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avclib_common.h"
+
+/* input are in the first 16 elements of block,
+   output must be in the location specified in Figure 8-6. */
+/* subclause 8.5.6 */
+void Intra16DCTrans(int16 *block, int Qq, int Rq)
+{
+    int m0, m1, m2, m3;
+    int j, offset;
+    int16 *inout;
+    int scale = dequant_coefres[Rq][0];
+
+    inout = block;
+    for (j = 0; j < 4; j++)
+    {
+        m0 = inout[0] + inout[4];
+        m1 = inout[0] - inout[4];
+        m2 = inout[8] + inout[12];
+        m3 = inout[8] - inout[12];
+
+
+        inout[0] = m0 + m2;
+        inout[4] = m0 - m2;
+        inout[8] = m1 - m3;
+        inout[12] = m1 + m3;
+        inout += 64;
+    }
+
+    inout = block;
+
+    if (Qq >= 2)  /* this way should be faster than JM */
+    {           /* they use (((m4*scale)<<(QPy/6))+2)>>2 for both cases. */
+        Qq -= 2;
+        for (j = 0; j < 4; j++)
+        {
+            m0 = inout[0] + inout[64];
+            m1 = inout[0] - inout[64];
+            m2 = inout[128] + inout[192];
+            m3 = inout[128] - inout[192];
+
+            inout[0] = ((m0 + m2) * scale) << Qq;
+            inout[64] = ((m0 - m2) * scale) << Qq;
+            inout[128] = ((m1 - m3) * scale) << Qq;
+            inout[192] = ((m1 + m3) * scale) << Qq;
+            inout += 4;
+        }
+    }
+    else
+    {
+        Qq = 2 - Qq;
+        offset = 1 << (Qq - 1);
+
+        for (j = 0; j < 4; j++)
+        {
+            m0 = inout[0] + inout[64];
+            m1 = inout[0] - inout[64];
+            m2 = inout[128] + inout[192];
+            m3 = inout[128] - inout[192];
+
+            inout[0] = (((m0 + m2) * scale + offset) >> Qq);
+            inout[64] = (((m0 - m2) * scale + offset) >> Qq);
+            inout[128] = (((m1 - m3) * scale + offset) >> Qq);
+            inout[192] = (((m1 + m3) * scale + offset) >> Qq);
+            inout += 4;
+        }
+    }
+
+    return ;
+}
+
+/* see subclase 8.5.8 */
+void itrans(int16 *block, uint8 *pred, uint8 *cur, int width)
+{
+    int e0, e1, e2, e3; /* note, at every step of the calculation, these values */
+    /* shall never exceed 16bit sign value, but we don't check */
+    int i;           /* to save the cycles. */
+    int16 *inout;
+
+    inout = block;
+
+    for (i = 4; i > 0; i--)
+    {
+        e0 = inout[0] + inout[2];
+        e1 = inout[0] - inout[2];
+        e2 = (inout[1] >> 1) - inout[3];
+        e3 = inout[1] + (inout[3] >> 1);
+
+        inout[0] = e0 + e3;
+        inout[1] = e1 + e2;
+        inout[2] = e1 - e2;
+        inout[3] = e0 - e3;
+
+        inout += 16;
+    }
+
+    for (i = 4; i > 0; i--)
+    {
+        e0 = block[0] + block[32];
+        e1 = block[0] - block[32];
+        e2 = (block[16] >> 1) - block[48];
+        e3 = block[16] + (block[48] >> 1);
+
+        e0 += e3;
+        e3 = (e0 - (e3 << 1)); /* e0-e3 */
+        e1 += e2;
+        e2 = (e1 - (e2 << 1)); /* e1-e2 */
+        e0 += 32;
+        e1 += 32;
+        e2 += 32;
+        e3 += 32;
+#ifdef USE_PRED_BLOCK
+        e0 = pred[0] + (e0 >> 6);
+        if ((uint)e0 > 0xFF)   e0 = 0xFF & (~(e0 >> 31));  /* clip */
+        e1 = pred[20] + (e1 >> 6);
+        if ((uint)e1 > 0xFF)   e1 = 0xFF & (~(e1 >> 31));  /* clip */
+        e2 = pred[40] + (e2 >> 6);
+        if ((uint)e2 > 0xFF)   e2 = 0xFF & (~(e2 >> 31));  /* clip */
+        e3 = pred[60] + (e3 >> 6);
+        if ((uint)e3 > 0xFF)   e3 = 0xFF & (~(e3 >> 31));  /* clip */
+        *cur = e0;
+        *(cur += width) = e1;
+        *(cur += width) = e2;
+        cur[width] = e3;
+        cur -= (width << 1);
+        cur++;
+        pred++;
+#else
+        OSCL_UNUSED_ARG(pred);
+
+        e0 = *cur + (e0 >> 6);
+        if ((uint)e0 > 0xFF)   e0 = 0xFF & (~(e0 >> 31));  /* clip */
+        *cur = e0;
+        e1 = *(cur += width) + (e1 >> 6);
+        if ((uint)e1 > 0xFF)   e1 = 0xFF & (~(e1 >> 31));  /* clip */
+        *cur = e1;
+        e2 = *(cur += width) + (e2 >> 6);
+        if ((uint)e2 > 0xFF)   e2 = 0xFF & (~(e2 >> 31));  /* clip */
+        *cur = e2;
+        e3 = cur[width] + (e3 >> 6);
+        if ((uint)e3 > 0xFF)   e3 = 0xFF & (~(e3 >> 31));  /* clip */
+        cur[width] = e3;
+        cur -= (width << 1);
+        cur++;
+#endif
+        block++;
+    }
+
+    return ;
+}
+
+/* see subclase 8.5.8 */
+void ictrans(int16 *block, uint8 *pred, uint8 *cur, int width)
+{
+    int e0, e1, e2, e3; /* note, at every step of the calculation, these values */
+    /* shall never exceed 16bit sign value, but we don't check */
+    int i;           /* to save the cycles. */
+    int16 *inout;
+
+    inout = block;
+
+    for (i = 4; i > 0; i--)
+    {
+        e0 = inout[0] + inout[2];
+        e1 = inout[0] - inout[2];
+        e2 = (inout[1] >> 1) - inout[3];
+        e3 = inout[1] + (inout[3] >> 1);
+
+        inout[0] = e0 + e3;
+        inout[1] = e1 + e2;
+        inout[2] = e1 - e2;
+        inout[3] = e0 - e3;
+
+        inout += 16;
+    }
+
+    for (i = 4; i > 0; i--)
+    {
+        e0 = block[0] + block[32];
+        e1 = block[0] - block[32];
+        e2 = (block[16] >> 1) - block[48];
+        e3 = block[16] + (block[48] >> 1);
+
+        e0 += e3;
+        e3 = (e0 - (e3 << 1)); /* e0-e3 */
+        e1 += e2;
+        e2 = (e1 - (e2 << 1)); /* e1-e2 */
+        e0 += 32;
+        e1 += 32;
+        e2 += 32;
+        e3 += 32;
+#ifdef USE_PRED_BLOCK
+        e0 = pred[0] + (e0 >> 6);
+        if ((uint)e0 > 0xFF)   e0 = 0xFF & (~(e0 >> 31));  /* clip */
+        e1 = pred[12] + (e1 >> 6);
+        if ((uint)e1 > 0xFF)   e1 = 0xFF & (~(e1 >> 31));  /* clip */
+        e2 = pred[24] + (e2 >> 6);
+        if ((uint)e2 > 0xFF)   e2 = 0xFF & (~(e2 >> 31));  /* clip */
+        e3 = pred[36] + (e3 >> 6);
+        if ((uint)e3 > 0xFF)   e3 = 0xFF & (~(e3 >> 31));  /* clip */
+        *cur = e0;
+        *(cur += width) = e1;
+        *(cur += width) = e2;
+        cur[width] = e3;
+        cur -= (width << 1);
+        cur++;
+        pred++;
+#else
+        OSCL_UNUSED_ARG(pred);
+
+        e0 = *cur + (e0 >> 6);
+        if ((uint)e0 > 0xFF)   e0 = 0xFF & (~(e0 >> 31));  /* clip */
+        *cur = e0;
+        e1 = *(cur += width) + (e1 >> 6);
+        if ((uint)e1 > 0xFF)   e1 = 0xFF & (~(e1 >> 31));  /* clip */
+        *cur = e1;
+        e2 = *(cur += width) + (e2 >> 6);
+        if ((uint)e2 > 0xFF)   e2 = 0xFF & (~(e2 >> 31));  /* clip */
+        *cur = e2;
+        e3 = cur[width] + (e3 >> 6);
+        if ((uint)e3 > 0xFF)   e3 = 0xFF & (~(e3 >> 31));  /* clip */
+        cur[width] = e3;
+        cur -= (width << 1);
+        cur++;
+#endif
+        block++;
+    }
+
+    return ;
+}
+
+/* see subclause 8.5.7 */
+void ChromaDCTrans(int16 *block, int Qq, int Rq)
+{
+    int c00, c01, c10, c11;
+    int f0, f1, f2, f3;
+    int scale = dequant_coefres[Rq][0];
+
+    c00 = block[0] + block[4];
+    c01 = block[0] - block[4];
+    c10 = block[64] + block[68];
+    c11 = block[64] - block[68];
+
+    f0 = c00 + c10;
+    f1 = c01 + c11;
+    f2 = c00 - c10;
+    f3 = c01 - c11;
+
+    if (Qq >= 1)
+    {
+        Qq -= 1;
+        block[0] = (f0 * scale) << Qq;
+        block[4] = (f1 * scale) << Qq;
+        block[64] = (f2 * scale) << Qq;
+        block[68] = (f3 * scale) << Qq;
+    }
+    else
+    {
+        block[0] = (f0 * scale) >> 1;
+        block[4] = (f1 * scale) >> 1;
+        block[64] = (f2 * scale) >> 1;
+        block[68] = (f3 * scale) >> 1;
+    }
+
+    return ;
+}
+
+
+void copy_block(uint8 *pred, uint8 *cur, int width, int pred_pitch)
+{
+    uint32 temp;
+
+    temp = *((uint32*)pred);
+    pred += pred_pitch;
+    *((uint32*)cur) = temp;
+    cur += width;
+    temp = *((uint32*)pred);
+    pred += pred_pitch;
+    *((uint32*)cur) = temp;
+    cur += width;
+    temp = *((uint32*)pred);
+    pred += pred_pitch;
+    *((uint32*)cur) = temp;
+    cur += width;
+    temp = *((uint32*)pred);
+    *((uint32*)cur) = temp;
+
+    return ;
+}
+
+
diff --git a/media/libstagefright/codecs/avc/dec/src/pred_inter.cpp b/media/libstagefright/codecs/avc/dec/src/pred_inter.cpp
new file mode 100644
index 0000000..ba36c37
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/pred_inter.cpp
@@ -0,0 +1,2329 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avcdec_lib.h"
+
+
+#define CLIP_RESULT(x)      if((uint)x > 0xFF){ \
+                 x = 0xFF & (~(x>>31));}
+
+/* (blkwidth << 2) + (dy << 1) + dx */
+static void (*const ChromaMC_SIMD[8])(uint8 *, int , int , int , uint8 *, int, int , int) =
+{
+    &ChromaFullMC_SIMD,
+    &ChromaHorizontalMC_SIMD,
+    &ChromaVerticalMC_SIMD,
+    &ChromaDiagonalMC_SIMD,
+    &ChromaFullMC_SIMD,
+    &ChromaHorizontalMC2_SIMD,
+    &ChromaVerticalMC2_SIMD,
+    &ChromaDiagonalMC2_SIMD
+};
+/* Perform motion prediction and compensation with residue if exist. */
+void InterMBPrediction(AVCCommonObj *video)
+{
+    AVCMacroblock *currMB = video->currMB;
+    AVCPictureData *currPic = video->currPic;
+    int mbPartIdx, subMbPartIdx;
+    int ref_idx;
+    int offset_MbPart_indx = 0;
+    int16 *mv;
+    uint32 x_pos, y_pos;
+    uint8 *curL, *curCb, *curCr;
+    uint8 *ref_l, *ref_Cb, *ref_Cr;
+    uint8 *predBlock, *predCb, *predCr;
+    int block_x, block_y, offset_x, offset_y, offsetP, offset;
+    int x_position = (video->mb_x << 4);
+    int y_position = (video->mb_y << 4);
+    int MbHeight, MbWidth, mbPartIdx_X, mbPartIdx_Y, offset_indx;
+    int picWidth = currPic->pitch;
+    int picHeight = currPic->height;
+    int16 *dataBlock;
+    uint32 cbp4x4;
+    uint32 tmp_word;
+
+    tmp_word = y_position * picWidth;
+    curL = currPic->Sl + tmp_word + x_position;
+    offset = (tmp_word >> 2) + (x_position >> 1);
+    curCb = currPic->Scb + offset;
+    curCr = currPic->Scr + offset;
+
+#ifdef USE_PRED_BLOCK
+    predBlock = video->pred + 84;
+    predCb = video->pred + 452;
+    predCr = video->pred + 596;
+#else
+    predBlock = curL;
+    predCb = curCb;
+    predCr = curCr;
+#endif
+
+    GetMotionVectorPredictor(video, false);
+
+    for (mbPartIdx = 0; mbPartIdx < currMB->NumMbPart; mbPartIdx++)
+    {
+        MbHeight = currMB->SubMbPartHeight[mbPartIdx];
+        MbWidth = currMB->SubMbPartWidth[mbPartIdx];
+        mbPartIdx_X = ((mbPartIdx + offset_MbPart_indx) & 1);
+        mbPartIdx_Y = (mbPartIdx + offset_MbPart_indx) >> 1;
+        ref_idx = currMB->ref_idx_L0[(mbPartIdx_Y << 1) + mbPartIdx_X];
+        offset_indx = 0;
+
+        ref_l = video->RefPicList0[ref_idx]->Sl;
+        ref_Cb = video->RefPicList0[ref_idx]->Scb;
+        ref_Cr = video->RefPicList0[ref_idx]->Scr;
+
+        for (subMbPartIdx = 0; subMbPartIdx < currMB->NumSubMbPart[mbPartIdx]; subMbPartIdx++)
+        {
+            block_x = (mbPartIdx_X << 1) + ((subMbPartIdx + offset_indx) & 1);  // check this
+            block_y = (mbPartIdx_Y << 1) + (((subMbPartIdx + offset_indx) >> 1) & 1);
+            mv = (int16*)(currMB->mvL0 + block_x + (block_y << 2));
+            offset_x = x_position + (block_x << 2);
+            offset_y = y_position + (block_y << 2);
+            x_pos = (offset_x << 2) + *mv++;   /*quarter pel */
+            y_pos = (offset_y << 2) + *mv;   /*quarter pel */
+
+            //offset = offset_y * currPic->width;
+            //offsetC = (offset >> 2) + (offset_x >> 1);
+#ifdef USE_PRED_BLOCK
+            offsetP = (block_y * 80) + (block_x << 2);
+            LumaMotionComp(ref_l, picWidth, picHeight, x_pos, y_pos,
+                           /*comp_Sl + offset + offset_x,*/
+                           predBlock + offsetP, 20, MbWidth, MbHeight);
+#else
+            offsetP = (block_y << 2) * picWidth + (block_x << 2);
+            LumaMotionComp(ref_l, picWidth, picHeight, x_pos, y_pos,
+                           /*comp_Sl + offset + offset_x,*/
+                           predBlock + offsetP, picWidth, MbWidth, MbHeight);
+#endif
+
+#ifdef USE_PRED_BLOCK
+            offsetP = (block_y * 24) + (block_x << 1);
+            ChromaMotionComp(ref_Cb, picWidth >> 1, picHeight >> 1, x_pos, y_pos,
+                             /*comp_Scb +  offsetC,*/
+                             predCb + offsetP, 12, MbWidth >> 1, MbHeight >> 1);
+            ChromaMotionComp(ref_Cr, picWidth >> 1, picHeight >> 1, x_pos, y_pos,
+                             /*comp_Scr +  offsetC,*/
+                             predCr + offsetP, 12, MbWidth >> 1, MbHeight >> 1);
+#else
+            offsetP = (block_y * picWidth) + (block_x << 1);
+            ChromaMotionComp(ref_Cb, picWidth >> 1, picHeight >> 1, x_pos, y_pos,
+                             /*comp_Scb +  offsetC,*/
+                             predCb + offsetP, picWidth >> 1, MbWidth >> 1, MbHeight >> 1);
+            ChromaMotionComp(ref_Cr, picWidth >> 1, picHeight >> 1, x_pos, y_pos,
+                             /*comp_Scr +  offsetC,*/
+                             predCr + offsetP, picWidth >> 1, MbWidth >> 1, MbHeight >> 1);
+#endif
+
+            offset_indx = currMB->SubMbPartWidth[mbPartIdx] >> 3;
+        }
+        offset_MbPart_indx = currMB->MbPartWidth >> 4;
+    }
+
+    /* used in decoder, used to be if(!encFlag)  */
+
+    /* transform in raster scan order */
+    dataBlock = video->block;
+    cbp4x4 = video->cbp4x4;
+    /* luma */
+    for (block_y = 4; block_y > 0; block_y--)
+    {
+        for (block_x = 4; block_x > 0; block_x--)
+        {
+#ifdef USE_PRED_BLOCK
+            if (cbp4x4&1)
+            {
+                itrans(dataBlock, predBlock, predBlock, 20);
+            }
+#else
+            if (cbp4x4&1)
+            {
+                itrans(dataBlock, curL, curL, picWidth);
+            }
+#endif
+            cbp4x4 >>= 1;
+            dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+            predBlock += 4;
+#else
+            curL += 4;
+#endif
+        }
+        dataBlock += 48;
+#ifdef USE_PRED_BLOCK
+        predBlock += 64;
+#else
+        curL += ((picWidth << 2) - 16);
+#endif
+    }
+
+    /* chroma */
+    picWidth = (picWidth >> 1);
+    for (block_y = 2; block_y > 0; block_y--)
+    {
+        for (block_x = 2; block_x > 0; block_x--)
+        {
+#ifdef USE_PRED_BLOCK
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, predCb, predCb, 12);
+            }
+#else
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, curCb, curCb, picWidth);
+            }
+#endif
+            cbp4x4 >>= 1;
+            dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+            predCb += 4;
+#else
+            curCb += 4;
+#endif
+        }
+        for (block_x = 2; block_x > 0; block_x--)
+        {
+#ifdef USE_PRED_BLOCK
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, predCr, predCr, 12);
+            }
+#else
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, curCr, curCr, picWidth);
+            }
+#endif
+            cbp4x4 >>= 1;
+            dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+            predCr += 4;
+#else
+            curCr += 4;
+#endif
+        }
+        dataBlock += 48;
+#ifdef USE_PRED_BLOCK
+        predCb += 40;
+        predCr += 40;
+#else
+        curCb += ((picWidth << 2) - 8);
+        curCr += ((picWidth << 2) - 8);
+#endif
+    }
+
+#ifdef MB_BASED_DEBLOCK
+    SaveNeighborForIntraPred(video, offset);
+#endif
+
+    return ;
+}
+
+
+/* preform the actual  motion comp here */
+void LumaMotionComp(uint8 *ref, int picwidth, int picheight,
+                    int x_pos, int y_pos,
+                    uint8 *pred, int pred_pitch,
+                    int blkwidth, int blkheight)
+{
+    int dx, dy;
+    uint8 temp[24][24]; /* for padding, make the size multiple of 4 for packing */
+    int temp2[21][21]; /* for intermediate results */
+    uint8 *ref2;
+
+    dx = x_pos & 3;
+    dy = y_pos & 3;
+    x_pos = x_pos >> 2;  /* round it to full-pel resolution */
+    y_pos = y_pos >> 2;
+
+    /* perform actual motion compensation */
+    if (dx == 0 && dy == 0)
+    {  /* fullpel position *//* G */
+        if (x_pos >= 0 && x_pos + blkwidth <= picwidth && y_pos >= 0 && y_pos + blkheight <= picheight)
+        {
+            ref += y_pos * picwidth + x_pos;
+            FullPelMC(ref, picwidth, pred, pred_pitch, blkwidth, blkheight);
+        }
+        else
+        {
+            CreatePad(ref, picwidth, picheight, x_pos, y_pos, &temp[0][0], blkwidth, blkheight);
+            FullPelMC(&temp[0][0], 24, pred, pred_pitch, blkwidth, blkheight);
+        }
+
+    }   /* other positions */
+    else  if (dy == 0)
+    { /* no vertical interpolation *//* a,b,c*/
+
+        if (x_pos - 2 >= 0 && x_pos + 3 + blkwidth <= picwidth && y_pos >= 0 && y_pos + blkheight <= picheight)
+        {
+            ref += y_pos * picwidth + x_pos;
+
+            HorzInterp1MC(ref, picwidth, pred, pred_pitch, blkwidth, blkheight, dx);
+        }
+        else  /* need padding */
+        {
+            CreatePad(ref, picwidth, picheight, x_pos - 2, y_pos, &temp[0][0], blkwidth + 5, blkheight);
+
+            HorzInterp1MC(&temp[0][2], 24, pred, pred_pitch, blkwidth, blkheight, dx);
+        }
+    }
+    else if (dx == 0)
+    { /*no horizontal interpolation *//* d,h,n */
+
+        if (x_pos >= 0 && x_pos + blkwidth <= picwidth && y_pos - 2 >= 0 && y_pos + 3 + blkheight <= picheight)
+        {
+            ref += y_pos * picwidth + x_pos;
+
+            VertInterp1MC(ref, picwidth, pred, pred_pitch, blkwidth, blkheight, dy);
+        }
+        else  /* need padding */
+        {
+            CreatePad(ref, picwidth, picheight, x_pos, y_pos - 2, &temp[0][0], blkwidth, blkheight + 5);
+
+            VertInterp1MC(&temp[2][0], 24, pred, pred_pitch, blkwidth, blkheight, dy);
+        }
+    }
+    else if (dy == 2)
+    {  /* horizontal cross *//* i, j, k */
+
+        if (x_pos - 2 >= 0 && x_pos + 3 + blkwidth <= picwidth && y_pos - 2 >= 0 && y_pos + 3 + blkheight <= picheight)
+        {
+            ref += y_pos * picwidth + x_pos - 2; /* move to the left 2 pixels */
+
+            VertInterp2MC(ref, picwidth, &temp2[0][0], 21, blkwidth + 5, blkheight);
+
+            HorzInterp2MC(&temp2[0][2], 21, pred, pred_pitch, blkwidth, blkheight, dx);
+        }
+        else /* need padding */
+        {
+            CreatePad(ref, picwidth, picheight, x_pos - 2, y_pos - 2, &temp[0][0], blkwidth + 5, blkheight + 5);
+
+            VertInterp2MC(&temp[2][0], 24, &temp2[0][0], 21, blkwidth + 5, blkheight);
+
+            HorzInterp2MC(&temp2[0][2], 21, pred, pred_pitch, blkwidth, blkheight, dx);
+        }
+    }
+    else if (dx == 2)
+    { /* vertical cross */ /* f,q */
+
+        if (x_pos - 2 >= 0 && x_pos + 3 + blkwidth <= picwidth && y_pos - 2 >= 0 && y_pos + 3 + blkheight <= picheight)
+        {
+            ref += (y_pos - 2) * picwidth + x_pos; /* move to up 2 lines */
+
+            HorzInterp3MC(ref, picwidth, &temp2[0][0], 21, blkwidth, blkheight + 5);
+            VertInterp3MC(&temp2[2][0], 21, pred, pred_pitch, blkwidth, blkheight, dy);
+        }
+        else  /* need padding */
+        {
+            CreatePad(ref, picwidth, picheight, x_pos - 2, y_pos - 2, &temp[0][0], blkwidth + 5, blkheight + 5);
+            HorzInterp3MC(&temp[0][2], 24, &temp2[0][0], 21, blkwidth, blkheight + 5);
+            VertInterp3MC(&temp2[2][0], 21, pred, pred_pitch, blkwidth, blkheight, dy);
+        }
+    }
+    else
+    { /* diagonal *//* e,g,p,r */
+
+        if (x_pos - 2 >= 0 && x_pos + 3 + (dx / 2) + blkwidth <= picwidth &&
+                y_pos - 2 >= 0 && y_pos + 3 + blkheight + (dy / 2) <= picheight)
+        {
+            ref2 = ref + (y_pos + (dy / 2)) * picwidth + x_pos;
+
+            ref += (y_pos * picwidth) + x_pos + (dx / 2);
+
+            DiagonalInterpMC(ref2, ref, picwidth, pred, pred_pitch, blkwidth, blkheight);
+        }
+        else  /* need padding */
+        {
+            CreatePad(ref, picwidth, picheight, x_pos - 2, y_pos - 2, &temp[0][0], blkwidth + 5 + (dx / 2), blkheight + 5 + (dy / 2));
+
+            ref2 = &temp[2 + (dy/2)][2];
+
+            ref = &temp[2][2 + (dx/2)];
+
+            DiagonalInterpMC(ref2, ref, 24, pred, pred_pitch, blkwidth, blkheight);
+        }
+    }
+
+    return ;
+}
+
+void CreateAlign(uint8 *ref, int picwidth, int y_pos,
+                 uint8 *out, int blkwidth, int blkheight)
+{
+    int i, j;
+    int offset, out_offset;
+    uint32 prev_pix, result, pix1, pix2, pix4;
+
+    out_offset = 24 - blkwidth;
+
+    //switch(x_pos&0x3){
+    switch (((uint32)ref)&0x3)
+    {
+        case 1:
+            ref += y_pos * picwidth;
+            offset =  picwidth - blkwidth - 3;
+            for (j = 0; j < blkheight; j++)
+            {
+                pix1 = *ref++;
+                pix2 = *((uint16*)ref);
+                ref += 2;
+                result = (pix2 << 8) | pix1;
+
+                for (i = 3; i < blkwidth; i += 4)
+                {
+                    pix4 = *((uint32*)ref);
+                    ref += 4;
+                    prev_pix = (pix4 << 24) & 0xFF000000; /* mask out byte belong to previous word */
+                    result |= prev_pix;
+                    *((uint32*)out) = result;  /* write 4 bytes */
+                    out += 4;
+                    result = pix4 >> 8; /* for the next loop */
+                }
+                ref += offset;
+                out += out_offset;
+            }
+            break;
+        case 2:
+            ref += y_pos * picwidth;
+            offset =  picwidth - blkwidth - 2;
+            for (j = 0; j < blkheight; j++)
+            {
+                result = *((uint16*)ref);
+                ref += 2;
+                for (i = 2; i < blkwidth; i += 4)
+                {
+                    pix4 = *((uint32*)ref);
+                    ref += 4;
+                    prev_pix = (pix4 << 16) & 0xFFFF0000; /* mask out byte belong to previous word */
+                    result |= prev_pix;
+                    *((uint32*)out) = result;  /* write 4 bytes */
+                    out += 4;
+                    result = pix4 >> 16; /* for the next loop */
+                }
+                ref += offset;
+                out += out_offset;
+            }
+            break;
+        case 3:
+            ref += y_pos * picwidth;
+            offset =  picwidth - blkwidth - 1;
+            for (j = 0; j < blkheight; j++)
+            {
+                result = *ref++;
+                for (i = 1; i < blkwidth; i += 4)
+                {
+                    pix4 = *((uint32*)ref);
+                    ref += 4;
+                    prev_pix = (pix4 << 8) & 0xFFFFFF00; /* mask out byte belong to previous word */
+                    result |= prev_pix;
+                    *((uint32*)out) = result;  /* write 4 bytes */
+                    out += 4;
+                    result = pix4 >> 24; /* for the next loop */
+                }
+                ref += offset;
+                out += out_offset;
+            }
+            break;
+    }
+}
+
+void CreatePad(uint8 *ref, int picwidth, int picheight, int x_pos, int y_pos,
+               uint8 *out, int blkwidth, int blkheight)
+{
+    int x_inc0, x_mid;
+    int y_inc, y_inc0, y_inc1, y_mid;
+    int i, j;
+    int offset;
+
+    if (x_pos < 0)
+    {
+        x_inc0 = 0;  /* increment for the first part */
+        x_mid = ((blkwidth + x_pos > 0) ? -x_pos : blkwidth);  /* stopping point */
+        x_pos = 0;
+    }
+    else if (x_pos + blkwidth > picwidth)
+    {
+        x_inc0 = 1;  /* increasing */
+        x_mid = ((picwidth > x_pos) ? picwidth - x_pos - 1 : 0);  /* clip negative to zero, encode fool proof! */
+    }
+    else    /* normal case */
+    {
+        x_inc0 = 1;
+        x_mid = blkwidth; /* just one run */
+    }
+
+
+    /* boundary for y_pos, taking the result from x_pos into account */
+    if (y_pos < 0)
+    {
+        y_inc0 = (x_inc0 ? - x_mid : -blkwidth + x_mid); /* offset depending on x_inc1 and x_inc0 */
+        y_inc1 = picwidth + y_inc0;
+        y_mid = ((blkheight + y_pos > 0) ? -y_pos : blkheight); /* clip to prevent memory corruption */
+        y_pos = 0;
+    }
+    else  if (y_pos + blkheight > picheight)
+    {
+        y_inc1 = (x_inc0 ? - x_mid : -blkwidth + x_mid); /* saturate */
+        y_inc0 = picwidth + y_inc1;                 /* increasing */
+        y_mid = ((picheight > y_pos) ? picheight - 1 - y_pos : 0);
+    }
+    else  /* normal case */
+    {
+        y_inc1 = (x_inc0 ? - x_mid : -blkwidth + x_mid);
+        y_inc0 = picwidth + y_inc1;
+        y_mid = blkheight;
+    }
+
+    /* clip y_pos and x_pos */
+    if (y_pos > picheight - 1) y_pos = picheight - 1;
+    if (x_pos > picwidth - 1) x_pos = picwidth - 1;
+
+    ref += y_pos * picwidth + x_pos;
+
+    y_inc = y_inc0;  /* start with top half */
+
+    offset = 24 - blkwidth; /* to use in offset out */
+    blkwidth -= x_mid; /* to use in the loop limit */
+
+    if (x_inc0 == 0)
+    {
+        for (j = 0; j < blkheight; j++)
+        {
+            if (j == y_mid)  /* put a check here to reduce the code size (for unrolling the loop) */
+            {
+                y_inc = y_inc1;  /* switch to lower half */
+            }
+            for (i = x_mid; i > 0; i--)   /* first or third quarter */
+            {
+                *out++ = *ref;
+            }
+            for (i = blkwidth; i > 0; i--)  /* second or fourth quarter */
+            {
+                *out++ = *ref++;
+            }
+            out += offset;
+            ref += y_inc;
+        }
+    }
+    else
+    {
+        for (j = 0; j < blkheight; j++)
+        {
+            if (j == y_mid)  /* put a check here to reduce the code size (for unrolling the loop) */
+            {
+                y_inc = y_inc1;  /* switch to lower half */
+            }
+            for (i = x_mid; i > 0; i--)   /* first or third quarter */
+            {
+                *out++ = *ref++;
+            }
+            for (i = blkwidth; i > 0; i--)  /* second or fourth quarter */
+            {
+                *out++ = *ref;
+            }
+            out += offset;
+            ref += y_inc;
+        }
+    }
+
+    return ;
+}
+
+void HorzInterp1MC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dx)
+{
+    uint8 *p_ref;
+    uint32 *p_cur;
+    uint32 tmp, pkres;
+    int result, curr_offset, ref_offset;
+    int j;
+    int32 r0, r1, r2, r3, r4, r5;
+    int32 r13, r6;
+
+    p_cur = (uint32*)out; /* assume it's word aligned */
+    curr_offset = (outpitch - blkwidth) >> 2;
+    p_ref = in;
+    ref_offset = inpitch - blkwidth;
+
+    if (dx&1)
+    {
+        dx = ((dx >> 1) ? -3 : -4); /* use in 3/4 pel */
+        p_ref -= 2;
+        r13 = 0;
+        for (j = blkheight; j > 0; j--)
+        {
+            tmp = (uint32)(p_ref + blkwidth);
+            r0 = p_ref[0];
+            r1 = p_ref[2];
+            r0 |= (r1 << 16);           /* 0,c,0,a */
+            r1 = p_ref[1];
+            r2 = p_ref[3];
+            r1 |= (r2 << 16);           /* 0,d,0,b */
+            while ((uint32)p_ref < tmp)
+            {
+                r2 = *(p_ref += 4); /* move pointer to e */
+                r3 = p_ref[2];
+                r2 |= (r3 << 16);           /* 0,g,0,e */
+                r3 = p_ref[1];
+                r4 = p_ref[3];
+                r3 |= (r4 << 16);           /* 0,h,0,f */
+
+                r4 = r0 + r3;       /* c+h, a+f */
+                r5 = r0 + r1;   /* c+d, a+b */
+                r6 = r2 + r3;   /* g+h, e+f */
+                r5 >>= 16;
+                r5 |= (r6 << 16);   /* e+f, c+d */
+                r4 += r5 * 20;      /* c+20*e+20*f+h, a+20*c+20*d+f */
+                r4 += 0x100010; /* +16, +16 */
+                r5 = r1 + r2;       /* d+g, b+e */
+                r4 -= r5 * 5;       /* c-5*d+20*e+20*f-5*g+h, a-5*b+20*c+20*d-5*e+f */
+                r4 >>= 5;
+                r13 |= r4;      /* check clipping */
+
+                r5 = p_ref[dx+2];
+                r6 = p_ref[dx+4];
+                r5 |= (r6 << 16);
+                r4 += r5;
+                r4 += 0x10001;
+                r4 = (r4 >> 1) & 0xFF00FF;
+
+                r5 = p_ref[4];  /* i */
+                r6 = (r5 << 16);
+                r5 = r6 | (r2 >> 16);/* 0,i,0,g */
+                r5 += r1;       /* d+i, b+g */ /* r5 not free */
+                r1 >>= 16;
+                r1 |= (r3 << 16); /* 0,f,0,d */ /* r1 has changed */
+                r1 += r2;       /* f+g, d+e */
+                r5 += 20 * r1;  /* d+20f+20g+i, b+20d+20e+g */
+                r0 >>= 16;
+                r0 |= (r2 << 16); /* 0,e,0,c */ /* r0 has changed */
+                r0 += r3;       /* e+h, c+f */
+                r5 += 0x100010; /* 16,16 */
+                r5 -= r0 * 5;       /* d-5e+20f+20g-5h+i, b-5c+20d+20e-5f+g */
+                r5 >>= 5;
+                r13 |= r5;      /* check clipping */
+
+                r0 = p_ref[dx+3];
+                r1 = p_ref[dx+5];
+                r0 |= (r1 << 16);
+                r5 += r0;
+                r5 += 0x10001;
+                r5 = (r5 >> 1) & 0xFF00FF;
+
+                r4 |= (r5 << 8);    /* pack them together */
+                *p_cur++ = r4;
+                r1 = r3;
+                r0 = r2;
+            }
+            p_cur += curr_offset; /* move to the next line */
+            p_ref += ref_offset;  /*    ref_offset = inpitch-blkwidth; */
+
+            if (r13&0xFF000700) /* need clipping */
+            {
+                /* move back to the beginning of the line */
+                p_ref -= (ref_offset + blkwidth);   /* input */
+                p_cur -= (outpitch >> 2);
+
+                tmp = (uint32)(p_ref + blkwidth);
+                for (; (uint32)p_ref < tmp;)
+                {
+
+                    r0 = *p_ref++;
+                    r1 = *p_ref++;
+                    r2 = *p_ref++;
+                    r3 = *p_ref++;
+                    r4 = *p_ref++;
+                    /* first pixel */
+                    r5 = *p_ref++;
+                    result = (r0 + r5);
+                    r0 = (r1 + r4);
+                    result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                    r0 = (r2 + r3);
+                    result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    /* 3/4 pel,  no need to clip */
+                    result = (result + p_ref[dx] + 1);
+                    pkres = (result >> 1) ;
+                    /* second pixel */
+                    r0 = *p_ref++;
+                    result = (r1 + r0);
+                    r1 = (r2 + r5);
+                    result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                    r1 = (r3 + r4);
+                    result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    /* 3/4 pel,  no need to clip */
+                    result = (result + p_ref[dx] + 1);
+                    result = (result >> 1);
+                    pkres  |= (result << 8);
+                    /* third pixel */
+                    r1 = *p_ref++;
+                    result = (r2 + r1);
+                    r2 = (r3 + r0);
+                    result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                    r2 = (r4 + r5);
+                    result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    /* 3/4 pel,  no need to clip */
+                    result = (result + p_ref[dx] + 1);
+                    result = (result >> 1);
+                    pkres  |= (result << 16);
+                    /* fourth pixel */
+                    r2 = *p_ref++;
+                    result = (r3 + r2);
+                    r3 = (r4 + r1);
+                    result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                    r3 = (r5 + r0);
+                    result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    /* 3/4 pel,  no need to clip */
+                    result = (result + p_ref[dx] + 1);
+                    result = (result >> 1);
+                    pkres  |= (result << 24);
+                    *p_cur++ = pkres; /* write 4 pixels */
+                    p_ref -= 5;  /* offset back to the middle of filter */
+                }
+                p_cur += curr_offset;  /* move to the next line */
+                p_ref += ref_offset;    /* move to the next line */
+            }
+        }
+    }
+    else
+    {
+        p_ref -= 2;
+        r13 = 0;
+        for (j = blkheight; j > 0; j--)
+        {
+            tmp = (uint32)(p_ref + blkwidth);
+            r0 = p_ref[0];
+            r1 = p_ref[2];
+            r0 |= (r1 << 16);           /* 0,c,0,a */
+            r1 = p_ref[1];
+            r2 = p_ref[3];
+            r1 |= (r2 << 16);           /* 0,d,0,b */
+            while ((uint32)p_ref < tmp)
+            {
+                r2 = *(p_ref += 4); /* move pointer to e */
+                r3 = p_ref[2];
+                r2 |= (r3 << 16);           /* 0,g,0,e */
+                r3 = p_ref[1];
+                r4 = p_ref[3];
+                r3 |= (r4 << 16);           /* 0,h,0,f */
+
+                r4 = r0 + r3;       /* c+h, a+f */
+                r5 = r0 + r1;   /* c+d, a+b */
+                r6 = r2 + r3;   /* g+h, e+f */
+                r5 >>= 16;
+                r5 |= (r6 << 16);   /* e+f, c+d */
+                r4 += r5 * 20;      /* c+20*e+20*f+h, a+20*c+20*d+f */
+                r4 += 0x100010; /* +16, +16 */
+                r5 = r1 + r2;       /* d+g, b+e */
+                r4 -= r5 * 5;       /* c-5*d+20*e+20*f-5*g+h, a-5*b+20*c+20*d-5*e+f */
+                r4 >>= 5;
+                r13 |= r4;      /* check clipping */
+                r4 &= 0xFF00FF; /* mask */
+
+                r5 = p_ref[4];  /* i */
+                r6 = (r5 << 16);
+                r5 = r6 | (r2 >> 16);/* 0,i,0,g */
+                r5 += r1;       /* d+i, b+g */ /* r5 not free */
+                r1 >>= 16;
+                r1 |= (r3 << 16); /* 0,f,0,d */ /* r1 has changed */
+                r1 += r2;       /* f+g, d+e */
+                r5 += 20 * r1;  /* d+20f+20g+i, b+20d+20e+g */
+                r0 >>= 16;
+                r0 |= (r2 << 16); /* 0,e,0,c */ /* r0 has changed */
+                r0 += r3;       /* e+h, c+f */
+                r5 += 0x100010; /* 16,16 */
+                r5 -= r0 * 5;       /* d-5e+20f+20g-5h+i, b-5c+20d+20e-5f+g */
+                r5 >>= 5;
+                r13 |= r5;      /* check clipping */
+                r5 &= 0xFF00FF; /* mask */
+
+                r4 |= (r5 << 8);    /* pack them together */
+                *p_cur++ = r4;
+                r1 = r3;
+                r0 = r2;
+            }
+            p_cur += curr_offset; /* move to the next line */
+            p_ref += ref_offset;  /*    ref_offset = inpitch-blkwidth; */
+
+            if (r13&0xFF000700) /* need clipping */
+            {
+                /* move back to the beginning of the line */
+                p_ref -= (ref_offset + blkwidth);   /* input */
+                p_cur -= (outpitch >> 2);
+
+                tmp = (uint32)(p_ref + blkwidth);
+                for (; (uint32)p_ref < tmp;)
+                {
+
+                    r0 = *p_ref++;
+                    r1 = *p_ref++;
+                    r2 = *p_ref++;
+                    r3 = *p_ref++;
+                    r4 = *p_ref++;
+                    /* first pixel */
+                    r5 = *p_ref++;
+                    result = (r0 + r5);
+                    r0 = (r1 + r4);
+                    result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                    r0 = (r2 + r3);
+                    result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    pkres  = result;
+                    /* second pixel */
+                    r0 = *p_ref++;
+                    result = (r1 + r0);
+                    r1 = (r2 + r5);
+                    result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                    r1 = (r3 + r4);
+                    result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    pkres  |= (result << 8);
+                    /* third pixel */
+                    r1 = *p_ref++;
+                    result = (r2 + r1);
+                    r2 = (r3 + r0);
+                    result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                    r2 = (r4 + r5);
+                    result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    pkres  |= (result << 16);
+                    /* fourth pixel */
+                    r2 = *p_ref++;
+                    result = (r3 + r2);
+                    r3 = (r4 + r1);
+                    result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                    r3 = (r5 + r0);
+                    result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    pkres  |= (result << 24);
+                    *p_cur++ = pkres;   /* write 4 pixels */
+                    p_ref -= 5;
+                }
+                p_cur += curr_offset; /* move to the next line */
+                p_ref += ref_offset;
+            }
+        }
+    }
+
+    return ;
+}
+
+void HorzInterp2MC(int *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dx)
+{
+    int *p_ref;
+    uint32 *p_cur;
+    uint32 tmp, pkres;
+    int result, result2, curr_offset, ref_offset;
+    int j, r0, r1, r2, r3, r4, r5;
+
+    p_cur = (uint32*)out; /* assume it's word aligned */
+    curr_offset = (outpitch - blkwidth) >> 2;
+    p_ref = in;
+    ref_offset = inpitch - blkwidth;
+
+    if (dx&1)
+    {
+        dx = ((dx >> 1) ? -3 : -4); /* use in 3/4 pel */
+
+        for (j = blkheight; j > 0 ; j--)
+        {
+            tmp = (uint32)(p_ref + blkwidth);
+            for (; (uint32)p_ref < tmp;)
+            {
+
+                r0 = p_ref[-2];
+                r1 = p_ref[-1];
+                r2 = *p_ref++;
+                r3 = *p_ref++;
+                r4 = *p_ref++;
+                /* first pixel */
+                r5 = *p_ref++;
+                result = (r0 + r5);
+                r0 = (r1 + r4);
+                result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                r0 = (r2 + r3);
+                result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dx] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                pkres = (result >> 1);
+                /* second pixel */
+                r0 = *p_ref++;
+                result = (r1 + r0);
+                r1 = (r2 + r5);
+                result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                r1 = (r3 + r4);
+                result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dx] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                pkres  |= (result << 8);
+                /* third pixel */
+                r1 = *p_ref++;
+                result = (r2 + r1);
+                r2 = (r3 + r0);
+                result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                r2 = (r4 + r5);
+                result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dx] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                pkres  |= (result << 16);
+                /* fourth pixel */
+                r2 = *p_ref++;
+                result = (r3 + r2);
+                r3 = (r4 + r1);
+                result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                r3 = (r5 + r0);
+                result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dx] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                pkres  |= (result << 24);
+                *p_cur++ = pkres; /* write 4 pixels */
+                p_ref -= 3;  /* offset back to the middle of filter */
+            }
+            p_cur += curr_offset;  /* move to the next line */
+            p_ref += ref_offset;    /* move to the next line */
+        }
+    }
+    else
+    {
+        for (j = blkheight; j > 0 ; j--)
+        {
+            tmp = (uint32)(p_ref + blkwidth);
+            for (; (uint32)p_ref < tmp;)
+            {
+
+                r0 = p_ref[-2];
+                r1 = p_ref[-1];
+                r2 = *p_ref++;
+                r3 = *p_ref++;
+                r4 = *p_ref++;
+                /* first pixel */
+                r5 = *p_ref++;
+                result = (r0 + r5);
+                r0 = (r1 + r4);
+                result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                r0 = (r2 + r3);
+                result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                pkres  = result;
+                /* second pixel */
+                r0 = *p_ref++;
+                result = (r1 + r0);
+                r1 = (r2 + r5);
+                result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                r1 = (r3 + r4);
+                result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                pkres  |= (result << 8);
+                /* third pixel */
+                r1 = *p_ref++;
+                result = (r2 + r1);
+                r2 = (r3 + r0);
+                result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                r2 = (r4 + r5);
+                result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                pkres  |= (result << 16);
+                /* fourth pixel */
+                r2 = *p_ref++;
+                result = (r3 + r2);
+                r3 = (r4 + r1);
+                result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                r3 = (r5 + r0);
+                result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                pkres  |= (result << 24);
+                *p_cur++ = pkres; /* write 4 pixels */
+                p_ref -= 3;  /* offset back to the middle of filter */
+            }
+            p_cur += curr_offset;  /* move to the next line */
+            p_ref += ref_offset;    /* move to the next line */
+        }
+    }
+
+    return ;
+}
+
+void HorzInterp3MC(uint8 *in, int inpitch, int *out, int outpitch,
+                   int blkwidth, int blkheight)
+{
+    uint8 *p_ref;
+    int   *p_cur;
+    uint32 tmp;
+    int result, curr_offset, ref_offset;
+    int j, r0, r1, r2, r3, r4, r5;
+
+    p_cur = out;
+    curr_offset = (outpitch - blkwidth);
+    p_ref = in;
+    ref_offset = inpitch - blkwidth;
+
+    for (j = blkheight; j > 0 ; j--)
+    {
+        tmp = (uint32)(p_ref + blkwidth);
+        for (; (uint32)p_ref < tmp;)
+        {
+
+            r0 = p_ref[-2];
+            r1 = p_ref[-1];
+            r2 = *p_ref++;
+            r3 = *p_ref++;
+            r4 = *p_ref++;
+            /* first pixel */
+            r5 = *p_ref++;
+            result = (r0 + r5);
+            r0 = (r1 + r4);
+            result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+            r0 = (r2 + r3);
+            result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+            *p_cur++ = result;
+            /* second pixel */
+            r0 = *p_ref++;
+            result = (r1 + r0);
+            r1 = (r2 + r5);
+            result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+            r1 = (r3 + r4);
+            result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+            *p_cur++ = result;
+            /* third pixel */
+            r1 = *p_ref++;
+            result = (r2 + r1);
+            r2 = (r3 + r0);
+            result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+            r2 = (r4 + r5);
+            result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+            *p_cur++ = result;
+            /* fourth pixel */
+            r2 = *p_ref++;
+            result = (r3 + r2);
+            r3 = (r4 + r1);
+            result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+            r3 = (r5 + r0);
+            result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+            *p_cur++ = result;
+            p_ref -= 3; /* move back to the middle of the filter */
+        }
+        p_cur += curr_offset; /* move to the next line */
+        p_ref += ref_offset;
+    }
+
+    return ;
+}
+void VertInterp1MC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dy)
+{
+    uint8 *p_cur, *p_ref;
+    uint32 tmp;
+    int result, curr_offset, ref_offset;
+    int j, i;
+    int32 r0, r1, r2, r3, r4, r5, r6, r7, r8, r13;
+    uint8  tmp_in[24][24];
+
+    /* not word-aligned */
+    if (((uint32)in)&0x3)
+    {
+        CreateAlign(in, inpitch, -2, &tmp_in[0][0], blkwidth, blkheight + 5);
+        in = &tmp_in[2][0];
+        inpitch = 24;
+    }
+    p_cur = out;
+    curr_offset = 1 - outpitch * (blkheight - 1); /* offset vertically back up and one pixel to right */
+    ref_offset = blkheight * inpitch; /* for limit */
+
+    curr_offset += 3;
+
+    if (dy&1)
+    {
+        dy = (dy >> 1) ? 0 : -inpitch;
+
+        for (j = 0; j < blkwidth; j += 4, in += 4)
+        {
+            r13 = 0;
+            p_ref = in;
+            p_cur -= outpitch;  /* compensate for the first offset */
+            tmp = (uint32)(p_ref + ref_offset); /* limit */
+            while ((uint32)p_ref < tmp)  /* the loop un-rolled  */
+            {
+                r0 = *((uint32*)(p_ref - (inpitch << 1))); /* load 4 bytes */
+                p_ref += inpitch;
+                r6 = (r0 >> 8) & 0xFF00FF; /* second and fourth byte */
+                r0 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref + (inpitch << 1)));  /* r1, r7, ref[3] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+
+                r0 += r1;
+                r6 += r7;
+
+                r2 = *((uint32*)p_ref); /* r2, r8, ref[1] */
+                r8 = (r2 >> 8) & 0xFF00FF;
+                r2 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref - inpitch)); /* r1, r7, ref[0] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+                r1 += r2;
+
+                r7 += r8;
+
+                r0 += 20 * r1;
+                r6 += 20 * r7;
+                r0 += 0x100010;
+                r6 += 0x100010;
+
+                r2 = *((uint32*)(p_ref - (inpitch << 1))); /* r2, r8, ref[-1] */
+                r8 = (r2 >> 8) & 0xFF00FF;
+                r2 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref + inpitch)); /* r1, r7, ref[2] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+                r1 += r2;
+
+                r7 += r8;
+
+                r0 -= 5 * r1;
+                r6 -= 5 * r7;
+
+                r0 >>= 5;
+                r6 >>= 5;
+                /* clip */
+                r13 |= r6;
+                r13 |= r0;
+                //CLIPPACK(r6,result)
+
+                r1 = *((uint32*)(p_ref + dy));
+                r2 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+                r0 += r1;
+                r6 += r2;
+                r0 += 0x10001;
+                r6 += 0x10001;
+                r0 = (r0 >> 1) & 0xFF00FF;
+                r6 = (r6 >> 1) & 0xFF00FF;
+
+                r0 |= (r6 << 8);  /* pack it back */
+                *((uint32*)(p_cur += outpitch)) = r0;
+            }
+            p_cur += curr_offset; /* offset to the next pixel */
+            if (r13 & 0xFF000700) /* this column need clipping */
+            {
+                p_cur -= 4;
+                for (i = 0; i < 4; i++)
+                {
+                    p_ref = in + i;
+                    p_cur -= outpitch;  /* compensate for the first offset */
+
+                    tmp = (uint32)(p_ref + ref_offset); /* limit */
+                    while ((uint32)p_ref < tmp)
+                    {                           /* loop un-rolled */
+                        r0 = *(p_ref - (inpitch << 1));
+                        r1 = *(p_ref - inpitch);
+                        r2 = *p_ref;
+                        r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+                        r4 = *(p_ref += inpitch);
+                        /* first pixel */
+                        r5 = *(p_ref += inpitch);
+                        result = (r0 + r5);
+                        r0 = (r1 + r4);
+                        result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                        r0 = (r2 + r3);
+                        result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        /* 3/4 pel,  no need to clip */
+                        result = (result + p_ref[dy-(inpitch<<1)] + 1);
+                        result = (result >> 1);
+                        *(p_cur += outpitch) = result;
+                        /* second pixel */
+                        r0 = *(p_ref += inpitch);
+                        result = (r1 + r0);
+                        r1 = (r2 + r5);
+                        result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                        r1 = (r3 + r4);
+                        result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        /* 3/4 pel,  no need to clip */
+                        result = (result + p_ref[dy-(inpitch<<1)] + 1);
+                        result = (result >> 1);
+                        *(p_cur += outpitch) = result;
+                        /* third pixel */
+                        r1 = *(p_ref += inpitch);
+                        result = (r2 + r1);
+                        r2 = (r3 + r0);
+                        result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                        r2 = (r4 + r5);
+                        result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        /* 3/4 pel,  no need to clip */
+                        result = (result + p_ref[dy-(inpitch<<1)] + 1);
+                        result = (result >> 1);
+                        *(p_cur += outpitch) = result;
+                        /* fourth pixel */
+                        r2 = *(p_ref += inpitch);
+                        result = (r3 + r2);
+                        r3 = (r4 + r1);
+                        result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                        r3 = (r5 + r0);
+                        result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        /* 3/4 pel,  no need to clip */
+                        result = (result + p_ref[dy-(inpitch<<1)] + 1);
+                        result = (result >> 1);
+                        *(p_cur += outpitch) = result;
+                        p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+                    }
+                    p_cur += (curr_offset - 3);
+                }
+            }
+        }
+    }
+    else
+    {
+        for (j = 0; j < blkwidth; j += 4, in += 4)
+        {
+            r13 = 0;
+            p_ref = in;
+            p_cur -= outpitch;  /* compensate for the first offset */
+            tmp = (uint32)(p_ref + ref_offset); /* limit */
+            while ((uint32)p_ref < tmp)  /* the loop un-rolled  */
+            {
+                r0 = *((uint32*)(p_ref - (inpitch << 1))); /* load 4 bytes */
+                p_ref += inpitch;
+                r6 = (r0 >> 8) & 0xFF00FF; /* second and fourth byte */
+                r0 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref + (inpitch << 1)));  /* r1, r7, ref[3] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+
+                r0 += r1;
+                r6 += r7;
+
+                r2 = *((uint32*)p_ref); /* r2, r8, ref[1] */
+                r8 = (r2 >> 8) & 0xFF00FF;
+                r2 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref - inpitch)); /* r1, r7, ref[0] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+                r1 += r2;
+
+                r7 += r8;
+
+                r0 += 20 * r1;
+                r6 += 20 * r7;
+                r0 += 0x100010;
+                r6 += 0x100010;
+
+                r2 = *((uint32*)(p_ref - (inpitch << 1))); /* r2, r8, ref[-1] */
+                r8 = (r2 >> 8) & 0xFF00FF;
+                r2 &= 0xFF00FF;
+
+                r1 = *((uint32*)(p_ref + inpitch)); /* r1, r7, ref[2] */
+                r7 = (r1 >> 8) & 0xFF00FF;
+                r1 &= 0xFF00FF;
+                r1 += r2;
+
+                r7 += r8;
+
+                r0 -= 5 * r1;
+                r6 -= 5 * r7;
+
+                r0 >>= 5;
+                r6 >>= 5;
+                /* clip */
+                r13 |= r6;
+                r13 |= r0;
+                //CLIPPACK(r6,result)
+                r0 &= 0xFF00FF;
+                r6 &= 0xFF00FF;
+                r0 |= (r6 << 8);  /* pack it back */
+                *((uint32*)(p_cur += outpitch)) = r0;
+            }
+            p_cur += curr_offset; /* offset to the next pixel */
+            if (r13 & 0xFF000700) /* this column need clipping */
+            {
+                p_cur -= 4;
+                for (i = 0; i < 4; i++)
+                {
+                    p_ref = in + i;
+                    p_cur -= outpitch;  /* compensate for the first offset */
+                    tmp = (uint32)(p_ref + ref_offset); /* limit */
+                    while ((uint32)p_ref < tmp)
+                    {                           /* loop un-rolled */
+                        r0 = *(p_ref - (inpitch << 1));
+                        r1 = *(p_ref - inpitch);
+                        r2 = *p_ref;
+                        r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+                        r4 = *(p_ref += inpitch);
+                        /* first pixel */
+                        r5 = *(p_ref += inpitch);
+                        result = (r0 + r5);
+                        r0 = (r1 + r4);
+                        result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                        r0 = (r2 + r3);
+                        result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        *(p_cur += outpitch) = result;
+                        /* second pixel */
+                        r0 = *(p_ref += inpitch);
+                        result = (r1 + r0);
+                        r1 = (r2 + r5);
+                        result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                        r1 = (r3 + r4);
+                        result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        *(p_cur += outpitch) = result;
+                        /* third pixel */
+                        r1 = *(p_ref += inpitch);
+                        result = (r2 + r1);
+                        r2 = (r3 + r0);
+                        result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                        r2 = (r4 + r5);
+                        result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        *(p_cur += outpitch) = result;
+                        /* fourth pixel */
+                        r2 = *(p_ref += inpitch);
+                        result = (r3 + r2);
+                        r3 = (r4 + r1);
+                        result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                        r3 = (r5 + r0);
+                        result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                        result = (result + 16) >> 5;
+                        CLIP_RESULT(result)
+                        *(p_cur += outpitch) = result;
+                        p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+                    }
+                    p_cur += (curr_offset - 3);
+                }
+            }
+        }
+    }
+
+    return ;
+}
+
+void VertInterp2MC(uint8 *in, int inpitch, int *out, int outpitch,
+                   int blkwidth, int blkheight)
+{
+    int *p_cur;
+    uint8 *p_ref;
+    uint32 tmp;
+    int result, curr_offset, ref_offset;
+    int j, r0, r1, r2, r3, r4, r5;
+
+    p_cur = out;
+    curr_offset = 1 - outpitch * (blkheight - 1); /* offset vertically back up and one pixel to right */
+    ref_offset = blkheight * inpitch; /* for limit */
+
+    for (j = 0; j < blkwidth; j++)
+    {
+        p_cur -= outpitch; /* compensate for the first offset */
+        p_ref = in++;
+
+        tmp = (uint32)(p_ref + ref_offset); /* limit */
+        while ((uint32)p_ref < tmp)
+        {                           /* loop un-rolled */
+            r0 = *(p_ref - (inpitch << 1));
+            r1 = *(p_ref - inpitch);
+            r2 = *p_ref;
+            r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+            r4 = *(p_ref += inpitch);
+            /* first pixel */
+            r5 = *(p_ref += inpitch);
+            result = (r0 + r5);
+            r0 = (r1 + r4);
+            result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+            r0 = (r2 + r3);
+            result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+            *(p_cur += outpitch) = result;
+            /* second pixel */
+            r0 = *(p_ref += inpitch);
+            result = (r1 + r0);
+            r1 = (r2 + r5);
+            result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+            r1 = (r3 + r4);
+            result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+            *(p_cur += outpitch) = result;
+            /* third pixel */
+            r1 = *(p_ref += inpitch);
+            result = (r2 + r1);
+            r2 = (r3 + r0);
+            result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+            r2 = (r4 + r5);
+            result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+            *(p_cur += outpitch) = result;
+            /* fourth pixel */
+            r2 = *(p_ref += inpitch);
+            result = (r3 + r2);
+            r3 = (r4 + r1);
+            result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+            r3 = (r5 + r0);
+            result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+            *(p_cur += outpitch) = result;
+            p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+        }
+        p_cur += curr_offset;
+    }
+
+    return ;
+}
+
+void VertInterp3MC(int *in, int inpitch, uint8 *out, int outpitch,
+                   int blkwidth, int blkheight, int dy)
+{
+    uint8 *p_cur;
+    int *p_ref;
+    uint32 tmp;
+    int result, result2, curr_offset, ref_offset;
+    int j, r0, r1, r2, r3, r4, r5;
+
+    p_cur = out;
+    curr_offset = 1 - outpitch * (blkheight - 1); /* offset vertically back up and one pixel to right */
+    ref_offset = blkheight * inpitch; /* for limit */
+
+    if (dy&1)
+    {
+        dy = (dy >> 1) ? -(inpitch << 1) : -(inpitch << 1) - inpitch;
+
+        for (j = 0; j < blkwidth; j++)
+        {
+            p_cur -= outpitch; /* compensate for the first offset */
+            p_ref = in++;
+
+            tmp = (uint32)(p_ref + ref_offset); /* limit */
+            while ((uint32)p_ref < tmp)
+            {                           /* loop un-rolled */
+                r0 = *(p_ref - (inpitch << 1));
+                r1 = *(p_ref - inpitch);
+                r2 = *p_ref;
+                r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+                r4 = *(p_ref += inpitch);
+                /* first pixel */
+                r5 = *(p_ref += inpitch);
+                result = (r0 + r5);
+                r0 = (r1 + r4);
+                result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                r0 = (r2 + r3);
+                result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dy] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                *(p_cur += outpitch) = result;
+                /* second pixel */
+                r0 = *(p_ref += inpitch);
+                result = (r1 + r0);
+                r1 = (r2 + r5);
+                result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                r1 = (r3 + r4);
+                result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dy] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                *(p_cur += outpitch) = result;
+                /* third pixel */
+                r1 = *(p_ref += inpitch);
+                result = (r2 + r1);
+                r2 = (r3 + r0);
+                result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                r2 = (r4 + r5);
+                result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dy] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                *(p_cur += outpitch) = result;
+                /* fourth pixel */
+                r2 = *(p_ref += inpitch);
+                result = (r3 + r2);
+                r3 = (r4 + r1);
+                result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                r3 = (r5 + r0);
+                result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                result2 = ((p_ref[dy] + 16) >> 5);
+                CLIP_RESULT(result2)
+                /* 3/4 pel,  no need to clip */
+                result = (result + result2 + 1);
+                result = (result >> 1);
+                *(p_cur += outpitch) = result;
+                p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+            }
+            p_cur += curr_offset;
+        }
+    }
+    else
+    {
+        for (j = 0; j < blkwidth; j++)
+        {
+            p_cur -= outpitch; /* compensate for the first offset */
+            p_ref = in++;
+
+            tmp = (uint32)(p_ref + ref_offset); /* limit */
+            while ((uint32)p_ref < tmp)
+            {                           /* loop un-rolled */
+                r0 = *(p_ref - (inpitch << 1));
+                r1 = *(p_ref - inpitch);
+                r2 = *p_ref;
+                r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+                r4 = *(p_ref += inpitch);
+                /* first pixel */
+                r5 = *(p_ref += inpitch);
+                result = (r0 + r5);
+                r0 = (r1 + r4);
+                result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                r0 = (r2 + r3);
+                result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                *(p_cur += outpitch) = result;
+                /* second pixel */
+                r0 = *(p_ref += inpitch);
+                result = (r1 + r0);
+                r1 = (r2 + r5);
+                result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                r1 = (r3 + r4);
+                result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                *(p_cur += outpitch) = result;
+                /* third pixel */
+                r1 = *(p_ref += inpitch);
+                result = (r2 + r1);
+                r2 = (r3 + r0);
+                result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                r2 = (r4 + r5);
+                result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                *(p_cur += outpitch) = result;
+                /* fourth pixel */
+                r2 = *(p_ref += inpitch);
+                result = (r3 + r2);
+                r3 = (r4 + r1);
+                result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                r3 = (r5 + r0);
+                result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                result = (result + 512) >> 10;
+                CLIP_RESULT(result)
+                *(p_cur += outpitch) = result;
+                p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+            }
+            p_cur += curr_offset;
+        }
+    }
+
+    return ;
+}
+
+void DiagonalInterpMC(uint8 *in1, uint8 *in2, int inpitch,
+                      uint8 *out, int outpitch,
+                      int blkwidth, int blkheight)
+{
+    int j, i;
+    int result;
+    uint8 *p_cur, *p_ref, *p_tmp8;
+    int curr_offset, ref_offset;
+    uint8 tmp_res[24][24], tmp_in[24][24];
+    uint32 *p_tmp;
+    uint32 tmp, pkres, tmp_result;
+    int32 r0, r1, r2, r3, r4, r5;
+    int32 r6, r7, r8, r9, r10, r13;
+
+    ref_offset = inpitch - blkwidth;
+    p_ref = in1 - 2;
+    /* perform horizontal interpolation */
+    /* not word-aligned */
+    /* It is faster to read 1 byte at time to avoid calling CreateAlign */
+    /*  if(((uint32)p_ref)&0x3)
+        {
+            CreateAlign(p_ref,inpitch,0,&tmp_in[0][0],blkwidth+8,blkheight);
+            p_ref = &tmp_in[0][0];
+            ref_offset = 24-blkwidth;
+        }*/
+
+    p_tmp = (uint32*) & (tmp_res[0][0]);
+    for (j = blkheight; j > 0; j--)
+    {
+        r13 = 0;
+        tmp = (uint32)(p_ref + blkwidth);
+
+        //r0 = *((uint32*)p_ref);   /* d,c,b,a */
+        //r1 = (r0>>8)&0xFF00FF;    /* 0,d,0,b */
+        //r0 &= 0xFF00FF;           /* 0,c,0,a */
+        /* It is faster to read 1 byte at a time,  */
+        r0 = p_ref[0];
+        r1 = p_ref[2];
+        r0 |= (r1 << 16);           /* 0,c,0,a */
+        r1 = p_ref[1];
+        r2 = p_ref[3];
+        r1 |= (r2 << 16);           /* 0,d,0,b */
+
+        while ((uint32)p_ref < tmp)
+        {
+            //r2 = *((uint32*)(p_ref+=4));/* h,g,f,e */
+            //r3 = (r2>>8)&0xFF00FF;  /* 0,h,0,f */
+            //r2 &= 0xFF00FF;           /* 0,g,0,e */
+            /* It is faster to read 1 byte at a time,  */
+            r2 = *(p_ref += 4);
+            r3 = p_ref[2];
+            r2 |= (r3 << 16);           /* 0,g,0,e */
+            r3 = p_ref[1];
+            r4 = p_ref[3];
+            r3 |= (r4 << 16);           /* 0,h,0,f */
+
+            r4 = r0 + r3;       /* c+h, a+f */
+            r5 = r0 + r1;   /* c+d, a+b */
+            r6 = r2 + r3;   /* g+h, e+f */
+            r5 >>= 16;
+            r5 |= (r6 << 16);   /* e+f, c+d */
+            r4 += r5 * 20;      /* c+20*e+20*f+h, a+20*c+20*d+f */
+            r4 += 0x100010; /* +16, +16 */
+            r5 = r1 + r2;       /* d+g, b+e */
+            r4 -= r5 * 5;       /* c-5*d+20*e+20*f-5*g+h, a-5*b+20*c+20*d-5*e+f */
+            r4 >>= 5;
+            r13 |= r4;      /* check clipping */
+            r4 &= 0xFF00FF; /* mask */
+
+            r5 = p_ref[4];  /* i */
+            r6 = (r5 << 16);
+            r5 = r6 | (r2 >> 16);/* 0,i,0,g */
+            r5 += r1;       /* d+i, b+g */ /* r5 not free */
+            r1 >>= 16;
+            r1 |= (r3 << 16); /* 0,f,0,d */ /* r1 has changed */
+            r1 += r2;       /* f+g, d+e */
+            r5 += 20 * r1;  /* d+20f+20g+i, b+20d+20e+g */
+            r0 >>= 16;
+            r0 |= (r2 << 16); /* 0,e,0,c */ /* r0 has changed */
+            r0 += r3;       /* e+h, c+f */
+            r5 += 0x100010; /* 16,16 */
+            r5 -= r0 * 5;       /* d-5e+20f+20g-5h+i, b-5c+20d+20e-5f+g */
+            r5 >>= 5;
+            r13 |= r5;      /* check clipping */
+            r5 &= 0xFF00FF; /* mask */
+
+            r4 |= (r5 << 8);    /* pack them together */
+            *p_tmp++ = r4;
+            r1 = r3;
+            r0 = r2;
+        }
+        p_tmp += ((24 - blkwidth) >> 2); /* move to the next line */
+        p_ref += ref_offset;  /*    ref_offset = inpitch-blkwidth; */
+
+        if (r13&0xFF000700) /* need clipping */
+        {
+            /* move back to the beginning of the line */
+            p_ref -= (ref_offset + blkwidth);   /* input */
+            p_tmp -= 6; /* intermediate output */
+            tmp = (uint32)(p_ref + blkwidth);
+            while ((uint32)p_ref < tmp)
+            {
+                r0 = *p_ref++;
+                r1 = *p_ref++;
+                r2 = *p_ref++;
+                r3 = *p_ref++;
+                r4 = *p_ref++;
+                /* first pixel */
+                r5 = *p_ref++;
+                result = (r0 + r5);
+                r0 = (r1 + r4);
+                result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                r0 = (r2 + r3);
+                result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                result = (result + 16) >> 5;
+                CLIP_RESULT(result)
+                pkres = result;
+                /* second pixel */
+                r0 = *p_ref++;
+                result = (r1 + r0);
+                r1 = (r2 + r5);
+                result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                r1 = (r3 + r4);
+                result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                result = (result + 16) >> 5;
+                CLIP_RESULT(result)
+                pkres |= (result << 8);
+                /* third pixel */
+                r1 = *p_ref++;
+                result = (r2 + r1);
+                r2 = (r3 + r0);
+                result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                r2 = (r4 + r5);
+                result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                result = (result + 16) >> 5;
+                CLIP_RESULT(result)
+                pkres |= (result << 16);
+                /* fourth pixel */
+                r2 = *p_ref++;
+                result = (r3 + r2);
+                r3 = (r4 + r1);
+                result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                r3 = (r5 + r0);
+                result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                result = (result + 16) >> 5;
+                CLIP_RESULT(result)
+                pkres |= (result << 24);
+
+                *p_tmp++ = pkres; /* write 4 pixel */
+                p_ref -= 5;
+            }
+            p_tmp += ((24 - blkwidth) >> 2); /* move to the next line */
+            p_ref += ref_offset;  /*    ref_offset = inpitch-blkwidth; */
+        }
+    }
+
+    /*  perform vertical interpolation */
+    /* not word-aligned */
+    if (((uint32)in2)&0x3)
+    {
+        CreateAlign(in2, inpitch, -2, &tmp_in[0][0], blkwidth, blkheight + 5);
+        in2 = &tmp_in[2][0];
+        inpitch = 24;
+    }
+
+    p_cur = out;
+    curr_offset = 1 - outpitch * (blkheight - 1); /* offset vertically up and one pixel right */
+    pkres = blkheight * inpitch; /* reuse it for limit */
+
+    curr_offset += 3;
+
+    for (j = 0; j < blkwidth; j += 4, in2 += 4)
+    {
+        r13 = 0;
+        p_ref = in2;
+        p_tmp8 = &(tmp_res[0][j]); /* intermediate result */
+        p_tmp8 -= 24;  /* compensate for the first offset */
+        p_cur -= outpitch;  /* compensate for the first offset */
+        tmp = (uint32)(p_ref + pkres); /* limit */
+        while ((uint32)p_ref < tmp)  /* the loop un-rolled  */
+        {
+            /* Read 1 byte at a time is too slow, too many read and pack ops, need to call CreateAlign,  */
+            /*p_ref8 = p_ref-(inpitch<<1);          r0 = p_ref8[0];         r1 = p_ref8[2];
+            r0 |= (r1<<16);         r6 = p_ref8[1];         r1 = p_ref8[3];
+            r6 |= (r1<<16);         p_ref+=inpitch; */
+            r0 = *((uint32*)(p_ref - (inpitch << 1))); /* load 4 bytes */
+            p_ref += inpitch;
+            r6 = (r0 >> 8) & 0xFF00FF; /* second and fourth byte */
+            r0 &= 0xFF00FF;
+
+            /*p_ref8 = p_ref+(inpitch<<1);
+            r1 = p_ref8[0];         r7 = p_ref8[2];         r1 |= (r7<<16);
+            r7 = p_ref8[1];         r2 = p_ref8[3];         r7 |= (r2<<16);*/
+            r1 = *((uint32*)(p_ref + (inpitch << 1)));  /* r1, r7, ref[3] */
+            r7 = (r1 >> 8) & 0xFF00FF;
+            r1 &= 0xFF00FF;
+
+            r0 += r1;
+            r6 += r7;
+
+            /*r2 = p_ref[0];            r8 = p_ref[2];          r2 |= (r8<<16);
+            r8 = p_ref[1];          r1 = p_ref[3];          r8 |= (r1<<16);*/
+            r2 = *((uint32*)p_ref); /* r2, r8, ref[1] */
+            r8 = (r2 >> 8) & 0xFF00FF;
+            r2 &= 0xFF00FF;
+
+            /*p_ref8 = p_ref-inpitch;           r1 = p_ref8[0];         r7 = p_ref8[2];
+            r1 |= (r7<<16);         r1 += r2;           r7 = p_ref8[1];
+            r2 = p_ref8[3];         r7 |= (r2<<16);*/
+            r1 = *((uint32*)(p_ref - inpitch)); /* r1, r7, ref[0] */
+            r7 = (r1 >> 8) & 0xFF00FF;
+            r1 &= 0xFF00FF;
+            r1 += r2;
+
+            r7 += r8;
+
+            r0 += 20 * r1;
+            r6 += 20 * r7;
+            r0 += 0x100010;
+            r6 += 0x100010;
+
+            /*p_ref8 = p_ref-(inpitch<<1);          r2 = p_ref8[0];         r8 = p_ref8[2];
+            r2 |= (r8<<16);         r8 = p_ref8[1];         r1 = p_ref8[3];         r8 |= (r1<<16);*/
+            r2 = *((uint32*)(p_ref - (inpitch << 1))); /* r2, r8, ref[-1] */
+            r8 = (r2 >> 8) & 0xFF00FF;
+            r2 &= 0xFF00FF;
+
+            /*p_ref8 = p_ref+inpitch;           r1 = p_ref8[0];         r7 = p_ref8[2];
+            r1 |= (r7<<16);         r1 += r2;           r7 = p_ref8[1];
+            r2 = p_ref8[3];         r7 |= (r2<<16);*/
+            r1 = *((uint32*)(p_ref + inpitch)); /* r1, r7, ref[2] */
+            r7 = (r1 >> 8) & 0xFF00FF;
+            r1 &= 0xFF00FF;
+            r1 += r2;
+
+            r7 += r8;
+
+            r0 -= 5 * r1;
+            r6 -= 5 * r7;
+
+            r0 >>= 5;
+            r6 >>= 5;
+            /* clip */
+            r13 |= r6;
+            r13 |= r0;
+            //CLIPPACK(r6,result)
+            /* add with horizontal results */
+            r10 = *((uint32*)(p_tmp8 += 24));
+            r9 = (r10 >> 8) & 0xFF00FF;
+            r10 &= 0xFF00FF;
+
+            r0 += r10;
+            r0 += 0x10001;
+            r0 = (r0 >> 1) & 0xFF00FF;   /* mask to 8 bytes */
+
+            r6 += r9;
+            r6 += 0x10001;
+            r6 = (r6 >> 1) & 0xFF00FF;   /* mask to 8 bytes */
+
+            r0 |= (r6 << 8);  /* pack it back */
+            *((uint32*)(p_cur += outpitch)) = r0;
+        }
+        p_cur += curr_offset; /* offset to the next pixel */
+        if (r13 & 0xFF000700) /* this column need clipping */
+        {
+            p_cur -= 4;
+            for (i = 0; i < 4; i++)
+            {
+                p_ref = in2 + i;
+                p_tmp8 = &(tmp_res[0][j+i]); /* intermediate result */
+                p_tmp8 -= 24;  /* compensate for the first offset */
+                p_cur -= outpitch;  /* compensate for the first offset */
+                tmp = (uint32)(p_ref + pkres); /* limit */
+                while ((uint32)p_ref < tmp)  /* the loop un-rolled  */
+                {
+                    r0 = *(p_ref - (inpitch << 1));
+                    r1 = *(p_ref - inpitch);
+                    r2 = *p_ref;
+                    r3 = *(p_ref += inpitch);  /* modify pointer before loading */
+                    r4 = *(p_ref += inpitch);
+                    /* first pixel */
+                    r5 = *(p_ref += inpitch);
+                    result = (r0 + r5);
+                    r0 = (r1 + r4);
+                    result -= (r0 * 5);//result -= r0;  result -= (r0<<2);
+                    r0 = (r2 + r3);
+                    result += (r0 * 20);//result += (r0<<4);    result += (r0<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    tmp_result = *(p_tmp8 += 24);  /* modify pointer before loading */
+                    result = (result + tmp_result + 1);  /* no clip */
+                    result = (result >> 1);
+                    *(p_cur += outpitch) = result;
+                    /* second pixel */
+                    r0 = *(p_ref += inpitch);
+                    result = (r1 + r0);
+                    r1 = (r2 + r5);
+                    result -= (r1 * 5);//result -= r1;  result -= (r1<<2);
+                    r1 = (r3 + r4);
+                    result += (r1 * 20);//result += (r1<<4);    result += (r1<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    tmp_result = *(p_tmp8 += 24);  /* intermediate result */
+                    result = (result + tmp_result + 1);  /* no clip */
+                    result = (result >> 1);
+                    *(p_cur += outpitch) = result;
+                    /* third pixel */
+                    r1 = *(p_ref += inpitch);
+                    result = (r2 + r1);
+                    r2 = (r3 + r0);
+                    result -= (r2 * 5);//result -= r2;  result -= (r2<<2);
+                    r2 = (r4 + r5);
+                    result += (r2 * 20);//result += (r2<<4);    result += (r2<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    tmp_result = *(p_tmp8 += 24);  /* intermediate result */
+                    result = (result + tmp_result + 1);  /* no clip */
+                    result = (result >> 1);
+                    *(p_cur += outpitch) = result;
+                    /* fourth pixel */
+                    r2 = *(p_ref += inpitch);
+                    result = (r3 + r2);
+                    r3 = (r4 + r1);
+                    result -= (r3 * 5);//result -= r3;  result -= (r3<<2);
+                    r3 = (r5 + r0);
+                    result += (r3 * 20);//result += (r3<<4);    result += (r3<<2);
+                    result = (result + 16) >> 5;
+                    CLIP_RESULT(result)
+                    tmp_result = *(p_tmp8 += 24);  /* intermediate result */
+                    result = (result + tmp_result + 1);  /* no clip */
+                    result = (result >> 1);
+                    *(p_cur += outpitch) = result;
+                    p_ref -= (inpitch << 1);  /* move back to center of the filter of the next one */
+                }
+                p_cur += (curr_offset - 3);
+            }
+        }
+    }
+
+    return ;
+}
+
+/* position G */
+void FullPelMC(uint8 *in, int inpitch, uint8 *out, int outpitch,
+               int blkwidth, int blkheight)
+{
+    int i, j;
+    int offset_in = inpitch - blkwidth;
+    int offset_out = outpitch - blkwidth;
+    uint32 temp;
+    uint8 byte;
+
+    if (((uint32)in)&3)
+    {
+        for (j = blkheight; j > 0; j--)
+        {
+            for (i = blkwidth; i > 0; i -= 4)
+            {
+                temp = *in++;
+                byte = *in++;
+                temp |= (byte << 8);
+                byte = *in++;
+                temp |= (byte << 16);
+                byte = *in++;
+                temp |= (byte << 24);
+
+                *((uint32*)out) = temp; /* write 4 bytes */
+                out += 4;
+            }
+            out += offset_out;
+            in += offset_in;
+        }
+    }
+    else
+    {
+        for (j = blkheight; j > 0; j--)
+        {
+            for (i = blkwidth; i > 0; i -= 4)
+            {
+                temp = *((uint32*)in);
+                *((uint32*)out) = temp;
+                in += 4;
+                out += 4;
+            }
+            out += offset_out;
+            in += offset_in;
+        }
+    }
+    return ;
+}
+
+void ChromaMotionComp(uint8 *ref, int picwidth, int picheight,
+                      int x_pos, int y_pos,
+                      uint8 *pred, int pred_pitch,
+                      int blkwidth, int blkheight)
+{
+    int dx, dy;
+    int offset_dx, offset_dy;
+    int index;
+    uint8 temp[24][24];
+
+    dx = x_pos & 7;
+    dy = y_pos & 7;
+    offset_dx = (dx + 7) >> 3;
+    offset_dy = (dy + 7) >> 3;
+    x_pos = x_pos >> 3;  /* round it to full-pel resolution */
+    y_pos = y_pos >> 3;
+
+    if ((x_pos >= 0 && x_pos + blkwidth + offset_dx <= picwidth) && (y_pos >= 0 && y_pos + blkheight + offset_dy <= picheight))
+    {
+        ref += y_pos * picwidth + x_pos;
+    }
+    else
+    {
+        CreatePad(ref, picwidth, picheight, x_pos, y_pos, &temp[0][0], blkwidth + offset_dx, blkheight + offset_dy);
+        ref = &temp[0][0];
+        picwidth = 24;
+    }
+
+    index = offset_dx + (offset_dy << 1) + ((blkwidth << 1) & 0x7);
+
+    (*(ChromaMC_SIMD[index]))(ref, picwidth , dx, dy, pred, pred_pitch, blkwidth, blkheight);
+    return ;
+}
+
+
+/* SIMD routines, unroll the loops in vertical direction, decreasing loops (things to be done)  */
+void ChromaDiagonalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                           uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    int32 r0, r1, r2, r3, result0, result1;
+    uint8 temp[288];
+    uint8 *ref, *out;
+    int i, j;
+    int dx_8 = 8 - dx;
+    int dy_8 = 8 - dy;
+
+    /* horizontal first */
+    out = temp;
+    for (i = 0; i < blkheight + 1; i++)
+    {
+        ref = pRef;
+        r0 = ref[0];
+        for (j = 0; j < blkwidth; j += 4)
+        {
+            r0 |= (ref[2] << 16);
+            result0 = dx_8 * r0;
+
+            r1 = ref[1] | (ref[3] << 16);
+            result0 += dx * r1;
+            *(int32 *)out = result0;
+
+            result0 = dx_8 * r1;
+
+            r2 = ref[4];
+            r0 = r0 >> 16;
+            r1 = r0 | (r2 << 16);
+            result0 += dx * r1;
+            *(int32 *)(out + 16) = result0;
+
+            ref += 4;
+            out += 4;
+            r0 = r2;
+        }
+        pRef += srcPitch;
+        out += (32 - blkwidth);
+    }
+
+//  pRef -= srcPitch*(blkheight+1);
+    ref = temp;
+
+    for (j = 0; j < blkwidth; j += 4)
+    {
+        r0 = *(int32 *)ref;
+        r1 = *(int32 *)(ref + 16);
+        ref += 32;
+        out = pOut;
+        for (i = 0; i < (blkheight >> 1); i++)
+        {
+            result0 = dy_8 * r0 + 0x00200020;
+            r2 = *(int32 *)ref;
+            result0 += dy * r2;
+            result0 >>= 6;
+            result0 &= 0x00FF00FF;
+            r0 = r2;
+
+            result1 = dy_8 * r1 + 0x00200020;
+            r3 = *(int32 *)(ref + 16);
+            result1 += dy * r3;
+            result1 >>= 6;
+            result1 &= 0x00FF00FF;
+            r1 = r3;
+            *(int32 *)out = result0 | (result1 << 8);
+            out += predPitch;
+            ref += 32;
+
+            result0 = dy_8 * r0 + 0x00200020;
+            r2 = *(int32 *)ref;
+            result0 += dy * r2;
+            result0 >>= 6;
+            result0 &= 0x00FF00FF;
+            r0 = r2;
+
+            result1 = dy_8 * r1 + 0x00200020;
+            r3 = *(int32 *)(ref + 16);
+            result1 += dy * r3;
+            result1 >>= 6;
+            result1 &= 0x00FF00FF;
+            r1 = r3;
+            *(int32 *)out = result0 | (result1 << 8);
+            out += predPitch;
+            ref += 32;
+        }
+        pOut += 4;
+        ref = temp + 4; /* since it can only iterate twice max  */
+    }
+    return;
+}
+
+void ChromaHorizontalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                             uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(dy);
+    int32 r0, r1, r2, result0, result1;
+    uint8 *ref, *out;
+    int i, j;
+    int dx_8 = 8 - dx;
+
+    /* horizontal first */
+    for (i = 0; i < blkheight; i++)
+    {
+        ref = pRef;
+        out = pOut;
+
+        r0 = ref[0];
+        for (j = 0; j < blkwidth; j += 4)
+        {
+            r0 |= (ref[2] << 16);
+            result0 = dx_8 * r0 + 0x00040004;
+
+            r1 = ref[1] | (ref[3] << 16);
+            result0 += dx * r1;
+            result0 >>= 3;
+            result0 &= 0x00FF00FF;
+
+            result1 = dx_8 * r1 + 0x00040004;
+
+            r2 = ref[4];
+            r0 = r0 >> 16;
+            r1 = r0 | (r2 << 16);
+            result1 += dx * r1;
+            result1 >>= 3;
+            result1 &= 0x00FF00FF;
+
+            *(int32 *)out = result0 | (result1 << 8);
+
+            ref += 4;
+            out += 4;
+            r0 = r2;
+        }
+
+        pRef += srcPitch;
+        pOut += predPitch;
+    }
+    return;
+}
+
+void ChromaVerticalMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                           uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(dx);
+    int32 r0, r1, r2, r3, result0, result1;
+    int i, j;
+    uint8 *ref, *out;
+    int dy_8 = 8 - dy;
+    /* vertical first */
+    for (i = 0; i < blkwidth; i += 4)
+    {
+        ref = pRef;
+        out = pOut;
+
+        r0 = ref[0] | (ref[2] << 16);
+        r1 = ref[1] | (ref[3] << 16);
+        ref += srcPitch;
+        for (j = 0; j < blkheight; j++)
+        {
+            result0 = dy_8 * r0 + 0x00040004;
+            r2 = ref[0] | (ref[2] << 16);
+            result0 += dy * r2;
+            result0 >>= 3;
+            result0 &= 0x00FF00FF;
+            r0 = r2;
+
+            result1 = dy_8 * r1 + 0x00040004;
+            r3 = ref[1] | (ref[3] << 16);
+            result1 += dy * r3;
+            result1 >>= 3;
+            result1 &= 0x00FF00FF;
+            r1 = r3;
+            *(int32 *)out = result0 | (result1 << 8);
+            ref += srcPitch;
+            out += predPitch;
+        }
+        pOut += 4;
+        pRef += 4;
+    }
+    return;
+}
+
+void ChromaDiagonalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                            uint8 *pOut,  int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(blkwidth);
+    int32 r0, r1, temp0, temp1, result;
+    int32 temp[9];
+    int32 *out;
+    int i, r_temp;
+    int dy_8 = 8 - dy;
+
+    /* horizontal first */
+    out = temp;
+    for (i = 0; i < blkheight + 1; i++)
+    {
+        r_temp = pRef[1];
+        temp0 = (pRef[0] << 3) + dx * (r_temp - pRef[0]);
+        temp1 = (r_temp << 3) + dx * (pRef[2] - r_temp);
+        r0 = temp0 | (temp1 << 16);
+        *out++ = r0;
+        pRef += srcPitch;
+    }
+
+    pRef -= srcPitch * (blkheight + 1);
+
+    out = temp;
+
+    r0 = *out++;
+
+    for (i = 0; i < blkheight; i++)
+    {
+        result = dy_8 * r0 + 0x00200020;
+        r1 = *out++;
+        result += dy * r1;
+        result >>= 6;
+        result &= 0x00FF00FF;
+        *(int16 *)pOut = (result >> 8) | (result & 0xFF);
+        r0 = r1;
+        pOut += predPitch;
+    }
+    return;
+}
+
+void ChromaHorizontalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                              uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(dy);
+    OSCL_UNUSED_ARG(blkwidth);
+    int i, temp, temp0, temp1;
+
+    /* horizontal first */
+    for (i = 0; i < blkheight; i++)
+    {
+        temp = pRef[1];
+        temp0 = ((pRef[0] << 3) + dx * (temp - pRef[0]) + 4) >> 3;
+        temp1 = ((temp << 3) + dx * (pRef[2] - temp) + 4) >> 3;
+
+        *(int16 *)pOut = temp0 | (temp1 << 8);
+        pRef += srcPitch;
+        pOut += predPitch;
+
+    }
+    return;
+}
+void ChromaVerticalMC2_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                            uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(dx);
+    OSCL_UNUSED_ARG(blkwidth);
+    int32 r0, r1, result;
+    int i;
+    int dy_8 = 8 - dy;
+    r0 = pRef[0] | (pRef[1] << 16);
+    pRef += srcPitch;
+    for (i = 0; i < blkheight; i++)
+    {
+        result = dy_8 * r0 + 0x00040004;
+        r1 = pRef[0] | (pRef[1] << 16);
+        result += dy * r1;
+        result >>= 3;
+        result &= 0x00FF00FF;
+        *(int16 *)pOut = (result >> 8) | (result & 0xFF);
+        r0 = r1;
+        pRef += srcPitch;
+        pOut += predPitch;
+    }
+    return;
+}
+
+void ChromaFullMC_SIMD(uint8 *pRef, int srcPitch, int dx, int dy,
+                       uint8 *pOut, int predPitch, int blkwidth, int blkheight)
+{
+    OSCL_UNUSED_ARG(dx);
+    OSCL_UNUSED_ARG(dy);
+    int i, j;
+    int offset_in = srcPitch - blkwidth;
+    int offset_out = predPitch - blkwidth;
+    uint16 temp;
+    uint8 byte;
+
+    if (((uint32)pRef)&1)
+    {
+        for (j = blkheight; j > 0; j--)
+        {
+            for (i = blkwidth; i > 0; i -= 2)
+            {
+                temp = *pRef++;
+                byte = *pRef++;
+                temp |= (byte << 8);
+                *((uint16*)pOut) = temp; /* write 2 bytes */
+                pOut += 2;
+            }
+            pOut += offset_out;
+            pRef += offset_in;
+        }
+    }
+    else
+    {
+        for (j = blkheight; j > 0; j--)
+        {
+            for (i = blkwidth; i > 0; i -= 2)
+            {
+                temp = *((uint16*)pRef);
+                *((uint16*)pOut) = temp;
+                pRef += 2;
+                pOut += 2;
+            }
+            pOut += offset_out;
+            pRef += offset_in;
+        }
+    }
+    return ;
+}
diff --git a/media/libstagefright/codecs/avc/dec/src/pred_intra.cpp b/media/libstagefright/codecs/avc/dec/src/pred_intra.cpp
new file mode 100644
index 0000000..0b613a4
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/pred_intra.cpp
@@ -0,0 +1,1786 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avcdec_lib.h"
+
+#define CLIP_COMP  *comp++ = (uint8)(((uint)temp>0xFF)? 0xFF&(~(temp>>31)): temp)
+#define CLIP_RESULT(x)      if((uint)x > 0xFF){ \
+                 x = 0xFF & (~(x>>31));}
+
+
+/* We should combine the Intra4x4 functions with residual decoding and compensation  */
+AVCStatus IntraMBPrediction(AVCCommonObj *video)
+{
+    int component, SubBlock_indx, temp;
+    AVCStatus status;
+    AVCMacroblock *currMB = video->currMB;
+    AVCPictureData *currPic = video->currPic;
+    uint8 *curL, *curCb, *curCr;
+    uint8 *comp;
+    int block_x, block_y, offset;
+    int16 *dataBlock = video->block;
+    uint8 *predCb, *predCr;
+#ifdef USE_PRED_BLOCK
+    uint8 *pred;
+#endif
+    int pitch = currPic->pitch;
+    uint32 cbp4x4 = video->cbp4x4;
+
+    offset = (video->mb_y << 4) * pitch + (video->mb_x << 4);
+    curL = currPic->Sl + offset;
+
+#ifdef USE_PRED_BLOCK
+    video->pred_block = video->pred + 84;  /* point to separate prediction memory */
+    pred = video->pred_block;
+    video->pred_pitch = 20;
+#else
+    video->pred_block = curL;   /* point directly to the frame buffer */
+    video->pred_pitch = pitch;
+#endif
+
+    if (currMB->mbMode == AVC_I4)
+    {
+        /* luminance first */
+        block_x = block_y = 0;
+        for (component = 0; component < 4; component++)
+        {
+            block_x = ((component & 1) << 1);
+            block_y = ((component >> 1) << 1);
+            comp = curL;// + (block_x<<2) + (block_y<<2)*currPic->pitch;
+
+            for (SubBlock_indx = 0; SubBlock_indx < 4; SubBlock_indx++)
+            {
+                status = Intra_4x4(video, block_x, block_y, comp);
+                if (status != AVC_SUCCESS)
+                {
+                    return status;
+                }
+                /* transform following the 4x4 prediction, can't be SIMD
+                with other blocks. */
+#ifdef USE_PRED_BLOCK
+                if (cbp4x4&(1 << ((block_y << 2) + block_x)))
+                {
+                    itrans(dataBlock, pred, pred, 20);
+                }
+#else
+                if (cbp4x4&(1 << ((block_y << 2) + block_x)))
+                {
+                    itrans(dataBlock, comp, comp, pitch);
+                }
+#endif
+                temp = SubBlock_indx & 1;
+                if (temp)
+                {
+                    block_y++;
+                    block_x--;
+                    dataBlock += 60;
+#ifdef USE_PRED_BLOCK
+                    pred += 76;
+#else
+                    comp += ((pitch << 2) - 4);
+#endif
+                }
+                else
+                {
+                    block_x++;
+                    dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+                    pred += 4;
+#else
+                    comp += 4;
+#endif
+                }
+            }
+            if (component&1)
+            {
+#ifdef USE_PRED_BLOCK
+                pred -= 8;
+#else
+                curL += (pitch << 3) - 8;
+#endif
+                dataBlock -= 8;
+            }
+            else
+            {
+#ifdef USE_PRED_BLOCK
+                pred -= 152;
+#else
+                curL += 8;
+#endif
+                dataBlock -= 120;
+            }
+        }
+        cbp4x4 >>= 16;
+    }
+    else   /* AVC_I16 */
+    {
+#ifdef MB_BASED_DEBLOCK
+        video->pintra_pred_top = video->intra_pred_top + (video->mb_x << 4);
+        video->pintra_pred_left = video->intra_pred_left + 1;
+        video->intra_pred_topleft = video->intra_pred_left[0];
+        pitch = 1;
+#else
+        video->pintra_pred_top = curL - pitch;
+        video->pintra_pred_left = curL - 1;
+        if (video->mb_y)
+        {
+            video->intra_pred_topleft = *(curL - pitch - 1);
+        }
+#endif
+        switch (currMB->i16Mode)
+        {
+            case AVC_I16_Vertical:      /* Intra_16x16_Vertical */
+                /* check availability of top */
+                if (video->intraAvailB)
+                {
+                    Intra_16x16_Vertical(video);
+                }
+                else
+                {
+                    return AVC_FAIL;
+                }
+                break;
+            case AVC_I16_Horizontal:        /* Intra_16x16_Horizontal */
+                /* check availability of left */
+                if (video->intraAvailA)
+                {
+                    Intra_16x16_Horizontal(video, pitch);
+                }
+                else
+                {
+                    return AVC_FAIL;
+                }
+                break;
+            case AVC_I16_DC:        /* Intra_16x16_DC */
+                Intra_16x16_DC(video, pitch);
+                break;
+            case AVC_I16_Plane:     /* Intra_16x16_Plane */
+                if (video->intraAvailA && video->intraAvailB && video->intraAvailD)
+                {
+                    Intra_16x16_Plane(video, pitch);
+                }
+                else
+                {
+                    return AVC_FAIL;
+                }
+                break;
+            default:
+                break;
+        }
+
+        pitch = currPic->pitch;
+
+        /* transform */
+        /* can go in raster scan order now */
+        /* can be done in SIMD,  */
+        for (block_y = 4; block_y > 0; block_y--)
+        {
+            for (block_x = 4; block_x > 0; block_x--)
+            {
+#ifdef USE_PRED_BLOCK
+                if (cbp4x4&1)
+                {
+                    itrans(dataBlock, pred, pred, 20);
+                }
+#else
+                if (cbp4x4&1)
+                {
+                    itrans(dataBlock, curL, curL, pitch);
+                }
+#endif
+                cbp4x4 >>= 1;
+                dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+                pred += 4;
+#else
+                curL += 4;
+#endif
+            }
+            dataBlock += 48;
+#ifdef USE_PRED_BLOCK
+            pred += 64;
+#else
+            curL += ((pitch << 2) - 16);
+#endif
+        }
+    }
+
+    offset = (offset >> 2) + (video->mb_x << 2); //((video->mb_y << 3)* pitch + (video->mb_x << 3));
+    curCb = currPic->Scb + offset;
+    curCr = currPic->Scr + offset;
+
+#ifdef MB_BASED_DEBLOCK
+    video->pintra_pred_top_cb = video->intra_pred_top_cb + (video->mb_x << 3);
+    video->pintra_pred_left_cb = video->intra_pred_left_cb + 1;
+    video->intra_pred_topleft_cb = video->intra_pred_left_cb[0];
+    video->pintra_pred_top_cr = video->intra_pred_top_cr + (video->mb_x << 3);
+    video->pintra_pred_left_cr = video->intra_pred_left_cr + 1;
+    video->intra_pred_topleft_cr = video->intra_pred_left_cr[0];
+    pitch  = 1;
+#else
+    pitch >>= 1;
+    video->pintra_pred_top_cb = curCb - pitch;
+    video->pintra_pred_left_cb = curCb - 1;
+    video->pintra_pred_top_cr = curCr - pitch;
+    video->pintra_pred_left_cr = curCr - 1;
+
+    if (video->mb_y)
+    {
+        video->intra_pred_topleft_cb = *(curCb - pitch - 1);
+        video->intra_pred_topleft_cr = *(curCr - pitch - 1);
+    }
+#endif
+
+#ifdef USE_PRED_BLOCK
+    predCb = video->pred + 452;
+    predCr = predCb + 144;
+    video->pred_pitch = 12;
+#else
+    predCb = curCb;
+    predCr = curCr;
+    video->pred_pitch = currPic->pitch >> 1;
+#endif
+    /* chrominance */
+    switch (currMB->intra_chroma_pred_mode)
+    {
+        case AVC_IC_DC:     /* Intra_Chroma_DC */
+            Intra_Chroma_DC(video, pitch, predCb, predCr);
+            break;
+        case AVC_IC_Horizontal:     /* Intra_Chroma_Horizontal */
+            if (video->intraAvailA)
+            {
+                /* check availability of left */
+                Intra_Chroma_Horizontal(video, pitch, predCb, predCr);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+        case AVC_IC_Vertical:       /* Intra_Chroma_Vertical */
+            if (video->intraAvailB)
+            {
+                /* check availability of top */
+                Intra_Chroma_Vertical(video, predCb, predCr);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+        case AVC_IC_Plane:      /* Intra_Chroma_Plane */
+            if (video->intraAvailA && video->intraAvailB && video->intraAvailD)
+            {
+                /* check availability of top and left */
+                Intra_Chroma_Plane(video, pitch, predCb, predCr);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+        default:
+            break;
+    }
+
+    /* transform, done in raster scan manner */
+    pitch = currPic->pitch >> 1;
+
+    for (block_y = 2; block_y > 0; block_y--)
+    {
+        for (block_x = 2; block_x > 0; block_x--)
+        {
+#ifdef USE_PRED_BLOCK
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, predCb, predCb, 12);
+            }
+#else
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, curCb, curCb, pitch);
+            }
+#endif
+            cbp4x4 >>= 1;
+            dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+            predCb += 4;
+#else
+            curCb += 4;
+#endif
+        }
+        for (block_x = 2; block_x > 0; block_x--)
+        {
+#ifdef USE_PRED_BLOCK
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, predCr, predCr, 12);
+            }
+#else
+            if (cbp4x4&1)
+            {
+                ictrans(dataBlock, curCr, curCr, pitch);
+            }
+#endif
+            cbp4x4 >>= 1;
+            dataBlock += 4;
+#ifdef USE_PRED_BLOCK
+            predCr += 4;
+#else
+            curCr += 4;
+#endif
+        }
+        dataBlock += 48;
+#ifdef USE_PRED_BLOCK
+        predCb += 40;
+        predCr += 40;
+#else
+        curCb += ((pitch << 2) - 8);
+        curCr += ((pitch << 2) - 8);
+#endif
+    }
+
+#ifdef MB_BASED_DEBLOCK
+    SaveNeighborForIntraPred(video, offset);
+#endif
+    return AVC_SUCCESS;
+}
+
+#ifdef MB_BASED_DEBLOCK
+void SaveNeighborForIntraPred(AVCCommonObj *video, int offset)
+{
+    AVCPictureData *currPic = video->currPic;
+    int pitch;
+    uint8 *pred, *predCb, *predCr;
+    uint8 *tmp_ptr, tmp_byte;
+    uint32 tmp_word;
+    int mb_x = video->mb_x;
+
+    /* save the value for intra prediction  */
+#ifdef USE_PRED_BLOCK
+    pitch = 20;
+    pred = video->pred + 384; /* bottom line for Y */
+    predCb = pred + 152;    /* bottom line for Cb */
+    predCr = predCb + 144;  /* bottom line for Cr */
+#else
+    pitch = currPic->pitch;
+    tmp_word = offset + (pitch << 2) - (pitch >> 1);
+    predCb = currPic->Scb + tmp_word;/* bottom line for Cb */
+    predCr = currPic->Scr + tmp_word;/* bottom line for Cr */
+
+    offset = (offset << 2) - (mb_x << 4);
+    pred = currPic->Sl + offset + (pitch << 4) - pitch;/* bottom line for Y */
+
+#endif
+
+    video->intra_pred_topleft = video->intra_pred_top[(mb_x<<4)+15];
+    video->intra_pred_topleft_cb = video->intra_pred_top_cb[(mb_x<<3)+7];
+    video->intra_pred_topleft_cr = video->intra_pred_top_cr[(mb_x<<3)+7];
+
+    /* then copy to video->intra_pred_top, intra_pred_top_cb, intra_pred_top_cr */
+    /*memcpy(video->intra_pred_top + (mb_x<<4), pred, 16);
+    memcpy(video->intra_pred_top_cb + (mb_x<<3), predCb, 8);
+    memcpy(video->intra_pred_top_cr + (mb_x<<3), predCr, 8);*/
+    tmp_ptr = video->intra_pred_top + (mb_x << 4);
+    *((uint32*)tmp_ptr) = *((uint32*)pred);
+    *((uint32*)(tmp_ptr + 4)) = *((uint32*)(pred + 4));
+    *((uint32*)(tmp_ptr + 8)) = *((uint32*)(pred + 8));
+    *((uint32*)(tmp_ptr + 12)) = *((uint32*)(pred + 12));
+    tmp_ptr = video->intra_pred_top_cb + (mb_x << 3);
+    *((uint32*)tmp_ptr) = *((uint32*)predCb);
+    *((uint32*)(tmp_ptr + 4)) = *((uint32*)(predCb + 4));
+    tmp_ptr = video->intra_pred_top_cr + (mb_x << 3);
+    *((uint32*)tmp_ptr) = *((uint32*)predCr);
+    *((uint32*)(tmp_ptr + 4)) = *((uint32*)(predCr + 4));
+
+
+    /* now save last column */
+#ifdef USE_PRED_BLOCK
+    pred = video->pred + 99;    /* last column*/
+#else
+    pred -= ((pitch << 4) - pitch - 15);    /* last column */
+#endif
+    tmp_ptr = video->intra_pred_left;
+    tmp_word = video->intra_pred_topleft;
+    tmp_byte = *(pred);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)tmp_ptr) = tmp_word;
+    tmp_word = *(pred += pitch);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)(tmp_ptr += 4)) = tmp_word;
+    tmp_word = *(pred += pitch);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)(tmp_ptr += 4)) = tmp_word;
+    tmp_word = *(pred += pitch);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(pred += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)(tmp_ptr += 4)) = tmp_word;
+    *(tmp_ptr += 4) = *(pred += pitch);
+
+    /* now for Cb */
+#ifdef USE_PRED_BLOCK
+    predCb = video->pred + 459;
+    pitch = 12;
+#else
+    pitch >>= 1;
+    predCb -= (7 * pitch - 7);
+#endif
+    tmp_ptr = video->intra_pred_left_cb;
+    tmp_word = video->intra_pred_topleft_cb;
+    tmp_byte = *(predCb);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(predCb += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(predCb += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)tmp_ptr) = tmp_word;
+    tmp_word = *(predCb += pitch);
+    tmp_byte = *(predCb += pitch);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(predCb += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(predCb += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)(tmp_ptr += 4)) = tmp_word;
+    *(tmp_ptr += 4) = *(predCb += pitch);
+
+    /* now for Cr */
+#ifdef USE_PRED_BLOCK
+    predCr = video->pred + 603;
+#else
+    predCr -= (7 * pitch - 7);
+#endif
+    tmp_ptr = video->intra_pred_left_cr;
+    tmp_word = video->intra_pred_topleft_cr;
+    tmp_byte = *(predCr);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(predCr += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(predCr += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)tmp_ptr) = tmp_word;
+    tmp_word = *(predCr += pitch);
+    tmp_byte = *(predCr += pitch);
+    tmp_word |= (tmp_byte << 8);
+    tmp_byte = *(predCr += pitch);
+    tmp_word |= (tmp_byte << 16);
+    tmp_byte = *(predCr += pitch);
+    tmp_word |= (tmp_byte << 24);
+    *((uint32*)(tmp_ptr += 4)) = tmp_word;
+    *(tmp_ptr += 4) = *(predCr += pitch);
+
+    return ;
+}
+#endif /* MB_BASED_DEBLOCK */
+
+AVCStatus Intra_4x4(AVCCommonObj *video, int block_x, int block_y, uint8 *comp)
+{
+    AVCMacroblock *currMB = video->currMB;
+    int block_offset;
+    AVCNeighborAvailability availability;
+    int pitch = video->currPic->pitch;
+
+#ifdef USE_PRED_BLOCK
+    block_offset = (block_y * 80) + (block_x << 2);
+#else
+    block_offset = (block_y << 2) * pitch + (block_x << 2);
+#endif
+
+#ifdef MB_BASED_DEBLOCK
+    /* boundary blocks use video->pred_intra_top, pred_intra_left, pred_intra_topleft */
+    if (!block_x)
+    {
+        video->pintra_pred_left = video->intra_pred_left + 1 + (block_y << 2);
+        pitch = 1;
+    }
+    else
+    {
+        video->pintra_pred_left = video->pred_block + block_offset - 1;
+        pitch = video->pred_pitch;
+    }
+
+    if (!block_y)
+    {
+        video->pintra_pred_top = video->intra_pred_top + (block_x << 2) + (video->mb_x << 4);
+    }
+    else
+    {
+        video->pintra_pred_top = video->pred_block + block_offset - video->pred_pitch;
+    }
+
+    if (!block_x)
+    {
+        video->intra_pred_topleft = video->intra_pred_left[block_y<<2];
+    }
+    else if (!block_y)
+    {
+        video->intra_pred_topleft = video->intra_pred_top[(video->mb_x<<4)+(block_x<<2)-1];
+    }
+    else
+    {
+        video->intra_pred_topleft = video->pred_block[block_offset - video->pred_pitch - 1];
+    }
+
+#else
+    /* normal case */
+    video->pintra_pred_top = comp - pitch;
+    video->pintra_pred_left = comp - 1;
+    if (video->mb_y || block_y)
+    {
+        video->intra_pred_topleft = *(comp - pitch - 1);
+    }
+#endif
+
+    switch (currMB->i4Mode[(block_y << 2) + block_x])
+    {
+        case AVC_I4_Vertical:       /* Intra_4x4_Vertical */
+            if (block_y > 0 || video->intraAvailB)/* to prevent out-of-bound access*/
+            {
+                Intra_4x4_Vertical(video,  block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+        case AVC_I4_Horizontal:     /* Intra_4x4_Horizontal */
+            if (block_x || video->intraAvailA)  /* to prevent out-of-bound access */
+            {
+                Intra_4x4_Horizontal(video, pitch, block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+        case AVC_I4_DC:     /* Intra_4x4_DC */
+            availability.left = TRUE;
+            availability.top = TRUE;
+            if (!block_y)
+            { /* check availability up */
+                availability.top = video->intraAvailB ;
+            }
+            if (!block_x)
+            { /* check availability left */
+                availability.left = video->intraAvailA ;
+            }
+            Intra_4x4_DC(video, pitch, block_offset, &availability);
+            break;
+
+        case AVC_I4_Diagonal_Down_Left:     /* Intra_4x4_Diagonal_Down_Left */
+            /* lookup table will be more appropriate for this case  */
+            if (block_y == 0 && !video->intraAvailB)
+            {
+                return AVC_FAIL;
+            }
+
+            availability.top_right = BlkTopRight[(block_y<<2) + block_x];
+
+            if (availability.top_right == 2)
+            {
+                availability.top_right = video->intraAvailB;
+            }
+            else if (availability.top_right == 3)
+            {
+                availability.top_right = video->intraAvailC;
+            }
+
+            Intra_4x4_Down_Left(video, block_offset, &availability);
+            break;
+
+        case AVC_I4_Diagonal_Down_Right:        /* Intra_4x4_Diagonal_Down_Right */
+            if ((block_y && block_x)  /* to prevent out-of-bound access */
+                    || (block_y && video->intraAvailA)
+                    || (block_x && video->intraAvailB)
+                    || (video->intraAvailA && video->intraAvailD && video->intraAvailB))
+            {
+                Intra_4x4_Diagonal_Down_Right(video, pitch, block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+        case AVC_I4_Vertical_Right:     /* Intra_4x4_Vertical_Right */
+            if ((block_y && block_x)  /* to prevent out-of-bound access */
+                    || (block_y && video->intraAvailA)
+                    || (block_x && video->intraAvailB)
+                    || (video->intraAvailA && video->intraAvailD && video->intraAvailB))
+            {
+                Intra_4x4_Diagonal_Vertical_Right(video, pitch, block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+        case AVC_I4_Horizontal_Down:        /* Intra_4x4_Horizontal_Down */
+            if ((block_y && block_x)  /* to prevent out-of-bound access */
+                    || (block_y && video->intraAvailA)
+                    || (block_x && video->intraAvailB)
+                    || (video->intraAvailA && video->intraAvailD && video->intraAvailB))
+            {
+                Intra_4x4_Diagonal_Horizontal_Down(video, pitch, block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+        case AVC_I4_Vertical_Left:      /* Intra_4x4_Vertical_Left */
+            /* lookup table may be more appropriate for this case  */
+            if (block_y == 0 && !video->intraAvailB)
+            {
+                return AVC_FAIL;
+            }
+
+            availability.top_right = BlkTopRight[(block_y<<2) + block_x];
+
+            if (availability.top_right == 2)
+            {
+                availability.top_right = video->intraAvailB;
+            }
+            else if (availability.top_right == 3)
+            {
+                availability.top_right = video->intraAvailC;
+            }
+
+            Intra_4x4_Vertical_Left(video,  block_offset, &availability);
+            break;
+
+        case AVC_I4_Horizontal_Up:      /* Intra_4x4_Horizontal_Up */
+            if (block_x || video->intraAvailA)
+            {
+                Intra_4x4_Horizontal_Up(video, pitch, block_offset);
+            }
+            else
+            {
+                return AVC_FAIL;
+            }
+            break;
+
+
+        default:
+
+            break;
+    }
+
+    return AVC_SUCCESS;
+}
+
+
+/* =============================== BEGIN 4x4
+MODES======================================*/
+void Intra_4x4_Vertical(AVCCommonObj *video,  int block_offset)
+{
+    uint8 *comp_ref = video->pintra_pred_top;
+    uint32 temp;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    /*P = (int) *comp_ref++;
+    Q = (int) *comp_ref++;
+    R = (int) *comp_ref++;
+    S = (int) *comp_ref++;
+    temp = S|(R<<8)|(Q<<16)|(P<<24);*/
+    temp = *((uint32*)comp_ref);
+
+    *((uint32*)pred) =  temp; /* write 4 at a time */
+    pred += pred_pitch;
+    *((uint32*)pred) =  temp;
+    pred += pred_pitch;
+    *((uint32*)pred) =  temp;
+    pred += pred_pitch;
+    *((uint32*)pred) =  temp;
+
+    return ;
+}
+
+void Intra_4x4_Horizontal(AVCCommonObj *video, int pitch, int block_offset)
+{
+    uint8   *comp_ref = video->pintra_pred_left;
+    uint32 temp;
+    int P;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    P = *comp_ref;
+    temp = P | (P << 8);
+    temp = temp | (temp << 16);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    comp_ref += pitch;
+    P = *comp_ref;
+    temp = P | (P << 8);
+    temp = temp | (temp << 16);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    comp_ref += pitch;
+    P = *comp_ref;
+    temp = P | (P << 8);
+    temp = temp | (temp << 16);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    comp_ref += pitch;
+    P = *comp_ref;
+    temp = P | (P << 8);
+    temp = temp | (temp << 16);
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+
+void Intra_4x4_DC(AVCCommonObj *video, int pitch, int block_offset,
+                  AVCNeighborAvailability *availability)
+{
+    uint8   *comp_ref = video->pintra_pred_left;
+    uint32  temp;
+    int DC;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    if (availability->left)
+    {
+        DC = *comp_ref;
+        comp_ref += pitch;
+        DC += *comp_ref;
+        comp_ref += pitch;
+        DC += *comp_ref;
+        comp_ref += pitch;
+        DC += *comp_ref;
+        comp_ref = video->pintra_pred_top;
+
+        if (availability->top)
+        {
+            DC = (comp_ref[0] + comp_ref[1] + comp_ref[2] + comp_ref[3] + DC + 4) >> 3;
+        }
+        else
+        {
+            DC = (DC + 2) >> 2;
+
+        }
+    }
+    else if (availability->top)
+    {
+        comp_ref = video->pintra_pred_top;
+        DC = (comp_ref[0] + comp_ref[1] + comp_ref[2] + comp_ref[3] + 2) >> 2;
+
+    }
+    else
+    {
+        DC = 128;
+    }
+
+    temp = DC | (DC << 8);
+    temp = temp | (temp << 16);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+
+void Intra_4x4_Down_Left(AVCCommonObj *video, int block_offset,
+                         AVCNeighborAvailability *availability)
+{
+    uint8   *comp_refx = video->pintra_pred_top;
+    uint32 temp;
+    int r0, r1, r2, r3, r4, r5, r6, r7;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    r0 = *comp_refx++;
+    r1 = *comp_refx++;
+    r2 = *comp_refx++;
+    r3 = *comp_refx++;
+    if (availability->top_right)
+    {
+        r4 = *comp_refx++;
+        r5 = *comp_refx++;
+        r6 = *comp_refx++;
+        r7 = *comp_refx++;
+    }
+    else
+    {
+        r4 = r3;
+        r5 = r3;
+        r6 = r3;
+        r7 = r3;
+    }
+
+    r0 += (r1 << 1);
+    r0 += r2;
+    r0 += 2;
+    r0 >>= 2;
+    r1 += (r2 << 1);
+    r1 += r3;
+    r1 += 2;
+    r1 >>= 2;
+    r2 += (r3 << 1);
+    r2 += r4;
+    r2 += 2;
+    r2 >>= 2;
+    r3 += (r4 << 1);
+    r3 += r5;
+    r3 += 2;
+    r3 >>= 2;
+    r4 += (r5 << 1);
+    r4 += r6;
+    r4 += 2;
+    r4 >>= 2;
+    r5 += (r6 << 1);
+    r5 += r7;
+    r5 += 2;
+    r5 >>= 2;
+    r6 += (3 * r7);
+    r6 += 2;
+    r6 >>= 2;
+
+    temp = r0 | (r1 << 8);
+    temp |= (r2 << 16);
+    temp |= (r3 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = (temp >> 8) | (r4 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = (temp >> 8) | (r5 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = (temp >> 8) | (r6 << 24);
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+
+void Intra_4x4_Diagonal_Down_Right(AVCCommonObj *video, int pitch, int
+                                   block_offset)
+{
+    uint8 *comp_refx = video->pintra_pred_top;
+    uint8 *comp_refy = video->pintra_pred_left;
+    uint32 temp;
+    int P_x, Q_x, R_x, P_y, Q_y, R_y, D;
+    int x0, x1, x2;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    temp = *((uint32*)comp_refx); /* read 4 bytes */
+    x0 = temp & 0xFF;
+    x1 = (temp >> 8) & 0xFF;
+    x2 = (temp >> 16) & 0xFF;
+
+    Q_x = (x0 + 2 * x1 + x2 + 2) >> 2;
+    R_x = (x1 + 2 * x2 + (temp >> 24) + 2) >> 2;
+
+    x2 = video->intra_pred_topleft; /* re-use x2 instead of y0 */
+    P_x = (x2 + 2 * x0 + x1 + 2) >> 2;
+
+    x1 = *comp_refy;
+    comp_refy += pitch; /* re-use x1 instead of y1 */
+    D = (x0 + 2 * x2 + x1 + 2) >> 2;
+
+    x0 = *comp_refy;
+    comp_refy += pitch; /* re-use x0 instead of y2 */
+    P_y = (x2 + 2 * x1 + x0 + 2) >> 2;
+
+    x2 = *comp_refy;
+    comp_refy += pitch; /* re-use x2 instead of y3 */
+    Q_y = (x1 + 2 * x0 + x2 + 2) >> 2;
+
+    x1 = *comp_refy;                    /* re-use x1 instead of y4 */
+    R_y = (x0 + 2 * x2 + x1 + 2) >> 2;
+
+    /* we can pack these  */
+    temp =  D | (P_x << 8);   //[D   P_x Q_x R_x]
+    //[P_y D   P_x Q_x]
+    temp |= (Q_x << 16); //[Q_y P_y D   P_x]
+    temp |= (R_x << 24);  //[R_y Q_y P_y D  ]
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp =  P_y | (D << 8);
+    temp |= (P_x << 16);
+    temp |= (Q_x << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp =  Q_y | (P_y << 8);
+    temp |= (D << 16);
+    temp |= (P_x << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = R_y | (Q_y << 8);
+    temp |= (P_y << 16);
+    temp |= (D << 24);
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+
+void    Intra_4x4_Diagonal_Vertical_Right(AVCCommonObj *video, int pitch, int block_offset)
+{
+    uint8   *comp_refx = video->pintra_pred_top;
+    uint8   *comp_refy = video->pintra_pred_left;
+    uint32 temp;
+    int P0, Q0, R0, S0, P1, Q1, R1, P2, Q2, D;
+    int x0, x1, x2;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    x0 = *comp_refx++;
+    x1 = *comp_refx++;
+    Q0 = x0 + x1 + 1;
+
+    x2 = *comp_refx++;
+    R0 = x1 + x2 + 1;
+
+    x1 = *comp_refx++; /* reuse x1 instead of x3 */
+    S0 = x2 + x1 + 1;
+
+    x1 = video->intra_pred_topleft; /* reuse x1 instead of y0 */
+    P0 = x1 + x0 + 1;
+
+    x2 = *comp_refy;
+    comp_refy += pitch; /* reuse x2 instead of y1 */
+    D = (x2 + 2 * x1 + x0 + 2) >> 2;
+
+    P1 = (P0 + Q0) >> 2;
+    Q1 = (Q0 + R0) >> 2;
+    R1 = (R0 + S0) >> 2;
+
+    P0 >>= 1;
+    Q0 >>= 1;
+    R0 >>= 1;
+    S0 >>= 1;
+
+    x0 = *comp_refy;
+    comp_refy += pitch; /* reuse x0 instead of y2 */
+    P2 = (x1 + 2 * x2 + x0 + 2) >> 2;
+    x1 = *comp_refy;
+    comp_refy += pitch; /* reuse x1 instead of y3 */
+    Q2 = (x2 + 2 * x0 + x1 + 2) >> 2;
+
+    temp =  P0 | (Q0 << 8);  //[P0 Q0 R0 S0]
+    //[D  P1 Q1 R1]
+    temp |= (R0 << 16); //[P2 P0 Q0 R0]
+    temp |= (S0 << 24); //[Q2 D  P1 Q1]
+    *((uint32*)pred) =  temp;
+    pred += pred_pitch;
+
+    temp =  D | (P1 << 8);
+    temp |= (Q1 << 16);
+    temp |= (R1 << 24);
+    *((uint32*)pred) =  temp;
+    pred += pred_pitch;
+
+    temp = P2 | (P0 << 8);
+    temp |= (Q0 << 16);
+    temp |= (R0 << 24);
+    *((uint32*)pred) =  temp;
+    pred += pred_pitch;
+
+    temp = Q2 | (D << 8);
+    temp |= (P1 << 16);
+    temp |= (Q1 << 24);
+    *((uint32*)pred) =  temp;
+
+    return ;
+}
+
+void Intra_4x4_Diagonal_Horizontal_Down(AVCCommonObj *video, int pitch,
+                                        int block_offset)
+{
+    uint8   *comp_refx = video->pintra_pred_top;
+    uint8   *comp_refy = video->pintra_pred_left;
+    uint32 temp;
+    int P0, Q0, R0, S0, P1, Q1, R1, P2, Q2, D;
+    int x0, x1, x2;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    x0 = *comp_refx++;
+    x1 = *comp_refx++;
+    x2 = *comp_refx++;
+    Q2 = (x0 + 2 * x1 + x2 + 2) >> 2;
+
+    x2 = video->intra_pred_topleft; /* reuse x2 instead of y0 */
+    P2 = (x2 + 2 * x0 + x1 + 2) >> 2;
+
+    x1 = *comp_refy;
+    comp_refy += pitch; /* reuse x1 instead of y1 */
+    D = (x1 + 2 * x2 + x0 + 2) >> 2;
+    P0 = x2 + x1 + 1;
+
+    x0 = *comp_refy;
+    comp_refy += pitch; /* reuse x0 instead of y2 */
+    Q0 = x1 + x0 + 1;
+
+    x1 = *comp_refy;
+    comp_refy += pitch; /* reuse x1 instead of y3 */
+    R0 = x0 + x1 + 1;
+
+    x2 = *comp_refy;    /* reuse x2 instead of y4 */
+    S0 = x1 + x2 + 1;
+
+    P1 = (P0 + Q0) >> 2;
+    Q1 = (Q0 + R0) >> 2;
+    R1 = (R0 + S0) >> 2;
+
+    P0 >>= 1;
+    Q0 >>= 1;
+    R0 >>= 1;
+    S0 >>= 1;
+
+
+    /* we can pack these  */
+    temp = P0 | (D << 8);   //[P0 D  P2 Q2]
+    //[Q0 P1 P0 D ]
+    temp |= (P2 << 16);  //[R0 Q1 Q0 P1]
+    temp |= (Q2 << 24); //[S0 R1 R0 Q1]
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = Q0 | (P1 << 8);
+    temp |= (P0 << 16);
+    temp |= (D << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = R0 | (Q1 << 8);
+    temp |= (Q0 << 16);
+    temp |= (P1 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = S0 | (R1 << 8);
+    temp |= (R0 << 16);
+    temp |= (Q1 << 24);
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+
+void Intra_4x4_Vertical_Left(AVCCommonObj *video, int block_offset, AVCNeighborAvailability *availability)
+{
+    uint8   *comp_refx = video->pintra_pred_top;
+    uint32 temp1, temp2;
+    int x0, x1, x2, x3, x4, x5, x6;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    x0 = *comp_refx++;
+    x1 = *comp_refx++;
+    x2 = *comp_refx++;
+    x3 = *comp_refx++;
+    if (availability->top_right)
+    {
+        x4 = *comp_refx++;
+        x5 = *comp_refx++;
+        x6 = *comp_refx++;
+    }
+    else
+    {
+        x4 = x3;
+        x5 = x3;
+        x6 = x3;
+    }
+
+    x0 += x1 + 1;
+    x1 += x2 + 1;
+    x2 += x3 + 1;
+    x3 += x4 + 1;
+    x4 += x5 + 1;
+    x5 += x6 + 1;
+
+    temp1 = (x0 >> 1);
+    temp1 |= ((x1 >> 1) << 8);
+    temp1 |= ((x2 >> 1) << 16);
+    temp1 |= ((x3 >> 1) << 24);
+
+    *((uint32*)pred) = temp1;
+    pred += pred_pitch;
+
+    temp2 = ((x0 + x1) >> 2);
+    temp2 |= (((x1 + x2) >> 2) << 8);
+    temp2 |= (((x2 + x3) >> 2) << 16);
+    temp2 |= (((x3 + x4) >> 2) << 24);
+
+    *((uint32*)pred) = temp2;
+    pred += pred_pitch;
+
+    temp1 = (temp1 >> 8) | ((x4 >> 1) << 24);   /* rotate out old value */
+    *((uint32*)pred) = temp1;
+    pred += pred_pitch;
+
+    temp2 = (temp2 >> 8) | (((x4 + x5) >> 2) << 24); /* rotate out old value */
+    *((uint32*)pred) = temp2;
+    pred += pred_pitch;
+
+    return ;
+}
+
+void Intra_4x4_Horizontal_Up(AVCCommonObj *video, int pitch, int block_offset)
+{
+    uint8   *comp_refy = video->pintra_pred_left;
+    uint32 temp;
+    int Q0, R0, Q1, D0, D1, P0, P1;
+    int y0, y1, y2, y3;
+    uint8 *pred = video->pred_block + block_offset;
+    int pred_pitch = video->pred_pitch;
+
+    y0 = *comp_refy;
+    comp_refy += pitch;
+    y1 = *comp_refy;
+    comp_refy += pitch;
+    y2 = *comp_refy;
+    comp_refy += pitch;
+    y3 = *comp_refy;
+
+    Q0 = (y1 + y2 + 1) >> 1;
+    Q1 = (y1 + (y2 << 1) + y3 + 2) >> 2;
+    P0 = ((y0 + y1 + 1) >> 1);
+    P1 = ((y0 + (y1 << 1) + y2 + 2) >> 2);
+
+    temp = P0 | (P1 << 8);      // [P0 P1 Q0 Q1]
+    temp |= (Q0 << 16);     // [Q0 Q1 R0 DO]
+    temp |= (Q1 << 24);     // [R0 D0 D1 D1]
+    *((uint32*)pred) = temp;      // [D1 D1 D1 D1]
+    pred += pred_pitch;
+
+    D0 = (y2 + 3 * y3 + 2) >> 2;
+    R0 = (y2 + y3 + 1) >> 1;
+
+    temp = Q0 | (Q1 << 8);
+    temp |= (R0 << 16);
+    temp |= (D0 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    D1 = y3;
+
+    temp = R0 | (D0 << 8);
+    temp |= (D1 << 16);
+    temp |= (D1 << 24);
+    *((uint32*)pred) = temp;
+    pred += pred_pitch;
+
+    temp = D1 | (D1 << 8);
+    temp |= (temp << 16);
+    *((uint32*)pred) = temp;
+
+    return ;
+}
+/* =============================== END 4x4 MODES======================================*/
+void  Intra_16x16_Vertical(AVCCommonObj *video)
+{
+    int i;
+    uint32 temp1, temp2, temp3, temp4;
+    uint8   *comp_ref = video->pintra_pred_top;
+    uint8 *pred = video->pred_block;
+    int pred_pitch = video->pred_pitch;
+
+    temp1 = *((uint32*)comp_ref);
+    comp_ref += 4;
+
+    temp2 = *((uint32*)comp_ref);
+    comp_ref += 4;
+
+    temp3 = *((uint32*)comp_ref);
+    comp_ref += 4;
+
+    temp4 = *((uint32*)comp_ref);
+    comp_ref += 4;
+
+    i = 16;
+    while (i > 0)
+    {
+        *((uint32*)pred) = temp1;
+        *((uint32*)(pred + 4)) = temp2;
+        *((uint32*)(pred + 8)) = temp3;
+        *((uint32*)(pred + 12)) = temp4;
+        pred += pred_pitch;
+        i--;
+    }
+
+    return ;
+}
+
+void Intra_16x16_Horizontal(AVCCommonObj *video, int pitch)
+{
+    int i;
+    uint32 temp;
+    uint8 *comp_ref = video->pintra_pred_left;
+    uint8 *pred = video->pred_block;
+    int pred_pitch = video->pred_pitch;
+
+    for (i = 0; i < 16; i++)
+    {
+        temp = *comp_ref;
+        temp |= (temp << 8);
+        temp |= (temp << 16);
+        *((uint32*)pred) = temp;
+        *((uint32*)(pred + 4)) = temp;
+        *((uint32*)(pred + 8)) = temp;
+        *((uint32*)(pred + 12)) = temp;
+        pred += pred_pitch;
+        comp_ref += pitch;
+    }
+}
+
+
+void  Intra_16x16_DC(AVCCommonObj *video, int pitch)
+{
+    int i;
+    uint32 temp, temp2;
+    uint8 *comp_ref_x = video->pintra_pred_top;
+    uint8 *comp_ref_y = video->pintra_pred_left;
+    int sum = 0;
+    uint8 *pred = video->pred_block;
+    int pred_pitch = video->pred_pitch;
+
+    if (video->intraAvailB)
+    {
+        temp = *((uint32*)comp_ref_x);
+        comp_ref_x += 4;
+        temp2 = (temp >> 8) & 0xFF00FF;
+        temp &= 0xFF00FF;
+        temp += temp2;
+        sum = temp + (temp >> 16);
+        temp = *((uint32*)comp_ref_x);
+        comp_ref_x += 4;
+        temp2 = (temp >> 8) & 0xFF00FF;
+        temp &= 0xFF00FF;
+        temp += temp2;
+        sum += temp + (temp >> 16);
+        temp = *((uint32*)comp_ref_x);
+        comp_ref_x += 4;
+        temp2 = (temp >> 8) & 0xFF00FF;
+        temp &= 0xFF00FF;
+        temp += temp2;
+        sum += temp + (temp >> 16);
+        temp = *((uint32*)comp_ref_x);
+        comp_ref_x += 4;
+        temp2 = (temp >> 8) & 0xFF00FF;
+        temp &= 0xFF00FF;
+        temp += temp2;
+        sum += temp + (temp >> 16);
+        sum &= 0xFFFF;
+
+        if (video->intraAvailA)
+        {
+            for (i = 0; i < 16; i++)
+            {
+                sum += (*comp_ref_y);
+                comp_ref_y += pitch;
+            }
+            sum = (sum + 16) >> 5;
+        }
+        else
+        {
+            sum = (sum + 8) >> 4;
+        }
+    }
+    else if (video->intraAvailA)
+    {
+        for (i = 0; i < 16; i++)
+        {
+            sum += *comp_ref_y;
+            comp_ref_y += pitch;
+        }
+        sum = (sum + 8) >> 4;
+    }
+    else
+    {
+        sum = 128;
+    }
+
+    temp = sum | (sum << 8);
+    temp |= (temp << 16);
+
+    for (i = 0; i < 16; i++)
+    {
+        *((uint32*)pred) = temp;
+        *((uint32*)(pred + 4)) = temp;
+        *((uint32*)(pred + 8)) = temp;
+        *((uint32*)(pred + 12)) = temp;
+        pred += pred_pitch;
+    }
+
+}
+
+void Intra_16x16_Plane(AVCCommonObj *video, int pitch)
+{
+    int i, a_16, b, c, factor_c;
+    uint8 *comp_ref_x = video->pintra_pred_top;
+    uint8 *comp_ref_y = video->pintra_pred_left;
+    uint8 *comp_ref_x0, *comp_ref_x1, *comp_ref_y0, *comp_ref_y1;
+    int H = 0, V = 0 , tmp;
+    uint8 *pred = video->pred_block;
+    uint32 temp;
+    uint8 byte1, byte2, byte3;
+    int value;
+    int pred_pitch = video->pred_pitch;
+
+    comp_ref_x0 = comp_ref_x + 8;
+    comp_ref_x1 = comp_ref_x + 6;
+    comp_ref_y0 = comp_ref_y + (pitch << 3);
+    comp_ref_y1 = comp_ref_y + 6 * pitch;
+
+    for (i = 1; i < 8; i++)
+    {
+        H += i * (*comp_ref_x0++ - *comp_ref_x1--);
+        V += i * (*comp_ref_y0 - *comp_ref_y1);
+        comp_ref_y0 += pitch;
+        comp_ref_y1 -= pitch;
+    }
+
+    H += i * (*comp_ref_x0++ - video->intra_pred_topleft);
+    V += i * (*comp_ref_y0 - *comp_ref_y1);
+
+
+    a_16 = ((*(comp_ref_x + 15) + *(comp_ref_y + 15 * pitch)) << 4) + 16;;
+    b = (5 * H + 32) >> 6;
+    c = (5 * V + 32) >> 6;
+
+    tmp = 0;
+
+    for (i = 0; i < 16; i++)
+    {
+        factor_c = a_16 + c * (tmp++ - 7);
+
+        factor_c -= 7 * b;
+
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte1 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte2 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte3 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        temp = byte1 | (byte2 << 8);
+        temp |= (byte3 << 16);
+        temp |= (value << 24);
+        *((uint32*)pred) = temp;
+
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte1 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte2 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte3 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        temp = byte1 | (byte2 << 8);
+        temp |= (byte3 << 16);
+        temp |= (value << 24);
+        *((uint32*)(pred + 4)) = temp;
+
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte1 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte2 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte3 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        temp = byte1 | (byte2 << 8);
+        temp |= (byte3 << 16);
+        temp |= (value << 24);
+        *((uint32*)(pred + 8)) = temp;
+
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte1 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte2 = value;
+        value = factor_c >> 5;
+        factor_c += b;
+        CLIP_RESULT(value)
+        byte3 = value;
+        value = factor_c >> 5;
+        CLIP_RESULT(value)
+        temp = byte1 | (byte2 << 8);
+        temp |= (byte3 << 16);
+        temp |= (value << 24);
+        *((uint32*)(pred + 12)) = temp;
+        pred += pred_pitch;
+    }
+}
+
+/************** Chroma intra prediction *********************/
+
+void Intra_Chroma_DC(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr)
+{
+    int i;
+    uint32 temp, temp2, pred_a, pred_b;
+    uint8 *comp_ref_x, *comp_ref_y;
+    uint8 *comp_ref_cb_x = video->pintra_pred_top_cb;
+    uint8 *comp_ref_cb_y = video->pintra_pred_left_cb;
+    uint8 *comp_ref_cr_x = video->pintra_pred_top_cr;
+    uint8 *comp_ref_cr_y = video->pintra_pred_left_cr;
+    int  component, j;
+    int  sum_x0, sum_x1, sum_y0, sum_y1;
+    int pred_0[2], pred_1[2], pred_2[2], pred_3[2];
+    int pred_pitch = video->pred_pitch;
+    uint8 *pred;
+
+    if (video->intraAvailB & video->intraAvailA)
+    {
+        comp_ref_x = comp_ref_cb_x;
+        comp_ref_y = comp_ref_cb_y;
+        for (i = 0; i < 2; i++)
+        {
+            temp = *((uint32*)comp_ref_x);
+            comp_ref_x += 4;
+            temp2 = (temp >> 8) & 0xFF00FF;
+            temp &= 0xFF00FF;
+            temp += temp2;
+            temp += (temp >> 16);
+            sum_x0 = temp & 0xFFFF;
+
+            temp = *((uint32*)comp_ref_x);
+            temp2 = (temp >> 8) & 0xFF00FF;
+            temp &= 0xFF00FF;
+            temp += temp2;
+            temp += (temp >> 16);
+            sum_x1 = temp & 0xFFFF;
+
+            pred_1[i] = (sum_x1 + 2) >> 2;
+
+            sum_y0 = *comp_ref_y;
+            sum_y0 += *(comp_ref_y += pitch);
+            sum_y0 += *(comp_ref_y += pitch);
+            sum_y0 += *(comp_ref_y += pitch);
+
+            sum_y1 = *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+
+            pred_2[i] = (sum_y1 + 2) >> 2;
+
+            pred_0[i] = (sum_y0 + sum_x0 + 4) >> 3;
+            pred_3[i] = (sum_y1 + sum_x1 + 4) >> 3;
+
+            comp_ref_x = comp_ref_cr_x;
+            comp_ref_y = comp_ref_cr_y;
+        }
+    }
+
+    else if (video->intraAvailA)
+    {
+        comp_ref_y = comp_ref_cb_y;
+        for (i = 0; i < 2; i++)
+        {
+            sum_y0 = *comp_ref_y;
+            sum_y0 += *(comp_ref_y += pitch);
+            sum_y0 += *(comp_ref_y += pitch);
+            sum_y0 += *(comp_ref_y += pitch);
+
+            sum_y1 = *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+            sum_y1 += *(comp_ref_y += pitch);
+
+            pred_0[i] = pred_1[i] = (sum_y0 + 2) >> 2;
+            pred_2[i] = pred_3[i] = (sum_y1 + 2) >> 2;
+            comp_ref_y = comp_ref_cr_y;
+        }
+    }
+    else if (video->intraAvailB)
+    {
+        comp_ref_x = comp_ref_cb_x;
+        for (i = 0; i < 2; i++)
+        {
+            temp = *((uint32*)comp_ref_x);
+            comp_ref_x += 4;
+            temp2 = (temp >> 8) & 0xFF00FF;
+            temp &= 0xFF00FF;
+            temp += temp2;
+            temp += (temp >> 16);
+            sum_x0 = temp & 0xFFFF;
+
+            temp = *((uint32*)comp_ref_x);
+            temp2 = (temp >> 8) & 0xFF00FF;
+            temp &= 0xFF00FF;
+            temp += temp2;
+            temp += (temp >> 16);
+            sum_x1 = temp & 0xFFFF;
+
+            pred_0[i] = pred_2[i] = (sum_x0 + 2) >> 2;
+            pred_1[i] = pred_3[i] = (sum_x1 + 2) >> 2;
+            comp_ref_x = comp_ref_cr_x;
+        }
+    }
+    else
+    {
+        pred_0[0] = pred_0[1] = pred_1[0] = pred_1[1] =
+                                                pred_2[0] = pred_2[1] = pred_3[0] = pred_3[1] = 128;
+    }
+
+    pred = predCb;
+    for (component = 0; component < 2; component++)
+    {
+        pred_a = pred_0[component];
+        pred_b = pred_1[component];
+        pred_a |= (pred_a << 8);
+        pred_a |= (pred_a << 16);
+        pred_b |= (pred_b << 8);
+        pred_b |= (pred_b << 16);
+
+        for (i = 4; i < 6; i++)
+        {
+            for (j = 0; j < 4; j++) /* 4 lines */
+            {
+                *((uint32*)pred) = pred_a;
+                *((uint32*)(pred + 4)) = pred_b;
+                pred += pred_pitch; /* move to the next line */
+            }
+            pred_a = pred_2[component];
+            pred_b = pred_3[component];
+            pred_a |= (pred_a << 8);
+            pred_a |= (pred_a << 16);
+            pred_b |= (pred_b << 8);
+            pred_b |= (pred_b << 16);
+        }
+        pred = predCr; /* point to cr */
+    }
+}
+
+void  Intra_Chroma_Horizontal(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr)
+{
+    int i;
+    uint32 temp;
+    uint8   *comp_ref_cb_y = video->pintra_pred_left_cb;
+    uint8   *comp_ref_cr_y = video->pintra_pred_left_cr;
+    uint8  *comp;
+    int component, j;
+    int     pred_pitch = video->pred_pitch;
+    uint8   *pred;
+
+    comp = comp_ref_cb_y;
+    pred = predCb;
+    for (component = 0; component < 2; component++)
+    {
+        for (i = 4; i < 6; i++)
+        {
+            for (j = 0; j < 4; j++)
+            {
+                temp = *comp;
+                comp += pitch;
+                temp |= (temp << 8);
+                temp |= (temp << 16);
+                *((uint32*)pred) = temp;
+                *((uint32*)(pred + 4)) = temp;
+                pred += pred_pitch;
+            }
+        }
+        comp = comp_ref_cr_y;
+        pred = predCr; /* point to cr */
+    }
+
+}
+
+void  Intra_Chroma_Vertical(AVCCommonObj *video, uint8 *predCb, uint8 *predCr)
+{
+    uint32  temp1, temp2;
+    uint8   *comp_ref_cb_x = video->pintra_pred_top_cb;
+    uint8   *comp_ref_cr_x = video->pintra_pred_top_cr;
+    uint8   *comp_ref;
+    int     component, j;
+    int     pred_pitch = video->pred_pitch;
+    uint8   *pred;
+
+    comp_ref = comp_ref_cb_x;
+    pred = predCb;
+    for (component = 0; component < 2; component++)
+    {
+        temp1 = *((uint32*)comp_ref);
+        temp2 = *((uint32*)(comp_ref + 4));
+        for (j = 0; j < 8; j++)
+        {
+            *((uint32*)pred) = temp1;
+            *((uint32*)(pred + 4)) = temp2;
+            pred += pred_pitch;
+        }
+        comp_ref = comp_ref_cr_x;
+        pred = predCr; /* point to cr */
+    }
+
+}
+
+void  Intra_Chroma_Plane(AVCCommonObj *video, int pitch, uint8 *predCb, uint8 *predCr)
+{
+    int i;
+    int a_16_C[2], b_C[2], c_C[2], a_16, b, c, factor_c;
+    uint8 *comp_ref_x, *comp_ref_y, *comp_ref_x0, *comp_ref_x1,  *comp_ref_y0, *comp_ref_y1;
+    int component, j;
+    int H, V, tmp;
+    uint32 temp;
+    uint8 byte1, byte2, byte3;
+    int value;
+    uint8 topleft;
+    int pred_pitch = video->pred_pitch;
+    uint8 *pred;
+
+    comp_ref_x = video->pintra_pred_top_cb;
+    comp_ref_y = video->pintra_pred_left_cb;
+    topleft = video->intra_pred_topleft_cb;
+
+    for (component = 0; component < 2; component++)
+    {
+        H = V = 0;
+        comp_ref_x0 = comp_ref_x + 4;
+        comp_ref_x1 = comp_ref_x + 2;
+        comp_ref_y0 = comp_ref_y + (pitch << 2);
+        comp_ref_y1 = comp_ref_y + (pitch << 1);
+        for (i = 1; i < 4; i++)
+        {
+            H += i * (*comp_ref_x0++ - *comp_ref_x1--);
+            V += i * (*comp_ref_y0 - *comp_ref_y1);
+            comp_ref_y0 += pitch;
+            comp_ref_y1 -= pitch;
+        }
+        H += i * (*comp_ref_x0++ - topleft);
+        V += i * (*comp_ref_y0 - *comp_ref_y1);
+
+        a_16_C[component] = ((*(comp_ref_x + 7) + *(comp_ref_y + 7 * pitch)) << 4) + 16;
+        b_C[component] = (17 * H + 16) >> 5;
+        c_C[component] = (17 * V + 16) >> 5;
+
+        comp_ref_x = video->pintra_pred_top_cr;
+        comp_ref_y = video->pintra_pred_left_cr;
+        topleft = video->intra_pred_topleft_cr;
+    }
+
+    pred = predCb;
+    for (component = 0; component < 2; component++)
+    {
+        a_16 = a_16_C[component];
+        b = b_C[component];
+        c = c_C[component];
+        tmp = 0;
+        for (i = 4; i < 6; i++)
+        {
+            for (j = 0; j < 4; j++)
+            {
+                factor_c = a_16 + c * (tmp++ - 3);
+
+                factor_c -= 3 * b;
+
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte1 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte2 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte3 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                temp = byte1 | (byte2 << 8);
+                temp |= (byte3 << 16);
+                temp |= (value << 24);
+                *((uint32*)pred) = temp;
+
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte1 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte2 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                byte3 = value;
+                value = factor_c >> 5;
+                factor_c += b;
+                CLIP_RESULT(value)
+                temp = byte1 | (byte2 << 8);
+                temp |= (byte3 << 16);
+                temp |= (value << 24);
+                *((uint32*)(pred + 4)) = temp;
+                pred += pred_pitch;
+            }
+        }
+        pred = predCr; /* point to cr */
+    }
+}
+
diff --git a/media/libstagefright/codecs/avc/dec/src/residual.cpp b/media/libstagefright/codecs/avc/dec/src/residual.cpp
new file mode 100644
index 0000000..c68550d
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/residual.cpp
@@ -0,0 +1,523 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#include <string.h>
+
+#include "avcdec_lib.h"
+#include "avcdec_bitstream.h"
+
+AVCDec_Status DecodeIntraPCM(AVCCommonObj *video, AVCDecBitstream *stream)
+{
+    AVCDec_Status status;
+    int j;
+    int mb_x, mb_y, offset1;
+    uint8 *pDst;
+    uint32 byte0, byte1;
+    int pitch;
+
+    mb_x = video->mb_x;
+    mb_y = video->mb_y;
+
+#ifdef USE_PRED_BLOCK
+    pDst = video->pred_block + 84;
+    pitch = 20;
+#else
+    offset1 = (mb_x << 4) + (mb_y << 4) * video->PicWidthInSamplesL;
+    pDst = video->currPic->Sl + offset1;
+    pitch = video->currPic->pitch;
+#endif
+
+    /* at this point bitstream is byte-aligned */
+    j = 16;
+    while (j > 0)
+    {
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)pDst) = byte0;
+
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)(pDst + 4)) = byte0;
+
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)(pDst + 8)) = byte0;
+
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)(pDst + 12)) = byte0;
+        j--;
+        pDst += pitch;
+
+        if (status != AVCDEC_SUCCESS)  /* check only once per line */
+            return status;
+    }
+
+#ifdef USE_PRED_BLOCK
+    pDst = video->pred_block + 452;
+    pitch = 12;
+#else
+    offset1 = (offset1 >> 2) + (mb_x << 2);
+    pDst = video->currPic->Scb + offset1;
+    pitch >>= 1;
+#endif
+
+    j = 8;
+    while (j > 0)
+    {
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)pDst) = byte0;
+
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)(pDst + 4)) = byte0;
+
+        j--;
+        pDst += pitch;
+
+        if (status != AVCDEC_SUCCESS)  /* check only once per line */
+            return status;
+    }
+
+#ifdef USE_PRED_BLOCK
+    pDst = video->pred_block + 596;
+    pitch = 12;
+#else
+    pDst = video->currPic->Scr + offset1;
+#endif
+    j = 8;
+    while (j > 0)
+    {
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)pDst) = byte0;
+
+        status = BitstreamReadBits(stream, 8, (uint*) & byte0);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 8);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 16);
+        status = BitstreamReadBits(stream, 8, (uint*) & byte1);
+        byte0 |= (byte1 << 24);
+        *((uint32*)(pDst + 4)) = byte0;
+
+        j--;
+        pDst += pitch;
+
+        if (status != AVCDEC_SUCCESS)  /* check only once per line */
+            return status;
+    }
+
+#ifdef MB_BASED_DEBLOCK
+    SaveNeighborForIntraPred(video, offset1);
+#endif
+
+    return AVCDEC_SUCCESS;
+}
+
+
+
+/* see subclause 7.3.5.3 and readCBPandCoeffsFromNAL() in JM*/
+AVCDec_Status residual(AVCDecObject *decvid, AVCMacroblock *currMB)
+{
+    AVCCommonObj *video = decvid->common;
+    int16 *block;
+    int level[16], run[16], numcoeff; /* output from residual_block_cavlc */
+    int block_x, i, j, k, idx, iCbCr;
+    int mbPartIdx, subMbPartIdx, mbPartIdx_X, mbPartIdx_Y;
+    int nC, maxNumCoeff = 16;
+    int coeffNum, start_scan = 0;
+    uint8 *zz_scan;
+    int Rq, Qq;
+    uint32 cbp4x4 = 0;
+
+    /* in 8.5.4, it only says if it's field macroblock. */
+
+    zz_scan = (uint8*) ZZ_SCAN_BLOCK;
+
+
+    /* see 8.5.8 for the initialization of these values */
+    Qq = video->QPy_div_6;
+    Rq = video->QPy_mod_6;
+
+    memset(video->block, 0, sizeof(int16)*NUM_PIXELS_IN_MB);
+
+    if (currMB->mbMode == AVC_I16)
+    {
+        nC = predict_nnz(video, 0, 0);
+        decvid->residual_block(decvid, nC, 16, level, run, &numcoeff);
+        /* then performs zigzag and transform */
+        block = video->block;
+        coeffNum = -1;
+        for (i = numcoeff - 1; i >= 0; i--)
+        {
+            coeffNum += run[i] + 1;
+            if (coeffNum > 15)
+            {
+                return AVCDEC_FAIL;
+            }
+            idx = zz_scan[coeffNum] << 2;
+            /*          idx = ((idx>>2)<<6) + ((idx&3)<<2); */
+            block[idx] = level[i];
+        }
+
+        /* inverse transform on Intra16x16DCLevel */
+        if (numcoeff)
+        {
+            Intra16DCTrans(block, Qq, Rq);
+            cbp4x4 = 0xFFFF;
+        }
+        maxNumCoeff = 15;
+        start_scan = 1;
+    }
+
+    memset(currMB->nz_coeff, 0, sizeof(uint8)*24);
+
+    for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
+    {
+        mbPartIdx_X = (mbPartIdx & 1) << 1;
+        mbPartIdx_Y = mbPartIdx & -2;
+
+        if (currMB->CBP&(1 << mbPartIdx))
+        {
+            for (subMbPartIdx = 0; subMbPartIdx < 4; subMbPartIdx++)
+            {
+                i = mbPartIdx_X + (subMbPartIdx & 1);  // check this
+                j = mbPartIdx_Y + (subMbPartIdx >> 1);
+                block = video->block + (j << 6) + (i << 2);  //
+                nC = predict_nnz(video, i, j);
+                decvid->residual_block(decvid, nC, maxNumCoeff, level, run, &numcoeff);
+
+                /* convert to raster scan and quantize*/
+                /* Note: for P mb in SP slice and SI mb in SI slice,
+                 the quantization cannot be done here.
+                 block[idx] should be assigned with level[k].
+                itrans will be done after the prediction.
+                There will be transformation on the predicted value,
+                then addition with block[idx], then this quantization
+                and transform.*/
+
+                coeffNum = -1 + start_scan;
+                for (k = numcoeff - 1; k >= 0; k--)
+                {
+                    coeffNum += run[k] + 1;
+                    if (coeffNum > 15)
+                    {
+                        return AVCDEC_FAIL;
+                    }
+                    idx = zz_scan[coeffNum];
+                    block[idx] = (level[k] * dequant_coefres[Rq][coeffNum]) << Qq ;
+                }
+
+                currMB->nz_coeff[(j<<2)+i] = numcoeff;
+                if (numcoeff)
+                {
+                    cbp4x4 |= (1 << ((j << 2) + i));
+                }
+            }
+        }
+    }
+
+    Qq = video->QPc_div_6;
+    Rq = video->QPc_mod_6;
+
+    if (currMB->CBP & (3 << 4)) /* chroma DC residual present */
+    {
+        for (iCbCr = 0; iCbCr < 2; iCbCr++)
+        {
+            decvid->residual_block(decvid, -1, 4, level, run, &numcoeff);
+            block = video->block + 256 + (iCbCr << 3);
+            coeffNum = -1;
+            for (i = numcoeff - 1; i >= 0; i--)
+            {
+                coeffNum += run[i] + 1;
+                if (coeffNum > 3)
+                {
+                    return AVCDEC_FAIL;
+                }
+                block[(coeffNum>>1)*64 + (coeffNum&1)*4] = level[i];
+            }
+            /* inverse transform on chroma DC */
+            /* for P in SP and SI in SI, this function can't be done here,
+            must do prediction transform/quant first. */
+            if (numcoeff)
+            {
+                ChromaDCTrans(block, Qq, Rq);
+                cbp4x4 |= (iCbCr ? 0xcc0000 : 0x330000);
+            }
+        }
+    }
+
+    if (currMB->CBP & (2 << 4))
+    {
+        for (block_x = 0; block_x < 4; block_x += 2) /* for iCbCr */
+        {
+            for (j = 4; j < 6; j++)  /* for each block inside Cb or Cr */
+            {
+                for (i = block_x; i < block_x + 2; i++)
+                {
+
+                    block = video->block + (j << 6) + (i << 2);
+
+                    nC = predict_nnz_chroma(video, i, j);
+                    decvid->residual_block(decvid, nC, 15, level, run, &numcoeff);
+
+                    /* convert to raster scan and quantize */
+                    /* for P MB in SP slice and SI MB in SI slice,
+                       the dequant and transform cannot be done here.
+                       It needs the prediction values. */
+                    coeffNum = 0;
+                    for (k = numcoeff - 1; k >= 0; k--)
+                    {
+                        coeffNum += run[k] + 1;
+                        if (coeffNum > 15)
+                        {
+                            return AVCDEC_FAIL;
+                        }
+                        idx = zz_scan[coeffNum];
+                        block[idx] = (level[k] * dequant_coefres[Rq][coeffNum]) << Qq;
+                    }
+
+
+                    /* then transform */
+                    //              itrans(block); /* transform */
+                    currMB->nz_coeff[(j<<2)+i] = numcoeff;    //
+                    if (numcoeff)
+                    {
+                        cbp4x4 |= (1 << ((j << 2) + i));
+                    }
+                }
+
+            }
+        }
+    }
+
+    video->cbp4x4 = cbp4x4;
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see subclause 7.3.5.3.1 and 9.2 and readCoeff4x4_CAVLC() in JM */
+AVCDec_Status residual_block_cavlc(AVCDecObject *decvid, int nC, int maxNumCoeff,
+                                   int *level, int *run, int *numcoeff)
+{
+    int i, j;
+    int TrailingOnes, TotalCoeff;
+    AVCDecBitstream *stream = decvid->bitstream;
+    int suffixLength;
+    uint trailing_ones_sign_flag, level_prefix, level_suffix;
+    int levelCode, levelSuffixSize, zerosLeft;
+    int run_before;
+
+
+    if (nC >= 0)
+    {
+        ce_TotalCoeffTrailingOnes(stream, &TrailingOnes, &TotalCoeff, nC);
+    }
+    else
+    {
+        ce_TotalCoeffTrailingOnesChromaDC(stream, &TrailingOnes, &TotalCoeff);
+    }
+
+    *numcoeff = TotalCoeff;
+
+    /* This part is done quite differently in ReadCoef4x4_CAVLC() */
+    if (TotalCoeff == 0)
+    {
+        return AVCDEC_SUCCESS;
+    }
+
+    if (TrailingOnes) /* keep reading the sign of those trailing ones */
+    {
+        /* instead of reading one bit at a time, read the whole thing at once */
+        BitstreamReadBits(stream, TrailingOnes, &trailing_ones_sign_flag);
+        trailing_ones_sign_flag <<= 1;
+        for (i = 0; i < TrailingOnes; i++)
+        {
+            level[i] = 1 - ((trailing_ones_sign_flag >> (TrailingOnes - i - 1)) & 2);
+        }
+    }
+
+    i = TrailingOnes;
+    suffixLength = 1;
+    if (TotalCoeff > TrailingOnes)
+    {
+        ce_LevelPrefix(stream, &level_prefix);
+        if (TotalCoeff < 11 || TrailingOnes == 3)
+        {
+            if (level_prefix < 14)
+            {
+//              levelSuffixSize = 0;
+                levelCode = level_prefix;
+            }
+            else if (level_prefix == 14)
+            {
+//              levelSuffixSize = 4;
+                BitstreamReadBits(stream, 4, &level_suffix);
+                levelCode = 14 + level_suffix;
+            }
+            else /* if (level_prefix == 15) */
+            {
+//              levelSuffixSize = 12;
+                BitstreamReadBits(stream, 12, &level_suffix);
+                levelCode = 30 + level_suffix;
+            }
+        }
+        else
+        {
+            /*              suffixLength = 1; */
+            if (level_prefix < 15)
+            {
+                levelSuffixSize = suffixLength;
+            }
+            else
+            {
+                levelSuffixSize = 12;
+            }
+            BitstreamReadBits(stream, levelSuffixSize, &level_suffix);
+
+            levelCode = (level_prefix << 1) + level_suffix;
+        }
+
+        if (TrailingOnes < 3)
+        {
+            levelCode += 2;
+        }
+
+        level[i] = (levelCode + 2) >> 1;
+        if (level[i] > 3)
+        {
+            suffixLength = 2;
+        }
+
+        if (levelCode & 1)
+        {
+            level[i] = -level[i];
+        }
+        i++;
+
+    }
+
+    for (j = TotalCoeff - i; j > 0 ; j--)
+    {
+        ce_LevelPrefix(stream, &level_prefix);
+        if (level_prefix < 15)
+        {
+            levelSuffixSize = suffixLength;
+        }
+        else
+        {
+            levelSuffixSize = 12;
+        }
+        BitstreamReadBits(stream, levelSuffixSize, &level_suffix);
+
+        levelCode = (level_prefix << suffixLength) + level_suffix;
+        level[i] = (levelCode >> 1) + 1;
+        if (level[i] > (3 << (suffixLength - 1)) && suffixLength < 6)
+        {
+            suffixLength++;
+        }
+        if (levelCode & 1)
+        {
+            level[i] = -level[i];
+        }
+        i++;
+    }
+
+
+    if (TotalCoeff < maxNumCoeff)
+    {
+        if (nC >= 0)
+        {
+            ce_TotalZeros(stream, &zerosLeft, TotalCoeff);
+        }
+        else
+        {
+            ce_TotalZerosChromaDC(stream, &zerosLeft, TotalCoeff);
+        }
+    }
+    else
+    {
+        zerosLeft = 0;
+    }
+
+    for (i = 0; i < TotalCoeff - 1; i++)
+    {
+        if (zerosLeft > 0)
+        {
+            ce_RunBefore(stream, &run_before, zerosLeft);
+            run[i] = run_before;
+        }
+        else
+        {
+            run[i] = 0;
+            zerosLeft = 0; // could be negative under error conditions
+        }
+
+        zerosLeft = zerosLeft - run[i];
+    }
+
+    if (zerosLeft < 0)
+    {
+        zerosLeft = 0;
+//      return AVCDEC_FAIL;
+    }
+
+    run[TotalCoeff-1] = zerosLeft;
+
+    /* leave the inverse zigzag scan part for the caller */
+
+
+    return AVCDEC_SUCCESS;
+}
diff --git a/media/libstagefright/codecs/avc/dec/src/slice.cpp b/media/libstagefright/codecs/avc/dec/src/slice.cpp
new file mode 100644
index 0000000..7a2ef3d
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/slice.cpp
@@ -0,0 +1,772 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/* Note for optimization: syntax decoding or operations related to B_SLICE should be
+commented out by macro definition or function pointers. */
+
+#include <string.h>
+
+#include "avcdec_lib.h"
+#include "avcdec_bitstream.h"
+
+const static int mbPart2raster[3][4] = {{0, 0, 0, 0}, {1, 1, 0, 0}, {1, 0, 1, 0}};
+/* decode_frame_slice() */
+/* decode_one_slice() */
+AVCDec_Status DecodeSlice(AVCDecObject *decvid)
+{
+    AVCDec_Status status;
+    AVCCommonObj *video = decvid->common;
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    AVCMacroblock *currMB ;
+    AVCDecBitstream *stream = decvid->bitstream;
+    uint slice_group_id;
+    uint CurrMbAddr, moreDataFlag;
+
+    /* set the first mb in slice */
+    CurrMbAddr = sliceHdr->first_mb_in_slice;
+    slice_group_id = video->MbToSliceGroupMap[CurrMbAddr];
+
+    if ((CurrMbAddr && (CurrMbAddr != (uint)(video->mbNum + 1))) && video->currSeqParams->constrained_set1_flag == 1)
+    {
+        ConcealSlice(decvid, video->mbNum, CurrMbAddr);
+    }
+
+    moreDataFlag = 1;
+    video->mb_skip_run = -1;
+
+
+    /* while loop , see subclause 7.3.4 */
+    do
+    {
+        if (CurrMbAddr >= video->PicSizeInMbs)
+        {
+            return AVCDEC_FAIL;
+        }
+
+        currMB = video->currMB = &(video->mblock[CurrMbAddr]);
+        video->mbNum = CurrMbAddr;
+        currMB->slice_id = video->slice_id;  //  slice
+
+        /* we can remove this check if we don't support Mbaff. */
+        /* we can wrap below into an initMB() function which will also
+        do necessary reset of macroblock related parameters. */
+
+        video->mb_x = CurrMbAddr % video->PicWidthInMbs;
+        video->mb_y = CurrMbAddr / video->PicWidthInMbs;
+
+        /* check the availability of neighboring macroblocks */
+        InitNeighborAvailability(video, CurrMbAddr);
+
+        /* read_macroblock and decode_one_macroblock() */
+        status = DecodeMB(decvid);
+        if (status != AVCDEC_SUCCESS)
+        {
+            return status;
+        }
+#ifdef MB_BASED_DEBLOCK
+        if (video->currPicParams->num_slice_groups_minus1 == 0)
+        {
+            MBInLoopDeblock(video); /* MB-based deblocking */
+        }
+        else    /* this mode cannot be used if the number of slice group is not one. */
+        {
+            return AVCDEC_FAIL;
+        }
+#endif
+        video->numMBs--;
+
+        moreDataFlag = more_rbsp_data(stream);
+
+
+        /* go to next MB */
+        while (++CurrMbAddr < video->PicSizeInMbs && video->MbToSliceGroupMap[CurrMbAddr] != (int)slice_group_id)
+        {
+        }
+
+    }
+    while ((moreDataFlag && video->numMBs > 0) || video->mb_skip_run > 0); /* even if no more data, but last few MBs are skipped */
+
+    if (video->numMBs == 0)
+    {
+        video->newPic = TRUE;
+        video->mbNum = 0;  // _Conceal
+        return AVCDEC_PICTURE_READY;
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/* read MB mode and motion vectors */
+/* perform Intra/Inter prediction and residue */
+/* update video->mb_skip_run */
+AVCDec_Status DecodeMB(AVCDecObject *decvid)
+{
+    AVCDec_Status status;
+    AVCCommonObj *video = decvid->common;
+    AVCDecBitstream *stream = decvid->bitstream;
+    AVCMacroblock *currMB = video->currMB;
+    uint mb_type;
+    int slice_type = video->slice_type;
+    int temp;
+
+    currMB->QPy = video->QPy;
+    currMB->QPc = video->QPc;
+
+    if (slice_type == AVC_P_SLICE)
+    {
+        if (video->mb_skip_run < 0)
+        {
+            ue_v(stream, (uint *)&(video->mb_skip_run));
+        }
+
+        if (video->mb_skip_run == 0)
+        {
+            /* this will not handle the case where the slice ends with a mb_skip_run == 0 and no following MB data  */
+            ue_v(stream, &mb_type);
+            if (mb_type > 30)
+            {
+                return AVCDEC_FAIL;
+            }
+            InterpretMBModeP(currMB, mb_type);
+            video->mb_skip_run = -1;
+        }
+        else
+        {
+            /* see subclause 7.4.4 for more details on how
+            mb_field_decoding_flag is derived in case of skipped MB */
+
+            currMB->mb_intra = FALSE;
+
+            currMB->mbMode = AVC_SKIP;
+            currMB->MbPartWidth = currMB->MbPartHeight = 16;
+            currMB->NumMbPart = 1;
+            currMB->NumSubMbPart[0] = currMB->NumSubMbPart[1] =
+                                          currMB->NumSubMbPart[2] = currMB->NumSubMbPart[3] = 1; //
+            currMB->SubMbPartWidth[0] = currMB->SubMbPartWidth[1] =
+                                            currMB->SubMbPartWidth[2] = currMB->SubMbPartWidth[3] = currMB->MbPartWidth;
+            currMB->SubMbPartHeight[0] = currMB->SubMbPartHeight[1] =
+                                             currMB->SubMbPartHeight[2] = currMB->SubMbPartHeight[3] = currMB->MbPartHeight;
+
+            memset(currMB->nz_coeff, 0, sizeof(uint8)*NUM_BLKS_IN_MB);
+
+            currMB->CBP = 0;
+            video->cbp4x4 = 0;
+            /* for skipped MB, always look at the first entry in RefPicList */
+            currMB->RefIdx[0] = currMB->RefIdx[1] =
+                                    currMB->RefIdx[2] = currMB->RefIdx[3] = video->RefPicList0[0]->RefIdx;
+            InterMBPrediction(video);
+            video->mb_skip_run--;
+            return AVCDEC_SUCCESS;
+        }
+
+    }
+    else
+    {
+        /* Then decode mode and MV */
+        ue_v(stream, &mb_type);
+        if (mb_type > 25)
+        {
+            return AVCDEC_FAIL;
+        }
+        InterpretMBModeI(currMB, mb_type);
+    }
+
+
+    if (currMB->mbMode != AVC_I_PCM)
+    {
+
+        if (currMB->mbMode == AVC_P8 || currMB->mbMode == AVC_P8ref0)
+        {
+            status = sub_mb_pred(video, currMB, stream);
+        }
+        else
+        {
+            status = mb_pred(video, currMB, stream) ;
+        }
+
+        if (status != AVCDEC_SUCCESS)
+        {
+            return status;
+        }
+
+        if (currMB->mbMode != AVC_I16)
+        {
+            /* decode coded_block_pattern */
+            status = DecodeCBP(currMB, stream);
+            if (status != AVCDEC_SUCCESS)
+            {
+                return status;
+            }
+        }
+
+        if (currMB->CBP > 0 || currMB->mbMode == AVC_I16)
+        {
+            se_v(stream, &temp);
+            if (temp)
+            {
+                temp += (video->QPy + 52);
+                currMB->QPy = video->QPy = temp - 52 * (temp * 79 >> 12);
+                if (currMB->QPy > 51 || currMB->QPy < 0)
+                {
+                    video->QPy = AVC_CLIP3(0, 51, video->QPy);
+//                  return AVCDEC_FAIL;
+                }
+                video->QPy_div_6 = (video->QPy * 43) >> 8;
+                video->QPy_mod_6 = video->QPy - 6 * video->QPy_div_6;
+                currMB->QPc = video->QPc = mapQPi2QPc[AVC_CLIP3(0, 51, video->QPy + video->currPicParams->chroma_qp_index_offset)];
+                video->QPc_div_6 = (video->QPc * 43) >> 8;
+                video->QPc_mod_6 = video->QPc - 6 * video->QPc_div_6;
+            }
+        }
+        /* decode residue and inverse transform */
+        status = residual(decvid, currMB);
+        if (status != AVCDEC_SUCCESS)
+        {
+            return status;
+        }
+    }
+    else
+    {
+        if (stream->bitcnt & 7)
+        {
+            BitstreamByteAlign(stream);
+        }
+        /* decode pcm_byte[i] */
+        DecodeIntraPCM(video, stream);
+
+        currMB->QPy = 0;  /* necessary for deblocking */ // _OPTIMIZE
+        currMB->QPc = mapQPi2QPc[AVC_CLIP3(0, 51, video->currPicParams->chroma_qp_index_offset)];
+
+        /* default values, don't know if really needed */
+        currMB->CBP = 0x3F;
+        video->cbp4x4 = 0xFFFF;
+        currMB->mb_intra = TRUE;
+        memset(currMB->nz_coeff, 16, sizeof(uint8)*NUM_BLKS_IN_MB);
+        return AVCDEC_SUCCESS;
+    }
+
+
+    /* do Intra/Inter prediction, together with the residue compensation */
+    /* This part should be common between the skip and no-skip */
+    if (currMB->mbMode == AVC_I4 || currMB->mbMode == AVC_I16)
+    {
+        IntraMBPrediction(video);
+    }
+    else
+    {
+        InterMBPrediction(video);
+    }
+
+
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see subclause 7.3.5.1 */
+AVCDec_Status mb_pred(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream)
+{
+    int mbPartIdx;
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    uint max_ref_idx;
+    const int *temp_0;
+    int16 *temp_1;
+    uint code;
+
+    if (currMB->mbMode == AVC_I4 || currMB->mbMode == AVC_I16)
+    {
+
+        video->intraAvailA = video->intraAvailB = video->intraAvailC = video->intraAvailD = 0;
+
+        if (!video->currPicParams->constrained_intra_pred_flag)
+        {
+            video->intraAvailA = video->mbAvailA;
+            video->intraAvailB = video->mbAvailB;
+            video->intraAvailC = video->mbAvailC;
+            video->intraAvailD = video->mbAvailD;
+        }
+        else
+        {
+            if (video->mbAvailA)
+            {
+                video->intraAvailA = video->mblock[video->mbAddrA].mb_intra;
+            }
+            if (video->mbAvailB)
+            {
+                video->intraAvailB = video->mblock[video->mbAddrB].mb_intra ;
+            }
+            if (video->mbAvailC)
+            {
+                video->intraAvailC = video->mblock[video->mbAddrC].mb_intra;
+            }
+            if (video->mbAvailD)
+            {
+                video->intraAvailD = video->mblock[video->mbAddrD].mb_intra;
+            }
+        }
+
+
+        if (currMB->mbMode == AVC_I4)
+        {
+            /* perform prediction to get the actual intra 4x4 pred mode */
+            DecodeIntra4x4Mode(video, currMB, stream);
+            /* output will be in currMB->i4Mode[4][4] */
+        }
+
+        ue_v(stream, &code);
+
+        if (code > 3)
+        {
+            return AVCDEC_FAIL; /* out of range */
+        }
+        currMB->intra_chroma_pred_mode = (AVCIntraChromaPredMode)code;
+    }
+    else
+    {
+
+        memset(currMB->ref_idx_L0, 0, sizeof(int16)*4);
+
+        /* see subclause 7.4.5.1 for the range of ref_idx_lX */
+//      max_ref_idx = sliceHdr->num_ref_idx_l0_active_minus1;
+        max_ref_idx = video->refList0Size - 1;
+
+        /* decode ref index for L0 */
+        if (sliceHdr->num_ref_idx_l0_active_minus1 > 0)
+        {
+            for (mbPartIdx = 0; mbPartIdx < currMB->NumMbPart; mbPartIdx++)
+            {
+                te_v(stream, &code, max_ref_idx);
+                if (code > (uint)max_ref_idx)
+                {
+                    return AVCDEC_FAIL;
+                }
+                currMB->ref_idx_L0[mbPartIdx] = code;
+            }
+        }
+
+        /* populate ref_idx_L0 */
+        temp_0 = &mbPart2raster[currMB->mbMode-AVC_P16][0];
+        temp_1 = &currMB->ref_idx_L0[3];
+
+        *temp_1-- = currMB->ref_idx_L0[*temp_0++];
+        *temp_1-- = currMB->ref_idx_L0[*temp_0++];
+        *temp_1-- = currMB->ref_idx_L0[*temp_0++];
+        *temp_1-- = currMB->ref_idx_L0[*temp_0++];
+
+        /* Global reference index, these values are used in deblock */
+        currMB->RefIdx[0] = video->RefPicList0[currMB->ref_idx_L0[0]]->RefIdx;
+        currMB->RefIdx[1] = video->RefPicList0[currMB->ref_idx_L0[1]]->RefIdx;
+        currMB->RefIdx[2] = video->RefPicList0[currMB->ref_idx_L0[2]]->RefIdx;
+        currMB->RefIdx[3] = video->RefPicList0[currMB->ref_idx_L0[3]]->RefIdx;
+
+        /* see subclause 7.4.5.1 for the range of ref_idx_lX */
+        max_ref_idx = sliceHdr->num_ref_idx_l1_active_minus1;
+        /* decode mvd_l0 */
+        for (mbPartIdx = 0; mbPartIdx < currMB->NumMbPart; mbPartIdx++)
+        {
+            se_v(stream, &(video->mvd_l0[mbPartIdx][0][0]));
+            se_v(stream, &(video->mvd_l0[mbPartIdx][0][1]));
+        }
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see subclause 7.3.5.2 */
+AVCDec_Status sub_mb_pred(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream)
+{
+    int mbPartIdx, subMbPartIdx;
+    AVCSliceHeader *sliceHdr = video->sliceHdr;
+    uint max_ref_idx;
+    uint sub_mb_type[4];
+    uint code;
+
+    memset(currMB->ref_idx_L0, 0, sizeof(int16)*4);
+
+    for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
+    {
+        ue_v(stream, &(sub_mb_type[mbPartIdx]));
+        if (sub_mb_type[mbPartIdx] > 3)
+        {
+            return AVCDEC_FAIL;
+        }
+
+    }
+    /* we have to check the values to make sure they are valid  */
+    /* assign values to currMB->sub_mb_type[], currMB->MBPartPredMode[][x] */
+
+    InterpretSubMBModeP(currMB, sub_mb_type);
+
+
+    /* see subclause 7.4.5.1 for the range of ref_idx_lX */
+//      max_ref_idx = sliceHdr->num_ref_idx_l0_active_minus1;
+    max_ref_idx = video->refList0Size - 1;
+
+    if (sliceHdr->num_ref_idx_l0_active_minus1 > 0 && currMB->mbMode != AVC_P8ref0)
+    {
+        for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
+        {
+            te_v(stream, (uint*)&code, max_ref_idx);
+            if (code > max_ref_idx)
+            {
+                return AVCDEC_FAIL;
+            }
+            currMB->ref_idx_L0[mbPartIdx] = code;
+        }
+    }
+    /* see subclause 7.4.5.1 for the range of ref_idx_lX */
+
+    max_ref_idx = sliceHdr->num_ref_idx_l1_active_minus1;
+    /*  if(video->MbaffFrameFlag && currMB->mb_field_decoding_flag)
+            max_ref_idx = 2*sliceHdr->num_ref_idx_l1_active_minus1 + 1;*/
+    for (mbPartIdx = 0; mbPartIdx < 4; mbPartIdx++)
+    {
+        for (subMbPartIdx = 0; subMbPartIdx < currMB->NumSubMbPart[mbPartIdx]; subMbPartIdx++)
+        {
+            se_v(stream, &(video->mvd_l0[mbPartIdx][subMbPartIdx][0]));
+            se_v(stream, &(video->mvd_l0[mbPartIdx][subMbPartIdx][1]));
+        }
+        /* used in deblocking */
+        currMB->RefIdx[mbPartIdx] = video->RefPicList0[currMB->ref_idx_L0[mbPartIdx]]->RefIdx;
+    }
+    return AVCDEC_SUCCESS;
+}
+
+void InterpretMBModeI(AVCMacroblock *mblock, uint mb_type)
+{
+    mblock->NumMbPart = 1;
+
+    mblock->mb_intra = TRUE;
+
+    if (mb_type == 0) /* I_4x4 */
+    {
+        mblock->mbMode = AVC_I4;
+    }
+    else if (mb_type < 25) /* I_PCM */
+    {
+        mblock->mbMode = AVC_I16;
+        mblock->i16Mode = (AVCIntra16x16PredMode)((mb_type - 1) & 0x3);
+        if (mb_type > 12)
+        {
+            mblock->CBP = (((mb_type - 13) >> 2) << 4) + 0x0F;
+        }
+        else
+        {
+            mblock->CBP = ((mb_type - 1) >> 2) << 4;
+        }
+    }
+    else
+    {
+        mblock->mbMode = AVC_I_PCM;
+    }
+
+    return ;
+}
+
+void InterpretMBModeP(AVCMacroblock *mblock, uint mb_type)
+{
+    const static int map2PartWidth[5] = {16, 16, 8, 8, 8};
+    const static int map2PartHeight[5] = {16, 8, 16, 8, 8};
+    const static int map2NumPart[5] = {1, 2, 2, 4, 4};
+    const static AVCMBMode map2mbMode[5] = {AVC_P16, AVC_P16x8, AVC_P8x16, AVC_P8, AVC_P8ref0};
+
+    mblock->mb_intra = FALSE;
+    if (mb_type < 5)
+    {
+        mblock->mbMode = map2mbMode[mb_type];
+        mblock->MbPartWidth = map2PartWidth[mb_type];
+        mblock->MbPartHeight = map2PartHeight[mb_type];
+        mblock->NumMbPart = map2NumPart[mb_type];
+        mblock->NumSubMbPart[0] = mblock->NumSubMbPart[1] =
+                                      mblock->NumSubMbPart[2] = mblock->NumSubMbPart[3] = 1;
+        mblock->SubMbPartWidth[0] = mblock->SubMbPartWidth[1] =
+                                        mblock->SubMbPartWidth[2] = mblock->SubMbPartWidth[3] = mblock->MbPartWidth;
+        mblock->SubMbPartHeight[0] = mblock->SubMbPartHeight[1] =
+                                         mblock->SubMbPartHeight[2] = mblock->SubMbPartHeight[3] = mblock->MbPartHeight;
+    }
+    else
+    {
+        InterpretMBModeI(mblock, mb_type - 5);
+        /* set MV and Ref_Idx codes of Intra blocks in P-slices  */
+        memset(mblock->mvL0, 0, sizeof(int32)*16);
+        mblock->ref_idx_L0[0] = mblock->ref_idx_L0[1] = mblock->ref_idx_L0[2] = mblock->ref_idx_L0[3] = -1;
+    }
+    return ;
+}
+
+void InterpretMBModeB(AVCMacroblock *mblock, uint mb_type)
+{
+    const static int map2PartWidth[23] = {8, 16, 16, 16, 16, 8, 16, 8, 16, 8,
+                                          16, 8, 16, 8, 16, 8, 16, 8, 16, 8, 16, 8, 8
+                                         };
+    const static int map2PartHeight[23] = {8, 16, 16, 16, 8, 16, 8, 16, 8,
+                                           16, 8, 16, 8, 16, 8, 16, 8, 16, 8, 16, 8, 16, 8
+                                          };
+    /* see enum AVCMBType declaration */
+    const static AVCMBMode map2mbMode[23] = {AVC_BDirect16, AVC_P16, AVC_P16, AVC_P16,
+                                            AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16,
+                                            AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16,
+                                            AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16, AVC_P16x8, AVC_P8x16, AVC_P8
+                                            };
+    const static int map2PredMode1[23] = {3, 0, 1, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 2, 2, 2, 2, -1};
+    const static int map2PredMode2[23] = { -1, -1, -1, -1, 0, 0, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 0, 0, 1, 1, 2, 2, -1};
+    const static int map2NumPart[23] = { -1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4};
+
+    mblock->mb_intra = FALSE;
+
+    if (mb_type < 23)
+    {
+        mblock->mbMode = map2mbMode[mb_type];
+        mblock->NumMbPart = map2NumPart[mb_type];
+        mblock->MBPartPredMode[0][0] = (AVCPredMode)map2PredMode1[mb_type];
+        if (mblock->NumMbPart > 1)
+        {
+            mblock->MBPartPredMode[1][0] = (AVCPredMode)map2PredMode2[mb_type];
+        }
+        mblock->MbPartWidth = map2PartWidth[mb_type];
+        mblock->MbPartHeight = map2PartHeight[mb_type];
+    }
+    else
+    {
+        InterpretMBModeI(mblock, mb_type - 23);
+    }
+
+    return ;
+}
+
+void InterpretMBModeSI(AVCMacroblock *mblock, uint mb_type)
+{
+    mblock->mb_intra = TRUE;
+
+    if (mb_type == 0)
+    {
+        mblock->mbMode = AVC_SI4;
+        /* other values are N/A */
+    }
+    else
+    {
+        InterpretMBModeI(mblock, mb_type - 1);
+    }
+    return ;
+}
+
+/* input is mblock->sub_mb_type[] */
+void InterpretSubMBModeP(AVCMacroblock *mblock, uint *sub_mb_type)
+{
+    int i,  sub_type;
+    /* see enum AVCMBType declaration */
+//  const static AVCSubMBMode map2subMbMode[4] = {AVC_8x8,AVC_8x4,AVC_4x8,AVC_4x4};
+    const static int map2subPartWidth[4] = {8, 8, 4, 4};
+    const static int map2subPartHeight[4] = {8, 4, 8, 4};
+    const static int map2numSubPart[4] = {1, 2, 2, 4};
+
+    for (i = 0; i < 4 ; i++)
+    {
+        sub_type = (int) sub_mb_type[i];
+        //  mblock->subMbMode[i] = map2subMbMode[sub_type];
+        mblock->NumSubMbPart[i] = map2numSubPart[sub_type];
+        mblock->SubMbPartWidth[i] = map2subPartWidth[sub_type];
+        mblock->SubMbPartHeight[i] = map2subPartHeight[sub_type];
+    }
+
+    return ;
+}
+
+void InterpretSubMBModeB(AVCMacroblock *mblock, uint *sub_mb_type)
+{
+    int i, j, sub_type;
+    /* see enum AVCMBType declaration */
+    const static AVCSubMBMode map2subMbMode[13] = {AVC_BDirect8, AVC_8x8, AVC_8x8,
+            AVC_8x8, AVC_8x4, AVC_4x8, AVC_8x4, AVC_4x8, AVC_8x4, AVC_4x8, AVC_4x4, AVC_4x4, AVC_4x4
+                                                  };
+    const static int map2subPartWidth[13] = {4, 8, 8, 8, 8, 4, 8, 4, 8, 4, 4, 4, 4};
+    const static int map2subPartHeight[13] = {4, 8, 8, 8, 4, 8, 4, 8, 4, 8, 4, 4, 4};
+    const static int map2numSubPart[13] = {1, 1, 1, 2, 2, 2, 2, 2, 2, 4, 4, 4};
+    const static int map2predMode[13] = {3, 0, 1, 2, 0, 0, 1, 1, 2, 2, 0, 1, 2};
+
+    for (i = 0; i < 4 ; i++)
+    {
+        sub_type = (int) sub_mb_type[i];
+        mblock->subMbMode[i] = map2subMbMode[sub_type];
+        mblock->NumSubMbPart[i] = map2numSubPart[sub_type];
+        mblock->SubMbPartWidth[i] = map2subPartWidth[sub_type];
+        mblock->SubMbPartHeight[i] = map2subPartHeight[sub_type];
+        for (j = 0; j < 4; j++)
+        {
+            mblock->MBPartPredMode[i][j] = (AVCPredMode)map2predMode[sub_type];
+        }
+    }
+
+    return ;
+}
+
+/* see subclause 8.3.1 */
+AVCDec_Status DecodeIntra4x4Mode(AVCCommonObj *video, AVCMacroblock *currMB, AVCDecBitstream *stream)
+{
+    int intra4x4PredModeA = 0, intra4x4PredModeB = 0, predIntra4x4PredMode = 0;
+    int component, SubBlock_indx, block_x, block_y;
+    int dcOnlyPredictionFlag;
+    uint    prev_intra4x4_pred_mode_flag[16];
+    int     rem_intra4x4_pred_mode[16];
+    int bindx = 0;
+
+    for (component = 0; component < 4; component++) /* partition index */
+    {
+        block_x = ((component & 1) << 1);
+        block_y = ((component >> 1) << 1);
+
+        for (SubBlock_indx = 0; SubBlock_indx < 4; SubBlock_indx++) /* sub-partition index */
+        {
+            BitstreamRead1Bit(stream, &(prev_intra4x4_pred_mode_flag[bindx]));
+
+            if (!prev_intra4x4_pred_mode_flag[bindx])
+            {
+                BitstreamReadBits(stream, 3, (uint*)&(rem_intra4x4_pred_mode[bindx]));
+            }
+
+            dcOnlyPredictionFlag = 0;
+            if (block_x > 0)
+            {
+                intra4x4PredModeA = currMB->i4Mode[(block_y << 2) + block_x - 1 ];
+            }
+            else
+            {
+                if (video->intraAvailA)
+                {
+                    if (video->mblock[video->mbAddrA].mbMode == AVC_I4)
+                    {
+                        intra4x4PredModeA = video->mblock[video->mbAddrA].i4Mode[(block_y << 2) + 3];
+                    }
+                    else
+                    {
+                        intra4x4PredModeA = AVC_I4_DC;
+                    }
+                }
+                else
+                {
+                    dcOnlyPredictionFlag = 1;
+                }
+            }
+
+            if (block_y > 0)
+            {
+                intra4x4PredModeB = currMB->i4Mode[((block_y-1) << 2) + block_x];
+            }
+            else
+            {
+                if (video->intraAvailB)
+                {
+                    if (video->mblock[video->mbAddrB].mbMode == AVC_I4)
+                    {
+                        intra4x4PredModeB = video->mblock[video->mbAddrB].i4Mode[(3 << 2) + block_x];
+                    }
+                    else
+                    {
+                        intra4x4PredModeB = AVC_I4_DC;
+                    }
+                }
+                else
+                {
+                    dcOnlyPredictionFlag = 1;
+                }
+            }
+
+            if (dcOnlyPredictionFlag)
+            {
+                intra4x4PredModeA = intra4x4PredModeB = AVC_I4_DC;
+            }
+
+            predIntra4x4PredMode = AVC_MIN(intra4x4PredModeA, intra4x4PredModeB);
+            if (prev_intra4x4_pred_mode_flag[bindx])
+            {
+                currMB->i4Mode[(block_y<<2)+block_x] = (AVCIntra4x4PredMode)predIntra4x4PredMode;
+            }
+            else
+            {
+                if (rem_intra4x4_pred_mode[bindx] < predIntra4x4PredMode)
+                {
+                    currMB->i4Mode[(block_y<<2)+block_x] = (AVCIntra4x4PredMode)rem_intra4x4_pred_mode[bindx];
+                }
+                else
+                {
+                    currMB->i4Mode[(block_y<<2)+block_x] = (AVCIntra4x4PredMode)(rem_intra4x4_pred_mode[bindx] + 1);
+                }
+            }
+            bindx++;
+            block_y += (SubBlock_indx & 1) ;
+            block_x += (1 - 2 * (SubBlock_indx & 1)) ;
+        }
+    }
+    return AVCDEC_SUCCESS;
+}
+AVCDec_Status ConcealSlice(AVCDecObject *decvid, int mbnum_start, int mbnum_end)
+{
+    AVCCommonObj *video = decvid->common;
+    AVCMacroblock *currMB ;
+
+    int CurrMbAddr;
+
+    if (video->RefPicList0[0] == NULL)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    for (CurrMbAddr = mbnum_start; CurrMbAddr < mbnum_end; CurrMbAddr++)
+    {
+        currMB = video->currMB = &(video->mblock[CurrMbAddr]);
+        video->mbNum = CurrMbAddr;
+        currMB->slice_id = video->slice_id++;  //  slice
+
+        /* we can remove this check if we don't support Mbaff. */
+        /* we can wrap below into an initMB() function which will also
+        do necessary reset of macroblock related parameters. */
+
+        video->mb_x = CurrMbAddr % video->PicWidthInMbs;
+        video->mb_y = CurrMbAddr / video->PicWidthInMbs;
+
+        /* check the availability of neighboring macroblocks */
+        InitNeighborAvailability(video, CurrMbAddr);
+
+        currMB->mb_intra = FALSE;
+
+        currMB->mbMode = AVC_SKIP;
+        currMB->MbPartWidth = currMB->MbPartHeight = 16;
+
+        currMB->NumMbPart = 1;
+        currMB->NumSubMbPart[0] = currMB->NumSubMbPart[1] =
+                                      currMB->NumSubMbPart[2] = currMB->NumSubMbPart[3] = 1;
+        currMB->SubMbPartWidth[0] = currMB->SubMbPartWidth[1] =
+                                        currMB->SubMbPartWidth[2] = currMB->SubMbPartWidth[3] = currMB->MbPartWidth;
+        currMB->SubMbPartHeight[0] = currMB->SubMbPartHeight[1] =
+                                         currMB->SubMbPartHeight[2] = currMB->SubMbPartHeight[3] = currMB->MbPartHeight;
+        currMB->QPy = 26;
+        currMB->QPc = 26;
+        memset(currMB->nz_coeff, 0, sizeof(uint8)*NUM_BLKS_IN_MB);
+
+        currMB->CBP = 0;
+        video->cbp4x4 = 0;
+        /* for skipped MB, always look at the first entry in RefPicList */
+        currMB->RefIdx[0] = currMB->RefIdx[1] =
+                                currMB->RefIdx[2] = currMB->RefIdx[3] = video->RefPicList0[0]->RefIdx;
+        InterMBPrediction(video);
+
+        video->numMBs--;
+
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
diff --git a/media/libstagefright/codecs/avc/dec/src/vlc.cpp b/media/libstagefright/codecs/avc/dec/src/vlc.cpp
new file mode 100644
index 0000000..f531249
--- /dev/null
+++ b/media/libstagefright/codecs/avc/dec/src/vlc.cpp
@@ -0,0 +1,815 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "avcdec_lib.h"
+#include "avcdec_bitstream.h"
+
+//#define PV_ARM_V5
+#ifdef PV_ARM_V5
+#define PV_CLZ(A,B) __asm{CLZ (A),(B)}  \
+    A -= 16;
+#else
+#define PV_CLZ(A,B) while (((B) & 0x8000) == 0) {(B) <<=1; A++;}
+#endif
+
+
+#define PV_NO_CLZ
+
+#ifndef PV_NO_CLZ
+typedef struct tagVLCNumCoeffTrail
+{
+    int trailing;
+    int total_coeff;
+    int length;
+} VLCNumCoeffTrail;
+
+typedef struct tagShiftOffset
+{
+    int shift;
+    int offset;
+} ShiftOffset;
+
+const VLCNumCoeffTrail NumCoeffTrailOnes[3][67] =
+{
+    {{0, 0, 1}, {1, 1, 2}, {2, 2, 3}, {1, 2, 6}, {0, 1, 6}, {3, 3, 5}, {3, 3, 5}, {3, 5, 7},
+        {2, 3, 7}, {3, 4, 6}, {3, 4, 6}, {3, 6, 8}, {2, 4, 8}, {1, 3, 8}, {0, 2, 8}, {3, 7, 9},
+        {2, 5, 9}, {1, 4, 9}, {0, 3, 9}, {3, 8, 10}, {2, 6, 10}, {1, 5, 10}, {0, 4, 10}, {3, 9, 11},
+        {2, 7, 11}, {1, 6, 11}, {0, 5, 11}, {0, 8, 13}, {2, 9, 13}, {1, 8, 13}, {0, 7, 13}, {3, 10, 13},
+        {2, 8, 13}, {1, 7, 13}, {0, 6, 13}, {3, 12, 14}, {2, 11, 14}, {1, 10, 14}, {0, 10, 14}, {3, 11, 14},
+        {2, 10, 14}, {1, 9, 14}, {0, 9, 14}, {3, 14, 15}, {2, 13, 15}, {1, 12, 15}, {0, 12, 15}, {3, 13, 15},
+        {2, 12, 15}, {1, 11, 15}, {0, 11, 15}, {3, 16, 16}, {2, 15, 16}, {1, 15, 16}, {0, 14, 16}, {3, 15, 16},
+        {2, 14, 16}, {1, 14, 16}, {0, 13, 16}, {0, 16, 16}, {2, 16, 16}, {1, 16, 16}, {0, 15, 16}, {1, 13, 15},
+        { -1, -1, -1}, { -1, -1, -1}, { -1, -1, -1}},
+
+    {{1, 1, 2}, {0, 0, 2}, {3, 4, 4}, {3, 3, 4}, {2, 2, 3}, {2, 2, 3}, {3, 6, 6}, {2, 3, 6},
+        {1, 3, 6}, {0, 1, 6}, {3, 5, 5}, {3, 5, 5}, {1, 2, 5}, {1, 2, 5}, {3, 7, 6}, {2, 4, 6},
+        {1, 4, 6}, {0, 2, 6}, {3, 8, 7}, {2, 5, 7}, {1, 5, 7}, {0, 3, 7}, {0, 5, 8}, {2, 6, 8},
+        {1, 6, 8}, {0, 4, 8}, {3, 9, 9}, {2, 7, 9}, {1, 7, 9}, {0, 6, 9}, {3, 11, 11}, {2, 9, 11},
+        {1, 9, 11}, {0, 8, 11}, {3, 10, 11}, {2, 8, 11}, {1, 8, 11}, {0, 7, 11}, {0, 11, 12}, {2, 11, 12},
+        {1, 11, 12}, {0, 10, 12}, {3, 12, 12}, {2, 10, 12}, {1, 10, 12}, {0, 9, 12}, {3, 14, 13}, {2, 13, 13},
+        {1, 13, 13}, {0, 13, 13}, {3, 13, 13}, {2, 12, 13}, {1, 12, 13}, {0, 12, 13}, {1, 15, 14}, {0, 15, 14},
+        {2, 15, 14}, {1, 14, 14}, {2, 14, 13}, {2, 14, 13}, {0, 14, 13}, {0, 14, 13}, {3, 16, 14}, {2, 16, 14},
+        {1, 16, 14}, {0, 16, 14}, {3, 15, 13}},
+
+    {{3, 7, 4}, {3, 6, 4}, {3, 5, 4}, {3, 4, 4}, {3, 3, 4}, {2, 2, 4}, {1, 1, 4}, {0, 0, 4},
+        {1, 5, 5}, {2, 5, 5}, {1, 4, 5}, {2, 4, 5}, {1, 3, 5}, {3, 8, 5}, {2, 3, 5}, {1, 2, 5},
+        {0, 3, 6}, {2, 7, 6}, {1, 7, 6}, {0, 2, 6}, {3, 9, 6}, {2, 6, 6}, {1, 6, 6}, {0, 1, 6},
+        {0, 7, 7}, {0, 6, 7}, {2, 9, 7}, {0, 5, 7}, {3, 10, 7}, {2, 8, 7}, {1, 8, 7}, {0, 4, 7},
+        {3, 12, 8}, {2, 11, 8}, {1, 10, 8}, {0, 9, 8}, {3, 11, 8}, {2, 10, 8}, {1, 9, 8}, {0, 8, 8},
+        {0, 12, 9}, {2, 13, 9}, {1, 12, 9}, {0, 11, 9}, {3, 13, 9}, {2, 12, 9}, {1, 11, 9}, {0, 10, 9},
+        {1, 15, 10}, {0, 14, 10}, {3, 14, 10}, {2, 14, 10}, {1, 14, 10}, {0, 13, 10}, {1, 13, 9}, {1, 13, 9},
+        {1, 16, 10}, {0, 15, 10}, {3, 15, 10}, {2, 15, 10}, {3, 16, 10}, {2, 16, 10}, {0, 16, 10}, { -1, -1, -1},
+        { -1, -1, -1}, { -1, -1, -1}, { -1, -1, -1}}
+};
+
+
+const ShiftOffset NumCoeffTrailOnes_indx[3][15] =
+{
+    {{15, -1}, {14, 0}, {13, 1}, {10, -1}, {9, 3}, {8, 7}, {7, 11}, {6, 15},
+        {5, 19}, {3, 19}, {2, 27}, {1, 35}, {0, 43}, {0, 55}, {1, 62}},
+
+    {{14, -2}, {12, -2}, {10, -2}, {10, 10}, {9, 14}, {8, 18}, {7, 22}, {5, 22},
+        {4, 30}, {3, 38}, {2, 46}, {2, 58}, {3, 65}, {16, 0}, {16, 0}},
+
+    {{12, -8}, {11, 0}, {10, 8}, {9, 16}, {8, 24}, {7, 32}, {6, 40}, {6, 52},
+        {6, 58}, {6, 61}, {16, 0}, {16, 0}, {16, 0}, {16, 0}, {16, 0}}
+};
+
+const static int nC_table[8] = {0, 0, 1, 1, 2, 2, 2, 2};
+
+#endif
+/**
+See algorithm in subclause 9.1, Table 9-1, Table 9-2. */
+AVCDec_Status ue_v(AVCDecBitstream *bitstream, uint *codeNum)
+{
+    uint temp, tmp_cnt;
+    int leading_zeros = 0;
+    BitstreamShowBits(bitstream, 16, &temp);
+    tmp_cnt = temp  | 0x1;
+
+    PV_CLZ(leading_zeros, tmp_cnt)
+
+    if (leading_zeros < 8)
+    {
+        *codeNum = (temp >> (15 - (leading_zeros << 1))) - 1;
+        BitstreamFlushBits(bitstream, (leading_zeros << 1) + 1);
+    }
+    else
+    {
+        BitstreamReadBits(bitstream, (leading_zeros << 1) + 1, &temp);
+        *codeNum = temp - 1;
+    }
+
+    return AVCDEC_SUCCESS;
+}
+
+/**
+See subclause 9.1.1, Table 9-3 */
+AVCDec_Status  se_v(AVCDecBitstream *bitstream, int *value)
+{
+    uint temp, tmp_cnt;
+    int leading_zeros = 0;
+    BitstreamShowBits(bitstream, 16, &temp);
+    tmp_cnt = temp | 0x1;
+
+    PV_CLZ(leading_zeros, tmp_cnt)
+
+    if (leading_zeros < 8)
+    {
+        temp >>= (15 - (leading_zeros << 1));
+        BitstreamFlushBits(bitstream, (leading_zeros << 1) + 1);
+    }
+    else
+    {
+        BitstreamReadBits(bitstream, (leading_zeros << 1) + 1, &temp);
+    }
+
+    *value = temp >> 1;
+
+    if (temp & 0x01)                          // lsb is signed bit
+        *value = -(*value);
+
+//  leading_zeros = temp >> 1;
+//  *value = leading_zeros - (leading_zeros*2*(temp&1));
+
+    return AVCDEC_SUCCESS;
+}
+
+AVCDec_Status  se_v32bit(AVCDecBitstream *bitstream, int32 *value)
+{
+    int leadingZeros;
+    uint32 infobits;
+    uint32 codeNum;
+
+    if (AVCDEC_SUCCESS != GetEGBitstring32bit(bitstream, &leadingZeros, &infobits))
+        return AVCDEC_FAIL;
+
+    codeNum = (1 << leadingZeros) - 1 + infobits;
+
+    *value = (codeNum + 1) / 2;
+
+    if ((codeNum & 0x01) == 0)                        // lsb is signed bit
+        *value = -(*value);
+
+    return AVCDEC_SUCCESS;
+}
+
+
+AVCDec_Status te_v(AVCDecBitstream *bitstream, uint *value, uint range)
+{
+    if (range > 1)
+    {
+        ue_v(bitstream, value);
+    }
+    else
+    {
+        BitstreamRead1Bit(bitstream, value);
+        *value = 1 - (*value);
+    }
+    return AVCDEC_SUCCESS;
+}
+
+
+
+/* This function is only used for syntax with range from -2^31 to 2^31-1 */
+/* only a few of them in the SPS and PPS */
+AVCDec_Status GetEGBitstring32bit(AVCDecBitstream *bitstream, int *leadingZeros, uint32 *infobits)
+{
+    int bit_value;
+    uint info_temp;
+
+    *leadingZeros = 0;
+
+    BitstreamRead1Bit(bitstream, (uint*)&bit_value);
+
+    while (!bit_value)
+    {
+        (*leadingZeros)++;
+        BitstreamRead1Bit(bitstream, (uint*)&bit_value);
+    }
+
+    if (*leadingZeros > 0)
+    {
+        if (sizeof(uint) == 4)  /* 32 bit machine */
+        {
+            BitstreamReadBits(bitstream, *leadingZeros, (uint*)&info_temp);
+            *infobits = (uint32)info_temp;
+        }
+        else if (sizeof(uint) == 2) /* 16 bit machine */
+        {
+            *infobits = 0;
+            if (*leadingZeros > 16)
+            {
+                BitstreamReadBits(bitstream, 16, (uint*)&info_temp);
+                (*leadingZeros) -= 16;
+                *infobits = ((uint32)info_temp) << (*leadingZeros);
+            }
+
+            BitstreamReadBits(bitstream, *leadingZeros, (uint*)&info_temp);
+            *infobits |= (uint32)info_temp ;
+        }
+    }
+    else
+        *infobits = 0;
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see Table 9-4 assignment of codeNum to values of coded_block_pattern. */
+const static uint8 MapCBP[48][2] =
+{
+    {47, 0}, {31, 16}, {15, 1}, { 0, 2}, {23, 4}, {27, 8}, {29, 32}, {30, 3}, { 7, 5}, {11, 10}, {13, 12}, {14, 15},
+    {39, 47}, {43, 7}, {45, 11}, {46, 13}, {16, 14}, { 3, 6}, { 5, 9}, {10, 31}, {12, 35}, {19, 37}, {21, 42}, {26, 44},
+    {28, 33}, {35, 34}, {37, 36}, {42, 40}, {44, 39}, { 1, 43}, { 2, 45}, { 4, 46}, { 8, 17}, {17, 18}, {18, 20}, {20, 24},
+    {24, 19}, { 6, 21}, { 9, 26}, {22, 28}, {25, 23}, {32, 27}, {33, 29}, {34, 30}, {36, 22}, {40, 25}, {38, 38}, {41, 41},
+};
+
+AVCDec_Status DecodeCBP(AVCMacroblock *currMB, AVCDecBitstream *stream)
+{
+    uint codeNum;
+    uint coded_block_pattern;
+
+    ue_v(stream, &codeNum);
+
+    if (codeNum > 47)
+    {
+        return AVCDEC_FAIL;
+    }
+
+    /* can get rid of the if _OPTIMIZE */
+    if (currMB->mbMode == AVC_I4)
+    {
+        coded_block_pattern = MapCBP[codeNum][0];
+    }
+    else
+    {
+        coded_block_pattern = MapCBP[codeNum][1];
+    }
+
+//  currMB->cbpL = coded_block_pattern&0xF;  /* modulo 16 */
+//  currMB->cbpC = coded_block_pattern>>4;   /* divide 16 */
+    currMB->CBP = coded_block_pattern;
+
+    return AVCDEC_SUCCESS;
+}
+
+
+/* TO BE OPTIMIZED !!!!! */
+AVCDec_Status ce_TotalCoeffTrailingOnes(AVCDecBitstream *stream, int *TrailingOnes, int *TotalCoeff, int nC)
+{
+#ifdef PV_NO_CLZ
+    const static uint8 TotCofNTrail1[75][3] = {{0, 0, 16}/*error */, {0, 0, 16}/*error */, {1, 13, 15}, {1, 13, 15}, {0, 16, 16}, {2, 16, 16}, {1, 16, 16}, {0, 15, 16},
+        {3, 16, 16}, {2, 15, 16}, {1, 15, 16}, {0, 14, 16}, {3, 15, 16}, {2, 14, 16}, {1, 14, 16}, {0, 13, 16},
+        {3, 14, 15}, {2, 13, 15}, {1, 12, 15}, {0, 12, 15}, {3, 13, 15}, {2, 12, 15}, {1, 11, 15}, {0, 11, 15},
+        {3, 12, 14}, {2, 11, 14}, {1, 10, 14}, {0, 10, 14}, {3, 11, 14}, {2, 10, 14}, {1, 9, 14}, {0, 9, 14},
+        {0, 8, 13}, {2, 9, 13}, {1, 8, 13}, {0, 7, 13}, {3, 10, 13}, {2, 8, 13}, {1, 7, 13}, {0, 6, 13},
+        {3, 9, 11}, {2, 7, 11}, {1, 6, 11}, {0, 5, 11}, {3, 8, 10},
+        {2, 6, 10}, {1, 5, 10}, {0, 4, 10}, {3, 7, 9}, {2, 5, 9}, {1, 4, 9}, {0, 3, 9}, {3, 6, 8},
+        {2, 4, 8}, {1, 3, 8}, {0, 2, 8}, {3, 5, 7}, {2, 3, 7}, {3, 4, 6}, {3, 4, 6}, {1, 2, 6},
+        {1, 2, 6}, {0, 1, 6}, {0, 1, 6}, {3, 3, 5}, {3, 3, 5}, {3, 3, 5}, {3, 3, 5}, {2, 2, 3},
+        {1, 1, 2}, {1, 1, 2}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}
+    };
+
+    const static uint8 TotCofNTrail2[84][3] = {{0, 0, 14 /* error */}, {0, 0, 14/*error */}, {3, 15, 13}, {3, 15, 13}, {3, 16, 14}, {2, 16, 14}, {1, 16, 14}, {0, 16, 14},
+        {1, 15, 14}, {0, 15, 14}, {2, 15, 14}, {1, 14, 14}, {2, 14, 13}, {2, 14, 13}, {0, 14, 13}, {0, 14, 13},
+        {3, 14, 13}, {2, 13, 13}, {1, 13, 13}, {0, 13, 13}, {3, 13, 13}, {2, 12, 13}, {1, 12, 13}, {0, 12, 13},
+        {0, 11, 12}, {2, 11, 12}, {1, 11, 12}, {0, 10, 12}, {3, 12, 12}, {2, 10, 12}, {1, 10, 12}, {0, 9, 12},
+        {3, 11, 11}, {2, 9, 11}, {1, 9, 11}, {0, 8, 11}, {3, 10, 11}, {2, 8, 11}, {1, 8, 11}, {0, 7, 11},
+        {3, 9, 9}, {2, 7, 9}, {1, 7, 9}, {0, 6, 9}, {0, 5, 8}, {0, 5, 8}, {2, 6, 8}, {2, 6, 8},
+        {1, 6, 8}, {1, 6, 8}, {0, 4, 8}, {0, 4, 8}, {3, 8, 7}, {2, 5, 7}, {1, 5, 7}, {0, 3, 7},
+        {3, 7, 6}, {3, 7, 6}, {2, 4, 6}, {2, 4, 6}, {1, 4, 6}, {1, 4, 6}, {0, 2, 6}, {0, 2, 6},
+        {3, 6, 6}, {2, 3, 6}, {1, 3, 6}, {0, 1, 6}, {3, 5, 5}, {3, 5, 5}, {1, 2, 5}, {1, 2, 5},
+        {3, 4, 4}, {3, 3, 4}, {2, 2, 3}, {2, 2, 3}, {1, 1, 2}, {1, 1, 2}, {1, 1, 2}, {1, 1, 2},
+        {0, 0, 2}, {0, 0, 2}, {0, 0, 2}, {0, 0, 2}
+    };
+
+    const static uint8 TotCofNTrail3[64][3] = {{0, 0, 10/*error*/}, {0, 16, 10}, {3, 16, 10}, {2, 16, 10}, {1, 16, 10}, {0, 15, 10}, {3, 15, 10},
+        {2, 15, 10}, {1, 15, 10}, {0, 14, 10}, {3, 14, 10}, {2, 14, 10}, {1, 14, 10}, {0, 13, 10}, {1, 13, 9},
+        {1, 13, 9}, {0, 12, 9}, {2, 13, 9}, {1, 12, 9}, {0, 11, 9}, {3, 13, 9}, {2, 12, 9}, {1, 11, 9},
+        {0, 10, 9}, {3, 12, 8}, {2, 11, 8}, {1, 10, 8}, {0, 9, 8}, {3, 11, 8}, {2, 10, 8}, {1, 9, 8},
+        {0, 8, 8}, {0, 7, 7}, {0, 6, 7}, {2, 9, 7}, {0, 5, 7}, {3, 10, 7}, {2, 8, 7}, {1, 8, 7},
+        {0, 4, 7}, {0, 3, 6}, {2, 7, 6}, {1, 7, 6}, {0, 2, 6}, {3, 9, 6}, {2, 6, 6}, {1, 6, 6},
+        {0, 1, 6}, {1, 5, 5}, {2, 5, 5}, {1, 4, 5}, {2, 4, 5}, {1, 3, 5}, {3, 8, 5}, {2, 3, 5},
+        {1, 2, 5}, {3, 7, 4}, {3, 6, 4}, {3, 5, 4}, {3, 4, 4}, {3, 3, 4}, {2, 2, 4}, {1, 1, 4},
+        {0, 0, 4}
+    };
+#endif
+    uint code;
+
+#ifdef PV_NO_CLZ
+    uint8 *pcode;
+    if (nC < 2)
+    {
+        BitstreamShowBits(stream, 16, &code);
+
+        if (code >= 8192)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>13)+65+2][0]);
+        }
+        else if (code >= 2048)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>9)+50+2][0]);
+        }
+        else if (code >= 1024)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>8)+46+2][0]);
+        }
+        else if (code >= 512)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>7)+42+2][0]);
+        }
+        else if (code >= 256)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>6)+38+2][0]);
+        }
+        else if (code >= 128)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>5)+34+2][0]);
+        }
+        else if (code >= 64)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>3)+22+2][0]);
+        }
+        else if (code >= 32)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>2)+14+2][0]);
+        }
+        else if (code >= 16)
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code>>1)+6+2][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotCofNTrail1[(code-2)+2][0]);
+        }
+
+        *TrailingOnes = pcode[0];
+        *TotalCoeff = pcode[1];
+
+        BitstreamFlushBits(stream, pcode[2]);
+    }
+    else if (nC < 4)
+    {
+        BitstreamShowBits(stream, 14, &code);
+
+        if (code >= 4096)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>10)+66+2][0]);
+        }
+        else if (code >= 2048)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>8)+54+2][0]);
+        }
+        else if (code >= 512)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>7)+46+2][0]);
+        }
+        else if (code >= 128)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>5)+34+2][0]);
+        }
+        else if (code >= 64)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>3)+22+2][0]);
+        }
+        else if (code >= 32)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>2)+14+2][0]);
+        }
+        else if (code >= 16)
+        {
+            pcode = (uint8*) & (TotCofNTrail2[(code>>1)+6+2][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotCofNTrail2[code-2+2][0]);
+        }
+        *TrailingOnes = pcode[0];
+        *TotalCoeff = pcode[1];
+
+        BitstreamFlushBits(stream, pcode[2]);
+    }
+    else if (nC < 8)
+    {
+        BitstreamShowBits(stream, 10, &code);
+
+        if (code >= 512)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>6)+47+1][0]);
+        }
+        else if (code >= 256)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>5)+39+1][0]);
+        }
+        else if (code >= 128)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>4)+31+1][0]);
+        }
+        else if (code >= 64)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>3)+23+1][0]);
+        }
+        else if (code >= 32)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>2)+15+1][0]);
+        }
+        else if (code >= 16)
+        {
+            pcode = (uint8*) & (TotCofNTrail3[(code>>1)+7+1][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotCofNTrail3[code-1+1][0]);
+        }
+        *TrailingOnes = pcode[0];
+        *TotalCoeff = pcode[1];
+
+        BitstreamFlushBits(stream, pcode[2]);
+    }
+    else
+    {
+        /* read 6 bit FLC */
+        BitstreamReadBits(stream, 6, &code);
+
+
+        *TrailingOnes = code & 3;
+        *TotalCoeff = (code >> 2) + 1;
+
+        if (*TotalCoeff > 16)
+        {
+            *TotalCoeff = 16;  // _ERROR
+        }
+
+        if (code == 3)
+        {
+            *TrailingOnes = 0;
+            (*TotalCoeff)--;
+        }
+    }
+#else
+    const VLCNumCoeffTrail *ptr;
+    const ShiftOffset *ptr_indx;
+    uint temp, leading_zeros = 0;
+
+    if (nC < 8)
+    {
+
+        BitstreamShowBits(stream, 16, &code);
+        temp = code | 1;
+
+        PV_CLZ(leading_zeros, temp)
+
+        temp = nC_table[nC];
+        ptr_indx = &NumCoeffTrailOnes_indx[temp][leading_zeros];
+        ptr = &NumCoeffTrailOnes[temp][(code >> ptr_indx->shift) + ptr_indx->offset];
+        *TrailingOnes = ptr->trailing;
+        *TotalCoeff = ptr->total_coeff;
+        BitstreamFlushBits(stream, ptr->length);
+    }
+    else
+    {
+        /* read 6 bit FLC */
+        BitstreamReadBits(stream, 6, &code);
+
+
+        *TrailingOnes = code & 3;
+        *TotalCoeff = (code >> 2) + 1;
+
+        if (*TotalCoeff > 16)
+        {
+            *TotalCoeff = 16;  // _ERROR
+        }
+
+        if (code == 3)
+        {
+            *TrailingOnes = 0;
+            (*TotalCoeff)--;
+        }
+    }
+#endif
+    return AVCDEC_SUCCESS;
+}
+
+/* TO BE OPTIMIZED !!!!! */
+AVCDec_Status ce_TotalCoeffTrailingOnesChromaDC(AVCDecBitstream *stream, int *TrailingOnes, int *TotalCoeff)
+{
+    AVCDec_Status status;
+
+    const static uint8 TotCofNTrail5[21][3] =
+    {
+        {3, 4, 7}, {3, 4, 7}, {2, 4, 8}, {1, 4, 8}, {2, 3, 7}, {2, 3, 7}, {1, 3, 7},
+        {1, 3, 7}, {0, 4, 6}, {0, 3, 6}, {0, 2, 6}, {3, 3, 6}, {1, 2, 6}, {0, 1, 6},
+        {2, 2, 3}, {0, 0, 2}, {0, 0, 2}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}
+    };
+
+    uint code;
+    uint8 *pcode;
+
+    status = BitstreamShowBits(stream, 8, &code);
+
+    if (code >= 32)
+    {
+        pcode = (uint8*) & (TotCofNTrail5[(code>>5)+13][0]);
+    }
+    else if (code >= 8)
+    {
+        pcode = (uint8*) & (TotCofNTrail5[(code>>2)+6][0]);
+    }
+    else
+    {
+        pcode = (uint8*) & (TotCofNTrail5[code][0]);
+    }
+
+    *TrailingOnes = pcode[0];
+    *TotalCoeff = pcode[1];
+
+    BitstreamFlushBits(stream, pcode[2]);
+
+    return status;
+}
+
+/* see Table 9-6 */
+AVCDec_Status ce_LevelPrefix(AVCDecBitstream *stream, uint *code)
+{
+    uint temp;
+    uint leading_zeros = 0;
+    BitstreamShowBits(stream, 16, &temp);
+    temp |= 1 ;
+
+    PV_CLZ(leading_zeros, temp)
+
+    BitstreamFlushBits(stream, leading_zeros + 1);
+    *code = leading_zeros;
+    return AVCDEC_SUCCESS;
+}
+
+/* see Table 9-7 and 9-8 */
+AVCDec_Status ce_TotalZeros(AVCDecBitstream *stream, int *code, int TotalCoeff)
+{
+    const static uint8 TotZero1[28][2] = {{15, 9}, {14, 9}, {13, 9}, {12, 8},
+        {12, 8}, {11, 8}, {11, 8}, {10, 7}, {9, 7}, {8, 6}, {8, 6}, {7, 6}, {7, 6}, {6, 5}, {6, 5},
+        {6, 5}, {6, 5}, {5, 5}, {5, 5}, {5, 5}, {5, 5}, {4, 4}, {3, 4},
+        {2, 3}, {2, 3}, {1, 3}, {1, 3}, {0, 1}
+    };
+
+    const static uint8 TotZero2n3[2][18][2] = {{{14, 6}, {13, 6}, {12, 6}, {11, 6},
+            {10, 5}, {10, 5}, {9, 5}, {9, 5}, {8, 4}, {7, 4}, {6, 4}, {5, 4}, {4, 3}, {4, 3},
+            {3, 3}, {2, 3}, {1, 3}, {0, 3}},
+
+        /*const static uint8 TotZero3[18][2]=*/{{13, 6}, {11, 6}, {12, 5}, {12, 5}, {10, 5},
+            {10, 5}, {9, 5}, {9, 5}, {8, 4}, {5, 4}, {4, 4}, {0, 4}, {7, 3}, {7, 3}, {6, 3}, {3, 3},
+            {2, 3}, {1, 3}}
+    };
+
+    const static uint8 TotZero4[17][2] = {{12, 5}, {11, 5}, {10, 5}, {0, 5}, {9, 4},
+        {9, 4}, {7, 4}, {7, 4}, {3, 4}, {3, 4}, {2, 4}, {2, 4}, {8, 3}, {6, 3}, {5, 3}, {4, 3}, {1, 3}
+    };
+
+    const static uint8 TotZero5[13][2] = {{11, 5}, {9, 5}, {10, 4}, {8, 4}, {2, 4},
+        {1, 4}, {0, 4}, {7, 3}, {7, 3}, {6, 3}, {5, 3}, {4, 3}, {3, 3}
+    };
+
+    const static uint8 TotZero6to10[5][15][2] = {{{10, 6}, {0, 6}, {1, 5}, {1, 5}, {8, 4},
+            {8, 4}, {8, 4}, {8, 4}, {9, 3}, {7, 3}, {6, 3}, {5, 3}, {4, 3}, {3, 3}, {2, 3}},
+
+        /*const static uint8 TotZero7[15][2]=*/{{9, 6}, {0, 6}, {1, 5}, {1, 5}, {7, 4},
+            {7, 4}, {7, 4}, {7, 4}, {8, 3}, {6, 3}, {4, 3}, {3, 3}, {2, 3}, {5, 2}, {5, 2}},
+
+        /*const static uint8 TotZero8[15][2]=*/{{8, 6}, {0, 6}, {2, 5}, {2, 5}, {1, 4},
+            {1, 4}, {1, 4}, {1, 4}, {7, 3}, {6, 3}, {3, 3}, {5, 2}, {5, 2}, {4, 2}, {4, 2}},
+
+        /*const static uint8 TotZero9[15][2]=*/{{1, 6}, {0, 6}, {7, 5}, {7, 5}, {2, 4},
+            {2, 4}, {2, 4}, {2, 4}, {5, 3}, {6, 2}, {6, 2}, {4, 2}, {4, 2}, {3, 2}, {3, 2}},
+
+        /*const static uint8 TotZero10[11][2]=*/{{1, 5}, {0, 5}, {6, 4}, {6, 4}, {2, 3},
+            {2, 3}, {2, 3}, {2, 3}, {5, 2}, {4, 2}, {3, 2}, {0, 0}, {0, 0}, {0, 0}, {0, 0}}
+    };
+
+    const static uint8 TotZero11[7][2] = {{0, 4}, {1, 4}, {2, 3}, {2, 3}, {3, 3}, {5, 3}, {4, 1}};
+
+    const static uint8 TotZero12to15[4][5][2] =
+    {
+        {{3, 1}, {2, 2}, {4, 3}, {1, 4}, {0, 4}},
+        {{2, 1}, {3, 2}, {1, 3}, {0, 3}, {0, 0}},
+        {{2, 1}, {1, 2}, {0, 2}, {0, 0}, {0, 0}},
+        {{1, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0}}
+    };
+
+    uint temp, mask;
+    int indx;
+    uint8 *pcode;
+
+    if (TotalCoeff == 1)
+    {
+        BitstreamShowBits(stream, 9, &temp);
+
+        if (temp >= 256)
+        {
+            pcode = (uint8*) & (TotZero1[27][0]);
+        }
+        else if (temp >= 64)
+        {
+            pcode = (uint8*) & (TotZero1[(temp>>5)+19][0]);
+        }
+        else if (temp >= 8)
+        {
+            pcode = (uint8*) & (TotZero1[(temp>>2)+5][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero1[temp-1][0]);
+        }
+
+    }
+    else if (TotalCoeff == 2 || TotalCoeff == 3)
+    {
+        BitstreamShowBits(stream, 6, &temp);
+
+        if (temp >= 32)
+        {
+            pcode = (uint8*) & (TotZero2n3[TotalCoeff-2][(temp>>3)+10][0]);
+        }
+        else if (temp >= 8)
+        {
+            pcode = (uint8*) & (TotZero2n3[TotalCoeff-2][(temp>>2)+6][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero2n3[TotalCoeff-2][temp][0]);
+        }
+    }
+    else if (TotalCoeff == 4)
+    {
+        BitstreamShowBits(stream, 5, &temp);
+
+        if (temp >= 12)
+        {
+            pcode = (uint8*) & (TotZero4[(temp>>2)+9][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero4[temp][0]);
+        }
+    }
+    else if (TotalCoeff == 5)
+    {
+        BitstreamShowBits(stream, 5, &temp);
+
+        if (temp >= 16)
+        {
+            pcode = (uint8*) & (TotZero5[(temp>>2)+5][0]);
+        }
+        else if (temp >= 2)
+        {
+            pcode = (uint8*) & (TotZero5[(temp>>1)+1][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero5[temp][0]);
+        }
+    }
+    else if (TotalCoeff >= 6 && TotalCoeff <= 10)
+    {
+        if (TotalCoeff == 10)
+        {
+            BitstreamShowBits(stream, 5, &temp);
+        }
+        else
+        {
+            BitstreamShowBits(stream, 6, &temp);
+        }
+
+
+        if (temp >= 8)
+        {
+            pcode = (uint8*) & (TotZero6to10[TotalCoeff-6][(temp>>3)+7][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero6to10[TotalCoeff-6][temp][0]);
+        }
+    }
+    else if (TotalCoeff == 11)
+    {
+        BitstreamShowBits(stream, 4, &temp);
+
+
+        if (temp >= 8)
+        {
+            pcode = (uint8*) & (TotZero11[6][0]);
+        }
+        else if (temp >= 4)
+        {
+            pcode = (uint8*) & (TotZero11[(temp>>1)+2][0]);
+        }
+        else
+        {
+            pcode = (uint8*) & (TotZero11[temp][0]);
+        }
+    }
+    else
+    {
+        BitstreamShowBits(stream, (16 - TotalCoeff), &temp);
+        mask = 1 << (15 - TotalCoeff);
+        indx = 0;
+        while ((temp&mask) == 0 && indx < (16 - TotalCoeff)) /* search location of 1 bit */
+        {
+            mask >>= 1;
+            indx++;
+        }
+
+        pcode = (uint8*) & (TotZero12to15[TotalCoeff-12][indx]);
+    }
+
+    *code = pcode[0];
+    BitstreamFlushBits(stream, pcode[1]);
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see Table 9-9 */
+AVCDec_Status ce_TotalZerosChromaDC(AVCDecBitstream *stream, int *code, int TotalCoeff)
+{
+    const static uint8 TotZeroChrom1to3[3][8][2] =
+    {
+        {{3, 3}, {2, 3}, {1, 2}, {1, 2}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
+        {{2, 2}, {2, 2}, {1, 2}, {1, 2}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
+        {{1, 1}, {1, 1}, {1, 1}, {1, 1}, {0, 1}, {0, 1}, {0, 1}, {0, 1}},
+    };
+
+
+    uint temp;
+    uint8 *pcode;
+
+    BitstreamShowBits(stream, 3, &temp);
+    pcode = (uint8*) & (TotZeroChrom1to3[TotalCoeff-1][temp]);
+
+    *code = pcode[0];
+
+    BitstreamFlushBits(stream, pcode[1]);
+
+    return AVCDEC_SUCCESS;
+}
+
+/* see Table 9-10 */
+AVCDec_Status ce_RunBefore(AVCDecBitstream *stream, int *code, int zerosLeft)
+{
+    const static int codlen[6] = {1, 2, 2, 3, 3, 3}; /* num bits to read */
+    const static uint8 RunBeforeTab[6][8][2] = {{{1, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}},
+        /*const static int RunBefore2[4][2]=*/{{2, 2}, {1, 2}, {0, 1}, {0, 1}, {0, 0}, {0, 0}, {0, 0}, {0, 0}},
+        /*const static int RunBefore3[4][2]=*/{{3, 2}, {2, 2}, {1, 2}, {0, 2}, {0, 0}, {0, 0}, {0, 0}, {0, 0}},
+        /*const static int RunBefore4[7][2]=*/{{4, 3}, {3, 3}, {2, 2}, {2, 2}, {1, 2}, {1, 2}, {0, 2}, {0, 2}},
+        /*const static int RunBefore5[7][2]=*/{{5, 3}, {4, 3}, {3, 3}, {2, 3}, {1, 2}, {1, 2}, {0, 2}, {0, 2}},
+        /*const static int RunBefore6[7][2]=*/{{1, 3}, {2, 3}, {4, 3}, {3, 3}, {6, 3}, {5, 3}, {0, 2}, {0, 2}}
+    };
+
+    uint temp;
+    uint8 *pcode;
+    int indx;
+
+    if (zerosLeft <= 6)
+    {
+        BitstreamShowBits(stream, codlen[zerosLeft-1], &temp);
+
+        pcode = (uint8*) & (RunBeforeTab[zerosLeft-1][temp][0]);
+
+        *code = pcode[0];
+
+        BitstreamFlushBits(stream, pcode[1]);
+    }
+    else
+    {
+        BitstreamReadBits(stream, 3, &temp);
+        if (temp)
+        {
+            *code = 7 - temp;
+        }
+        else
+        {
+            BitstreamShowBits(stream, 9, &temp);
+            temp <<= 7;
+            temp |= 1;
+            indx = 0;
+            PV_CLZ(indx, temp)
+            *code = 7 + indx;
+            BitstreamFlushBits(stream, indx + 1);
+        }
+    }
+
+
+    return AVCDEC_SUCCESS;
+}
diff --git a/media/libstagefright/codecs/avc/patent_disclaimer.txt b/media/libstagefright/codecs/avc/patent_disclaimer.txt
new file mode 100644
index 0000000..b4bf11d
--- /dev/null
+++ b/media/libstagefright/codecs/avc/patent_disclaimer.txt
@@ -0,0 +1,9 @@
+
+THIS IS NOT A GRANT OF PATENT RIGHTS.
+
+Google makes no representation or warranty that the codecs for which
+source code is made available hereunder are unencumbered by
+third-party patents.  Those intending to use this source code in
+hardware or software products are advised that implementations of
+these codecs, including in open source software or shareware, may
+require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/m4v_h263/Android.mk b/media/libstagefright/codecs/m4v_h263/Android.mk
new file mode 100644
index 0000000..2e43120
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/Android.mk
@@ -0,0 +1,4 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/media/libstagefright/codecs/m4v_h263/dec/Android.mk b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
new file mode 100644
index 0000000..403da58
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/Android.mk
@@ -0,0 +1,50 @@
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+ 	M4vH263Decoder.cpp \
+ 	src/adaptive_smooth_no_mmx.cpp \
+ 	src/bitstream.cpp \
+ 	src/block_idct.cpp \
+ 	src/cal_dc_scaler.cpp \
+ 	src/chvr_filter.cpp \
+ 	src/chv_filter.cpp \
+ 	src/combined_decode.cpp \
+ 	src/conceal.cpp \
+ 	src/datapart_decode.cpp \
+ 	src/dcac_prediction.cpp \
+ 	src/dec_pred_intra_dc.cpp \
+ 	src/deringing_chroma.cpp \
+ 	src/deringing_luma.cpp \
+ 	src/find_min_max.cpp \
+ 	src/get_pred_adv_b_add.cpp \
+ 	src/get_pred_outside.cpp \
+ 	src/idct.cpp \
+ 	src/idct_vca.cpp \
+ 	src/mb_motion_comp.cpp \
+ 	src/mb_utils.cpp \
+ 	src/packet_util.cpp \
+ 	src/post_filter.cpp \
+ 	src/post_proc_semaphore.cpp \
+ 	src/pp_semaphore_chroma_inter.cpp \
+ 	src/pp_semaphore_luma.cpp \
+ 	src/pvdec_api.cpp \
+ 	src/scaling_tab.cpp \
+ 	src/vlc_decode.cpp \
+ 	src/vlc_dequant.cpp \
+ 	src/vlc_tab.cpp \
+ 	src/vop.cpp \
+ 	src/zigzag_tab.cpp
+
+
+LOCAL_MODULE := libstagefright_m4vh263dec
+
+LOCAL_C_INCLUDES := \
+	$(LOCAL_PATH)/src \
+	$(LOCAL_PATH)/include \
+	$(TOP)/frameworks/base/media/libstagefright/include \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
+
+LOCAL_CFLAGS := -DOSCL_EXPORT_REF= -DOSCL_IMPORT_REF=
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp b/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp
new file mode 100644
index 0000000..c3ef0d2
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp
@@ -0,0 +1,202 @@
+/*
+ * 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.
+ */
+//#define LOG_NDEBUG 0
+#define LOG_TAG "M4vH263Decoder"
+#include <utils/Log.h>
+#include <stdlib.h> // for free
+#include "ESDS.h"
+#include "M4vH263Decoder.h"
+
+#include "mp4dec_api.h"
+
+#include <OMX_Component.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>
+#include <media/stagefright/Utils.h>
+
+namespace android {
+
+M4vH263Decoder::M4vH263Decoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mHandle(new tagvideoDecControls),
+      mInputBuffer(NULL),
+      mNumSamplesOutput(0) {
+
+    LOGV("M4vH263Decoder");
+    memset(mHandle, 0, sizeof(tagvideoDecControls));
+    mFormat = new MetaData;
+    mFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
+    CHECK(mSource->getFormat()->findInt32(kKeyWidth, &mWidth));
+    CHECK(mSource->getFormat()->findInt32(kKeyHeight, &mHeight));
+    mFormat->setInt32(kKeyWidth, mWidth);
+    mFormat->setInt32(kKeyHeight, mHeight);
+    mFormat->setInt32(kKeyColorFormat, OMX_COLOR_FormatYUV420Planar);
+    mFormat->setCString(kKeyDecoderComponent, "M4vH263Decoder");
+}
+
+M4vH263Decoder::~M4vH263Decoder() {
+    if (mStarted) {
+        stop();
+    }
+
+    delete mHandle;
+    mHandle = NULL;
+}
+
+status_t M4vH263Decoder::start(MetaData *) {
+    CHECK(!mStarted);
+
+    const char *mime = NULL;
+    CHECK(mSource->getFormat()->findCString(kKeyMIMEType, &mime));
+
+    MP4DecodingMode mode;
+    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
+        mode = MPEG4_MODE;
+    } else {
+        CHECK(!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime));
+        mode = H263_MODE;
+    }
+
+    uint32_t type;
+    const void *data = NULL;
+    size_t size = 0;
+    uint8_t *vol_data[1] = {0};
+    int32_t vol_size = 0;
+    if (mSource->getFormat()->findData(kKeyESDS, &type, &data, &size)) {
+        ESDS esds((const uint8_t *)data, size);
+        CHECK_EQ(esds.InitCheck(), OK);
+
+        const void *codec_specific_data;
+        size_t codec_specific_data_size;
+        esds.getCodecSpecificInfo(&codec_specific_data, &codec_specific_data_size);
+
+        vol_data[0] = (uint8_t *) malloc(codec_specific_data_size);
+        memcpy(vol_data[0], codec_specific_data, codec_specific_data_size);
+        vol_size = codec_specific_data_size;
+    } else {
+        vol_data[0] = NULL;
+        vol_size = 0;
+
+    }
+    CHECK_EQ(PV_TRUE, PVInitVideoDecoder(
+            mHandle, vol_data, &vol_size, 1, mWidth, mHeight, mode));
+    if (vol_data[0]) free(vol_data[0]);
+    MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
+    CHECK_EQ(mode, actualMode);
+
+    PVSetPostProcType((VideoDecControls *) mHandle, 0);
+    size_t frameSize = (((mWidth + 15) & - 16) * ((mHeight + 15) & - 16) * 3) / 2;
+    for (uint32_t i = 0; i < 2; ++i) {
+        mFrames[i] = new MediaBuffer(frameSize);
+        mFrames[i]->setObserver(this);
+    }
+    PVSetReferenceYUV(mHandle, (uint8_t *)mFrames[1]->data());
+
+    mSource->start();
+
+    mNumSamplesOutput = 0;
+    mStarted = true;
+
+    return OK;
+}
+
+status_t M4vH263Decoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    mSource->stop();
+
+    releaseFrames();
+
+    mStarted = false;
+    return (PVCleanUpVideoDecoder(mHandle) == PV_TRUE)? OK: UNKNOWN_ERROR;
+}
+
+sp<MetaData> M4vH263Decoder::getFormat() {
+    return mFormat;
+}
+
+status_t M4vH263Decoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        CHECK_EQ(PVResetVideoDecoder(mHandle), PV_TRUE);
+    }
+
+    MediaBuffer *inputBuffer = NULL;
+    status_t err = mSource->read(&inputBuffer, options);
+    if (err != OK) {
+        return err;
+    }
+
+    uint8_t *bitstream = (uint8_t *) inputBuffer->data() + inputBuffer->range_offset();
+    uint32_t timestamp = 0xFFFFFFFF;
+    int32_t bufferSize = inputBuffer->range_length();
+    uint32_t useExtTimestamp = 0;
+    CHECK_EQ(PV_TRUE, PVDecodeVideoFrame(mHandle, &bitstream, &timestamp, &bufferSize,
+            &useExtTimestamp,  (uint8_t *)mFrames[mNumSamplesOutput & 0x01]->data()));
+
+    // Check whether video dimension is changed.
+    // If so, notify the client about the change.
+    int32_t width, height;
+    PVGetVideoDimensions(mHandle, &width, &height);
+    if (mWidth != width || mHeight != height) {
+        mFormat->setInt32(kKeyWidth, width);
+        mFormat->setInt32(kKeyHeight, height);
+        return INFO_FORMAT_CHANGED;
+    }
+
+    PVSetReferenceYUV(mHandle, (uint8_t *)mFrames[mNumSamplesOutput & 0x01]->data());
+    *out = mFrames[mNumSamplesOutput & 0x01];
+    (*out)->add_ref();
+
+    int64_t timeUs;
+    CHECK(inputBuffer->meta_data()->findInt64(kKeyTime, &timeUs));
+    (*out)->meta_data()->setInt64(kKeyTime, timeUs);
+
+    ++mNumSamplesOutput;
+    inputBuffer->release();
+
+    return OK;
+}
+
+void M4vH263Decoder::releaseFrames() {
+    for (size_t i = 0; i < sizeof(mFrames) / sizeof(mFrames[0]); ++i) {
+        MediaBuffer *buffer = mFrames[i];
+
+        buffer->setObserver(NULL);
+        buffer->release();
+
+        mFrames[i] = NULL;
+    }
+}
+
+void M4vH263Decoder::signalBufferReturned(MediaBuffer *buffer) {
+    LOGV("signalBufferReturned");
+}
+
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h b/media/libstagefright/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h
new file mode 100644
index 0000000..ec6871f
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/include/m4vh263_decoder_pv_types.h
@@ -0,0 +1,67 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------$
+ */
+
+#ifndef M4V_H263_DECODER_PV_TYPES_H_
+#define M4V_H263_DECODER_PV_TYPES_H_
+
+#include <stdint.h>
+#include <string.h>
+#include <stdlib.h> // for free, malloc, etc
+
+// Redefine the int types
+typedef uint8_t uint8;
+typedef uint16_t uint16;
+typedef int16_t int16;
+typedef uint32_t uint32;
+typedef int32_t int32;
+typedef unsigned int uint;
+
+// Redefine the oscl memory management routines
+#define oscl_memcpy memcpy
+#define oscl_memset memset
+#define oscl_malloc malloc
+#define oscl_free free
+#define oscl_memcmp memcmp
+#define OSCL_DELETE(ptr) { delete(ptr); }
+
+// Request status values.  These are negative so that
+// they won't conflict with system error codes.
+const int32 OSCL_REQUEST_ERR_NONE = 0;
+const int32 OSCL_REQUEST_PENDING = (-0x7fffffff);
+const int32 OSCL_REQUEST_ERR_CANCEL = (-1);
+const int32 OSCL_REQUEST_ERR_GENERAL = (-2);
+
+// Request status type
+class OsclAOStatus
+{
+    public:
+        OsclAOStatus();
+        OsclAOStatus(int32 aStatus);
+        int32 operator=(int32 aStatus);
+        int32 operator==(int32 aStatus) const;
+        int32 operator!=(int32 aStatus) const;
+        int32 operator>=(int32 aStatus) const;
+        int32 operator<=(int32 aStatus) const;
+        int32 operator>(int32 aStatus) const;
+        int32 operator<(int32 aStatus) const;
+        int32 Value() const;
+    private:
+        int32 iStatus;
+};
+
+#endif  // M4V_H263_DECODER_PV_TYPES_H_
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h b/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.h
new file mode 100644
index 0000000..ef09900
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/include/mp4dec_api.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.
+ * -------------------------------------------------------------------
+ */
+#ifndef _MP4DEC_API_H_
+#define _MP4DEC_API_H_
+
+#include "m4vh263_decoder_pv_types.h"
+
+#define PV_TOLERATE_VOL_ERRORS
+#define PV_MEMORY_POOL
+
+#ifndef _PV_TYPES_
+#define _PV_TYPES_
+
+typedef uint Bool;
+
+#define PV_CODEC_INIT  0
+#define PV_CODEC_STOP  1
+#endif
+
+#define PV_TRUE  1
+#define PV_FALSE 0
+
+/* flag for post-processing  4/25/00 */
+
+#ifdef DEC_NOPOSTPROC
+#undef PV_POSTPROC_ON   /* enable compilation of post-processing code */
+#else
+#define PV_POSTPROC_ON
+#endif
+
+#define PV_NO_POST_PROC 0
+#define PV_DEBLOCK 1
+#define PV_DERING  2
+
+
+
+#include "visual_header.h" // struct VolInfo is defined
+
+
+/**@name Structure and Data Types
+ * These type definitions specify the input / output from the PVMessage
+ * library.
+ */
+
+/*@{*/
+/* The application has to allocate space for this structure */
+typedef struct tagOutputFrame
+{
+    uint8       *data;          /* pointer to output YUV buffer */
+    uint32      timeStamp;      /* time stamp */
+} OutputFrame;
+
+typedef struct tagApplicationData
+{
+    int layer;          /* current video layer */
+    void *object;       /* some optional data field */
+} applicationData;
+
+/* Application controls, this structed shall be allocated */
+/*    and initialized in the application.                 */
+typedef struct tagvideoDecControls
+{
+    /* The following fucntion pointer is copied to BitstreamDecVideo structure  */
+    /*    upon initialization and never used again. */
+    int (*readBitstreamData)(uint8 *buf, int nbytes_required, void *appData);
+    applicationData appData;
+
+    uint8 *outputFrame;
+    void *videoDecoderData;     /* this is an internal pointer that is only used */
+    /* in the decoder library.   */
+#ifdef PV_MEMORY_POOL
+    int32 size;
+#endif
+    int nLayers;
+    /* pointers to VOL data for frame-based decoding. */
+    uint8 *volbuf[2];           /* maximum of 2 layers for now */
+    int32 volbuf_size[2];
+
+} VideoDecControls;
+
+typedef enum
+{
+    H263_MODE = 0, MPEG4_MODE, UNKNOWN_MODE
+} MP4DecodingMode;
+
+typedef enum
+{
+    MP4_I_FRAME, MP4_P_FRAME, MP4_B_FRAME, MP4_BAD_FRAME
+} MP4FrameType;
+
+typedef struct tagVopHeaderInfo
+{
+    int     currLayer;
+    uint32  timestamp;
+    MP4FrameType    frameType;
+    int     refSelCode;
+    int16       quantizer;
+} VopHeaderInfo;
+
+/*--------------------------------------------------------------------------*
+ * VideoRefCopyInfo:
+ * OMAP DSP specific typedef structure, to support the user (ARM) copying
+ * of a Reference Frame into the Video Decoder.
+ *--------------------------------------------------------------------------*/
+typedef struct tagVideoRefCopyInfoPtr
+{
+    uint8   *yChan;             /* The Y component frame the user can copy a new reference to */
+    uint8   *uChan;             /* The U component frame the user can copy a new reference to */
+    uint8   *vChan;             /* The V component frame the user can copy a new reference to */
+    uint8   *currentVop;        /* The Vop for video the user can copy a new reference to */
+} VideoRefCopyInfoPtr;
+
+typedef struct tagVideoRefCopyInfoData
+{
+    int16   width;              /* Width */
+    int16   height;             /* Height */
+    int16   realWidth;          /* Non-padded width, not a multiple of 16. */
+    int16   realHeight;         /* Non-padded height, not a multiple of 16. */
+} VideoRefCopyInfoData;
+
+typedef struct tagVideoRefCopyInfo
+{
+    VideoRefCopyInfoData data;
+    VideoRefCopyInfoPtr ptrs;
+} VideoRefCopyInfo;
+
+/*@}*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    OSCL_IMPORT_REF Bool    PVInitVideoDecoder(VideoDecControls *decCtrl, uint8 *volbuf[], int32 *volbuf_size, int nLayers, int width, int height, MP4DecodingMode mode);
+    Bool    PVAllocVideoData(VideoDecControls *decCtrl, int width, int height, int nLayers);
+    OSCL_IMPORT_REF Bool    PVCleanUpVideoDecoder(VideoDecControls *decCtrl);
+    Bool    PVResetVideoDecoder(VideoDecControls *decCtrl);
+    OSCL_IMPORT_REF void    PVSetReferenceYUV(VideoDecControls *decCtrl, uint8 *refYUV);
+    Bool    PVDecSetReference(VideoDecControls *decCtrl, uint8 *refYUV, uint32 timestamp);
+    Bool    PVDecSetEnhReference(VideoDecControls *decCtrl, uint8 *refYUV, uint32 timestamp);
+    OSCL_IMPORT_REF Bool    PVDecodeVideoFrame(VideoDecControls *decCtrl, uint8 *bitstream[], uint32 *timestamp, int32 *buffer_size, uint use_ext_timestamp[], uint8* currYUV);
+    Bool    PVDecodeVopHeader(VideoDecControls *decCtrl, uint8 *buffer[], uint32 timestamp[], int32 buffer_size[], VopHeaderInfo *header_info, uint use_ext_timestamp[], uint8 *currYUV);
+    Bool    PVDecodeVopBody(VideoDecControls *decCtrl, int32 buffer_size[]);
+    void    PVDecPostProcess(VideoDecControls *decCtrl, uint8 *outputYUV);
+    OSCL_IMPORT_REF void    PVGetVideoDimensions(VideoDecControls *decCtrl, int32 *display_width, int32 *display_height);
+    OSCL_IMPORT_REF void    PVSetPostProcType(VideoDecControls *decCtrl, int mode);
+    uint32  PVGetVideoTimeStamp(VideoDecControls *decoderControl);
+    int     PVGetDecBitrate(VideoDecControls *decCtrl);
+    int     PVGetDecFramerate(VideoDecControls *decCtrl);
+    uint8   *PVGetDecOutputFrame(VideoDecControls *decCtrl);
+    int     PVGetLayerID(VideoDecControls *decCtrl);
+    int32   PVGetDecMemoryUsage(VideoDecControls *decCtrl);
+    OSCL_IMPORT_REF MP4DecodingMode PVGetDecBitstreamMode(VideoDecControls *decCtrl);
+    Bool    PVExtractVolHeader(uint8 *video_buffer, uint8 *vol_header, int32 *vol_header_size);
+    int32   PVLocateFrameHeader(uint8 *video_buffer, int32 vop_size);
+    int32   PVLocateH263FrameHeader(uint8 *video_buffer, int32 vop_size);
+    Bool    PVGetVolInfo(VideoDecControls *decCtrl, VolInfo *pVolInfo); // BX 6/24/04
+    Bool    IsIntraFrame(VideoDecControls *decoderControl);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* _MP4DEC_API_H_ */
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/include/visual_header.h b/media/libstagefright/codecs/m4v_h263/dec/include/visual_header.h
new file mode 100644
index 0000000..48da0dc
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/include/visual_header.h
@@ -0,0 +1,51 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef _VISUAL_HEADER_H
+#define _VISUAL_HEADER_H
+
+#ifndef _PV_TYPES_ // In order to compile in MDF wrapper
+#define _PV_TYPES_
+
+#include "m4vh263_decoder_pv_types.h"
+
+typedef uint Bool;
+
+#endif // #ifndef _PV_TYPES_
+
+
+typedef struct tagVolInfo
+{
+    int32   shortVideoHeader;       /* shortVideoHeader mode */
+
+    /* Error Resilience Flags */
+    int32   errorResDisable;        /* VOL disable error resilence mode(Use Resynch markers) */
+    int32   useReverseVLC;          /* VOL reversible VLCs */
+    int32   dataPartitioning;       /* VOL data partitioning */
+
+    /* Parameters used for scalability */
+    int32   scalability;            /* VOL scalability (flag) */
+
+    int32   nbitsTimeIncRes;        /* number of bits for time increment () */
+
+    int32   profile_level_id;       /* profile and level */
+
+
+} VolInfo;
+
+#endif // #ifndef _VISUAL_HEADER_H
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp
new file mode 100644
index 0000000..e2761eb
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/adaptive_smooth_no_mmx.cpp
@@ -0,0 +1,421 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+
+ Description: Separated modules into one function per file and put into
+    new template.
+
+ Description: Optimizing C code and adding comments.  Also changing variable
+    names to make them more meaningful.
+
+ Who:                   Date:
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    Rec_Y = pointer to 0th position in buffer containing luminance values
+        of type uint8.
+    y_start = value of y coordinate of type int that specifies the first
+        row of pixels to be used in the filter algorithm.
+    x_start = value of x coordinate of type int that specifies the first
+        column of pixels to be used in the filter algorithm.
+    y_blk_start = value of the y coordinate of type int that specifies the
+        row of pixels which contains the start of a block. The row
+        specified by y_blk_start+BLK_SIZE is the last row of pixels
+        that are used in the filter algorithm.
+    x_blk_start = value of the x coordinate of type int that specifies the
+        column of pixels which contains the start of a block.  The
+        column specified by x_blk_start+BLK_SIZE is the last column of
+        pixels that are used in the filter algorithm.
+    thr = value of type int that is compared to the elements in Rec_Y to
+        determine if a particular value in Rec_Y will be modified by
+        the filter or not
+    width = value of type int that specifies the width of the display
+        in pixels (or pels, equivalently).
+    max_diff = value of type int that specifies the value that may be added
+        or subtracted from the pixel in Rec_Y that is being filtered
+        if the filter algorithm decides to change that particular
+        pixel's luminance value.
+
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    Buffer pointed to by Rec_Y is modified with the filtered
+    luminance values.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function implements a motion compensated noise filter using adaptive
+ weighted averaging of luminance values.  *Rec_Y contains the luminance values
+ that are being filtered.
+
+ The picture below depicts a 3x3 group of pixel luminance values.  The "u", "c",
+ and "l" stand for "upper", "center" and "lower", respectively.  The location
+ of pelc0 is specified by x_start and y_start in the 1-D array "Rec_Y" as
+ follows (assuming x_start=0):
+
+ location of pelc0 = [(y_start+1) * width] + x_start
+
+ Moving up or down 1 row (moving from pelu2 to pelc2, for example) is done by
+ incrementing or decrementing "width" elements within Rec_Y.
+
+ The coordinates of the upper left hand corner of a block (not the group of
+ 9 pixels depicted in the figure below) is specified by
+ (y_blk_start, x_blk_start).  The width and height of the block is BLKSIZE.
+ (y_start,x_start) may be specified independently of (y_blk_start, x_blk_start).
+
+    (y_start,x_start)
+ -----------|--------------------------
+    |   |   |   |   |
+    |   X   | pelu1 | pelu2 |
+    | pelu0 |   |   |
+    |   |   |   |
+ --------------------------------------
+    |   |   |   |
+    | pelc0 | pelc1 | pelc2 |
+    |   |   |   |
+    |   |   |   |
+ --------------------------------------
+    |   |   |   |
+    | pell0 | pell1 | pell2 |
+    |   |   |   |
+    |   |   |   |
+ --------------------------------------
+
+ The filtering of the luminance values is achieved by comparing the 9
+ luminance values to a threshold value ("thr") and then changing the
+ luminance value of pelc1 if all of the values are above or all of the values
+ are below the threshold.  The amount that the luminance value is changed
+ depends on a weighted sum of the 9 luminance values. The position of Pelc1
+ is then advanced to the right by one (as well as all of the surrounding pixels)
+ and the same calculation is performed again for the luminance value of the new
+ Pelc1. This continues row-wise until pixels in the last row of the block are
+ filtered.
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ None.
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ ..\corelibs\decoder\common\src\post_proc.c
+
+------------------------------------------------------------------------------
+ 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    "mp4dec_lib.h"
+#include    "post_proc.h"
+#include    "mp4def.h"
+
+#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef PV_POSTPROC_ON
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void AdaptiveSmooth_NoMMX(
+    uint8 *Rec_Y,       /* i/o  */
+    int y_start,        /* i    */
+    int x_start,        /* i    */
+    int y_blk_start,    /* i    */
+    int x_blk_start,    /* i    */
+    int thr,        /* i    */
+    int width,      /* i    */
+    int max_diff        /* i    */
+)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int  sign_v[15];
+    int sum_v[15];
+    int *sum_V_ptr;
+    int *sign_V_ptr;
+    uint8 pelu;
+    uint8 pelc;
+    uint8 pell;
+    uint8 *pelp;
+    uint8 oldrow[15];
+    int  sum;
+    int sum1;
+    uint8 *Rec_Y_ptr;
+    int32  addr_v;
+    int row_cntr;
+    int col_cntr;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /*  first row
+    */
+    addr_v = (int32)(y_start + 1) * width;  /* y coord of 1st element in the row  /
+                     /containing pelc pixel /     */
+    Rec_Y_ptr = &Rec_Y[addr_v + x_start];  /* initializing pointer to
+                           /  pelc0 position  */
+    sum_V_ptr = &sum_v[0];  /* initializing pointer to 0th element of array
+                /   that will contain weighted sums of pixel
+                /   luminance values */
+    sign_V_ptr = &sign_v[0];  /*  initializing pointer to 0th element of
+                  /   array that will contain sums that indicate
+                  /    how many of the 9 pixels are above or below
+                  /    the threshold value (thr)    */
+    pelp = &oldrow[0];  /* initializing pointer to the 0th element of array
+                /    that will contain current values of pelc that
+                /   are saved and used as values of pelu when the
+                /   next row of pixels are filtered */
+
+    pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu0 to pelu  */
+    *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc0 to pelc and
+                     /  storing this value in pelp which
+                     /   will be used as value of pelu0 when
+                     /  next row is filtered */
+    pell = *(Rec_Y_ptr + width);  /* assigning value of pell0 to pell */
+    Rec_Y_ptr++; /* advancing pointer from pelc0 to pelc1 */
+    *sum_V_ptr++ = pelu + (pelc << 1) + pell;  /* weighted sum of pelu0,
+                         /  pelc0 and pell0  */
+    /* sum of 0's and 1's (0 if pixel value is below thr, 1 if value
+    /is above thr)  */
+    *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) + INDEX(pell, thr);
+
+
+    pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu1 to pelu */
+    *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc1 to pelc and
+                     /  storing this value in pelp which
+                     /  will be used as the value of pelu1 when
+                     /  next row is filtered */
+    pell = *(Rec_Y_ptr + width);  /* assigning value of pell1 to pell */
+    Rec_Y_ptr++;  /* advancing pointer from pelc1 to pelc2 */
+    *sum_V_ptr++ = pelu + (pelc << 1) + pell; /* weighted sum of pelu1,
+                        / pelc1 and pell1  */
+    /* sum of 0's and 1's (0 if pixel value is below thr, 1 if value
+    /is above thr)  */
+    *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) + INDEX(pell, thr);
+
+    /* The loop below performs the filtering for the first row of
+    /   pixels in the region.  It steps across the remaining pixels in
+    /   the row and alters the luminance value of pelc1 if necessary,
+    /   depending on the luminance values of the adjacent pixels*/
+
+    for (col_cntr = (x_blk_start + BLKSIZE - 1) - x_start; col_cntr > 0; col_cntr--)
+    {
+        pelu = *(Rec_Y_ptr - width);  /* assigning value of pelu2 to
+                        /   pelu */
+        *pelp++ = pelc = *Rec_Y_ptr; /* assigning value of pelc2 to pelc
+                         / and storing this value in pelp
+                         / which will be used   as value of pelu2
+                         / when next row is filtered */
+        pell = *(Rec_Y_ptr + width); /* assigning value of pell2 to pell */
+
+        /* weighted sum of pelu1, pelc1 and pell1  */
+        *sum_V_ptr = pelu + (pelc << 1) + pell;
+        /* sum of 0's and 1's (0 if pixel value is below thr,
+        /1 if value is above thr)  */
+        *sign_V_ptr = INDEX(pelu, thr) + INDEX(pelc, thr) +
+                      INDEX(pell, thr);
+        /* the value of sum1 indicates how many of the 9 pixels'
+        /luminance values are above or equal to thr */
+        sum1 = *(sign_V_ptr - 2) + *(sign_V_ptr - 1) + *sign_V_ptr;
+
+        /* alter the luminance value of pelc1 if all 9 luminance values
+        /are above or equal to thr or if all 9 values are below thr */
+        if (sum1 == 0 || sum1 == 9)
+        {
+            /* sum is a weighted average of the 9 pixel luminance
+            /values   */
+            sum = (*(sum_V_ptr - 2) + (*(sum_V_ptr - 1) << 1) +
+                   *sum_V_ptr + 8) >> 4;
+
+            Rec_Y_ptr--;  /* move pointer back to pelc1  */
+            /* If luminance value of pelc1 is larger than
+            / sum by more than max_diff, then subract max_diff
+            / from luminance value of pelc1*/
+            if ((int)(*Rec_Y_ptr - sum) > max_diff)
+            {
+                sum = *Rec_Y_ptr - max_diff;
+            }
+            /* If luminance value of pelc1 is smaller than
+            / sum by more than max_diff, then add max_diff
+            / to luminance value of pelc1*/
+            else if ((int)(*Rec_Y_ptr - sum) < -max_diff)
+            {
+                sum = *Rec_Y_ptr + max_diff;
+            }
+            *Rec_Y_ptr++ = sum; /* assign value of sum to pelc1
+                         and advance pointer to pelc2 */
+        }
+        Rec_Y_ptr++; /* advance pointer to new value of pelc2
+                 /   old pelc2 is now treated as pelc1*/
+        sum_V_ptr++; /* pointer is advanced so next weighted sum may
+                 /  be saved */
+        sign_V_ptr++; /* pointer is advanced so next sum of 0's and
+                  / 1's may be saved  */
+    }
+
+    /* The nested loops below perform the filtering for the remaining rows */
+
+    addr_v = (y_start + 2) * width;  /* advance addr_v to the next row
+                     /   (corresponding to pell0)*/
+    /* The outer loop steps throught the rows.   */
+    for (row_cntr = (y_blk_start + BLKSIZE) - (y_start + 2); row_cntr > 0; row_cntr--)
+    {
+        Rec_Y_ptr = &Rec_Y[addr_v + x_start]; /* advance pointer to
+            /the old pell0, which has become the new pelc0 */
+        addr_v += width;  /* move addr_v down 1 row */
+        sum_V_ptr = &sum_v[0];  /* re-initializing pointer */
+        sign_V_ptr = &sign_v[0];  /* re-initilaizing pointer */
+        pelp = &oldrow[0]; /* re-initializing pointer */
+
+        pelu = *pelp; /* setting pelu0 to old value of pelc0 */
+        *pelp++ = pelc = *Rec_Y_ptr;
+        pell = *(Rec_Y_ptr + width);
+        Rec_Y_ptr++;
+        *sum_V_ptr++ = pelu + (pelc << 1) + pell;
+        *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) +
+                        INDEX(pell, thr);
+
+        pelu = *pelp; /* setting pelu1 to old value of pelc1 */
+        *pelp++ = pelc = *Rec_Y_ptr;
+        pell = *(Rec_Y_ptr + width);
+        Rec_Y_ptr++;
+        *sum_V_ptr++ = pelu + (pelc << 1) + pell;
+        *sign_V_ptr++ = INDEX(pelu, thr) + INDEX(pelc, thr) +
+                        INDEX(pell, thr);
+        /* The inner loop steps through the columns */
+        for (col_cntr = (x_blk_start + BLKSIZE - 1) - x_start; col_cntr > 0; col_cntr--)
+        {
+            pelu = *pelp; /* setting pelu2 to old value of pelc2 */
+            *pelp++ = pelc = *Rec_Y_ptr;
+            pell = *(Rec_Y_ptr + width);
+
+            *sum_V_ptr = pelu + (pelc << 1) + pell;
+            *sign_V_ptr = INDEX(pelu, thr) + INDEX(pelc, thr) +
+                          INDEX(pell, thr);
+
+            sum1 = *(sign_V_ptr - 2) + *(sign_V_ptr - 1) + *sign_V_ptr;
+            /* the "if" statement below is the same as the one in
+            / the first loop */
+            if (sum1 == 0 || sum1 == 9)
+            {
+                sum = (*(sum_V_ptr - 2) + (*(sum_V_ptr - 1) << 1) +
+                       *sum_V_ptr + 8) >> 4;
+
+                Rec_Y_ptr--;
+                if ((int)(*Rec_Y_ptr - sum) > max_diff)
+                {
+                    sum = *Rec_Y_ptr - max_diff;
+                }
+                else if ((int)(*Rec_Y_ptr - sum) < -max_diff)
+                {
+                    sum = *Rec_Y_ptr + max_diff;
+                }
+                *Rec_Y_ptr++ = (uint8) sum;
+            }
+            Rec_Y_ptr++;
+            sum_V_ptr++;
+            sign_V_ptr++;
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.cpp
new file mode 100644
index 0000000..37250f3
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.cpp
@@ -0,0 +1,1001 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "bitstream.h"
+#include "mp4dec_lib.h"
+
+
+#define OSCL_DISABLE_WARNING_CONDITIONAL_IS_CONSTANT
+/* to mask the n least significant bits of an integer */
+static const uint32 msk[33] =
+{
+    0x00000000, 0x00000001, 0x00000003, 0x00000007,
+    0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f,
+    0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff,
+    0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff,
+    0x0000ffff, 0x0001ffff, 0x0003ffff, 0x0007ffff,
+    0x000fffff, 0x001fffff, 0x003fffff, 0x007fffff,
+    0x00ffffff, 0x01ffffff, 0x03ffffff, 0x07ffffff,
+    0x0fffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff,
+    0xffffffff
+};
+
+
+/* ======================================================================== */
+/*  Function : BitstreamFillCache()                                         */
+/*  Date     : 08/29/2000                                                   */
+/*  Purpose  : Read more bitstream data into buffer & the 24-byte cache.    */
+/*              This function is different from BitstreamFillBuffer in      */
+/*              that the buffer is the frame-based buffer provided by       */
+/*              the application.                                            */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if successed, PV_FAIL if failed.                  */
+/*  Modified : 4/16/01  : removed return of PV_END_OF_BUFFER                */
+/* ======================================================================== */
+PV_STATUS BitstreamFillCache(BitstreamDecVideo *stream)
+{
+    uint8 *bitstreamBuffer = stream->bitstreamBuffer;
+    uint8 *v;
+    int num_bits, i;
+
+    stream->curr_word |= (stream->next_word >> stream->incnt);   // stream->incnt cannot be 32
+    stream->next_word <<= (31 - stream->incnt);
+    stream->next_word <<= 1;
+    num_bits = stream->incnt_next + stream->incnt;
+    if (num_bits >= 32)
+    {
+        stream->incnt_next -= (32 - stream->incnt);
+        stream->incnt = 32;
+        return PV_SUCCESS;
+    }
+    /* this check can be removed if there is additional extra 4 bytes at the end of the bitstream */
+    v = bitstreamBuffer + stream->read_point;
+
+    if (stream->read_point > stream->data_end_pos - 4)
+    {
+        if (stream->data_end_pos <= stream->read_point)
+        {
+            stream->incnt = num_bits;
+            stream->incnt_next = 0;
+            return PV_SUCCESS;
+        }
+
+        stream->next_word = 0;
+
+        for (i = 0; i < stream->data_end_pos - stream->read_point; i++)
+        {
+            stream->next_word |= (v[i] << ((3 - i) << 3));
+        }
+
+        stream->read_point = stream->data_end_pos;
+        stream->curr_word |= (stream->next_word >> num_bits); // this is safe
+
+        stream->next_word <<= (31 - num_bits);
+        stream->next_word <<= 1;
+        num_bits = i << 3;
+        stream->incnt += stream->incnt_next;
+        stream->incnt_next = num_bits - (32 - stream->incnt);
+        if (stream->incnt_next < 0)
+        {
+            stream->incnt +=  num_bits;
+            stream->incnt_next = 0;
+        }
+        else
+        {
+            stream->incnt = 32;
+        }
+        return PV_SUCCESS;
+    }
+
+    stream->next_word = ((uint32)v[0] << 24) | (v[1] << 16) | (v[2] << 8) | v[3];
+    stream->read_point += 4;
+
+    stream->curr_word |= (stream->next_word >> num_bits); // this is safe
+    stream->next_word <<= (31 - num_bits);
+    stream->next_word <<= 1;
+    stream->incnt_next += stream->incnt;
+    stream->incnt = 32;
+    return PV_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : BitstreamReset()                                             */
+/*  Date     : 08/29/2000                                                   */
+/*  Purpose  : Initialize the bitstream buffer for frame-based decoding.    */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+void BitstreamReset(BitstreamDecVideo *stream, uint8 *buffer, int32 buffer_size)
+{
+    /* set up frame-based bitstream buffer */
+    oscl_memset(stream, 0, sizeof(BitstreamDecVideo));
+    stream->data_end_pos = buffer_size;
+    stream->bitstreamBuffer = buffer;
+}
+
+
+/* ======================================================================== */
+/*  Function : BitstreamOpen()                                              */
+/*  Purpose  : Initialize the bitstream data structure.                     */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int BitstreamOpen(BitstreamDecVideo *stream, int)
+{
+    int buffer_size = 0;
+    /* set up linear bitstream buffer */
+//  stream->currentBytePos = 0;
+    stream->data_end_pos = 0;
+
+    stream->incnt = 0;
+    stream->incnt_next = 0;
+    stream->bitcnt = 0;
+    stream->curr_word = stream->next_word = 0;
+    stream->read_point = stream->data_end_pos;
+    return buffer_size;
+}
+
+
+/* ======================================================================== */
+/*  Function : BitstreamClose()                                             */
+/*  Purpose  : Cleanup the bitstream data structure.                        */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+void BitstreamClose(BitstreamDecVideo *)
+{
+    return;
+}
+
+
+/***********************************************************CommentBegin******
+*
+* -- BitstreamShowBits32HC
+* Shows 32 bits
+***********************************************************CommentEnd********/
+
+PV_STATUS BitstreamShowBits32HC(BitstreamDecVideo *stream, uint32 *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    if (stream->incnt < 32)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word;
+    return status;
+}
+
+/***********************************************************CommentBegin******
+*
+* -- BitstreamShowBits32
+* Shows upto and including 31 bits
+***********************************************************CommentEnd********/
+PV_STATUS BitstreamShowBits32(BitstreamDecVideo *stream, int nbits, uint32 *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    if (stream->incnt < nbits)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word >> (32 - nbits);
+    return status;
+}
+
+
+#ifndef PV_BS_INLINE
+/*========================================================================= */
+/*  Function:   BitstreamShowBits16()                                       */
+/*  Date:       12/18/2000                                                  */
+/*  Purpose:    To see the next "nbits"(nbits<=16) bitstream bits           */
+/*              without advancing the read pointer                          */
+/*                                                                          */
+/* =========================================================================*/
+PV_STATUS BitstreamShowBits16(BitstreamDecVideo *stream, int nbits, uint *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+
+    if (stream->incnt < nbits)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+
+    *code = stream->curr_word >> (32 - nbits);
+    return status;
+}
+
+
+/*========================================================================= */
+/*  Function:   BitstreamShow15Bits()                                       */
+/*  Date:       01/23/2001                                                  */
+/*  Purpose:    To see the next 15 bitstream bits                           */
+/*              without advancing the read pointer                          */
+/*                                                                          */
+/* =========================================================================*/
+PV_STATUS BitstreamShow15Bits(BitstreamDecVideo *stream, uint *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    if (stream->incnt < 15)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word >> 17;
+    return status;
+}
+/*========================================================================= */
+/*  Function: BitstreamShow13Bits                                           */
+/*  Date:       050923                                              */
+/*  Purpose:    Faciliate and speed up showing 13 bit from bitstream        */
+/*              used in VlcTCOEFF decoding                                  */
+/*  Modified:                            */
+/* =========================================================================*/
+PV_STATUS BitstreamShow13Bits(BitstreamDecVideo *stream, uint *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    if (stream->incnt < 13)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    *code = stream->curr_word >> 19;
+    return status;
+}
+
+uint BitstreamReadBits16_INLINE(BitstreamDecVideo *stream, int nbits)
+{
+    uint code;
+    PV_STATUS status;
+
+    if (stream->incnt < nbits)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    code = stream->curr_word >> (32 - nbits);
+    PV_BitstreamFlushBits(stream, nbits);
+    return code;
+}
+
+
+uint BitstreamRead1Bits_INLINE(BitstreamDecVideo *stream)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint    code;
+
+
+    if (stream->incnt < 1)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+    code = stream->curr_word >> 31;
+    PV_BitstreamFlushBits(stream, 1);
+
+    return code;
+}
+
+#endif
+
+/* ======================================================================== */
+/*  Function : BitstreamReadBits16()                                        */
+/*  Purpose  : Read bits (nbits <=16) from bitstream buffer.                */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/* ======================================================================== */
+uint BitstreamReadBits16(BitstreamDecVideo *stream, int nbits)
+{
+    uint code;
+
+    if (stream->incnt < nbits)
+    {
+        /* frame-based decoding */
+        BitstreamFillCache(stream);
+    }
+    code = stream->curr_word >> (32 - nbits);
+    PV_BitstreamFlushBits(stream, nbits);
+    return code;
+}
+
+/* ======================================================================== */
+/*  Function : BitstreamRead1Bits()                                         */
+/*  Date     : 10/23/2000                                                   */
+/*  Purpose  : Faciliate and speed up reading 1 bit from bitstream.         */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/* ======================================================================== */
+
+uint BitstreamRead1Bits(BitstreamDecVideo *stream)
+{
+    uint    code;
+
+    if (stream->incnt < 1)
+    {
+        /* frame-based decoding */
+        BitstreamFillCache(stream);
+    }
+    code = stream->curr_word >> 31;
+    PV_BitstreamFlushBits(stream, 1);
+
+    return code;
+}
+
+/* ======================================================================== */
+/*  Function : PV_BitstreamFlushBitsCheck()                                 */
+/*  Purpose  : Flush nbits bits from bitstream buffer. Check for cache      */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+PV_STATUS PV_BitstreamFlushBitsCheck(BitstreamDecVideo *stream, int nbits)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    stream->bitcnt += nbits;
+    stream->incnt -= nbits;
+    if (stream->incnt < 0)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+
+        if (stream->incnt < 0)
+        {
+            stream->bitcnt += stream->incnt;
+            stream->incnt = 0;
+        }
+    }
+    stream->curr_word <<= nbits;
+    return status;
+}
+
+/* ======================================================================== */
+/*  Function : BitstreamReadBits32()                                        */
+/*  Purpose  : Read bits from bitstream buffer.                             */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/* ======================================================================== */
+uint32 BitstreamReadBits32(BitstreamDecVideo *stream, int nbits)
+{
+    uint32 code;
+
+    if (stream->incnt < nbits)
+    {
+        /* frame-based decoding */
+        BitstreamFillCache(stream);
+    }
+    code = stream->curr_word >> (32 - nbits);
+    PV_BitstreamFlushBits(stream, nbits);
+    return code;
+}
+
+uint32 BitstreamReadBits32HC(BitstreamDecVideo *stream)
+{
+    uint32 code;
+
+    BitstreamShowBits32HC(stream, &code);
+    stream->bitcnt += 32;
+    stream->incnt = 0;
+    stream->curr_word = 0;
+    return code;
+}
+
+/* ======================================================================== */
+/*  Function : BitstreamCheckEndBuffer()                                    */
+/*  Date     : 03/30/2001                                                   */
+/*  Purpose  : Check to see if we are at the end of buffer                  */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+PV_STATUS BitstreamCheckEndBuffer(BitstreamDecVideo *stream)
+{
+    if (stream->read_point >= stream->data_end_pos && stream->incnt <= 0) return PV_END_OF_VOP;
+    return PV_SUCCESS;
+}
+
+
+PV_STATUS PV_BitstreamShowBitsByteAlign(BitstreamDecVideo *stream, int nbits, uint32 *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    int n_stuffed;
+
+    n_stuffed = 8 - (stream->bitcnt & 0x7); /*  07/05/01 */
+
+    if (stream->incnt < (nbits + n_stuffed))
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+
+    *code = (stream->curr_word << n_stuffed) >> (32 - nbits);
+    return status;
+}
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+PV_STATUS PV_BitstreamShowBitsByteAlignNoForceStuffing(BitstreamDecVideo *stream, int nbits, uint32 *code)
+{
+    PV_STATUS status = PV_SUCCESS;
+
+    int n_stuffed;
+
+    n_stuffed = (8 - (stream->bitcnt & 0x7)) & 7;
+
+    if (stream->incnt < (nbits + n_stuffed))
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+
+    *code = (stream->curr_word << n_stuffed) >> (32 - nbits);
+    return status;
+}
+#endif
+
+PV_STATUS PV_BitstreamByteAlign(BitstreamDecVideo *stream)
+{
+    PV_STATUS status = PV_SUCCESS;
+    int n_stuffed;
+
+    n_stuffed = 8 - (stream->bitcnt & 0x7); /*  07/05/01 */
+
+    /* We have to make sure we have enough bits in the cache.   08/15/2000 */
+    if (stream->incnt < n_stuffed)
+    {
+        /* frame-based decoding */
+        status = BitstreamFillCache(stream);
+    }
+
+
+    stream->bitcnt += n_stuffed;
+    stream->incnt -= n_stuffed;
+    stream->curr_word <<= n_stuffed;
+    if (stream->incnt < 0)
+    {
+        stream->bitcnt += stream->incnt;
+        stream->incnt = 0;
+    }
+    return status;
+}
+
+
+PV_STATUS BitstreamByteAlignNoForceStuffing(BitstreamDecVideo *stream)
+{
+    uint n_stuffed;
+
+    n_stuffed = (8 - (stream->bitcnt & 0x7)) & 0x7; /*  07/05/01 */
+
+    stream->bitcnt += n_stuffed;
+    stream->incnt -= n_stuffed;
+
+    if (stream->incnt < 0)
+    {
+        stream->bitcnt += stream->incnt;
+        stream->incnt = 0;
+    }
+    stream->curr_word <<= n_stuffed;
+    return PV_SUCCESS;
+}
+
+
+/* ==================================================================== */
+/*  Function : getPointer()                                             */
+/*  Date     : 10/98                                                    */
+/*  Purpose  : get current position of file pointer                     */
+/*  In/out   :                                                          */
+/*  Return   :                                                          */
+/* ==================================================================== */
+int32 getPointer(BitstreamDecVideo *stream)
+{
+    return stream->bitcnt;
+}
+
+
+
+
+/* ====================================================================== /
+Function : movePointerTo()
+Date     : 05/14/2004
+Purpose  : move bitstream pointer to a desired position
+In/out   :
+Return   :
+Modified :
+/ ====================================================================== */
+PV_STATUS movePointerTo(BitstreamDecVideo *stream, int32 pos)
+{
+    int32 byte_pos;
+    if (pos < 0)
+    {
+        pos = 0;
+    }
+
+    byte_pos = pos >> 3;
+
+    if (byte_pos > stream->data_end_pos)
+    {
+        byte_pos = stream->data_end_pos;
+    }
+
+    stream->read_point = byte_pos & -4;
+    stream->bitcnt = stream->read_point << 3;;
+    stream->curr_word = 0;
+    stream->next_word = 0;
+    stream->incnt = 0;
+    stream->incnt_next = 0;
+    BitstreamFillCache(stream);
+    PV_BitstreamFlushBits(stream, ((pos & 0x7) + ((byte_pos & 0x3) << 3)));
+    return PV_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : validStuffing()                                              */
+/*  Date     : 04/11/2000                                                   */
+/*  Purpose  : Check whether we have valid stuffing at current position.    */
+/*  In/out   :                                                              */
+/*  Return   : PV_TRUE if successed, PV_FALSE if failed.                    */
+/*  Modified : 12/18/2000 : changed the pattern type to uint    */
+/*             04/01/2001 : removed PV_END_OF_BUFFER                        */
+/* ======================================================================== */
+Bool validStuffing(BitstreamDecVideo *stream)
+{
+    uint n_stuffed;
+    uint pattern;
+
+
+    n_stuffed = 8 - (stream->bitcnt & 0x7);
+    BitstreamShowBits16(stream, n_stuffed, &pattern);
+    if (pattern == msk[n_stuffed-1]) return PV_TRUE;
+    return PV_FALSE;
+}
+#ifdef PV_ANNEX_IJKT_SUPPORT
+Bool validStuffing_h263(BitstreamDecVideo *stream)
+{
+    uint n_stuffed;
+    uint pattern;
+
+
+    n_stuffed = (8 - (stream->bitcnt & 0x7)) & 7;  //  stream->incnt % 8
+    if (n_stuffed == 0)
+    {
+        return PV_TRUE;
+    }
+    BitstreamShowBits16(stream, n_stuffed, &pattern);
+    if (pattern == 0) return PV_TRUE;
+    return PV_FALSE;
+}
+#endif
+
+
+/* ======================================================================== */
+/*  Function : PVSearchNextH263Frame()                                      */
+/*  Date     : 04/08/2005                                                   */
+/*  Purpose  : search for 0x00 0x00 0x80                                    */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if succeeded  or PV_END_OF_VOP if failed          */
+/*  Modified :                                                              */
+/* ======================================================================== */
+PV_STATUS PVSearchNextH263Frame(BitstreamDecVideo *stream)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint8 *ptr;
+    int32 i;
+    int32 initial_byte_aligned_position = (stream->bitcnt + 7) >> 3;
+
+    ptr = stream->bitstreamBuffer + initial_byte_aligned_position;
+
+    i = PVLocateH263FrameHeader(ptr, stream->data_end_pos - initial_byte_aligned_position);
+    if (stream->data_end_pos <= initial_byte_aligned_position + i)
+    {
+        status = PV_END_OF_VOP;
+    }
+    (void)movePointerTo(stream, ((i + initial_byte_aligned_position) << 3)); /* ptr + i */
+    return status;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVSearchNextM4VFrame()                                       */
+/*  Date     : 04/08/2005                                                   */
+/*  Purpose  : search for 0x00 0x00 0x01 and move the pointer to the        */
+/*  beginning of the start code                                             */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if succeeded  or PV_END_OF_VOP if failed          */
+/*  Modified :                                                              */
+/* ======================================================================== */
+
+PV_STATUS PVSearchNextM4VFrame(BitstreamDecVideo *stream)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint8 *ptr;
+    int32 i;
+    int32 initial_byte_aligned_position = (stream->bitcnt + 7) >> 3;
+
+    ptr = stream->bitstreamBuffer + initial_byte_aligned_position;
+
+    i = PVLocateFrameHeader(ptr, stream->data_end_pos - initial_byte_aligned_position);
+    if (stream->data_end_pos <= initial_byte_aligned_position + i)
+    {
+        status = PV_END_OF_VOP;
+    }
+    (void)movePointerTo(stream, ((i + initial_byte_aligned_position) << 3)); /* ptr + i */
+    return status;
+}
+
+
+
+void PVLocateM4VFrameBoundary(BitstreamDecVideo *stream)
+{
+    uint8 *ptr;
+    int32 byte_pos = (stream->bitcnt >> 3);
+
+    stream->searched_frame_boundary = 1;
+    ptr = stream->bitstreamBuffer + byte_pos;
+
+    stream->data_end_pos = PVLocateFrameHeader(ptr, (int32)stream->data_end_pos - byte_pos) + byte_pos;
+}
+
+void PVLocateH263FrameBoundary(BitstreamDecVideo *stream)
+{
+    uint8 *ptr;
+    int32 byte_pos = (stream->bitcnt >> 3);
+
+    stream->searched_frame_boundary = 1;
+    ptr = stream->bitstreamBuffer + byte_pos;
+
+    stream->data_end_pos = PVLocateH263FrameHeader(ptr, (int32)stream->data_end_pos - byte_pos) + byte_pos;
+}
+
+/* ======================================================================== */
+/*  Function : quickSearchVideoPacketHeader()               */
+/*  Date     : 05/08/2000                           */
+/*  Purpose  : Quick search for the next video packet header        */
+/*  In/out   :                              */
+/*  Return   : PV_TRUE if successed, PV_FALSE if failed.            */
+/*  Modified :                              */
+/* ======================================================================== */
+PV_STATUS quickSearchVideoPacketHeader(BitstreamDecVideo *stream, int marker_length)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint32 tmpvar;
+
+
+    if (stream->searched_frame_boundary == 0)
+    {
+        PVLocateM4VFrameBoundary(stream);
+    }
+
+    do
+    {
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) break;
+        PV_BitstreamShowBitsByteAlign(stream, marker_length, &tmpvar);
+        if (tmpvar == RESYNC_MARKER) break;
+        PV_BitstreamFlushBits(stream, 8);
+    }
+    while (status == PV_SUCCESS);
+
+    return status;
+}
+#ifdef PV_ANNEX_IJKT_SUPPORT
+PV_STATUS quickSearchH263SliceHeader(BitstreamDecVideo *stream)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint32 tmpvar;
+
+
+    if (stream->searched_frame_boundary == 0)
+    {
+        PVLocateH263FrameBoundary(stream);
+    }
+
+    do
+    {
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) break;
+        PV_BitstreamShowBitsByteAlignNoForceStuffing(stream, 17, &tmpvar);
+        if (tmpvar == RESYNC_MARKER) break;
+        PV_BitstreamFlushBits(stream, 8);
+    }
+    while (status == PV_SUCCESS);
+
+    return status;
+}
+#endif
+/* ======================================================================== */
+/*          The following functions are for Error Concealment.              */
+/* ======================================================================== */
+
+/****************************************************/
+//  01/22/99 Quick search of Resync Marker
+// (actually the first part of it, i.e. 16 0's and a 1.
+
+/* We are not using the fastest algorithm possible. What this function does is
+to locate 11 consecutive 0's and then check if the 5 bits before them and
+the 1 bit after them are all 1's.
+*/
+
+//  Table used for quick search of markers. Gives the last `1' in
+// 4 bits. The MSB is bit #1, the LSB is bit #4.
+const int lastOne[] =
+{
+    0,  4,  3,  4,  2,  4,  3,  4,
+    1,  4,  3,  4,  2,  4,  3,  4
+};
+
+//  Table used for quick search of markers. Gives the last `0' in
+// 4 bits. The MSB is bit #1, the LSB is bit #4.
+/*const int lastZero[]=
+{
+    4,  3,  4,  2,  4,  3,  4,  1,
+        4,  3,  4,  2,  4,  3,  4,  0
+};
+*/
+//  Table used for quick search of markers. Gives the first `0' in
+// 4 bits. The MSB is bit #1, the LSB is bit #4.
+const int firstZero[] =
+{
+    1, 1, 1, 1, 1, 1, 1, 1,
+    2, 2, 2, 2, 3, 3, 4, 0
+};
+
+//  Table used for quick search of markers. Gives the first `1' in
+// 4 bits. The MSB is bit #1, the LSB is bit #4.
+const int firstOne[] =
+{
+    0, 4, 3, 3, 2, 2, 2, 2,
+    1, 1, 1, 1, 1, 1, 1, 1
+};
+
+
+/* ======================================================================== */
+/*  Function : quickSearchMarkers()                                         */
+/*  Date     : 01/25/99                                                     */
+/*  Purpose  : Quick search for Motion marker                               */
+/*  In/out   :                                                              */
+/*  Return   : Boolean true of false                                        */
+/*  Modified : 12/18/2000 : 32-bit version                    */
+/* ======================================================================== */
+PV_STATUS quickSearchMotionMarker(BitstreamDecVideo *stream)
+// MM: (11111000000000001)
+{
+    PV_STATUS status;
+    uint32 tmpvar, tmpvar2;
+
+    if (stream->searched_frame_boundary == 0)
+    {
+        PVLocateM4VFrameBoundary(stream);
+    }
+
+    while (TRUE)
+    {
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) return PV_END_OF_VOP;
+
+        BitstreamShowBits32(stream, 17, &tmpvar);
+        if (!tmpvar) return PV_FAIL;
+
+        if (tmpvar & 1) //  Check if the 17th bit from the curr bit pos is a '1'
+        {
+            if (tmpvar == MOTION_MARKER_COMB)
+            {
+                return PV_SUCCESS; //  Found
+            }
+            else
+            {
+                tmpvar >>= 1;
+                tmpvar &= 0xF;
+                PV_BitstreamFlushBits(stream, (int)(12 + firstZero[tmpvar]));
+            }
+        }
+        else
+        {
+            //  01/25/99 Get the first 16 bits
+            tmpvar >>= 1;
+            tmpvar2 = tmpvar & 0xF;
+
+            //  01/26/99 Check bits #13 ~ #16
+            if (tmpvar2)
+            {
+                PV_BitstreamFlushBits(stream, (int)(7 + lastOne[tmpvar2]));
+            }
+            else
+            {
+                tmpvar >>= 4;
+                tmpvar2 = tmpvar & 0xF;
+
+                //  01/26/99 Check bits #9 ~ #12
+                if (tmpvar2)
+                {
+                    PV_BitstreamFlushBits(stream, (int)(3 + lastOne[tmpvar2]));
+                }
+                else
+                {
+                    tmpvar >>= 4;
+                    tmpvar2 = tmpvar & 0xF;
+
+                    //  01/26/99 Check bits #5 ~ #8
+                    // We don't need to check further
+                    // for the first 5 bits should be all 1's
+                    if (lastOne[tmpvar2] < 2)
+                    {
+                        /* we already have too many consecutive 0's. */
+                        /* Go directly pass the last of the 17 bits. */
+                        PV_BitstreamFlushBits(stream, 17);
+                    }
+                    else
+                    {
+                        PV_BitstreamFlushBits(stream, (int)(lastOne[tmpvar2] - 1));
+                    }
+                }
+            }
+        }
+
+    }
+}
+
+/* ======================================================================== */
+/*  Function : quickSearchDCM()                                             */
+/*  Date     : 01/22/99                                                     */
+/*  Purpose  : Quick search for DC Marker                                   */
+/*              We are not using the fastest algorithm possible.  What this */
+/*              function does is to locate 11 consecutive 0's and then      */
+/*              check if the 7 bits before them and the 1 bit after them    */
+/*              are correct.  (actually the first part of it, i.e. 16 0's   */
+/*              and a 1.                                                    */
+/*  In/out   :                                                              */
+/*  Return   : Boolean true of false                                        */
+/*  Modified : 12/18/2000 : 32-bit version                    */
+/* ======================================================================== */
+PV_STATUS quickSearchDCM(BitstreamDecVideo *stream)
+// DCM: (110 1011 0000 0000 0001)
+{
+    PV_STATUS status;
+    uint32 tmpvar, tmpvar2;
+
+    if (stream->searched_frame_boundary == 0)
+    {
+        PVLocateM4VFrameBoundary(stream);
+    }
+
+    while (TRUE)
+    {
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) return PV_END_OF_VOP;
+        BitstreamShowBits32(stream, 19, &tmpvar);
+
+        if (tmpvar & 1) //  Check if the 17th bit from the curr bit pos is a '1'
+        {
+            if (tmpvar == DC_MARKER)
+            {
+                return PV_SUCCESS; //  Found
+            }
+            else
+            {
+                //  01/25/99 We treat the last of the 19 bits as its 7th bit (which is
+                // also a `1'
+                PV_BitstreamFlushBits(stream, 12);
+            }
+        }
+        else
+        {
+            tmpvar >>= 1;
+            tmpvar2 = tmpvar & 0xF;
+
+            if (tmpvar2)
+            {
+                PV_BitstreamFlushBits(stream, (int)(7 + lastOne[tmpvar2]));
+            }
+            else
+            {
+                tmpvar >>= 4;
+                tmpvar2 = tmpvar & 0xF;
+                if (tmpvar2)
+                {
+                    PV_BitstreamFlushBits(stream, (int)(3 + lastOne[tmpvar2]));
+                }
+                else
+                {
+                    tmpvar >>= 4;
+                    tmpvar2 = tmpvar & 0xF;
+                    if (lastOne[tmpvar2] < 2)
+                    {
+                        /* we already have too many consecutive 0's. */
+                        /* Go directly pass the last of the 17 bits. */
+                        PV_BitstreamFlushBits(stream, 19);
+                    }
+                    else
+                    {
+                        PV_BitstreamFlushBits(stream, (int)(lastOne[tmpvar2] - 1));
+                    }
+                }
+            }
+        }
+    }
+}
+
+/* ======================================================================== */
+/*  Function : quickSearchGOBHeader()   0000 0000 0000 0000 1               */
+/*  Date     : 07/06/01                                                     */
+/*  Purpose  : Quick search of GOBHeader (not byte aligned)                 */
+/*  In/out   :                                                              */
+/*  Return   : Integer value indicates type of marker found                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+PV_STATUS quickSearchGOBHeader(BitstreamDecVideo *stream)
+{
+    PV_STATUS status;
+    int byte0, byte1, byte2, shift, tmpvar;
+
+    BitstreamByteAlignNoForceStuffing(stream);
+
+    if (stream->searched_frame_boundary == 0)
+    {
+        PVLocateH263FrameBoundary(stream);
+    }
+
+    while (TRUE)
+    {
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) return PV_END_OF_VOP;
+
+        if (stream->incnt < 24)
+        {
+            status = BitstreamFillCache(stream);
+        }
+
+
+        byte1 = (stream->curr_word << 8) >> 24;
+        if (byte1 == 0)
+        {
+            byte2 = (stream->curr_word << 16) >> 24;
+            if (byte2)
+            {
+                tmpvar = byte2 >> 4;
+
+                if (tmpvar)
+                {
+                    shift = 9 - firstOne[tmpvar];
+                }
+                else
+                {
+                    shift = 5 - firstOne[byte2];
+                }
+                byte0 = stream->curr_word >> 24;
+                if ((byte0 & msk[shift]) == 0)
+                {
+                    PV_BitstreamFlushBits(stream, 8 - shift);
+                    return PV_SUCCESS;
+                }
+                PV_BitstreamFlushBits(stream, 8);    /* third_byte is not zero */
+            }
+        }
+
+        PV_BitstreamFlushBits(stream, 8);
+    }
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.h b/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.h
new file mode 100644
index 0000000..d52fa87
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/bitstream.h
@@ -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.
+ * -------------------------------------------------------------------
+ */
+
+#ifndef _BITSTREAM_D_H_
+#define _BITSTREAM_D_H_
+
+#include "mp4dec_lib.h" /* video decoder function prototypes */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#define PV_BS_INLINE  /* support inline bitstream functions */
+
+#define PV_BitstreamFlushBits(A,B)  {(A)->bitcnt += (B); (A)->incnt -= (B); (A)->curr_word <<= (B);}
+
+    PV_STATUS BitstreamFillBuffer(BitstreamDecVideo *stream);
+    PV_STATUS BitstreamFillCache(BitstreamDecVideo *stream);
+    void BitstreamReset(BitstreamDecVideo *stream, uint8 *buffer, int32 buffer_size);
+    int BitstreamOpen(BitstreamDecVideo *stream, int layer);
+    void BitstreamClose(BitstreamDecVideo *stream);
+
+    PV_STATUS BitstreamShowBits32(BitstreamDecVideo *stream, int nbits, uint32 *code);
+    uint32 BitstreamReadBits32(BitstreamDecVideo *stream, int nbits);
+
+    uint BitstreamReadBits16(BitstreamDecVideo *stream, int nbits);
+    uint BitstreamRead1Bits(BitstreamDecVideo *stream);
+#ifndef PV_BS_INLINE
+    PV_STATUS BitstreamShowBits16(BitstreamDecVideo *stream, int nbits, uint *code);
+    PV_STATUS BitstreamShow15Bits(BitstreamDecVideo *stream, uint *code);
+    PV_STATUS BitstreamShow13Bits(BitstreamDecVideo *stream, uint *code);
+    uint BitstreamReadBits16_INLINE(BitstreamDecVideo *stream, int nbits);
+    uint BitstreamRead1Bits_INLINE(BitstreamDecVideo *stream);
+#else
+    __inline PV_STATUS BitstreamShowBits16(BitstreamDecVideo *stream, int nbits, uint *code)
+    {
+        PV_STATUS status = PV_SUCCESS;
+
+
+        if (stream->incnt < nbits)
+        {
+            /* frame-based decoding */
+            status = BitstreamFillCache(stream);
+        }
+
+        *code = stream->curr_word >> (32 - nbits);
+        return status;
+    }
+
+
+
+    /* =========================================================================*/
+    __inline PV_STATUS BitstreamShow15Bits(BitstreamDecVideo *stream, uint *code)
+    {
+        PV_STATUS status = PV_SUCCESS;
+
+        if (stream->incnt < 15)
+        {
+            /* frame-based decoding */
+            status = BitstreamFillCache(stream);
+        }
+        *code = stream->curr_word >> 17;
+        return status;
+    }
+
+
+    __inline PV_STATUS BitstreamShow13Bits(BitstreamDecVideo *stream, uint *code)
+    {
+        PV_STATUS status = PV_SUCCESS;
+
+        if (stream->incnt < 13)
+        {
+            /* frame-based decoding */
+            status = BitstreamFillCache(stream);
+        }
+        *code = stream->curr_word >> 19;
+        return status;
+    }
+    __inline uint BitstreamReadBits16_INLINE(BitstreamDecVideo *stream, int nbits)
+    {
+        uint code;
+
+        if (stream->incnt < nbits)
+        {
+            /* frame-based decoding */
+            BitstreamFillCache(stream);
+        }
+        code = stream->curr_word >> (32 - nbits);
+        PV_BitstreamFlushBits(stream, nbits);
+        return code;
+    }
+
+
+    __inline uint BitstreamRead1Bits_INLINE(BitstreamDecVideo *stream)
+    {
+        uint    code;
+
+        if (stream->incnt < 1)
+        {
+            /* frame-based decoding */
+            BitstreamFillCache(stream);
+        }
+        code = stream->curr_word >> 31;
+        PV_BitstreamFlushBits(stream, 1);
+
+        return code;
+    }
+
+#endif
+
+
+
+
+
+
+
+    PV_STATUS PV_BitstreamFlushBitsCheck(BitstreamDecVideo *stream, int nbits);
+
+    uint32 BitstreamReadBits32HC(BitstreamDecVideo *stream);
+    PV_STATUS BitstreamShowBits32HC(BitstreamDecVideo *stream, uint32 *code);
+
+
+
+    PV_STATUS BitstreamCheckEndBuffer(BitstreamDecVideo *stream);
+
+    PV_STATUS PV_BitstreamShowBitsByteAlign(BitstreamDecVideo *stream, int nbits, uint32 *code);
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    PV_STATUS PV_BitstreamShowBitsByteAlignNoForceStuffing(BitstreamDecVideo *stream, int nbits, uint32 *code);
+    Bool validStuffing_h263(BitstreamDecVideo *stream);
+    PV_STATUS quickSearchH263SliceHeader(BitstreamDecVideo *stream);
+#endif
+    PV_STATUS PV_BitstreamByteAlign(BitstreamDecVideo *stream);
+    PV_STATUS BitstreamByteAlignNoForceStuffing(BitstreamDecVideo *stream);
+    Bool validStuffing(BitstreamDecVideo *stream);
+
+    PV_STATUS movePointerTo(BitstreamDecVideo *stream, int32 pos);
+    PV_STATUS PVSearchNextM4VFrame(BitstreamDecVideo *stream);
+    PV_STATUS PVSearchNextH263Frame(BitstreamDecVideo *stream);
+    PV_STATUS quickSearchVideoPacketHeader(BitstreamDecVideo *stream, int marker_length);
+
+
+    /* for error concealment & soft-decoding */
+    void PVLocateM4VFrameBoundary(BitstreamDecVideo *stream);
+    void PVSearchH263FrameBoundary(BitstreamDecVideo *stream);
+
+    PV_STATUS quickSearchMotionMarker(BitstreamDecVideo *stream);
+    PV_STATUS quickSearchDCM(BitstreamDecVideo *stream);
+    PV_STATUS quickSearchGOBHeader(BitstreamDecVideo *stream);
+    void BitstreamShowBuffer(BitstreamDecVideo *stream, int32 startbit, int32 endbit, uint8 *bitBfr);
+
+    /*  10/8/98 New prototyps. */
+    int32 getPointer(BitstreamDecVideo *stream);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus  */
+
+#endif /* _BITSTREAM_D_H_ */
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp
new file mode 100644
index 0000000..a75483a
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/block_idct.cpp
@@ -0,0 +1,911 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ 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 "mp4dec_lib.h"
+#include "idct.h"
+#include "motion_comp.h"
+
+#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+/* private prototypes */
+static void idctrow(int16 *blk, uint8 *pred, uint8 *dst, int width);
+static void idctrow_intra(int16 *blk, PIXEL *, int width);
+static void idctcol(int16 *blk);
+
+#ifdef FAST_IDCT
+// mapping from nz_coefs to functions to be used
+
+
+// ARM4 does not allow global data when they are not constant hence
+// an array of function pointers cannot be considered as array of constants
+// (actual addresses are only known when the dll is loaded).
+// So instead of arrays of function pointers, we'll store here
+// arrays of rows or columns and then call the idct function
+// corresponding to such the row/column number:
+
+
+static void (*const idctcolVCA[10][4])(int16*) =
+{
+    {&idctcol1, &idctcol0, &idctcol0, &idctcol0},
+    {&idctcol1, &idctcol1, &idctcol0, &idctcol0},
+    {&idctcol2, &idctcol1, &idctcol0, &idctcol0},
+    {&idctcol3, &idctcol1, &idctcol0, &idctcol0},
+    {&idctcol3, &idctcol2, &idctcol0, &idctcol0},
+    {&idctcol3, &idctcol2, &idctcol1, &idctcol0},
+    {&idctcol3, &idctcol2, &idctcol1, &idctcol1},
+    {&idctcol3, &idctcol2, &idctcol2, &idctcol1},
+    {&idctcol3, &idctcol3, &idctcol2, &idctcol1},
+    {&idctcol4, &idctcol3, &idctcol2, &idctcol1}
+};
+
+
+static void (*const idctrowVCA[10])(int16*, uint8*, uint8*, int) =
+{
+    &idctrow1,
+    &idctrow2,
+    &idctrow2,
+    &idctrow2,
+    &idctrow2,
+    &idctrow3,
+    &idctrow4,
+    &idctrow4,
+    &idctrow4,
+    &idctrow4
+};
+
+
+static void (*const idctcolVCA2[16])(int16*) =
+{
+    &idctcol0, &idctcol4, &idctcol3, &idctcol4,
+    &idctcol2, &idctcol4, &idctcol3, &idctcol4,
+    &idctcol1, &idctcol4, &idctcol3, &idctcol4,
+    &idctcol2, &idctcol4, &idctcol3, &idctcol4
+};
+
+static void (*const idctrowVCA2[8])(int16*, uint8*, uint8*, int) =
+{
+    &idctrow1, &idctrow4, &idctrow3, &idctrow4,
+    &idctrow2, &idctrow4, &idctrow3, &idctrow4
+};
+
+static void (*const idctrowVCA_intra[10])(int16*, PIXEL *, int) =
+{
+    &idctrow1_intra,
+    &idctrow2_intra,
+    &idctrow2_intra,
+    &idctrow2_intra,
+    &idctrow2_intra,
+    &idctrow3_intra,
+    &idctrow4_intra,
+    &idctrow4_intra,
+    &idctrow4_intra,
+    &idctrow4_intra
+};
+
+static void (*const idctrowVCA2_intra[8])(int16*, PIXEL *, int) =
+{
+    &idctrow1_intra, &idctrow4_intra, &idctrow3_intra, &idctrow4_intra,
+    &idctrow2_intra, &idctrow4_intra, &idctrow3_intra, &idctrow4_intra
+};
+#endif
+
+/*----------------------------------------------------------------------------
+; 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 MBlockIDCT(VideoDecData *video)
+{
+    Vop *currVop = video->currVop;
+    MacroBlock *mblock = video->mblock;
+    PIXEL *c_comp;
+    PIXEL *cu_comp;
+    PIXEL *cv_comp;
+    int x_pos = video->mbnum_col;
+    int y_pos = video->mbnum_row;
+    int width, width_uv;
+    int32 offset;
+    width = video->width;
+    width_uv = width >> 1;
+    offset = (int32)(y_pos << 4) * width + (x_pos << 4);
+
+    c_comp  = currVop->yChan + offset;
+    cu_comp = currVop->uChan + (offset >> 2) + (x_pos << 2);
+    cv_comp = currVop->vChan + (offset >> 2) + (x_pos << 2);
+
+    BlockIDCT_intra(mblock, c_comp, 0, width);
+    BlockIDCT_intra(mblock, c_comp + 8, 1, width);
+    BlockIDCT_intra(mblock, c_comp + (width << 3), 2, width);
+    BlockIDCT_intra(mblock, c_comp + (width << 3) + 8, 3, width);
+    BlockIDCT_intra(mblock, cu_comp, 4, width_uv);
+    BlockIDCT_intra(mblock, cv_comp, 5, width_uv);
+}
+
+
+void BlockIDCT_intra(
+    MacroBlock *mblock, PIXEL *c_comp, int comp, int width)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int16 *coeff_in = mblock->block[comp];
+#ifdef INTEGER_IDCT
+#ifdef FAST_IDCT  /* VCA IDCT using nzcoefs and bitmaps*/
+    int i, bmapr;
+    int nz_coefs = mblock->no_coeff[comp];
+    uint8 *bitmapcol = mblock->bitmapcol[comp];
+    uint8 bitmaprow = mblock->bitmaprow[comp];
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    if (nz_coefs <= 10)
+    {
+        bmapr = (nz_coefs - 1);
+
+        (*(idctcolVCA[bmapr]))(coeff_in);
+        (*(idctcolVCA[bmapr][1]))(coeff_in + 1);
+        (*(idctcolVCA[bmapr][2]))(coeff_in + 2);
+        (*(idctcolVCA[bmapr][3]))(coeff_in + 3);
+
+        (*idctrowVCA_intra[nz_coefs-1])(coeff_in, c_comp, width);
+    }
+    else
+    {
+        i = 8;
+        while (i--)
+        {
+            bmapr = (int)bitmapcol[i];
+            if (bmapr)
+            {
+                if ((bmapr&0xf) == 0)         /*  07/18/01 */
+                {
+                    (*(idctcolVCA2[bmapr>>4]))(coeff_in + i);
+                }
+                else
+                {
+                    idctcol(coeff_in + i);
+                }
+            }
+        }
+        if ((bitmapcol[4] | bitmapcol[5] | bitmapcol[6] | bitmapcol[7]) == 0)
+        {
+            bitmaprow >>= 4;
+            (*(idctrowVCA2_intra[(int)bitmaprow]))(coeff_in, c_comp, width);
+        }
+        else
+        {
+            idctrow_intra(coeff_in, c_comp, width);
+        }
+    }
+#else
+    void idct_intra(int *block, uint8 *comp, int width);
+    idct_intra(coeff_in, c_comp, width);
+#endif
+#else
+    void idctref_intra(int *block, uint8 *comp, int width);
+    idctref_intra(coeff_in, c_comp, width);
+#endif
+
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+/*  08/04/05, no residue, just copy from pred to output */
+void Copy_Blk_to_Vop(uint8 *dst, uint8 *pred, int width)
+{
+    /* copy 4 bytes at a time */
+    width -= 4;
+    *((uint32*)dst) = *((uint32*)pred);
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+    *((uint32*)(dst += width)) = *((uint32*)(pred += 12));
+    *((uint32*)(dst += 4)) = *((uint32*)(pred += 4));
+
+    return ;
+}
+
+/*  08/04/05 compute IDCT and add prediction at the end  */
+void BlockIDCT(
+    uint8 *dst,  /* destination */
+    uint8 *pred, /* prediction block, pitch 16 */
+    int16   *coeff_in,  /* DCT data, size 64 */
+    int width, /* width of dst */
+    int nz_coefs,
+    uint8 *bitmapcol,
+    uint8 bitmaprow
+)
+{
+#ifdef INTEGER_IDCT
+#ifdef FAST_IDCT  /* VCA IDCT using nzcoefs and bitmaps*/
+    int i, bmapr;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    if (nz_coefs <= 10)
+    {
+        bmapr = (nz_coefs - 1);
+        (*(idctcolVCA[bmapr]))(coeff_in);
+        (*(idctcolVCA[bmapr][1]))(coeff_in + 1);
+        (*(idctcolVCA[bmapr][2]))(coeff_in + 2);
+        (*(idctcolVCA[bmapr][3]))(coeff_in + 3);
+
+        (*idctrowVCA[nz_coefs-1])(coeff_in, pred, dst, width);
+        return ;
+    }
+    else
+    {
+        i = 8;
+
+        while (i--)
+        {
+            bmapr = (int)bitmapcol[i];
+            if (bmapr)
+            {
+                if ((bmapr&0xf) == 0)         /*  07/18/01 */
+                {
+                    (*(idctcolVCA2[bmapr>>4]))(coeff_in + i);
+                }
+                else
+                {
+                    idctcol(coeff_in + i);
+                }
+            }
+        }
+        if ((bitmapcol[4] | bitmapcol[5] | bitmapcol[6] | bitmapcol[7]) == 0)
+        {
+            (*(idctrowVCA2[bitmaprow>>4]))(coeff_in, pred, dst, width);
+        }
+        else
+        {
+            idctrow(coeff_in, pred, dst, width);
+        }
+        return ;
+    }
+#else // FAST_IDCT
+    void idct(int *block, uint8 *pred, uint8 *dst, int width);
+    idct(coeff_in, pred, dst, width);
+    return;
+#endif // FAST_IDCT
+#else // INTEGER_IDCT
+    void idctref(int *block, uint8 *pred, uint8 *dst, int width);
+    idctref(coeff_in, pred, dst, width);
+    return;
+#endif // INTEGER_IDCT
+
+}
+/*----------------------------------------------------------------------------
+;  End Function: block_idct
+----------------------------------------------------------------------------*/
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: idctrow
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS FOR idctrow
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION FOR idctrow
+
+------------------------------------------------------------------------------
+ REQUIREMENTS FOR idctrow
+
+------------------------------------------------------------------------------
+ REFERENCES FOR idctrow
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE FOR idctrow
+
+------------------------------------------------------------------------------
+ RESOURCES USED FOR idctrow
+   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)
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; Function Code FOR idctrow
+----------------------------------------------------------------------------*/
+void idctrow(
+    int16 *blk, uint8 *pred, uint8 *dst, int width
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+    int i = 8;
+    uint32 pred_word, dst_word;
+    int res, res2;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* row (horizontal) IDCT
+    *
+    * 7                       pi         1 dst[k] = sum c[l] * src[l] * cos( -- *
+    * ( k + - ) * l ) l=0                      8          2
+    *
+    * where: c[0]    = 128 c[1..7] = 128*sqrt(2) */
+
+    /* preset the offset, such that we can take advantage pre-offset addressing mode   */
+    width -= 4;
+    dst -= width;
+    pred -= 12;
+    blk -= 8;
+
+    while (i--)
+    {
+        x1 = (int32)blk[12] << 8;
+        blk[12] = 0;
+        x2 = blk[14];
+        blk[14] = 0;
+        x3 = blk[10];
+        blk[10] = 0;
+        x4 = blk[9];
+        blk[9] = 0;
+        x5 = blk[15];
+        blk[15] = 0;
+        x6 = blk[13];
+        blk[13] = 0;
+        x7 = blk[11];
+        blk[11] = 0;
+        x0 = ((*(blk += 8)) << 8) + 8192;
+        blk[0] = 0;   /* for proper rounding in the fourth stage */
+
+        /* first stage */
+        x8 = W7 * (x4 + x5) + 4;
+        x4 = (x8 + (W1 - W7) * x4) >> 3;
+        x5 = (x8 - (W1 + W7) * x5) >> 3;
+        x8 = W3 * (x6 + x7) + 4;
+        x6 = (x8 - (W3 - W5) * x6) >> 3;
+        x7 = (x8 - (W3 + W5) * x7) >> 3;
+
+        /* second stage */
+        x8 = x0 + x1;
+        x0 -= x1;
+        x1 = W6 * (x3 + x2) + 4;
+        x2 = (x1 - (W2 + W6) * x2) >> 3;
+        x3 = (x1 + (W2 - W6) * x3) >> 3;
+        x1 = x4 + x6;
+        x4 -= x6;
+        x6 = x5 + x7;
+        x5 -= x7;
+
+        /* third stage */
+        x7 = x8 + x3;
+        x8 -= x3;
+        x3 = x0 + x2;
+        x0 -= x2;
+        x2 = (181 * (x4 + x5) + 128) >> 8;
+        x4 = (181 * (x4 - x5) + 128) >> 8;
+
+        /* fourth stage */
+        pred_word = *((uint32*)(pred += 12)); /* read 4 bytes from pred */
+
+        res = (x7 + x1) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x3 + x2) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x0 + x4) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x8 + x6) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += width)) = dst_word; /* save 4 bytes to dst */
+
+        pred_word = *((uint32*)(pred += 4)); /* read 4 bytes from pred */
+
+        res = (x8 - x6) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x0 - x4) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x3 - x2) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x7 - x1) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += 4)) = dst_word; /* save 4 bytes to dst */
+    }
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+void idctrow_intra(
+    int16 *blk, PIXEL *comp, int width
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8, temp;
+    int i = 8;
+    int offset = width;
+    int32 word;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* row (horizontal) IDCT
+    *
+    * 7                       pi         1 dst[k] = sum c[l] * src[l] * cos( -- *
+    * ( k + - ) * l ) l=0                      8          2
+    *
+    * where: c[0]    = 128 c[1..7] = 128*sqrt(2) */
+    while (i--)
+    {
+        x1 = (int32)blk[4] << 8;
+        blk[4] = 0;
+        x2 = blk[6];
+        blk[6] = 0;
+        x3 = blk[2];
+        blk[2] = 0;
+        x4 = blk[1];
+        blk[1] = 0;
+        x5 = blk[7];
+        blk[7] = 0;
+        x6 = blk[5];
+        blk[5] = 0;
+        x7 = blk[3];
+        blk[3] = 0;
+#ifndef FAST_IDCT
+        /* shortcut */  /* covered by idctrow1  01/9/2001 */
+        if (!(x1 | x2 | x3 | x4 | x5 | x6 | x7))
+        {
+            blk[0] = blk[1] = blk[2] = blk[3] = blk[4] = blk[5] = blk[6] = blk[7] = (blk[0] + 32) >> 6;
+            return;
+        }
+#endif
+        x0 = ((int32)blk[0] << 8) + 8192;
+        blk[0] = 0;  /* for proper rounding in the fourth stage */
+
+        /* first stage */
+        x8 = W7 * (x4 + x5) + 4;
+        x4 = (x8 + (W1 - W7) * x4) >> 3;
+        x5 = (x8 - (W1 + W7) * x5) >> 3;
+        x8 = W3 * (x6 + x7) + 4;
+        x6 = (x8 - (W3 - W5) * x6) >> 3;
+        x7 = (x8 - (W3 + W5) * x7) >> 3;
+
+        /* second stage */
+        x8 = x0 + x1;
+        x0 -= x1;
+        x1 = W6 * (x3 + x2) + 4;
+        x2 = (x1 - (W2 + W6) * x2) >> 3;
+        x3 = (x1 + (W2 - W6) * x3) >> 3;
+        x1 = x4 + x6;
+        x4 -= x6;
+        x6 = x5 + x7;
+        x5 -= x7;
+
+        /* third stage */
+        x7 = x8 + x3;
+        x8 -= x3;
+        x3 = x0 + x2;
+        x0 -= x2;
+        x2 = (181 * (x4 + x5) + 128) >> 8;
+        x4 = (181 * (x4 - x5) + 128) >> 8;
+
+        /* fourth stage */
+        word = ((x7 + x1) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x3 + x2) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+        temp = ((x0 + x4) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x8 + x6) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp)) = word;
+
+        word = ((x8 - x6) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x0 - x4) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+        temp = ((x3 - x2) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x7 - x1) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp + 4)) = word;
+        comp += offset;
+
+        blk += B_SIZE;
+    }
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+/*----------------------------------------------------------------------------
+; End Function: idctrow
+----------------------------------------------------------------------------*/
+
+
+/****************************************************************************/
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: idctcol
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS FOR idctcol
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION FOR idctcol
+
+------------------------------------------------------------------------------
+ REQUIREMENTS FOR idctcol
+
+------------------------------------------------------------------------------
+ REFERENCES FOR idctcol
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE FOR idctcol
+
+------------------------------------------------------------------------------
+ RESOURCES USED FOR idctcol
+   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)
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; Function Code FOR idctcol
+----------------------------------------------------------------------------*/
+void idctcol(
+    int16 *blk
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* column (vertical) IDCT
+    *
+    * 7                         pi         1 dst[8*k] = sum c[l] * src[8*l] *
+    * cos( -- * ( k + - ) * l ) l=0                        8          2
+    *
+    * where: c[0]    = 1/1024 c[1..7] = (1/1024)*sqrt(2) */
+    x1 = (int32)blk[32] << 11;
+    x2 = blk[48];
+    x3 = blk[16];
+    x4 = blk[8];
+    x5 = blk[56];
+    x6 = blk[40];
+    x7 = blk[24];
+#ifndef FAST_IDCT
+    /* shortcut */        /* covered by idctcolumn1  01/9/2001 */
+    if (!(x1 | x2 | x3 | x4 | x5 | x6 | x7))
+    {
+        blk[0] = blk[8] = blk[16] = blk[24] = blk[32] = blk[40] = blk[48] = blk[56]
+                                              = blk[0] << 3;
+        return;
+    }
+#endif
+
+    x0 = ((int32)blk[0] << 11) + 128;
+
+    /* first stage */
+    x8 = W7 * (x4 + x5);
+    x4 = x8 + (W1 - W7) * x4;
+    x5 = x8 - (W1 + W7) * x5;
+    x8 = W3 * (x6 + x7);
+    x6 = x8 - (W3 - W5) * x6;
+    x7 = x8 - (W3 + W5) * x7;
+
+    /* second stage */
+    x8 = x0 + x1;
+    x0 -= x1;
+    x1 = W6 * (x3 + x2);
+    x2 = x1 - (W2 + W6) * x2;
+    x3 = x1 + (W2 - W6) * x3;
+    x1 = x4 + x6;
+    x4 -= x6;
+    x6 = x5 + x7;
+    x5 -= x7;
+
+    /* third stage */
+    x7 = x8 + x3;
+    x8 -= x3;
+    x3 = x0 + x2;
+    x0 -= x2;
+    x2 = (181 * (x4 + x5) + 128) >> 8;
+    x4 = (181 * (x4 - x5) + 128) >> 8;
+
+    /* fourth stage */
+    blk[0]    = (x7 + x1) >> 8;
+    blk[8] = (x3 + x2) >> 8;
+    blk[16] = (x0 + x4) >> 8;
+    blk[24] = (x8 + x6) >> 8;
+    blk[32] = (x8 - x6) >> 8;
+    blk[40] = (x0 - x4) >> 8;
+    blk[48] = (x3 - x2) >> 8;
+    blk[56] = (x7 - x1) >> 8;
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+/*----------------------------------------------------------------------------
+;  End Function: idctcol
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp
new file mode 100644
index 0000000..85889d3
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/cal_dc_scaler.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This module calculates the DC quantization scale according
+ to the incoming Q and type.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ [List requirements to be satisfied by this module.]
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [List all references used in designing this module.]
+
+------------------------------------------------------------------------------
+ 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    "mp4dec_lib.h"
+#include    "vlc_decode.h"
+#include    "bitstream.h"
+#include    "zigzag.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
+----------------------------------------------------------------------------*/
+int cal_dc_scaler(
+    int QP,
+    int type)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int dc_scaler;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    if (type == LUMINANCE_DC_TYPE)
+    {
+        if (QP > 0 && QP < 5) dc_scaler = 8;
+        else if (QP > 4 && QP < 9) dc_scaler = 2 * QP;
+        else if (QP > 8 && QP < 25) dc_scaler = QP + 8;
+        else dc_scaler = 2 * QP - 16;
+    }
+    else /* if (type == CHROMINANCE_DC_TYPE), there is no other types.  */
+    {
+        if (QP > 0 && QP < 5) dc_scaler = 8;
+        else if (QP > 4 && QP < 25) dc_scaler = (QP + 13) >> 1;
+        else dc_scaler = QP - 6;
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return dc_scaler;
+}
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp
new file mode 100644
index 0000000..6593b48
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/chv_filter.cpp
@@ -0,0 +1,654 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    [input_variable_name] = [description of the input to module, its type
+                 definition, and length (when applicable)]
+
+ Local Stores/Buffers/Pointers Needed:
+    [local_store_name] = [description of the local store, its type
+                  definition, and length (when applicable)]
+    [local_buffer_name] = [description of the local buffer, its type
+                   definition, and length (when applicable)]
+    [local_ptr_name] = [description of the local pointer, its type
+                definition, and length (when applicable)]
+
+ Global Stores/Buffers/Pointers Needed:
+    [global_store_name] = [description of the global store, its type
+                   definition, and length (when applicable)]
+    [global_buffer_name] = [description of the global buffer, its type
+                definition, and length (when applicable)]
+    [global_ptr_name] = [description of the global pointer, its type
+                 definition, and length (when applicable)]
+
+ Outputs:
+    [return_variable_name] = [description of data/pointer returned
+                  by module, its type definition, and length
+                  (when applicable)]
+
+ Pointers and Buffers Modified:
+    [variable_bfr_ptr] points to the [describe where the
+      variable_bfr_ptr points to, its type definition, and length
+      (when applicable)]
+    [variable_bfr] contents are [describe the new contents of
+      variable_bfr]
+
+ Local Stores Modified:
+    [local_store_name] = [describe new contents, its type
+                  definition, and length (when applicable)]
+
+ Global Stores Modified:
+    [global_store_name] = [describe new contents, its type
+                   definition, and length (when applicable)]
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   For fast Deblock filtering
+   Newer version (macroblock based processing)
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+ [List requirements to be satisfied by this module.]
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [List all references used in designing this module.]
+
+------------------------------------------------------------------------------
+ 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    "mp4dec_lib.h"
+#include    "post_proc.h"
+
+#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+//#define FILTER_LEN_8
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef PV_POSTPROC_ON
+
+/*************************************************************************
+    Function prototype : void CombinedHorzVertFilter(   uint8 *rec,
+                                                        int width,
+                                                        int height,
+                                                        int *QP_store,
+                                                        int chr,
+                                                        uint8 *pp_mod)
+    Parameters  :
+        rec     :   pointer to the decoded frame buffer.
+        width   :   width of decoded frame.
+        height  :   height of decoded frame
+        QP_store:   pointer to the array of QP corresponding to the decoded frame.
+                    It had only one value for each MB.
+        chr     :   luma or color indication
+                    == 0 luma
+                    == 1 color
+        pp_mod  :   The semphore used for deblocking
+
+    Remark      :   The function do the deblocking on decoded frames.
+                    First based on the semaphore info., it is divided into hard and soft filtering.
+                    To differentiate real and fake edge, it then check the difference with QP to
+                    decide whether to do the filtering or not.
+
+*************************************************************************/
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void CombinedHorzVertFilter(
+    uint8 *rec,
+    int width,
+    int height,
+    int16 *QP_store,
+    int chr,
+    uint8 *pp_mod)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int br, bc, mbr, mbc;
+    int QP = 1;
+    uint8 *ptr, *ptr_e;
+    int pp_w, pp_h;
+    int brwidth;
+
+    int jVal0, jVal1, jVal2;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    pp_w = (width >> 3);
+    pp_h = (height >> 3);
+
+    for (mbr = 0; mbr < pp_h; mbr += 2)         /* row of blocks */
+    {
+        brwidth = mbr * pp_w;               /* number of blocks above current block row */
+        for (mbc = 0; mbc < pp_w; mbc += 2)     /* col of blocks */
+        {
+            if (!chr)
+                QP = QP_store[(brwidth>>2) + (mbc>>1)]; /* QP is per MB based value */
+
+            /********* for each block **************/
+            /****************** Horiz. Filtering ********************/
+            for (br = mbr + 1; br < mbr + 3; br++)  /* 2x2 blocks */
+            {
+                brwidth += pp_w;                    /* number of blocks above & left current block row */
+                /* the profile on ARM920T shows separate these two boundary check is faster than combine them */
+                if (br < pp_h)                  /* boundary : don't do it on the lowest row block */
+                    for (bc = mbc; bc < mbc + 2; bc++)
+                    {
+                        /****** check boundary for deblocking ************/
+                        if (bc < pp_w)              /* boundary : don't do it on the most right col block */
+                        {
+                            ptr = rec + (brwidth << 6) + (bc << 3);
+                            jVal0 = brwidth + bc;
+                            if (chr)    QP = QP_store[jVal0];
+
+                            ptr_e = ptr + 8;        /* pointer to where the loop ends */
+
+                            if (((pp_mod[jVal0]&0x02)) && ((pp_mod[jVal0-pp_w]&0x02)))
+                            {
+                                /* Horiz Hard filter */
+                                do
+                                {
+                                    jVal0 = *(ptr - width);     /* C */
+                                    jVal1 = *ptr;               /* D */
+                                    jVal2 = jVal1 - jVal0;
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1)))) /* (D-C) compared with 2QP */
+                                    {
+                                        /* differentiate between real and fake edge */
+                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (D+C)/2 */
+                                        *(ptr - width) = (uint8)(jVal0);    /*  C */
+                                        *ptr = (uint8)(jVal0);          /*  D */
+
+                                        jVal0 = *(ptr - (width << 1));      /* B */
+                                        jVal1 = *(ptr + width);         /* E */
+                                        jVal2 = jVal1 - jVal0;      /* E-B */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal0 += ((jVal2 + 3) >> 2);
+                                            jVal1 -= ((jVal2 + 3) >> 2);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
+                                            *(ptr + width) = (uint8)jVal1;          /* store E */
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal0 -= ((3 - jVal2) >> 2);
+                                            jVal1 += ((3 - jVal2) >> 2);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
+                                            *(ptr + width) = (uint8)jVal1;          /* store E */
+                                        }
+
+                                        jVal0 = *(ptr - (width << 1) - width);  /* A */
+                                        jVal1 = *(ptr + (width << 1));      /* F */
+                                        jVal2 = jVal1 - jVal0;              /* (F-A) */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal0 += ((jVal2 + 7) >> 3);
+                                            jVal1 -= ((jVal2 + 7) >> 3);
+                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
+                                            *(ptr + (width << 1)) = (uint8)(jVal1);
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal0 -= ((7 - jVal2) >> 3);
+                                            jVal1 += ((7 - jVal2) >> 3);
+                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
+                                            *(ptr + (width << 1)) = (uint8)(jVal1);
+                                        }
+                                    }/* a3_0 > 2QP */
+                                }
+                                while (++ptr < ptr_e);
+                            }
+                            else   /* Horiz soft filter*/
+                            {
+                                do
+                                {
+                                    jVal0 = *(ptr - width); /* B */
+                                    jVal1 = *ptr;           /* C */
+                                    jVal2 = jVal1 - jVal0;  /* C-B */
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP)))) /* (C-B) compared with QP */
+                                    {
+
+                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (B+C)/2 cannot overflow; ceil() */
+                                        *(ptr - width) = (uint8)(jVal0);    /* B = (B+C)/2 */
+                                        *ptr = (uint8)jVal0;            /* C = (B+C)/2 */
+
+                                        jVal0 = *(ptr - (width << 1));      /* A */
+                                        jVal1 = *(ptr + width);         /* D */
+                                        jVal2 = jVal1 - jVal0;          /* D-A */
+
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= ((jVal2 + 7) >> 3);
+                                            jVal0 += ((jVal2 + 7) >> 3);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /* A */
+                                            *(ptr + width) = (uint8)jVal1;          /* D */
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 += ((7 - jVal2) >> 3);
+                                            jVal0 -= ((7 - jVal2) >> 3);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /* A */
+                                            *(ptr + width) = (uint8)jVal1;          /* D */
+                                        }
+                                    }
+                                }
+                                while (++ptr < ptr_e);
+                            } /* Soft filter*/
+                        }/* boundary checking*/
+                    }/*bc*/
+            }/*br*/
+            brwidth -= (pp_w << 1);
+            /****************** Vert. Filtering ********************/
+            for (br = mbr; br < mbr + 2; br++)
+            {
+                if (br < pp_h)
+                    for (bc = mbc + 1; bc < mbc + 3; bc++)
+                    {
+                        /****** check boundary for deblocking ************/
+                        if (bc < pp_w)
+                        {
+                            ptr = rec + (brwidth << 6) + (bc << 3);
+                            jVal0 = brwidth + bc;
+                            if (chr)    QP = QP_store[jVal0];
+
+                            ptr_e = ptr + (width << 3);
+
+                            if (((pp_mod[jVal0-1]&0x01)) && ((pp_mod[jVal0]&0x01)))
+                            {
+                                /* Vert Hard filter */
+                                do
+                                {
+                                    jVal1 = *ptr;       /* D */
+                                    jVal0 = *(ptr - 1); /* C */
+                                    jVal2 = jVal1 - jVal0;  /* D-C */
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1))))
+                                    {
+                                        jVal1 = (jVal0 + jVal1) >> 1;   /* (C+D)/2 */
+                                        *ptr        =   jVal1;
+                                        *(ptr - 1)  =   jVal1;
+
+                                        jVal1 = *(ptr + 1);     /* E */
+                                        jVal0 = *(ptr - 2);     /* B */
+                                        jVal2 = jVal1 - jVal0;      /* E-B */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= ((jVal2 + 3) >> 2);        /* E = E -(E-B)/4 */
+                                            jVal0 += ((jVal2 + 3) >> 2);        /* B = B +(E-B)/4 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 += ((3 - jVal2) >> 2);        /* E = E -(E-B)/4 */
+                                            jVal0 -= ((3 - jVal2) >> 2);        /* B = B +(E-B)/4 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+                                        }
+
+                                        jVal1 = *(ptr + 2);     /* F */
+                                        jVal0 = *(ptr - 3);     /* A */
+
+                                        jVal2 = jVal1 - jVal0;          /* (F-A) */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= ((jVal2 + 7) >> 3);    /* F -= (F-A)/8 */
+                                            jVal0 += ((jVal2 + 7) >> 3);    /* A += (F-A)/8 */
+                                            *(ptr + 2) = jVal1;
+                                            *(ptr - 3) = jVal0;
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 -= ((jVal2 - 7) >> 3);    /* F -= (F-A)/8 */
+                                            jVal0 += ((jVal2 - 7) >> 3);    /* A += (F-A)/8 */
+                                            *(ptr + 2) = jVal1;
+                                            *(ptr - 3) = jVal0;
+                                        }
+                                    }   /* end of ver hard filetering */
+                                }
+                                while ((ptr += width) < ptr_e);
+                            }
+                            else   /* Vert soft filter*/
+                            {
+                                do
+                                {
+                                    jVal1 = *ptr;               /* C */
+                                    jVal0 = *(ptr - 1);         /* B */
+                                    jVal2 = jVal1 - jVal0;
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP))))
+                                    {
+
+                                        jVal1 = (jVal0 + jVal1 + 1) >> 1;
+                                        *ptr = jVal1;           /* C */
+                                        *(ptr - 1) = jVal1;     /* B */
+
+                                        jVal1 = *(ptr + 1);     /* D */
+                                        jVal0 = *(ptr - 2);     /* A */
+                                        jVal2 = (jVal1 - jVal0);        /* D- A */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= (((jVal2) + 7) >> 3);      /* D -= (D-A)/8 */
+                                            jVal0 += (((jVal2) + 7) >> 3);      /* A += (D-A)/8 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 += ((7 - (jVal2)) >> 3);      /* D -= (D-A)/8 */
+                                            jVal0 -= ((7 - (jVal2)) >> 3);      /* A += (D-A)/8 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+                                        }
+                                    }
+                                }
+                                while ((ptr += width) < ptr_e);
+                            } /* Soft filter*/
+                        } /* boundary*/
+                    } /*bc*/
+                brwidth += pp_w;
+            }/*br*/
+            brwidth -= (pp_w << 1);
+        }/*mbc*/
+        brwidth += (pp_w << 1);
+    }/*mbr*/
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+void CombinedHorzVertFilter_NoSoftDeblocking(
+    uint8 *rec,
+    int width,
+    int height,
+    int16 *QP_store,
+    int chr,
+    uint8 *pp_mod)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int br, bc, mbr, mbc;
+    int QP = 1;
+    uint8 *ptr, *ptr_e;
+    int pp_w, pp_h;
+    int brwidth;
+
+    int jVal0, jVal1, jVal2;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    pp_w = (width >> 3);
+    pp_h = (height >> 3);
+
+    for (mbr = 0; mbr < pp_h; mbr += 2)         /* row of blocks */
+    {
+        brwidth = mbr * pp_w;               /* number of blocks above current block row */
+        for (mbc = 0; mbc < pp_w; mbc += 2)     /* col of blocks */
+        {
+            if (!chr)
+                QP = QP_store[(brwidth>>2) + (mbc>>1)]; /* QP is per MB based value */
+
+            /********* for each block **************/
+            /****************** Horiz. Filtering ********************/
+            for (br = mbr + 1; br < mbr + 3; br++)  /* 2x2 blocks */
+            {
+                brwidth += pp_w;                    /* number of blocks above & left current block row */
+                /* the profile on ARM920T shows separate these two boundary check is faster than combine them */
+                if (br < pp_h)                  /* boundary : don't do it on the lowest row block */
+                    for (bc = mbc; bc < mbc + 2; bc++)
+                    {
+                        /****** check boundary for deblocking ************/
+                        if (bc < pp_w)              /* boundary : don't do it on the most right col block */
+                        {
+                            ptr = rec + (brwidth << 6) + (bc << 3);
+                            jVal0 = brwidth + bc;
+                            if (chr)    QP = QP_store[jVal0];
+
+                            ptr_e = ptr + 8;        /* pointer to where the loop ends */
+
+                            if (((pp_mod[jVal0]&0x02)) && ((pp_mod[jVal0-pp_w]&0x02)))
+                            {
+                                /* Horiz Hard filter */
+                                do
+                                {
+                                    jVal0 = *(ptr - width);     /* C */
+                                    jVal1 = *ptr;               /* D */
+                                    jVal2 = jVal1 - jVal0;
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1)))) /* (D-C) compared with 2QP */
+                                    {
+                                        /* differentiate between real and fake edge */
+                                        jVal0 = ((jVal0 + jVal1) >> 1);     /* (D+C)/2 */
+                                        *(ptr - width) = (uint8)(jVal0);    /*  C */
+                                        *ptr = (uint8)(jVal0);          /*  D */
+
+                                        jVal0 = *(ptr - (width << 1));      /* B */
+                                        jVal1 = *(ptr + width);         /* E */
+                                        jVal2 = jVal1 - jVal0;      /* E-B */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal0 += ((jVal2 + 3) >> 2);
+                                            jVal1 -= ((jVal2 + 3) >> 2);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
+                                            *(ptr + width) = (uint8)jVal1;          /* store E */
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal0 -= ((3 - jVal2) >> 2);
+                                            jVal1 += ((3 - jVal2) >> 2);
+                                            *(ptr - (width << 1)) = (uint8)jVal0;       /*  store B */
+                                            *(ptr + width) = (uint8)jVal1;          /* store E */
+                                        }
+
+                                        jVal0 = *(ptr - (width << 1) - width);  /* A */
+                                        jVal1 = *(ptr + (width << 1));      /* F */
+                                        jVal2 = jVal1 - jVal0;              /* (F-A) */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal0 += ((jVal2 + 7) >> 3);
+                                            jVal1 -= ((jVal2 + 7) >> 3);
+                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
+                                            *(ptr + (width << 1)) = (uint8)(jVal1);
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal0 -= ((7 - jVal2) >> 3);
+                                            jVal1 += ((7 - jVal2) >> 3);
+                                            *(ptr - (width << 1) - width) = (uint8)(jVal0);
+                                            *(ptr + (width << 1)) = (uint8)(jVal1);
+                                        }
+                                    }/* a3_0 > 2QP */
+                                }
+                                while (++ptr < ptr_e);
+                            }
+
+                        }/* boundary checking*/
+                    }/*bc*/
+            }/*br*/
+            brwidth -= (pp_w << 1);
+            /****************** Vert. Filtering ********************/
+            for (br = mbr; br < mbr + 2; br++)
+            {
+                if (br < pp_h)
+                    for (bc = mbc + 1; bc < mbc + 3; bc++)
+                    {
+                        /****** check boundary for deblocking ************/
+                        if (bc < pp_w)
+                        {
+                            ptr = rec + (brwidth << 6) + (bc << 3);
+                            jVal0 = brwidth + bc;
+                            if (chr)    QP = QP_store[jVal0];
+
+                            ptr_e = ptr + (width << 3);
+
+                            if (((pp_mod[jVal0-1]&0x01)) && ((pp_mod[jVal0]&0x01)))
+                            {
+                                /* Vert Hard filter */
+                                do
+                                {
+                                    jVal1 = *ptr;       /* D */
+                                    jVal0 = *(ptr - 1); /* C */
+                                    jVal2 = jVal1 - jVal0;  /* D-C */
+
+                                    if (((jVal2 > 0) && (jVal2 < (QP << 1)))
+                                            || ((jVal2 < 0) && (jVal2 > -(QP << 1))))
+                                    {
+                                        jVal1 = (jVal0 + jVal1) >> 1;   /* (C+D)/2 */
+                                        *ptr        =   jVal1;
+                                        *(ptr - 1)  =   jVal1;
+
+                                        jVal1 = *(ptr + 1);     /* E */
+                                        jVal0 = *(ptr - 2);     /* B */
+                                        jVal2 = jVal1 - jVal0;      /* E-B */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= ((jVal2 + 3) >> 2);        /* E = E -(E-B)/4 */
+                                            jVal0 += ((jVal2 + 3) >> 2);        /* B = B +(E-B)/4 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 += ((3 - jVal2) >> 2);        /* E = E -(E-B)/4 */
+                                            jVal0 -= ((3 - jVal2) >> 2);        /* B = B +(E-B)/4 */
+                                            *(ptr + 1) = jVal1;
+                                            *(ptr - 2) = jVal0;
+                                        }
+
+                                        jVal1 = *(ptr + 2);     /* F */
+                                        jVal0 = *(ptr - 3);     /* A */
+
+                                        jVal2 = jVal1 - jVal0;          /* (F-A) */
+
+                                        if (jVal2 > 0)
+                                        {
+                                            jVal1 -= ((jVal2 + 7) >> 3);    /* F -= (F-A)/8 */
+                                            jVal0 += ((jVal2 + 7) >> 3);    /* A += (F-A)/8 */
+                                            *(ptr + 2) = jVal1;
+                                            *(ptr - 3) = jVal0;
+                                        }
+                                        else if (jVal2)
+                                        {
+                                            jVal1 -= ((jVal2 - 7) >> 3);    /* F -= (F-A)/8 */
+                                            jVal0 += ((jVal2 - 7) >> 3);    /* A += (F-A)/8 */
+                                            *(ptr + 2) = jVal1;
+                                            *(ptr - 3) = jVal0;
+                                        }
+                                    }   /* end of ver hard filetering */
+                                }
+                                while ((ptr += width) < ptr_e);
+                            }
+
+                        } /* boundary*/
+                    } /*bc*/
+                brwidth += pp_w;
+            }/*br*/
+            brwidth -= (pp_w << 1);
+        }/*mbc*/
+        brwidth += (pp_w << 1);
+    }/*mbr*/
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp
new file mode 100644
index 0000000..795cf71
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/chvr_filter.cpp
@@ -0,0 +1,565 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include    "mp4dec_lib.h"
+#include    "post_proc.h"
+
+#ifdef PV_POSTPROC_ON
+
+void CombinedHorzVertRingFilter(
+    uint8 *rec,
+    int width,
+    int height,
+    int16 *QP_store,
+    int chr,
+    uint8 *pp_mod)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int index, counter;
+    int br, bc, incr, mbr, mbc;
+    int QP = 1;
+    int v[5];
+    uint8 *ptr, *ptr_c, *ptr_n;
+    int w1, w2, w3, w4;
+    int pp_w, pp_h, brwidth;
+    int sum, delta;
+    int a3_0, a3_1, a3_2, A3_0;
+    /* for Deringing Threshold approach (MPEG4)*/
+    int max_diff, thres, v0, h0, min_blk, max_blk;
+    int cnthflag;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Calculate the width and height of the area in blocks (divide by 8) */
+    pp_w = (width >> 3);
+    pp_h = (height >> 3);
+
+    /* Set up various values needed for updating pointers into rec */
+    w1 = width;             /* Offset to next row in pixels */
+    w2 = width << 1;        /* Offset to two rows in pixels */
+    w3 = w1 + w2;           /* Offset to three rows in pixels */
+    w4 = w2 << 1;           /* Offset to four rows in pixels */
+    incr = width - BLKSIZE; /* Offset to next row after processing block */
+
+    /* Work through the area hortizontally by two rows per step */
+    for (mbr = 0; mbr < pp_h; mbr += 2)
+    {
+        /* brwidth contains the block number of the leftmost block
+         * of the current row */
+        brwidth = mbr * pp_w;
+
+        /* Work through the area vertically by two columns per step */
+        for (mbc = 0; mbc < pp_w; mbc += 2)
+        {
+            /* if the data is luminance info, get the correct
+                    * quantization paramenter. One parameter per macroblock */
+            if (!chr)
+            {
+                /* brwidth/4 is the macroblock number and mbc/2 is the macroblock col number*/
+                QP = QP_store[(brwidth>>2) + (mbc>>1)];
+            }
+
+            /****************** Horiz. Filtering ********************/
+            /* Process four blocks for the filtering        */
+            /********************************************************/
+            /* Loop over two rows of blocks */
+            for (br = mbr + 1; br < mbr + 3; br++)    /* br is the row counter in blocks */
+            {
+                /* Set brwidth to the first (leftmost) block number of the next row */
+                /* brwidth is used as an index when counting blocks */
+                brwidth += pp_w;
+
+                /* Loop over two columns of blocks in the row */
+                for (bc = mbc; bc < mbc + 2; bc++)    /* bc is the column counter in blocks */
+                {
+                    /****** check boundary for deblocking ************/
+                    /* Execute if the row and column counters are within the area */
+                    if (br < pp_h && bc < pp_w)
+                    {
+                        /* Set the ptr to the first pixel of the first block of the second row
+                        * brwidth * 64 is the pixel row offset
+                        * bc * 8 is the pixel column offset */
+                        ptr = rec + (brwidth << 6) + (bc << 3);
+
+                        /* Set the index to the current block of the second row counting in blocks */
+                        index = brwidth + bc;
+
+                        /* if the data is chrominance info, get the correct
+                         * quantization paramenter. One parameter per block. */
+                        if (chr)
+                        {
+                            QP = QP_store[index];
+                        }
+
+                        /* Execute hard horizontal filter if semaphore for horizontal deblocking
+                          * is set for the current block and block immediately above it */
+                        if (((pp_mod[index]&0x02) != 0) && ((pp_mod[index-pp_w]&0x02) != 0))
+                        {   /* Hard filter */
+
+                            /* Set HorzHflag (bit 4) in the pp_mod location */
+                            pp_mod[index-pp_w] |= 0x10; /*  4/26/00 reuse pp_mod for HorzHflag*/
+
+                            /* Filter across the 8 pixels of the block */
+                            for (index = BLKSIZE; index > 0; index--)
+                            {
+                                /* Difference between the current pixel and the pixel above it */
+                                a3_0 = *ptr - *(ptr - w1);
+
+                                /* if the magnitude of the difference is greater than the KThH threshold
+                                 * and within the quantization parameter, apply hard filter */
+                                if ((a3_0 > KThH || a3_0 < -KThH) && a3_0<QP && a3_0> -QP)
+                                {
+                                    ptr_c = ptr - w3;   /* Points to pixel three rows above */
+                                    ptr_n = ptr + w1;   /* Points to pixel one row below */
+                                    v[0] = (int)(*(ptr_c - w3));
+                                    v[1] = (int)(*(ptr_c - w2));
+                                    v[2] = (int)(*(ptr_c - w1));
+                                    v[3] = (int)(*ptr_c);
+                                    v[4] = (int)(*(ptr_c + w1));
+
+                                    sum = v[0]
+                                          + v[1]
+                                          + v[2]
+                                          + *ptr_c
+                                          + v[4]
+                                          + (*(ptr_c + w2))
+                                          + (*(ptr_c + w3));  /* Current pixel */
+
+                                    delta = (sum + *ptr_c + 4) >> 3;   /* Average pixel values with rounding */
+                                    *(ptr_c) = (uint8) delta;
+
+                                    /* Move pointer down one row of pixels (points to pixel two rows
+                                     * above current pixel) */
+                                    ptr_c += w1;
+
+                                    for (counter = 0; counter < 5; counter++)
+                                    {
+                                        /* Subtract off highest pixel and add in pixel below */
+                                        sum = sum - v[counter] + *ptr_n;
+                                        /* Average the pixel values with rounding */
+                                        delta = (sum + *ptr_c + 4) >> 3;
+                                        *ptr_c = (uint8)(delta);
+
+                                        /* Increment pointers to next pixel row */
+                                        ptr_c += w1;
+                                        ptr_n += w1;
+                                    }
+                                }
+                                /* Increment pointer to next pixel */
+                                ++ptr;
+                            } /* index*/
+                        }
+                        else
+                        { /* soft filter*/
+
+                            /* Clear HorzHflag (bit 4) in the pp_mod location */
+                            pp_mod[index-pp_w] &= 0xef; /* reset 1110,1111 */
+
+                            for (index = BLKSIZE; index > 0; index--)
+                            {
+                                /* Difference between the current pixel and the pixel above it */
+                                a3_0 = *(ptr) - *(ptr - w1);
+
+                                /* if the magnitude of the difference is greater than the KTh threshold,
+                                 * apply soft filter */
+                                if ((a3_0 > KTh || a3_0 < -KTh))
+                                {
+
+                                    /* Sum of weighted differences */
+                                    a3_0 += ((*(ptr - w2) - *(ptr + w1)) << 1) + (a3_0 << 2);
+
+                                    /* Check if sum is less than the quantization parameter */
+                                    if (PV_ABS(a3_0) < (QP << 3))
+                                    {
+                                        a3_1 = *(ptr - w2) - *(ptr - w3);
+                                        a3_1 += ((*(ptr - w4) - *(ptr - w1)) << 1) + (a3_1 << 2);
+
+                                        a3_2  = *(ptr + w2) - *(ptr + w1);
+                                        a3_2 += ((*(ptr) - *(ptr + w3)) << 1) + (a3_2 << 2);
+
+                                        A3_0 = PV_ABS(a3_0) - PV_MIN(PV_ABS(a3_1), PV_ABS(a3_2));
+
+                                        if (A3_0 > 0)
+                                        {
+                                            A3_0 += A3_0 << 2;
+                                            A3_0 = (A3_0 + 32) >> 6;
+                                            if (a3_0 > 0)
+                                            {
+                                                A3_0 = -A3_0;
+                                            }
+
+                                            delta = (*(ptr - w1) - *(ptr)) >> 1;
+                                            if (delta >= 0)
+                                            {
+                                                if (delta >= A3_0)
+                                                {
+                                                    delta = PV_MAX(A3_0, 0);
+                                                }
+                                            }
+                                            else
+                                            {
+                                                if (A3_0 > 0)
+                                                {
+                                                    delta = 0;
+                                                }
+                                                else
+                                                {
+                                                    delta = PV_MAX(A3_0, delta);
+                                                }
+                                            }
+
+                                            *(ptr - w1) = (uint8)(*(ptr - w1) - delta);
+                                            *(ptr) = (uint8)(*(ptr) + delta);
+                                        }
+                                    } /*threshold*/
+                                }
+                                /* Increment pointer to next pixel */
+                                ++ptr;
+                            } /*index*/
+                        } /* Soft filter*/
+                    }/* boundary checking*/
+                }/*bc*/
+            }/*br*/
+            brwidth -= (pp_w << 1);
+
+
+            /****************** Vert. Filtering *********************/
+            /* Process four blocks for the filtering        */
+            /********************************************************/
+            /* Loop over two rows of blocks */
+            for (br = mbr; br < mbr + 2; br++)      /* br is the row counter in blocks */
+            {
+                for (bc = mbc + 1; bc < mbc + 3; bc++)  /* bc is the column counter in blocks */
+                {
+                    /****** check boundary for deblocking ************/
+                    /* Execute if the row and column counters are within the area */
+                    if (br < pp_h && bc < pp_w)
+                    {
+                        /* Set the ptr to the first pixel of the first block of the second row
+                        * brwidth * 64 is the pixel row offset
+                        * bc * 8 is the pixel column offset */
+                        ptr = rec + (brwidth << 6) + (bc << 3);
+
+                        /* Set the index to the current block of the second row counting in blocks */
+                        index = brwidth + bc;
+
+                        /* if the data is chrominance info, get the correct
+                         * quantization paramenter. One parameter per block. */
+                        if (chr)
+                        {
+                            QP = QP_store[index];
+                        }
+
+                        /* Execute hard vertical filter if semaphore for vertical deblocking
+                          * is set for the current block and block immediately left of it */
+                        if (((pp_mod[index-1]&0x01) != 0) && ((pp_mod[index]&0x01) != 0))
+                        {   /* Hard filter */
+
+                            /* Set VertHflag (bit 5) in the pp_mod location of previous block*/
+                            pp_mod[index-1] |= 0x20; /*  4/26/00 reuse pp_mod for VertHflag*/
+
+                            /* Filter across the 8 pixels of the block */
+                            for (index = BLKSIZE; index > 0; index--)
+                            {
+                                /* Difference between the current pixel
+                                * and the pixel to left of it */
+                                a3_0 = *ptr - *(ptr - 1);
+
+                                /* if the magnitude of the difference is greater than the KThH threshold
+                                 * and within the quantization parameter, apply hard filter */
+                                if ((a3_0 > KThH || a3_0 < -KThH) && a3_0<QP && a3_0> -QP)
+                                {
+                                    ptr_c = ptr - 3;
+                                    ptr_n = ptr + 1;
+                                    v[0] = (int)(*(ptr_c - 3));
+                                    v[1] = (int)(*(ptr_c - 2));
+                                    v[2] = (int)(*(ptr_c - 1));
+                                    v[3] = (int)(*ptr_c);
+                                    v[4] = (int)(*(ptr_c + 1));
+
+                                    sum = v[0]
+                                          + v[1]
+                                          + v[2]
+                                          + *ptr_c
+                                          + v[4]
+                                          + (*(ptr_c + 2))
+                                          + (*(ptr_c + 3));
+
+                                    delta = (sum + *ptr_c + 4) >> 3;
+                                    *(ptr_c) = (uint8) delta;
+
+                                    /* Move pointer down one pixel to the right */
+                                    ptr_c += 1;
+                                    for (counter = 0; counter < 5; counter++)
+                                    {
+                                        /* Subtract off highest pixel and add in pixel below */
+                                        sum = sum - v[counter] + *ptr_n;
+                                        /* Average the pixel values with rounding */
+                                        delta = (sum + *ptr_c + 4) >> 3;
+                                        *ptr_c = (uint8)(delta);
+
+                                        /* Increment pointers to next pixel */
+                                        ptr_c += 1;
+                                        ptr_n += 1;
+                                    }
+                                }
+                                /* Increment pointers to next pixel row */
+                                ptr += w1;
+                            } /* index*/
+                        }
+                        else
+                        { /* soft filter*/
+
+                            /* Clear VertHflag (bit 5) in the pp_mod location */
+                            pp_mod[index-1] &= 0xdf; /* reset 1101,1111 */
+                            for (index = BLKSIZE; index > 0; index--)
+                            {
+                                /* Difference between the current pixel and the pixel above it */
+                                a3_0 = *(ptr) - *(ptr - 1);
+
+                                /* if the magnitude of the difference is greater than the KTh threshold,
+                                 * apply soft filter */
+                                if ((a3_0 > KTh || a3_0 < -KTh))
+                                {
+
+                                    /* Sum of weighted differences */
+                                    a3_0 += ((*(ptr - 2) - *(ptr + 1)) << 1) + (a3_0 << 2);
+
+                                    /* Check if sum is less than the quantization parameter */
+                                    if (PV_ABS(a3_0) < (QP << 3))
+                                    {
+                                        a3_1 = *(ptr - 2) - *(ptr - 3);
+                                        a3_1 += ((*(ptr - 4) - *(ptr - 1)) << 1) + (a3_1 << 2);
+
+                                        a3_2  = *(ptr + 2) - *(ptr + 1);
+                                        a3_2 += ((*(ptr) - *(ptr + 3)) << 1) + (a3_2 << 2);
+
+                                        A3_0 = PV_ABS(a3_0) - PV_MIN(PV_ABS(a3_1), PV_ABS(a3_2));
+
+                                        if (A3_0 > 0)
+                                        {
+                                            A3_0 += A3_0 << 2;
+                                            A3_0 = (A3_0 + 32) >> 6;
+                                            if (a3_0 > 0)
+                                            {
+                                                A3_0 = -A3_0;
+                                            }
+
+                                            delta = (*(ptr - 1) - *(ptr)) >> 1;
+                                            if (delta >= 0)
+                                            {
+                                                if (delta >= A3_0)
+                                                {
+                                                    delta = PV_MAX(A3_0, 0);
+                                                }
+                                            }
+                                            else
+                                            {
+                                                if (A3_0 > 0)
+                                                {
+                                                    delta = 0;
+                                                }
+                                                else
+                                                {
+                                                    delta = PV_MAX(A3_0, delta);
+                                                }
+                                            }
+
+                                            *(ptr - 1) = (uint8)(*(ptr - 1) - delta);
+                                            *(ptr) = (uint8)(*(ptr) + delta);
+                                        }
+                                    } /*threshold*/
+                                }
+                                ptr += w1;
+                            } /*index*/
+                        } /* Soft filter*/
+                    } /* boundary*/
+                } /*bc*/
+                /* Increment pointer to next row of pixels */
+                brwidth += pp_w;
+            }/*br*/
+            brwidth -= (pp_w << 1);
+
+            /****************** Deringing ***************************/
+            /* Process four blocks for the filtering        */
+            /********************************************************/
+            /* Loop over two rows of blocks */
+            for (br = mbr; br < mbr + 2; br++)
+            {
+                /* Loop over two columns of blocks in the row */
+                for (bc = mbc; bc < mbc + 2; bc++)
+                {
+                    /* Execute if the row and column counters are within the area */
+                    if (br < pp_h && bc < pp_w)
+                    {
+                        /* Set the index to the current block */
+                        index = brwidth + bc;
+
+                        /* Execute deringing if semaphore for deringing (bit-3 of pp_mod)
+                         * is set for the current block */
+                        if ((pp_mod[index]&0x04) != 0)
+                        {
+                            /* Don't process deringing if on an edge block */
+                            if (br > 0 && bc > 0 && br < pp_h - 1 && bc < pp_w - 1)
+                            {
+                                /* cnthflag = weighted average of HorzHflag of current,
+                                 * one above, previous blocks*/
+                                cnthflag = ((pp_mod[index] & 0x10) +
+                                            (pp_mod[index-pp_w] & 0x10) +
+                                            ((pp_mod[index-1] >> 1) & 0x10) +
+                                            ((pp_mod[index] >> 1) & 0x10)) >> 4; /* 4/26/00*/
+
+                                /* Do the deringing if decision flags indicate it's necessary */
+                                if (cnthflag < 3)
+                                {
+                                    /* if the data is chrominance info, get the correct
+                                     * quantization paramenter. One parameter per block. */
+                                    if (chr)
+                                    {
+                                        QP = QP_store[index];
+                                    }
+
+                                    /* Set amount to change luminance if it needs to be changed
+                                     * based on quantization parameter */
+                                    max_diff = (QP >> 2) + 4;
+
+                                    /* Set pointer to first pixel of current block */
+                                    ptr = rec + (brwidth << 6) + (bc << 3);
+
+                                    /* Find minimum and maximum value of pixel block */
+                                    FindMaxMin(ptr, &min_blk, &max_blk, incr);
+
+                                    /* threshold determination */
+                                    thres = (max_blk + min_blk + 1) >> 1;
+
+                                    /* If pixel range is greater or equal than DERING_THR, smooth the region */
+                                    if ((max_blk - min_blk) >= DERING_THR) /*smooth 8x8 region*/
+#ifndef NoMMX
+                                    {
+                                        /* smooth all pixels in the block*/
+                                        DeringAdaptiveSmoothMMX(ptr, width, thres, max_diff);
+                                    }
+#else
+                                    {
+                                        /* Setup the starting point of the region to smooth */
+                                        v0 = (br << 3) - 1;
+                                        h0 = (bc << 3) - 1;
+
+                                        /*smooth 8x8 region*/
+                                        AdaptiveSmooth_NoMMX(rec, v0, h0, v0 + 1, h0 + 1, thres, width, max_diff);
+                                    }
+#endif
+                                }/*cnthflag*/
+                            } /*dering br==1 or bc==1 (boundary block)*/
+                            else    /* Process the boundary blocks */
+                            {
+                                /* Decide to perform deblocking based on the semaphore flags
+                                   * of the neighboring blocks in each case. A certain number of
+                                 * hard filtering flags have to be set in order to signal need
+                                 * for smoothing */
+                                if (br > 0 && br < pp_h - 1)
+                                {
+                                    if (bc > 0)
+                                    {
+                                        cnthflag = ((pp_mod[index-pp_w] & 0x10) +
+                                                    (pp_mod[index] & 0x10) +
+                                                    ((pp_mod[index-1] >> 1) & 0x10)) >> 4;
+                                    }
+                                    else
+                                    {
+                                        cnthflag = ((pp_mod[index] & 0x10) +
+                                                    (pp_mod[index-pp_w] & 0x10) +
+                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
+                                    }
+                                }
+                                else if (bc > 0 && bc < pp_w - 1)
+                                {
+                                    if (br > 0)
+                                    {
+                                        cnthflag = ((pp_mod[index-pp_w] & 0x10) +
+                                                    ((pp_mod[index-1] >> 1) & 0x10) +
+                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
+                                    }
+                                    else
+                                    {
+                                        cnthflag = ((pp_mod[index] & 0x10) +
+                                                    ((pp_mod[index-1] >> 1) & 0x10) +
+                                                    ((pp_mod[index] >> 1) & 0x10)) >> 4;
+                                    }
+                                }
+                                else /* at the corner do default*/
+                                {
+                                    cnthflag = 0;
+                                }
+
+                                /* Do the deringing if decision flags indicate it's necessary */
+                                if (cnthflag < 2)
+                                {
+
+                                    /* if the data is chrominance info, get the correct
+                                                         * quantization paramenter. One parameter per block. */
+                                    if (chr)
+                                    {
+                                        QP = QP_store[index];
+                                    }
+
+                                    /* Set amount to change luminance if it needs to be changed
+                                     * based on quantization parameter */
+                                    max_diff = (QP >> 2) + 4;
+
+                                    /* Set pointer to first pixel of current block */
+                                    ptr = rec + (brwidth << 6) + (bc << 3);
+
+                                    /* Find minimum and maximum value of pixel block */
+                                    FindMaxMin(ptr, &min_blk, &max_blk, incr);
+
+                                    /* threshold determination */
+                                    thres = (max_blk + min_blk + 1) >> 1;
+
+                                    /* Setup the starting point of the region to smooth
+                                     * This is going to be a 4x4 region */
+                                    v0 = (br << 3) + 1;
+                                    h0 = (bc << 3) + 1;
+
+                                    /* If pixel range is greater or equal than DERING_THR, smooth the region */
+                                    if ((max_blk - min_blk) >= DERING_THR)
+                                    {
+                                        /* Smooth 4x4 region */
+                                        AdaptiveSmooth_NoMMX(rec, v0, h0, v0 - 3, h0 - 3, thres, width, max_diff);
+                                    }
+                                }/*cnthflag*/
+                            } /* br==0, bc==0*/
+                        }  /* dering*/
+                    } /*boundary condition*/
+                }/*bc*/
+                brwidth += pp_w;
+            }/*br*/
+            brwidth -= (pp_w << 1);
+        }/*mbc*/
+        brwidth += (pp_w << 1);
+    }/*mbr*/
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return ;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp
new file mode 100644
index 0000000..6499233
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/combined_decode.cpp
@@ -0,0 +1,840 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h" /* video decoder function prototypes */
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "scaling.h"
+#include "mbtype_mode.h"
+
+#define OSCL_DISABLE_WARNING_CONDITIONAL_IS_CONSTANT
+/* ======================================================================== */
+/*  Function : DecodeFrameCombinedMode()                                    */
+/*  Purpose  : Decode a frame of MPEG4 bitstream in combined mode.          */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/*                                                                          */
+/*      03/30/2000 : Cleaned up and optimized the code.             */
+/*      03/31/2000 : Added proper handling of MB stuffing.          */
+/*      04/13/2000 : Rewrote this combined mode path completely     */
+/*                           so that it handles "Combined Mode With Error   */
+/*                           Resilience."  Now the code resembles the       */
+/*                           pseudo codes in MPEG-4 standard better.        */
+/*      10/13/2000 : Add fast VLC+dequant                           */
+/*      04/13/2001 : fix MB_stuffing                               */
+/*      08/07/2001 : remove MBzero                                  */
+/* ======================================================================== */
+PV_STATUS DecodeFrameCombinedMode(VideoDecData *video)
+{
+    PV_STATUS status;
+    int mbnum;
+    Vop *currVop = video->currVop;
+    BitstreamDecVideo *stream = video->bitstream;
+    int shortVideoHeader = video->shortVideoHeader;
+    int16 QP, *QPMB = video->QPMB;
+    uint8 *Mode = video->headerInfo.Mode;
+    int nTotalMB = video->nTotalMB;
+    int nMBPerRow = video->nMBPerRow;
+    int slice_counter;
+    uint32 tmpvar, long_zero_bits;
+    uint code;
+    int valid_stuffing;
+    int resync_marker_length;
+    int stuffing_length;
+
+    /* add this for error resilient, 05/18/2000 */
+    int32 startPacket;
+    int mb_start;
+    /* copy and pad to prev_Vop for INTER coding */
+    switch (currVop->predictionType)
+    {
+        case I_VOP :
+//      oscl_memset(Mode, MODE_INTRA, sizeof(uint8)*nTotalMB);
+            resync_marker_length = 17;
+            stuffing_length = 9;
+            break;
+        case P_VOP :
+            oscl_memset(video->motX, 0, sizeof(MOT)*4*nTotalMB);
+            oscl_memset(video->motY, 0, sizeof(MOT)*4*nTotalMB);
+//      oscl_memset(Mode, MODE_INTER, sizeof(uint8)*nTotalMB);
+            resync_marker_length = 16 + currVop->fcodeForward;
+            stuffing_length = 10;
+            break;
+        default :
+            mp4dec_log("DecodeFrameCombinedMode(): Vop type not supported.\n");
+            return PV_FAIL;
+    }
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    if (video->shortVideoHeader)
+    {
+        if (video->advanced_INTRA)
+        {
+            if (video->modified_quant)
+            {
+                video->vlcDecCoeffIntra = &VlcDecTCOEFShortHeader_AnnexIT;
+                video->vlcDecCoeffInter = &VlcDecTCOEFShortHeader_AnnexT;
+            }
+            else
+            {
+                video->vlcDecCoeffIntra = &VlcDecTCOEFShortHeader_AnnexI;
+                video->vlcDecCoeffInter = &VlcDecTCOEFShortHeader;
+            }
+        }
+        else
+        {
+            if (video->modified_quant)
+            {
+                video->vlcDecCoeffInter = video->vlcDecCoeffIntra = &VlcDecTCOEFShortHeader_AnnexT;
+            }
+            else
+            {
+                video->vlcDecCoeffInter = video->vlcDecCoeffIntra = &VlcDecTCOEFShortHeader;
+            }
+        }
+    }
+
+#endif
+
+    /** Initialize sliceNo ***/
+    mbnum = slice_counter = 0;
+//  oscl_memset(video->sliceNo, 0, sizeof(uint8)*nTotalMB);
+    QP = video->currVop->quantizer;
+
+    do
+    {
+        /* This section is equivalent to motion_shape_texture() */
+        /*    in the MPEG-4 standard.     04/13/2000          */
+        mb_start = mbnum;
+        video->usePrevQP = 0;             /*  04/27/01 */
+        startPacket = getPointer(stream);
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (video->modified_quant)
+        {
+            video->QP_CHR = MQ_chroma_QP_table[QP];
+        }
+        else
+        {
+            video->QP_CHR = QP;     /* ANNEX_T */
+        }
+#endif
+        /* remove any stuffing bits */
+        BitstreamShowBits16(stream, stuffing_length, &code);
+        while (code == 1)
+        {
+            PV_BitstreamFlushBits(stream, stuffing_length);
+            BitstreamShowBits16(stream, stuffing_length, &code);
+        }
+
+        do
+        {
+            /* we need video->mbnum in lower level functions */
+            video->mbnum = mbnum;
+            video->mbnum_row = PV_GET_ROW(mbnum, nMBPerRow);
+            video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+            /* assign slice number for each macroblocks */
+            video->sliceNo[mbnum] = (uint8) slice_counter;
+
+            /* decode COD, MCBPC, ACpred_flag, CPBY and DQUANT */
+            /* We have to discard stuffed MB header */
+            status = GetMBheader(video, &QP);
+
+            if (status != PV_SUCCESS)
+            {
+                VideoDecoderErrorDetected(video);
+                video->mbnum = mb_start;
+                movePointerTo(stream, (startPacket & -8));
+                break;
+            }
+
+            /* Store the QP value for later use in AC prediction */
+            QPMB[mbnum] = QP;
+
+            if (Mode[mbnum] != MODE_SKIPPED)
+            {
+                /* decode the DCT coeficients for the MB */
+                status = GetMBData(video);
+                if (status != PV_SUCCESS)
+                {
+                    VideoDecoderErrorDetected(video);
+                    video->mbnum = mb_start;
+                    movePointerTo(stream, (startPacket & -8));
+                    break;
+                }
+            }
+            else /* MODE_SKIPPED */
+            {
+                SkippedMBMotionComp(video); /*  08/04/05 */
+            }
+            // Motion compensation and put video->mblock->pred_block
+            mbnum++;
+
+            /* remove any stuffing bits */
+            BitstreamShowBits16(stream, stuffing_length, &code);
+            while (code == 1)
+            {
+                PV_BitstreamFlushBits(stream, stuffing_length);
+                BitstreamShowBits16(stream, stuffing_length, &code);
+            }
+
+            /* have we reached the end of the video packet or vop? */
+            if (shortVideoHeader)
+            {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+                if (!video->slice_structure)
+                {
+#endif
+                    if (mbnum >= (int)(video->mbnum_row + 1)*video->nMBinGOB)   /*  10/11/01 */
+                    {
+                        if (mbnum >= nTotalMB) return PV_SUCCESS;
+                        status = BitstreamShowBits32(stream, GOB_RESYNC_MARKER_LENGTH, &tmpvar);
+
+                        if (tmpvar == GOB_RESYNC_MARKER)
+                        {
+                            break;
+                        }
+                        else
+                        {
+                            status = PV_BitstreamShowBitsByteAlign(stream, GOB_RESYNC_MARKER_LENGTH, &tmpvar);
+                            if (tmpvar == GOB_RESYNC_MARKER) break;
+                        }
+                    }
+#ifdef PV_ANNEX_IJKT_SUPPORT
+                }
+                else
+                {
+
+                    if (mbnum >= nTotalMB)  /* in case no valid stuffing  06/23/01 */
+                    {
+                        valid_stuffing = validStuffing_h263(stream);
+                        if (valid_stuffing == 0)
+                        {
+                            VideoDecoderErrorDetected(video);
+                            ConcealPacket(video, mb_start, nTotalMB, slice_counter);
+                        }
+                        return PV_SUCCESS;
+                    }
+                    /* ANNEX_K */
+                    PV_BitstreamShowBitsByteAlignNoForceStuffing(stream, 17, &tmpvar);
+                    if (tmpvar == RESYNC_MARKER)
+                    {
+                        valid_stuffing = validStuffing_h263(stream);
+                        if (valid_stuffing)
+                            break; /*  06/21/01 */
+                    }
+
+                }
+#endif
+            }
+            else
+            {
+                if (mbnum >= nTotalMB)  /* in case no valid stuffing  06/23/01 */
+                {
+                    /*  11/01/2002 if we are at the end of the frame and there is some garbage data
+                    at the end of the frame (i.e. no next startcode) break if the stuffing is valid */
+                    valid_stuffing = validStuffing(stream);
+                    if (valid_stuffing == 0)
+                    {
+                        /* end 11/01/2002 */
+                        VideoDecoderErrorDetected(video);
+                        ConcealPacket(video, mb_start, nTotalMB, slice_counter);
+                    }
+                    PV_BitstreamByteAlign(stream);
+                    return PV_SUCCESS;
+                }
+
+                status = PV_BitstreamShowBitsByteAlign(stream, 23, &tmpvar); /* this call is valid for f_code < 8 */
+                long_zero_bits = !tmpvar;
+
+                if ((tmpvar >> (23 - resync_marker_length)) == RESYNC_MARKER || long_zero_bits)
+                {
+                    valid_stuffing = validStuffing(stream);
+                    if (valid_stuffing)
+                        break; /*  06/21/01 */
+                }
+
+            }
+        }
+        while (TRUE);
+
+        if (shortVideoHeader)
+        { /* We need to check newgob to refresh quantizer */
+#ifdef PV_ANNEX_IJKT_SUPPORT
+            if (!video->slice_structure)
+            {
+#endif
+                while ((status = PV_GobHeader(video)) == PV_FAIL)
+                {
+                    if ((status = quickSearchGOBHeader(stream)) != PV_SUCCESS)
+                    {
+                        break;
+                    }
+                }
+
+                mbnum = currVop->gobNumber * video->nMBinGOB;
+#ifdef PV_ANNEX_IJKT_SUPPORT
+            }
+            else
+            {
+                while ((status = PV_H263SliceHeader(video, &mbnum)) == PV_FAIL)
+                {
+                    if ((status = quickSearchH263SliceHeader(stream)) != PV_SUCCESS)
+                    {
+                        break;
+                    }
+                }
+            }
+
+#endif
+        }
+        else
+        {
+            while ((status = PV_ReadVideoPacketHeader(video, &mbnum)) == PV_FAIL)
+            {
+                if ((status = quickSearchVideoPacketHeader(stream, resync_marker_length)) != PV_SUCCESS)
+                {
+                    break;
+                }
+            }
+        }
+
+        if (status == PV_END_OF_VOP)
+        {
+            mbnum = nTotalMB;
+        }
+
+        if (mbnum > video->mbnum + 1)
+        {
+            ConcealPacket(video, video->mbnum, mbnum, slice_counter);
+        }
+        QP = video->currVop->quantizer;
+        slice_counter++;
+        if (mbnum >= nTotalMB) break;
+
+    }
+    while (TRUE);
+    return PV_SUCCESS;
+}
+
+
+/* ============================================================================ */
+/*  Function : GetMBHeader()                                                    */
+/*  Purpose  : Decode MB header, not_coded, mcbpc, ac_pred_flag, cbpy, dquant.  */
+/*  In/out   :                                                                  */
+/*  Return   :                                                                  */
+/*  Modified :                                                                  */
+/*                                                                              */
+/*      3/29/00 : Changed the returned value and optimized the code.    */
+/*      4/01/01 : new ACDC prediction structure                         */
+/* ============================================================================ */
+PV_STATUS GetMBheader(VideoDecData *video, int16 *QP)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int mbnum = video->mbnum;
+    uint8 *Mode = video->headerInfo.Mode;
+    int x_pos = video->mbnum_col;
+    typeDCStore *DC = video->predDC + mbnum;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+    const static int16  DQ_tab[4] = { -1, -2, 1, 2};
+
+    int CBPY, CBPC;
+    int MBtype, VopType;
+    int MCBPC;
+    uint DQUANT;
+    int comp;
+    Bool mb_coded;
+
+    VopType = video->currVop->predictionType;
+    mb_coded = ((VopType == I_VOP) ? TRUE : !BitstreamRead1Bits_INLINE(stream));
+
+    if (!mb_coded)
+    {
+        /* skipped macroblock */
+        Mode[mbnum] = MODE_SKIPPED;
+        //oscl_memset(DCAC_row, 0, sizeof(typeDCACStore));   /*  SKIPPED_ACDC */
+        //oscl_memset(DCAC_col, 0, sizeof(typeDCACStore));
+        ZERO_OUT_64BYTES(DCAC_row);
+        ZERO_OUT_64BYTES(DCAC_col); /*  08/12/05 */
+
+        for (comp = 0; comp < 6; comp++)
+        {
+            (*DC)[comp] = mid_gray;
+        }
+    }
+    else
+    {
+        /* coded macroblock */
+        if (VopType == I_VOP)
+        {
+            MCBPC = PV_VlcDecMCBPC_com_intra(stream);
+        }
+        else
+        {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+            if (!video->deblocking)
+            {
+                MCBPC = PV_VlcDecMCBPC_com_inter(stream);
+            }
+            else
+            {
+                MCBPC = PV_VlcDecMCBPC_com_inter_H263(stream);
+            }
+#else
+            MCBPC = PV_VlcDecMCBPC_com_inter(stream);
+#endif
+        }
+
+        if (VLC_ERROR_DETECTED(MCBPC))
+        {
+            return PV_FAIL;
+        }
+
+        Mode[mbnum] = (uint8)(MBtype = MBtype_mode[MCBPC & 7]);
+        CBPC = (MCBPC >> 4) & 3;
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (MBtype & INTRA_MASK)
+        {
+            if (!video->shortVideoHeader)
+            {
+                video->acPredFlag[mbnum] = (uint8) BitstreamRead1Bits(stream);
+            }
+            else
+            {
+                if (video->advanced_INTRA)
+                {
+                    if (!BitstreamRead1Bits(stream))
+                    {
+                        video->acPredFlag[mbnum] = 0;
+                    }
+                    else
+                    {
+                        video->acPredFlag[mbnum] = 1;
+                        if (BitstreamRead1Bits(stream))
+                        {
+                            video->mblock->direction = 0;
+                        }
+                        else
+                        {
+                            video->mblock->direction = 1;
+                        }
+                    }
+                }
+                else
+                {
+                    video->acPredFlag[mbnum] = 0;
+                }
+            }
+        }
+#else
+        if ((MBtype & INTRA_MASK) && !video->shortVideoHeader)
+        {
+            video->acPredFlag[mbnum] = (uint8) BitstreamRead1Bits_INLINE(stream);
+        }
+        else
+        {
+            video->acPredFlag[mbnum] = 0;
+        }
+#endif
+        CBPY = PV_VlcDecCBPY(stream, MBtype & INTRA_MASK); /* INTRA || INTRA_Q */
+        if (CBPY < 0)
+        {
+            return PV_FAIL;
+        }
+
+        // GW 04/23/99
+        video->headerInfo.CBP[mbnum] = (uint8)(CBPY << 2 | (CBPC & 3));
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (MBtype & Q_MASK)
+        {
+            if (!video->modified_quant)
+            {
+                DQUANT = BitstreamReadBits16(stream, 2);
+                *QP += DQ_tab[DQUANT];
+
+                if (*QP < 1) *QP = 1;
+                else if (*QP > 31) *QP = 31;
+                video->QP_CHR = *QP;  /* ANNEX_T */
+            }
+            else
+            {
+                if (BitstreamRead1Bits(stream))
+                {
+                    if (BitstreamRead1Bits(stream))
+                    {
+                        *QP += DQ_tab_Annex_T_11[*QP];
+                    }
+                    else
+                    {
+                        *QP += DQ_tab_Annex_T_10[*QP];
+                    }
+                    if (*QP < 1) *QP = 1;
+                    else if (*QP > 31) *QP = 31;
+                }
+                else
+                {
+                    *QP = (int16)BitstreamReadBits16(stream, 5);
+                }
+                video->QP_CHR =  MQ_chroma_QP_table[*QP];
+            }
+        }
+#else
+        if (MBtype & Q_MASK)
+        {
+            DQUANT = BitstreamReadBits16(stream, 2);
+            *QP += DQ_tab[DQUANT];
+
+            if (*QP < 1) *QP = 1;
+            else if (*QP > 31) *QP = 31;
+        }
+#endif
+    }
+    return PV_SUCCESS;
+}
+
+
+
+
+
+/***********************************************************CommentBegin******
+*       3/10/00  : initial modification to the
+*                new PV-Decoder Lib format.
+*       4/2/2000 : Cleanup and error-handling modification.  This
+*                   function has been divided into several sub-functions for
+*                   better coding style and maintainance reason.  I also
+*                   greatly shrunk the code size here.
+*       9/18/2000 : VlcDecode+Dequant optimization *
+*       4/01/2001 : new ACDC prediction structure
+*       3/29/2002 : removed GetIntraMB and GetInterMB
+***********************************************************CommentEnd********/
+PV_STATUS GetMBData(VideoDecData *video)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int mbnum = video->mbnum;
+    MacroBlock *mblock = video->mblock;
+    int16 *dataBlock;
+    PIXEL *c_comp;
+    uint mode = video->headerInfo.Mode[mbnum];
+    uint CBP = video->headerInfo.CBP[mbnum];
+    typeDCStore *DC = video->predDC + mbnum;
+    int intra_dc_vlc_thr = video->currVop->intraDCVlcThr;
+    int16 QP = video->QPMB[mbnum];
+    int16 QP_tmp = QP;
+    int width = video->width;
+    int  comp;
+    int  switched;
+    int ncoeffs[6] = {0, 0, 0, 0, 0, 0};
+    int *no_coeff = mblock->no_coeff;
+    int16 DC_coeff;
+    PV_STATUS status;
+
+#ifdef PV_POSTPROC_ON
+    /* post-processing */
+    uint8 *pp_mod[6];
+    int TotalMB = video->nTotalMB;
+    int MB_in_width = video->nMBPerRow;
+#endif
+    int y_pos = video->mbnum_row;
+    int x_pos = video->mbnum_col;
+    int32 offset = (int32)(y_pos << 4) * width + (x_pos << 4);
+
+    /* Decode each 8-by-8 blocks. comp 0 ~ 3 are luminance blocks, 4 ~ 5 */
+    /*  are chrominance blocks.   04/03/2000.                          */
+#ifdef PV_POSTPROC_ON
+    if (video->postFilterType != PV_NO_POST_PROC)
+    {
+        /** post-processing ***/
+        pp_mod[0] = video->pstprcTypCur + (y_pos << 1) * (MB_in_width << 1) + (x_pos << 1);
+        pp_mod[1] = pp_mod[0] + 1;
+        pp_mod[2] = pp_mod[0] + (MB_in_width << 1);
+        pp_mod[3] = pp_mod[2] + 1;
+        pp_mod[4] = video->pstprcTypCur + (TotalMB << 2) + mbnum;
+        pp_mod[5] = pp_mod[4] + TotalMB;
+    }
+#endif
+
+    /*  oscl_memset(mblock->block, 0, sizeof(typeMBStore));    Aug 9,2005 */
+
+    if (mode & INTRA_MASK) /* MODE_INTRA || MODE_INTRA_Q */
+    {
+        switched = 0;
+        if (intra_dc_vlc_thr)
+        {
+            if (video->usePrevQP)
+                QP_tmp = video->QPMB[mbnum-1];   /* running QP  04/26/01 */
+
+            switched = (intra_dc_vlc_thr == 7 || QP_tmp >= intra_dc_vlc_thr * 2 + 11);
+        }
+
+        mblock->DCScalarLum = cal_dc_scaler(QP, LUMINANCE_DC_TYPE);   /*  3/01/01 */
+        mblock->DCScalarChr = cal_dc_scaler(QP, CHROMINANCE_DC_TYPE);
+
+        for (comp = 0; comp < 6; comp++)
+        {
+            dataBlock = mblock->block[comp];    /* 10/20/2000 */
+
+            if (video->shortVideoHeader)
+            {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+                if (!video->advanced_INTRA)
+                {
+#endif
+                    DC_coeff = (int16) BitstreamReadBits16_INLINE(stream, 8);
+
+                    if ((DC_coeff & 0x7f) == 0) /* 128 & 0  */
+                    {
+                        /* currently we will only signal FAIL for 128. We will ignore the 0 case  */
+                        if (DC_coeff == 128)
+                        {
+                            return PV_FAIL;
+                        }
+                        else
+                        {
+                            VideoDecoderErrorDetected(video);
+                        }
+                    }
+                    if (DC_coeff == 255)
+                    {
+                        DC_coeff = 128;
+                    }
+                    dataBlock[0] = (int16) DC_coeff;
+#ifdef PV_ANNEX_IJKT_SUPPORT
+                }
+#endif
+                ncoeffs[comp] = VlcDequantH263IntraBlock_SH(video, comp, mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+
+            }
+            else
+            {
+                if (switched == 0)
+                {
+                    status = PV_DecodePredictedIntraDC(comp, stream, &DC_coeff);
+                    if (status != PV_SUCCESS) return PV_FAIL;
+
+                    dataBlock[0] = (int16) DC_coeff;
+                }
+                ncoeffs[comp] = VlcDequantH263IntraBlock(video, comp,
+                                switched, mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+            }
+
+            if (VLC_ERROR_DETECTED(ncoeffs[comp]))
+            {
+                if (switched)
+                    return PV_FAIL;
+                else
+                {
+                    ncoeffs[comp] = 1;
+                    oscl_memset((dataBlock + 1), 0, sizeof(int16)*63);
+                }
+            }
+            no_coeff[comp] = ncoeffs[comp];
+
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[comp] = (uint8) PostProcSemaphore(dataBlock);
+#endif
+        }
+        MBlockIDCT(video);
+    }
+    else      /* INTER modes */
+    {   /*  moved it here Aug 15, 2005 */
+        /* decode the motion vector (if there are any) */
+        status = PV_GetMBvectors(video, mode);
+        if (status != PV_SUCCESS)
+        {
+            return status;
+        }
+
+
+        MBMotionComp(video, CBP);
+        c_comp  = video->currVop->yChan + offset;
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        for (comp = 0; comp < 4; comp++)
+        {
+            (*DC)[comp] = mid_gray;
+            if (CBP & (1 << (5 - comp)))
+            {
+                ncoeffs[comp] = VlcDequantH263InterBlock(video, comp, mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+                if (VLC_ERROR_DETECTED(ncoeffs[comp])) return PV_FAIL;
+
+                BlockIDCT(c_comp + (comp&2)*(width << 2) + 8*(comp&1), mblock->pred_block + (comp&2)*64 + 8*(comp&1), mblock->block[comp], width, ncoeffs[comp],
+                          mblock->bitmapcol[comp], mblock->bitmaprow[comp]);
+
+#ifdef PV_POSTPROC_ON
+                /* for inter just test for ringing */
+                if (video->postFilterType != PV_NO_POST_PROC)
+                    *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
+#endif
+            }
+            else
+            {
+                /* no IDCT for all zeros blocks  03/28/2002 */
+                /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+                if (video->postFilterType != PV_NO_POST_PROC)
+                    *pp_mod[comp] = 0;
+#endif
+            }
+        }
+
+        video->QPMB[mbnum] = video->QP_CHR;     /* ANNEX_T */
+
+
+
+        (*DC)[4] = mid_gray;
+        if (CBP & 2)
+        {
+            ncoeffs[4] = VlcDequantH263InterBlock(video, 4, mblock->bitmapcol[4], &mblock->bitmaprow[4]);
+            if (VLC_ERROR_DETECTED(ncoeffs[4])) return PV_FAIL;
+
+            BlockIDCT(video->currVop->uChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 256, mblock->block[4], width >> 1, ncoeffs[4],
+                      mblock->bitmapcol[4], mblock->bitmaprow[4]);
+
+#ifdef PV_POSTPROC_ON
+            /* for inter just test for ringing */
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
+#endif
+        }
+        else
+        {
+            /* no IDCT for all zeros blocks  03/28/2002 */
+            /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[4] = 0;
+#endif
+        }
+        (*DC)[5] = mid_gray;
+        if (CBP & 1)
+        {
+            ncoeffs[5] = VlcDequantH263InterBlock(video, 5, mblock->bitmapcol[5], &mblock->bitmaprow[5]);
+            if (VLC_ERROR_DETECTED(ncoeffs[5])) return PV_FAIL;
+
+            BlockIDCT(video->currVop->vChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 264, mblock->block[5], width >> 1, ncoeffs[5],
+                      mblock->bitmapcol[5], mblock->bitmaprow[5]);
+
+#ifdef PV_POSTPROC_ON
+            /* for inter just test for ringing */
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
+#endif
+        }
+        else
+        {
+            /* no IDCT for all zeros blocks  03/28/2002 */
+            /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[5] = 0;
+#endif
+        }
+        video->QPMB[mbnum] = QP;  /* restore the QP values  ANNEX_T*/
+#else
+        for (comp = 0; comp < 4; comp++)
+        {
+            (*DC)[comp] = mid_gray;
+            if (CBP & (1 << (5 - comp)))
+            {
+                ncoeffs[comp] = VlcDequantH263InterBlock(video, comp, mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+                if (VLC_ERROR_DETECTED(ncoeffs[comp])) return PV_FAIL;
+
+                BlockIDCT(c_comp + (comp&2)*(width << 2) + 8*(comp&1), mblock->pred_block + (comp&2)*64 + 8*(comp&1), mblock->block[comp], width, ncoeffs[comp],
+                          mblock->bitmapcol[comp], mblock->bitmaprow[comp]);
+
+#ifdef PV_POSTPROC_ON
+                /* for inter just test for ringing */
+                if (video->postFilterType != PV_NO_POST_PROC)
+                    *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
+#endif
+            }
+            else
+            {
+                /* no IDCT for all zeros blocks  03/28/2002 */
+                /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+                if (video->postFilterType != PV_NO_POST_PROC)
+                    *pp_mod[comp] = 0;
+#endif
+            }
+        }
+
+        (*DC)[4] = mid_gray;
+        if (CBP & 2)
+        {
+            ncoeffs[4] = VlcDequantH263InterBlock(video, 4, mblock->bitmapcol[4], &mblock->bitmaprow[4]);
+            if (VLC_ERROR_DETECTED(ncoeffs[4])) return PV_FAIL;
+
+            BlockIDCT(video->currVop->uChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 256, mblock->block[4], width >> 1, ncoeffs[4],
+                      mblock->bitmapcol[4], mblock->bitmaprow[4]);
+
+#ifdef PV_POSTPROC_ON
+            /* for inter just test for ringing */
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
+#endif
+        }
+        else
+        {
+            /* no IDCT for all zeros blocks  03/28/2002 */
+            /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[4] = 0;
+#endif
+        }
+        (*DC)[5] = mid_gray;
+        if (CBP & 1)
+        {
+            ncoeffs[5] = VlcDequantH263InterBlock(video, 5, mblock->bitmapcol[5], &mblock->bitmaprow[5]);
+            if (VLC_ERROR_DETECTED(ncoeffs[5])) return PV_FAIL;
+
+            BlockIDCT(video->currVop->vChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 264, mblock->block[5], width >> 1, ncoeffs[5],
+                      mblock->bitmapcol[5], mblock->bitmaprow[5]);
+
+#ifdef PV_POSTPROC_ON
+            /* for inter just test for ringing */
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
+#endif
+        }
+        else
+        {
+            /* no IDCT for all zeros blocks  03/28/2002 */
+            /*              BlockIDCT();                */
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[5] = 0;
+#endif
+#endif  // PV_ANNEX_IJKT_SUPPORT
+
+
+
+
+
+
+    }
+
+    video->usePrevQP = 1;          /* should be set after decoding the first Coded  04/27/01 */
+    return PV_SUCCESS;
+}
+
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
new file mode 100644
index 0000000..e9ead01
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/conceal.cpp
@@ -0,0 +1,193 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h" /* video decoder function prototypes */
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "scaling.h"
+
+/* ====================================================================== /
+Function : ConcealTexture_I()
+Date     : 06/12/2001
+Purpose  : Conceal texture for I-partition
+In/out   :
+Return   :
+Modified :
+/ ====================================================================== */
+void ConcealTexture_I(VideoDecData *video, int32 startFirstPartition, int mb_start, int mb_stop, int slice_counter)
+{
+    int mbnum;
+    BitstreamDecVideo *stream = video->bitstream;
+    int16 QP;
+    int intra_dc_vlc_thr = video->currVop->intraDCVlcThr;
+
+    movePointerTo(stream, startFirstPartition);
+
+    video->usePrevQP = 0;
+    for (mbnum = mb_start; mbnum < mb_stop; mbnum++)
+    {
+        video->mbnum = mbnum;
+        video->mbnum_row = PV_GET_ROW(mbnum, video->nMBPerRow);
+        video->mbnum_col = mbnum - video->mbnum_row * video->nMBPerRow;
+        video->sliceNo[mbnum] = (uint8) slice_counter;
+        QP = video->QPMB[mbnum];
+        PV_VlcDecMCBPC_com_intra(stream);
+        GetMBheaderDataPart_DQUANT_DC(video, &QP);
+
+        if (intra_dc_vlc_thr)
+        {
+            if (video->usePrevQP)
+                QP = video->QPMB[mbnum-1];
+            if (intra_dc_vlc_thr == 7 || QP >= intra_dc_vlc_thr*2 + 11)  /* if switched then conceal from previous frame  */
+            {
+                ConcealPacket(video, mbnum, mb_stop, slice_counter);
+                video->mbnum = mb_stop - 1;
+                video->mbnum_row = PV_GET_ROW(video->mbnum, video->nMBPerRow);
+                video->mbnum_col = video->mbnum - video->mbnum_row * video->nMBPerRow;
+                break;
+            }
+        }
+
+        video->headerInfo.CBP[mbnum] = 0;
+        video->acPredFlag[mbnum] = 0;
+        GetMBData_DataPart(video);
+        video->usePrevQP = 1;
+    }
+    return;
+}
+
+/* ====================================================================== /
+Function : ConcealTexture_P()
+Date     : 05/16/2000
+Purpose  : Conceal texture for P-partition
+In/out   :
+Return   :
+/ ====================================================================== */
+
+void ConcealTexture_P(VideoDecData *video, int mb_start, int mb_stop, int slice_counter)
+{
+    int mbnum;
+
+    for (mbnum = mb_start; mbnum < mb_stop; mbnum++)
+    {
+        video->mbnum = mbnum;
+        video->mbnum_row = PV_GET_ROW(mbnum, video->nMBPerRow);
+        video->mbnum_col = mbnum - video->mbnum_row * video->nMBPerRow;
+        video->sliceNo[mbnum] = (uint8) slice_counter;
+        oscl_memset(video->mblock->block, 0, sizeof(typeMBStore));
+        /*  to get rid of dark region caused by INTRA blocks */
+        /* 05/19/2000 */
+        if (video->headerInfo.Mode[mbnum] & INTER_MASK)
+        {
+            MBMotionComp(video, 0);
+        }
+        else
+        {
+            video->headerInfo.Mode[mbnum] = MODE_SKIPPED;
+            SkippedMBMotionComp(video);
+        }
+    }
+
+    return;
+}
+
+/***************************************************************
+Function:   ConcealPacket
+Purpose :   Conceal motion and texture of a packet by direct
+copying from previous frame.
+Returned:   void
+Modified:
+*************************************************************/
+void ConcealPacket(VideoDecData *video,
+                   int mb_start,
+                   int mb_stop,
+                   int slice_counter)
+{
+    int i;
+    for (i = mb_start; i < mb_stop; i++)
+    {
+        CopyVopMB(video->currVop, video->concealFrame, i, video->width, video->height);
+        video->sliceNo[i] = (uint8) slice_counter;
+        video->headerInfo.Mode[i] = MODE_SKIPPED;
+    }
+
+    return;
+}
+
+/****************************************************************************
+Function:   CopyVopMB
+Purpose :   Fill a macroblock with previous Vop.
+Returned    :   void
+Modified:   6/04/2001 rewrote the function
+            copies from concealFrame
+****************************************************************************/
+void CopyVopMB(Vop *curr, uint8 *prevFrame, int mbnum, int width_Y, int height)
+{
+    int width_C = width_Y >> 1;
+    int row = MB_SIZE;
+    uint8              *y1, *y2, *u1, *u2, *v1, *v2;
+    int xpos, ypos, MB_in_width;
+    int32 lumstart, chrstart, size;
+
+    MB_in_width = (width_Y + 15) >> 4;
+    ypos = PV_GET_ROW(mbnum, MB_in_width);
+    xpos = mbnum - ypos * MB_in_width;
+    lumstart = (ypos << 4) * (int32)width_Y  + (xpos << 4);
+    chrstart = (ypos << 3) * (int32)width_C  + (xpos << 3);
+
+    size = (int32)height * width_Y;
+
+    y1 =  curr->yChan + lumstart;
+    u1 =  curr->uChan + chrstart;
+    v1 =  curr->vChan + chrstart;
+    y2 =  prevFrame + lumstart;
+    u2 =  prevFrame + size + chrstart;
+    v2 =  prevFrame + size + (size >> 2) + chrstart;
+    while (row)
+    {
+        oscl_memcpy(y1, y2, MB_SIZE);
+        y1 += width_Y;
+        y2 += width_Y;
+        oscl_memcpy(y1, y2, MB_SIZE);
+        y1 += width_Y;
+        y2 += width_Y;
+        oscl_memcpy(y1, y2, MB_SIZE);
+        y1 += width_Y;
+        y2 += width_Y;
+        oscl_memcpy(y1, y2, MB_SIZE);
+        y1 += width_Y;
+        y2 += width_Y;
+
+        oscl_memcpy(u1, u2, B_SIZE);
+        u1 += width_C;
+        u2 += width_C;
+        oscl_memcpy(u1, u2, B_SIZE);
+        u1 += width_C;
+        u2 += width_C;
+
+        oscl_memcpy(v1, v2, B_SIZE);
+        v1 += width_C;
+        v2 += width_C;
+        oscl_memcpy(v1, v2, B_SIZE);
+        v1 += width_C;
+        v2 += width_C;
+
+        row -= 4;
+    }
+    return;
+}               /* CopyVopMB */
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp
new file mode 100644
index 0000000..00db04b
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/datapart_decode.cpp
@@ -0,0 +1,794 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "scaling.h"
+#include "mbtype_mode.h"
+#include "idct.h"
+
+#define OSCL_DISABLE_WARNING_CONDITIONAL_IS_CONSTANT
+/* ======================================================================== */
+/*  Function : DecodeFrameDataPartMode()                                    */
+/*  Purpose  : Decode a frame of MPEG4 bitstream in datapartitioning mode.  */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Modified :                                                              */
+/*                                                                          */
+/*      04/25/2000 : Rewrite the data partitioning path completely  */
+/*                           according to the pseudo codes in MPEG-4        */
+/*                           standard.                                      */
+/*  Modified : 09/18/2000 add fast VlcDecode+Dequant                    */
+/*             04/17/2001 cleanup                                       */
+/* ======================================================================== */
+PV_STATUS DecodeFrameDataPartMode(VideoDecData *video)
+{
+    PV_STATUS status;
+    Vop *currVop = video->currVop;
+    BitstreamDecVideo *stream = video->bitstream;
+
+    int nMBPerRow = video->nMBPerRow;
+
+    int vopType = currVop->predictionType;
+    int mbnum;
+    int nTotalMB = video->nTotalMB;
+    int slice_counter;
+    int resync_marker_length;
+
+    /* copy and pad to prev_Vop for INTER coding */
+    switch (vopType)
+    {
+        case I_VOP :
+//      oscl_memset(Mode, MODE_INTRA, sizeof(uint8)*nTotalMB);
+            resync_marker_length = 17;
+            break;
+        case P_VOP :
+            oscl_memset(video->motX, 0, sizeof(MOT)*4*nTotalMB);
+            oscl_memset(video->motY, 0, sizeof(MOT)*4*nTotalMB);
+//      oscl_memset(Mode, MODE_INTER, sizeof(uint8)*nTotalMB);
+            resync_marker_length = 16 + currVop->fcodeForward;
+            break;
+        default :
+            mp4dec_log("DecodeFrameDataPartMode(): Vop type not supported.\n");
+            return PV_FAIL;
+    }
+
+    /** Initialize sliceNo ***/
+    mbnum = slice_counter = 0;
+//  oscl_memset(video->sliceNo, 0, sizeof(uint8)*nTotalMB);
+
+    do
+    {
+        /* This section is equivalent to motion_shape_texture() */
+        /* in the MPEG-4 standard.            04/13/2000      */
+        video->mbnum = mbnum;
+        video->mbnum_row = PV_GET_ROW(mbnum, nMBPerRow);   /*  This is needed if nbnum is read from the packet header */
+        video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+
+        switch (vopType)
+        {
+            case I_VOP :
+                status = DecodeDataPart_I_VideoPacket(video, slice_counter);
+                break;
+
+            case P_VOP :
+                status = DecodeDataPart_P_VideoPacket(video, slice_counter);
+                break;
+
+            default :
+                mp4dec_log("DecodeFrameDataPartMode(): Vop type not supported.\n");
+                return PV_FAIL;
+        }
+
+        while ((status = PV_ReadVideoPacketHeader(video, &mbnum)) == PV_FAIL)
+        {
+            if ((status = quickSearchVideoPacketHeader(stream, resync_marker_length)) != PV_SUCCESS)
+            {
+                break;
+            }
+        }
+
+        if (status == PV_END_OF_VOP)
+        {
+            mbnum = nTotalMB;
+        }
+
+        if (mbnum > video->mbnum + 1)
+        {
+            ConcealPacket(video, video->mbnum, mbnum, slice_counter);
+        }
+        slice_counter++;
+        if (mbnum >= nTotalMB)
+        {
+            break;
+        }
+
+
+    }
+    while (TRUE);
+
+    return PV_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : DecodeDataPart_I_VideoPacket()                               */
+/*  Date     : 04/25/2000                                                   */
+/*  Purpose  : Decode Data Partitioned Mode Video Packet in I-VOP           */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if successed, PV_FAIL if failed.                  */
+/*  Modified : 09/18/2000 add fast VlcDecode+Dequant                    */
+/*             04/01/2001 fixed MB_stuffing, removed unnecessary code   */
+/* ======================================================================== */
+PV_STATUS DecodeDataPart_I_VideoPacket(VideoDecData *video, int slice_counter)
+{
+    PV_STATUS status;
+    uint8 *Mode = video->headerInfo.Mode;
+    BitstreamDecVideo *stream = video->bitstream;
+    int  nTotalMB = video->nTotalMB;
+    int  mbnum, mb_start, mb_end;
+    int16 QP, *QPMB = video->QPMB;
+    int  MBtype, MCBPC, CBPY;
+    uint32 tmpvar;
+    uint code;
+    int nMBPerRow = video->nMBPerRow;
+    Bool valid_stuffing;
+    int32 startSecondPart, startFirstPart = getPointer(stream);
+
+    /* decode the first partition */
+    QP = video->currVop->quantizer;
+    mb_start = mbnum = video->mbnum;
+    video->usePrevQP = 0;         /*  04/27/01 */
+
+
+    BitstreamShowBits16(stream, 9, &code);
+    while (code == 1)
+    {
+        PV_BitstreamFlushBits(stream, 9);
+        BitstreamShowBits16(stream, 9, &code);
+    }
+
+    do
+    {
+        /* decode COD, MCBPC, ACpred_flag, CPBY and DQUANT */
+        MCBPC = PV_VlcDecMCBPC_com_intra(stream);
+
+        if (!VLC_ERROR_DETECTED(MCBPC))
+        {
+            Mode[mbnum] = (uint8)(MBtype = MBtype_mode[MCBPC & 7]);
+            video->headerInfo.CBP[mbnum] = (uint8)((MCBPC >> 4) & 3);
+            status = GetMBheaderDataPart_DQUANT_DC(video, &QP);
+            video->usePrevQP = 1;        /* set it after the first coded MB      04/27/01 */
+        }
+        else
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            video->mbnum = mb_start;
+            movePointerTo(stream, startFirstPart);
+            return PV_FAIL;
+        }
+
+        video->sliceNo[mbnum] = (uint8) slice_counter;
+        QPMB[mbnum] = QP;
+        video->mbnum = ++mbnum;
+
+        BitstreamShowBits16(stream, 9, &code);
+        while (code == 1)
+        {
+            PV_BitstreamFlushBits(stream, 9);
+            BitstreamShowBits16(stream, 9, &code);
+        }
+        /* have we reached the end of the video packet or vop? */
+        status = BitstreamShowBits32(stream, DC_MARKER_LENGTH, &tmpvar);
+
+    }
+    while (tmpvar != DC_MARKER && video->mbnum < nTotalMB);
+
+    if (tmpvar == DC_MARKER)
+    {
+        PV_BitstreamFlushBits(stream, DC_MARKER_LENGTH);
+    }
+    else
+    {
+        status = quickSearchDCM(stream);
+        if (status == PV_SUCCESS)
+        {
+            /* only way you can end up being here is in the last packet,and there is stuffing at
+            the end of the first partition */
+            PV_BitstreamFlushBits(stream, DC_MARKER_LENGTH);
+        }
+        else
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            movePointerTo(stream, startFirstPart);
+            video->mbnum = mb_start;
+            /* concealment will be taken care of in the upper layer */
+            return PV_FAIL;
+        }
+    }
+
+    /* decode the second partition */
+    startSecondPart = getPointer(stream);
+
+    mb_end = video->mbnum;
+
+    for (mbnum = mb_start; mbnum < mb_end; mbnum++)
+    {
+        MBtype = Mode[mbnum];
+        /* No skipped mode in I-packets  3/1/2001    */
+        video->mbnum = mbnum;
+
+        video->mbnum_row = PV_GET_ROW(mbnum, nMBPerRow);   /*  This is needed if nbnum is read from the packet header */
+        video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+        /* there is always acdcpred in DataPart mode  04/10/01 */
+        video->acPredFlag[mbnum] = (uint8) BitstreamRead1Bits(stream);
+
+        CBPY = PV_VlcDecCBPY(stream, MBtype & INTRA_MASK); /* MODE_INTRA || MODE_INTRA_Q */
+        if (CBPY < 0)
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            movePointerTo(stream, startSecondPart); /*  */
+            /* Conceal packet,  05/15/2000 */
+            ConcealTexture_I(video, startFirstPart, mb_start, mb_end, slice_counter);
+            return PV_FAIL;
+        }
+
+        video->headerInfo.CBP[mbnum] |= (uint8)(CBPY << 2);
+    }
+
+    video->usePrevQP = 0;
+
+    for (mbnum = mb_start; mbnum < mb_end; mbnum++)
+    {
+        video->mbnum = mbnum;
+
+        video->mbnum_row = PV_GET_ROW(mbnum , nMBPerRow);  /*  This is needed if nbnum is read from the packet header */
+        video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+        /* No skipped mode in I-packets  3/1/2001    */
+        /* decode the DCT coeficients for the MB */
+        status = GetMBData_DataPart(video);
+        if (status != PV_SUCCESS)
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            movePointerTo(stream, startSecondPart); /*  */
+            /* Conceal packet,  05/15/2000 */
+            ConcealTexture_I(video, startFirstPart, mb_start, mb_end, slice_counter);
+            return status;
+        }
+        video->usePrevQP = 1;           /*  04/27/01 should be set after decoding first MB */
+    }
+
+    valid_stuffing = validStuffing(stream);
+    if (!valid_stuffing)
+    {
+        VideoDecoderErrorDetected(video);
+        movePointerTo(stream, startSecondPart);
+        ConcealTexture_I(video, startFirstPart, mb_start, mb_end, slice_counter);
+        return PV_FAIL;
+    }
+    return PV_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : DecodeDataPart_P_VideoPacket()                               */
+/*  Date     : 04/25/2000                                                   */
+/*  Purpose  : Decode Data Partitioned Mode Video Packet in P-VOP           */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if successed, PV_FAIL if failed.                  */
+/*  Modified :   09/18/2000,  fast VlcDecode+Dequant                        */
+/*              04/13/2001,  fixed MB_stuffing, new ACDC pred structure,  */
+/*                              cleanup                                     */
+/*              08/07/2001,  remove MBzero                              */
+/* ======================================================================== */
+PV_STATUS DecodeDataPart_P_VideoPacket(VideoDecData *video, int slice_counter)
+{
+    PV_STATUS status;
+    uint8 *Mode = video->headerInfo.Mode;
+    BitstreamDecVideo *stream = video->bitstream;
+    int nTotalMB = video->nTotalMB;
+    int mbnum, mb_start, mb_end;
+    int16 QP, *QPMB = video->QPMB;
+    int MBtype, CBPY;
+    Bool valid_stuffing;
+    int intra_MB;
+    uint32 tmpvar;
+    uint code;
+    int32  startFirstPart, startSecondPart;
+    int nMBPerRow = video->nMBPerRow;
+    uint8 *pbyte;
+    /* decode the first partition */
+    startFirstPart = getPointer(stream);
+    mb_start = video->mbnum;
+    video->usePrevQP = 0;            /*  04/27/01 */
+
+    BitstreamShowBits16(stream, 10, &code);
+    while (code == 1)
+    {
+        PV_BitstreamFlushBits(stream, 10);
+        BitstreamShowBits16(stream, 10, &code);
+    }
+
+    do
+    {
+        /* decode COD, MCBPC, ACpred_flag, CPBY and DQUANT */
+        /* We have to discard stuffed MB header */
+
+        status = GetMBheaderDataPart_P(video);
+
+        if (status != PV_SUCCESS)
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            movePointerTo(stream, startFirstPart);
+            video->mbnum = mb_start;
+            return PV_FAIL;
+        }
+
+        /* we must update slice_counter before motion vector decoding.   */
+        video->sliceNo[video->mbnum] = (uint8) slice_counter;
+
+        if (Mode[video->mbnum] & INTER_MASK) /* INTER || INTER_Q || INTER_4V */
+        {
+            /* decode the motion vector (if there are any) */
+            status = PV_GetMBvectors(video, Mode[video->mbnum]);
+            if (status != PV_SUCCESS)
+            {
+                /* Report the error to the application.   06/20/2000 */
+                VideoDecoderErrorDetected(video);
+                movePointerTo(stream, startFirstPart);
+                video->mbnum = mb_start;
+                return PV_FAIL;
+            }
+        }
+        video->mbnum++;
+
+        video->mbnum_row = PV_GET_ROW(video->mbnum, nMBPerRow);   /*  This is needed if mbnum is read from the packet header */
+        video->mbnum_col = video->mbnum - video->mbnum_row * nMBPerRow;
+
+        BitstreamShowBits16(stream, 10, &code);
+        while (code == 1)
+        {
+            PV_BitstreamFlushBits(stream, 10);
+            BitstreamShowBits16(stream, 10, &code);
+        }
+        /* have we reached the end of the video packet or vop? */
+        status = BitstreamShowBits32(stream, MOTION_MARKER_COMB_LENGTH, &tmpvar);
+        /*      if (status != PV_SUCCESS && status != PV_END_OF_BUFFER) return status;  */
+    }
+    while (tmpvar != MOTION_MARKER_COMB && video->mbnum < nTotalMB);
+
+    if (tmpvar == MOTION_MARKER_COMB)
+    {
+        PV_BitstreamFlushBits(stream, MOTION_MARKER_COMB_LENGTH);
+    }
+    else
+    {
+        status = quickSearchMotionMarker(stream);
+        if (status == PV_SUCCESS)
+        {
+            /* only way you can end up being here is in the last packet,and there is stuffing at
+            the end of the first partition */
+            PV_BitstreamFlushBits(stream, MOTION_MARKER_COMB_LENGTH);
+        }
+        else
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            movePointerTo(stream, startFirstPart);
+            video->mbnum = mb_start;
+            /* concealment will be taken care of in the upper layer  */
+            return PV_FAIL;
+        }
+    }
+
+    /* decode the second partition */
+    startSecondPart = getPointer(stream);
+    QP = video->currVop->quantizer;
+
+    mb_end = video->mbnum;
+
+    for (mbnum = mb_start; mbnum < mb_end; mbnum++)
+    {
+        MBtype = Mode[mbnum];
+
+        if (MBtype == MODE_SKIPPED)
+        {
+            QPMB[mbnum] = QP; /*  03/01/01 */
+            continue;
+        }
+        intra_MB = (MBtype & INTRA_MASK); /* (MBtype == MODE_INTRA || MBtype == MODE_INTRA_Q) */
+        video->mbnum = mbnum;
+        video->mbnum_row = PV_GET_ROW(mbnum, nMBPerRow);   /*  This is needed if nbnum is read from the packet header */
+        video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+
+        /* there is always acdcprediction in DataPart mode    04/10/01 */
+        if (intra_MB)
+        {
+            video->acPredFlag[mbnum] = (uint8) BitstreamRead1Bits_INLINE(stream);
+        }
+
+        CBPY = PV_VlcDecCBPY(stream, intra_MB);
+        if (CBPY < 0)
+        {
+            /* Report the error to the application.   06/20/2000 */
+            VideoDecoderErrorDetected(video);
+            /* Conceal second partition,  5/15/2000 */
+            movePointerTo(stream, startSecondPart);
+            ConcealTexture_P(video, mb_start, mb_end, slice_counter);
+            return PV_FAIL;
+        }
+
+        video->headerInfo.CBP[mbnum] |= (uint8)(CBPY << 2);
+        if (intra_MB || MBtype == MODE_INTER_Q)                     /*  04/26/01 */
+        {
+            status = GetMBheaderDataPart_DQUANT_DC(video, &QP);
+            if (status != PV_SUCCESS) return status;
+        }
+        video->usePrevQP = 1;        /*  04/27/01 */
+        QPMB[mbnum] = QP;
+    }
+
+    video->usePrevQP = 0;  /*  04/27/01 */
+
+    for (mbnum = mb_start; mbnum < mb_end; mbnum++)
+    {
+        video->mbnum = mbnum;
+        video->mbnum_row = PV_GET_ROW(mbnum, nMBPerRow);  /*  This is needed if nbnum is read from the packet header */
+        video->mbnum_col = mbnum - video->mbnum_row * nMBPerRow;
+
+
+        if (Mode[mbnum] != MODE_SKIPPED)
+        {
+            /* decode the DCT coeficients for the MB */
+            status = GetMBData_DataPart(video);
+            if (status != PV_SUCCESS)
+            {
+                /* Report the error to the application.   06/20/2000 */
+                VideoDecoderErrorDetected(video);
+
+                /* Conceal second partition,  5/15/2000 */
+                movePointerTo(stream, startSecondPart);
+                ConcealTexture_P(video, mb_start, mb_end, slice_counter);
+                return status;
+            }
+            video->usePrevQP = 1;  /*  04/27/01 */
+        }
+        else
+        {   // SKIPPED
+
+            /* Motion compensation and put it to video->mblock->pred_block */
+            SkippedMBMotionComp(video);
+
+            //oscl_memset(video->predDCAC_row + video->mbnum_col, 0, sizeof(typeDCACStore)); /*  SKIPPED_ACDC */
+            //oscl_memset(video->predDCAC_col, 0, sizeof(typeDCACStore));
+            /*  08/08/2005 */
+            pbyte = (uint8*)(video->predDCAC_row + video->mbnum_col);
+            ZERO_OUT_64BYTES(pbyte);
+            pbyte = (uint8*)(video->predDCAC_col);
+            ZERO_OUT_64BYTES(pbyte);
+
+        }
+    }
+
+    valid_stuffing = validStuffing(stream);   /*  */
+    if (!valid_stuffing)
+    {
+        VideoDecoderErrorDetected(video);
+        movePointerTo(stream, startSecondPart); /*  */
+        ConcealTexture_P(video, mb_start, mb_end, slice_counter);
+
+        return PV_FAIL;
+    }
+    return PV_SUCCESS;
+}
+
+
+/* ======================================================================== */
+/*  Function : GetMBheaderDataPart_DQUANT_DC()                              */
+/*  Date     : 04/26/2000                                                   */
+/*  Purpose  : Decode DQUANT and DC in Data Partitioned Mode for both       */
+/*             I-VOP and P-VOP.                                             */
+/*  In/out   :                                                              */
+/*  Return   : PV_SUCCESS if successed, PV_FAIL if failed.                  */
+/*  Modified : 02/13/2001 new ACDC prediction structure,        */
+/*                                       cleanup                            */
+/* ======================================================================== */
+PV_STATUS GetMBheaderDataPart_DQUANT_DC(VideoDecData *video, int16 *QP)
+{
+    PV_STATUS status = PV_SUCCESS;
+    BitstreamDecVideo *stream = video->bitstream;
+    int mbnum = video->mbnum;
+    int intra_dc_vlc_thr = video->currVop->intraDCVlcThr;
+    uint8 *Mode = video->headerInfo.Mode;
+    int  MBtype = Mode[mbnum];
+    typeDCStore *DC = video->predDC + mbnum;
+    int  comp;
+    Bool switched;
+    uint  DQUANT;
+    int16 QP_tmp;
+
+    const static int  DQ_tab[4] = { -1, -2, 1, 2};
+
+    if (MBtype & Q_MASK)             /* INTRA_Q || INTER_Q */
+    {
+        DQUANT = BitstreamReadBits16(stream, 2);
+        *QP += DQ_tab[DQUANT];
+
+        if (*QP < 1) *QP = 1;
+        else if (*QP > 31) *QP = 31;
+    }
+    if (MBtype & INTRA_MASK)  /* INTRA || INTRA_Q */ /* no switch, code DC separately */
+    {
+        QP_tmp = *QP;                      /* running QP  04/26/01*/
+        switched = 0;
+        if (intra_dc_vlc_thr)                 /*  04/27/01 */
+        {
+            if (video->usePrevQP)
+                QP_tmp = video->QPMB[mbnum-1];
+            switched = (intra_dc_vlc_thr == 7 || QP_tmp >= intra_dc_vlc_thr * 2 + 11);
+        }
+        if (!switched)
+        {
+            for (comp = 0; comp < 6; comp++)
+            {
+                status = PV_DecodePredictedIntraDC(comp, stream, (*DC + comp));   /*  03/01/01 */
+                if (status != PV_SUCCESS) return PV_FAIL;
+            }
+        }
+        else
+        {
+            for (comp = 0; comp < 6; comp++)
+            {
+                (*DC)[comp] = 0;   /*  04/26/01 needed for switched case*/
+            }
+        }
+    }
+    return status;
+}
+
+
+/***********************************************************CommentBegin******
+*       04/25/2000 : Initial modification to the new PV Lib format.
+*       04/17/2001 : new ACDC pred structure
+***********************************************************CommentEnd********/
+PV_STATUS GetMBheaderDataPart_P(VideoDecData *video)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int mbnum = video->mbnum;
+    uint8 *Mode = video->headerInfo.Mode;
+    typeDCStore *DC = video->predDC + mbnum;
+    uint no_dct_flag;
+    int comp;
+    int MCBPC;
+
+    no_dct_flag = BitstreamRead1Bits_INLINE(stream);
+
+    if (no_dct_flag)
+    {
+        /* skipped macroblock */
+        Mode[mbnum] = MODE_SKIPPED;
+
+        for (comp = 0; comp < 6; comp++)
+        {
+            (*DC)[comp] = mid_gray;
+            /*  ACDC REMOVE AC coefs are set in DecodeDataPart_P */
+        }
+    }
+    else
+    {
+        /* coded macroblock */
+        MCBPC = PV_VlcDecMCBPC_com_inter(stream);
+
+        if (VLC_ERROR_DETECTED(MCBPC))
+        {
+            return PV_FAIL;
+        }
+
+        Mode[mbnum] = (uint8)MBtype_mode[MCBPC & 7];
+        video->headerInfo.CBP[mbnum] = (uint8)((MCBPC >> 4) & 3);
+    }
+
+    return PV_SUCCESS;
+}
+
+
+/***********************************************************CommentBegin******
+*       04/17/01  new ACDC pred structure, reorganized code, cleanup
+***********************************************************CommentEnd********/
+PV_STATUS GetMBData_DataPart(VideoDecData *video)
+{
+    int mbnum = video->mbnum;
+    int16 *dataBlock;
+    MacroBlock *mblock = video->mblock;
+    int QP = video->QPMB[mbnum];
+    int32 offset;
+    PIXEL *c_comp;
+    int width = video->width;
+    int intra_dc_vlc_thr = video->currVop->intraDCVlcThr;
+    uint CBP = video->headerInfo.CBP[mbnum];
+    uint8 mode = video->headerInfo.Mode[mbnum];
+    int x_pos = video->mbnum_col;
+    typeDCStore *DC = video->predDC + mbnum;
+    int  ncoeffs[6], *no_coeff = mblock->no_coeff;
+    int  comp;
+    Bool  switched;
+    int QP_tmp = QP;
+
+    int y_pos = video->mbnum_row;
+#ifdef PV_POSTPROC_ON
+    uint8 *pp_mod[6];
+    int TotalMB = video->nTotalMB;
+    int MB_in_width = video->nMBPerRow;
+#endif
+
+
+
+    /*****
+    *     Decoding of the 6 blocks (depending on transparent pattern)
+    *****/
+#ifdef PV_POSTPROC_ON
+    if (video->postFilterType != PV_NO_POST_PROC)
+    {
+        /** post-processing ***/
+        pp_mod[0] = video->pstprcTypCur + (y_pos << 1) * (MB_in_width << 1) + (x_pos << 1);
+        pp_mod[1] = pp_mod[0] + 1;
+        pp_mod[2] = pp_mod[0] + (MB_in_width << 1);
+        pp_mod[3] = pp_mod[2] + 1;
+        pp_mod[4] = video->pstprcTypCur + (TotalMB << 2) + mbnum;
+        pp_mod[5] = pp_mod[4] + TotalMB;
+    }
+#endif
+
+    /*  oscl_memset(mblock->block, 0, sizeof(typeMBStore));    Aug 9,2005 */
+
+    if (mode & INTRA_MASK) /* MODE_INTRA || mode == MODE_INTRA_Q */
+    {
+        switched = 0;
+        if (intra_dc_vlc_thr)
+        {
+            if (video->usePrevQP)
+                QP_tmp = video->QPMB[mbnum-1];   /* running QP  04/26/01 */
+
+            switched = (intra_dc_vlc_thr == 7 || QP_tmp >= intra_dc_vlc_thr * 2 + 11);
+        }
+
+        mblock->DCScalarLum = cal_dc_scaler(QP, LUMINANCE_DC_TYPE);     /*   ACDC 03/01/01 */
+        mblock->DCScalarChr = cal_dc_scaler(QP, CHROMINANCE_DC_TYPE);
+
+        for (comp = 0; comp < 6; comp++)
+        {
+            dataBlock = mblock->block[comp];    /*, 10/20/2000 */
+
+            dataBlock[0] = (*DC)[comp];
+
+            ncoeffs[comp] = VlcDequantH263IntraBlock(video, comp,
+                            switched, mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+
+            if (VLC_ERROR_DETECTED(ncoeffs[comp]))         /*  */
+            {
+                if (switched)
+                    return PV_FAIL;
+                else
+                {
+                    ncoeffs[comp] = 1;
+                    oscl_memset((dataBlock + 1), 0, sizeof(int16)*63);
+                }
+            }
+            no_coeff[comp] = ncoeffs[comp];
+            /*  modified to new semaphore for post-proc */
+            // Future work:: can be combined in the dequant function
+            // @todo Deblocking Semaphore for INTRA block
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[comp] = (uint8) PostProcSemaphore(dataBlock);
+#endif
+        }
+        MBlockIDCT(video);
+    }
+    else /* MODE INTER*/
+    {
+
+
+
+
+        MBMotionComp(video, CBP);
+        offset = (int32)(y_pos << 4) * width + (x_pos << 4);
+        c_comp  = video->currVop->yChan + offset;
+
+
+        for (comp = 0; comp < 4; comp++)
+        {
+            (*DC)[comp] = mid_gray;
+
+            if (CBP & (1 << (5 - comp)))
+            {
+                ncoeffs[comp] = VlcDequantH263InterBlock(video, comp,
+                                mblock->bitmapcol[comp], &mblock->bitmaprow[comp]);
+                if (VLC_ERROR_DETECTED(ncoeffs[comp]))
+                    return PV_FAIL;
+
+
+                BlockIDCT(c_comp + (comp&2)*(width << 2) + 8*(comp&1), mblock->pred_block + (comp&2)*64 + 8*(comp&1), mblock->block[comp], width, ncoeffs[comp],
+                          mblock->bitmapcol[comp], mblock->bitmaprow[comp]);
+
+            }
+            else
+            {
+                ncoeffs[comp] = 0;
+            }
+
+            /*  @todo Deblocking Semaphore for INTRA block, for inter just test for ringing  */
+#ifdef PV_POSTPROC_ON
+            if (video->postFilterType != PV_NO_POST_PROC)
+                *pp_mod[comp] = (uint8)((ncoeffs[comp] > 3) ? 4 : 0);
+#endif
+        }
+
+        (*DC)[4] = mid_gray;
+        if (CBP & 2)
+        {
+            ncoeffs[4] = VlcDequantH263InterBlock(video, 4,
+                                                  mblock->bitmapcol[4], &mblock->bitmaprow[4]);
+            if (VLC_ERROR_DETECTED(ncoeffs[4]))
+                return PV_FAIL;
+
+            BlockIDCT(video->currVop->uChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 256, mblock->block[4], width >> 1, ncoeffs[4],
+                      mblock->bitmapcol[4], mblock->bitmaprow[4]);
+
+        }
+        else
+        {
+            ncoeffs[4] = 0;
+        }
+#ifdef PV_POSTPROC_ON
+        if (video->postFilterType != PV_NO_POST_PROC)
+            *pp_mod[4] = (uint8)((ncoeffs[4] > 3) ? 4 : 0);
+#endif
+        (*DC)[5] = mid_gray;
+        if (CBP & 1)
+        {
+            ncoeffs[5] = VlcDequantH263InterBlock(video, 5,
+                                                  mblock->bitmapcol[5], &mblock->bitmaprow[5]);
+            if (VLC_ERROR_DETECTED(ncoeffs[5]))
+                return PV_FAIL;
+
+            BlockIDCT(video->currVop->vChan + (offset >> 2) + (x_pos << 2), mblock->pred_block + 264, mblock->block[5], width >> 1, ncoeffs[5],
+                      mblock->bitmapcol[5], mblock->bitmaprow[5]);
+
+        }
+        else
+        {
+            ncoeffs[5] = 0;
+        }
+#ifdef PV_POSTPROC_ON
+        if (video->postFilterType != PV_NO_POST_PROC)
+            *pp_mod[5] = (uint8)((ncoeffs[5] > 3) ? 4 : 0);
+#endif
+
+
+
+
+        /* Motion compensation and put it to video->mblock->pred_block */
+    }
+    return PV_SUCCESS;
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/dcac_prediction.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/dcac_prediction.cpp
new file mode 100644
index 0000000..2a8bf1e
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/dcac_prediction.cpp
@@ -0,0 +1,368 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "zigzag.h"
+#include "scaling.h"
+
+void    doDCACPrediction(
+    VideoDecData *video,
+    int comp,
+    int16 *q_block,
+    int *direction
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int i;
+    int mbnum = video->mbnum;
+    int nMBPerRow = video->nMBPerRow;
+    int x_pos = video->mbnum_col;
+    int y_pos = video->mbnum_row;
+    int16 *AC_tmp;
+    int QP_tmp;
+    int16 *QP_store = video->QPMB + mbnum;
+    int QP = video->QPMB[mbnum];
+    int QP_half = QP >> 1;
+    int32 val;
+    int flag_0 = FALSE, flag_1 = FALSE;
+    uint8 *slice_nb = video->sliceNo;
+    typeDCStore *DC_store = video->predDC + mbnum;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+
+    uint ACpred_flag = (uint) video->acPredFlag[mbnum];
+
+    int left_bnd, up_bnd;
+
+    static const int Xpos[6] = { -1, 0, -1, 0, -1, -1};
+    static const int Ypos[6] = { -1, -1, 0, 0, -1, -1};
+
+    static const int Xtab[6] = {1, 0, 3, 2, 4, 5};
+    static const int Ytab[6] = {2, 3, 0, 1, 4, 5};
+    static const int Ztab[6] = {3, 2, 1, 0, 4, 5};
+
+    /* I added these to speed up comparisons */
+    static const int Pos0[6] = { 1, 1, 0, 0, 1, 1};
+    static const int Pos1[6] = { 1, 0, 1, 0, 1, 1};
+
+    static const int B_Xtab[6] = {0, 1, 0, 1, 2, 3};
+    static const int B_Ytab[6] = {0, 0, 1, 1, 2, 3};
+
+//  int *direction;     /* 0: HORIZONTAL, 1: VERTICAL */
+    int block_A, block_B, block_C;
+    int DC_pred;
+    int y_offset, x_offset, x_tab, y_tab, z_tab;    /* speedup coefficients */
+    int b_xtab, b_ytab;
+
+    if (!comp && x_pos && !(video->headerInfo.Mode[mbnum-1]&INTRA_MASK)) /* not intra */
+    {
+        oscl_memset(DCAC_col, 0, sizeof(typeDCACStore));
+    }
+    if (!comp && y_pos && !(video->headerInfo.Mode[mbnum-nMBPerRow]&INTRA_MASK)) /* not intra */
+    {
+        oscl_memset(DCAC_row, 0, sizeof(typeDCACStore));
+    }
+
+    y_offset = Ypos[comp] * nMBPerRow;
+    x_offset = Xpos[comp];
+    x_tab = Xtab[comp];
+    y_tab = Ytab[comp];
+    z_tab = Ztab[comp];
+
+    b_xtab = B_Xtab[comp];
+    b_ytab = B_Ytab[comp];
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Find the direction of prediction and the DC prediction */
+
+    if (x_pos == 0 && y_pos == 0)
+    {   /* top left corner */
+        block_A = (comp == 1 || comp == 3) ? flag_0 = TRUE, DC_store[0][x_tab] : mid_gray;
+        block_B = (comp == 3) ? DC_store[x_offset][z_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3) ? flag_1 = TRUE, DC_store[0][y_tab] : mid_gray;
+    }
+    else if (x_pos == 0)
+    {   /* left edge */
+        up_bnd   = Pos0[comp] && slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow];
+
+        block_A = (comp == 1 || comp == 3) ? flag_0 = TRUE, DC_store[0][x_tab] : mid_gray;
+        block_B = ((comp == 1 && up_bnd) || comp == 3) ?  DC_store[y_offset+x_offset][z_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3 || up_bnd) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+    else if (y_pos == 0)
+    { /* top row */
+        left_bnd = Pos1[comp] && slice_nb[mbnum] == slice_nb[mbnum-1];
+
+        block_A = (comp == 1 || comp == 3 || left_bnd) ? flag_0 = TRUE, DC_store[x_offset][x_tab] : mid_gray;
+        block_B = ((comp == 2 && left_bnd) || comp == 3) ? DC_store[y_offset + x_offset][z_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+    else
+    {
+        up_bnd   = Pos0[comp] && slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow];
+        left_bnd = Pos1[comp] && slice_nb[mbnum] == slice_nb[mbnum-1];
+
+        block_A = (comp == 1 || comp == 3 || left_bnd) ? flag_0 = TRUE, DC_store[x_offset][x_tab] : mid_gray;
+        block_B = (((comp == 0 || comp == 4 || comp == 5) && slice_nb[mbnum] == slice_nb[mbnum-1-nMBPerRow]) ||
+                   (comp == 1 && up_bnd) || (comp == 2 && left_bnd) || (comp == 3)) ? DC_store[y_offset+x_offset][z_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3 || up_bnd) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+
+
+    if ((PV_ABS((block_A - block_B))) < (PV_ABS((block_B - block_C))))
+    {
+        DC_pred = block_C;
+        *direction = 1;
+        if (ACpred_flag == 1)
+        {
+            if (flag_1)
+            {
+                AC_tmp = DCAC_row[0][b_xtab];
+                QP_tmp = QP_store[y_offset];
+                if (QP_tmp == QP)
+                {
+                    for (i = 1; i < 8; i++)
+                    {
+                        q_block[i] = *AC_tmp++;
+                    }
+                }
+                else
+                {
+                    for (i = 1; i < 8; i++)
+                    {
+                        val = (int32)(*AC_tmp++) * QP_tmp;
+                        q_block[i] = (val < 0) ? (int16)((val - QP_half) / QP) : (int16)((val + QP_half) / QP);
+                        /* Vertical, top ROW of block C */
+                    }
+                }
+            }
+        }
+    }
+    else
+    {
+        DC_pred = block_A;
+        *direction = 0;
+        if (ACpred_flag == 1)
+        {
+            if (flag_0)
+            {
+                AC_tmp = DCAC_col[0][b_ytab];
+                QP_tmp = QP_store[x_offset];
+                if (QP_tmp == QP)
+                {
+                    for (i = 1; i < 8; i++)
+                    {
+                        q_block[i<<3] = *AC_tmp++;
+                    }
+                }
+                else
+                {
+                    for (i = 1; i < 8; i++)
+                    {
+                        val = (int32)(*AC_tmp++) * QP_tmp;
+                        q_block[i<<3] = (val < 0) ? (int16)((val - QP_half) / QP) : (int16)((val + QP_half) / QP);
+                        /* Vertical, top ROW of block C */
+                    }
+                }
+            }
+        }
+    }
+
+    /* Now predict the DC coefficient */
+    QP_tmp = (comp < 4) ? video->mblock->DCScalarLum : video->mblock->DCScalarChr;
+    q_block[0] += (int16)((DC_pred + (QP_tmp >> 1)) * scale[QP_tmp] >> 18);
+//      q_block[0] += (DC_pred+(QP_tmp>>1))/QP_tmp;
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#ifdef PV_ANNEX_IJKT_SUPPORT
+void    doDCACPrediction_I(
+    VideoDecData *video,
+    int comp,
+    int16 *q_block
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int mbnum = video->mbnum;
+    int nMBPerRow = video->nMBPerRow;
+    int x_pos = video->mbnum_col;
+    int y_pos = video->mbnum_row;
+    int16 *AC_tmp;
+    int flag_0 = FALSE, flag_1 = FALSE;
+    uint8 *slice_nb = video->sliceNo;
+    typeDCStore *DC_store = video->predDC + mbnum;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+    int left_bnd, up_bnd;
+    uint8 *mode = video->headerInfo.Mode;
+    uint ACpred_flag = (uint) video->acPredFlag[mbnum];
+
+
+
+    static const int Xpos[6] = { -1, 0, -1, 0, -1, -1};
+    static const int Ypos[6] = { -1, -1, 0, 0, -1, -1};
+
+    static const int Xtab[6] = {1, 0, 3, 2, 4, 5};
+    static const int Ytab[6] = {2, 3, 0, 1, 4, 5};
+
+    /* I added these to speed up comparisons */
+    static const int Pos0[6] = { 1, 1, 0, 0, 1, 1};
+    static const int Pos1[6] = { 1, 0, 1, 0, 1, 1};
+
+    static const int B_Xtab[6] = {0, 1, 0, 1, 2, 3};
+    static const int B_Ytab[6] = {0, 0, 1, 1, 2, 3};
+
+//  int *direction;     /* 0: HORIZONTAL, 1: VERTICAL */
+    int block_A, block_C;
+    int y_offset, x_offset, x_tab, y_tab;   /* speedup coefficients */
+    int b_xtab, b_ytab;
+    y_offset = Ypos[comp] * nMBPerRow;
+    x_offset = Xpos[comp];
+    x_tab = Xtab[comp];
+    y_tab = Ytab[comp];
+
+    b_xtab = B_Xtab[comp];
+    b_ytab = B_Ytab[comp];
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Find the direction of prediction and the DC prediction */
+
+    if (x_pos == 0 && y_pos == 0)
+    {   /* top left corner */
+        block_A = (comp == 1 || comp == 3) ? flag_0 = TRUE, DC_store[0][x_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3) ? flag_1 = TRUE, DC_store[0][y_tab] : mid_gray;
+    }
+    else if (x_pos == 0)
+    {   /* left edge */
+        up_bnd   = (Pos0[comp] && slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow])
+                   && (mode[mbnum-nMBPerRow] == MODE_INTRA || mode[mbnum-nMBPerRow] == MODE_INTRA_Q);;
+
+        block_A = (comp == 1 || comp == 3) ? flag_0 = TRUE, DC_store[0][x_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3 || up_bnd) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+    else if (y_pos == 0)
+    { /* top row */
+        left_bnd = (Pos1[comp] && slice_nb[mbnum] == slice_nb[mbnum-1])
+                   && (mode[mbnum-1] == MODE_INTRA || mode[mbnum-1] == MODE_INTRA_Q);
+
+        block_A = (comp == 1 || comp == 3 || left_bnd) ? flag_0 = TRUE, DC_store[x_offset][x_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+    else
+    {
+        up_bnd   = (Pos0[comp] && slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow])
+                   && (mode[mbnum-nMBPerRow] == MODE_INTRA || mode[mbnum-nMBPerRow] == MODE_INTRA_Q);
+        left_bnd = (Pos1[comp] && slice_nb[mbnum] == slice_nb[mbnum-1])
+                   && (mode[mbnum-1] == MODE_INTRA || mode[mbnum-1] == MODE_INTRA_Q);
+
+        block_A = (comp == 1 || comp == 3 || left_bnd) ? flag_0 = TRUE, DC_store[x_offset][x_tab] : mid_gray;
+        block_C = (comp == 2 || comp == 3 || up_bnd) ? flag_1 = TRUE, DC_store[y_offset][y_tab] : mid_gray;
+    }
+
+    if (ACpred_flag == 0)
+    {
+        if (flag_0 == TRUE)
+        {
+            if (flag_1 == TRUE)
+            {
+                q_block[0] = (int16)((block_A + block_C) >> 1);
+            }
+            else
+            {
+                q_block[0] = (int16)block_A;
+            }
+        }
+        else
+        {
+            if (flag_1 == TRUE)
+            {
+                q_block[0] = (int16)block_C;
+            }
+            else
+            {
+                q_block[0] = mid_gray;
+            }
+        }
+
+    }
+    else
+    {
+        if (video->mblock->direction == 1)
+        {
+            if (flag_1 == TRUE)
+            {
+                q_block[0] = (int16)block_C;
+
+                AC_tmp = DCAC_row[0][b_xtab];
+                q_block[1] = AC_tmp[0];
+                q_block[2] = AC_tmp[1];
+                q_block[3] = AC_tmp[2];
+                q_block[4] = AC_tmp[3];
+                q_block[5] = AC_tmp[4];
+                q_block[6] = AC_tmp[5];
+                q_block[7] = AC_tmp[6];
+            }
+            else
+            {
+                q_block[0] = mid_gray;
+            }
+        }
+        else
+        {
+            if (flag_0 == TRUE)
+            {
+                q_block[0] = (int16)block_A;
+
+                AC_tmp = DCAC_col[0][b_ytab];
+                q_block[8] = AC_tmp[0];
+                q_block[16] = AC_tmp[1];
+                q_block[24] = AC_tmp[2];
+                q_block[32] = AC_tmp[3];
+                q_block[40] = AC_tmp[4];
+                q_block[48] = AC_tmp[5];
+                q_block[56] = AC_tmp[6];
+            }
+            else
+            {
+                q_block[0] = mid_gray;
+            }
+        }
+    }
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp
new file mode 100644
index 0000000..c19c23a
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/dec_pred_intra_dc.cpp
@@ -0,0 +1,75 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "zigzag.h"
+
+PV_STATUS PV_DecodePredictedIntraDC(
+    int compnum,
+    BitstreamDecVideo *stream,
+    int16 *INTRADC_delta)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    PV_STATUS status = PV_SUCCESS;
+    uint DC_size;
+    uint code;
+    int first_bit;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* read DC size 2 - 8 bits */
+    status = PV_VlcDecIntraDCPredSize(stream, compnum, &DC_size);
+
+    if (status == PV_SUCCESS)
+    {
+        if (DC_size == 0)
+        {
+            *INTRADC_delta = 0;
+        }
+        else
+        {
+            /* read delta DC 0 - 8 bits */
+            code = (int) BitstreamReadBits16_INLINE(stream, DC_size);
+
+            first_bit = code >> (DC_size - 1);
+
+            if (first_bit == 0)
+            {
+                /* negative delta INTRA DC */
+                *INTRADC_delta = code ^((1 << DC_size) - 1);
+                *INTRADC_delta = -(*INTRADC_delta);
+            }
+            else
+            { /* positive delta INTRA DC */
+                *INTRADC_delta = code;
+            }
+            if (DC_size > 8) BitstreamRead1Bits_INLINE(stream);
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return status;
+}
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp
new file mode 100644
index 0000000..ce779b0
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_chroma.cpp
@@ -0,0 +1,215 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include    "mp4dec_lib.h"
+#include    "post_proc.h"
+
+#ifdef PV_POSTPROC_ON
+
+void Deringing_Chroma(
+    uint8 *Rec_C,
+    int width,
+    int height,
+    int16 *QP_store,
+    int,
+    uint8 *pp_mod
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int thres;
+    int v_blk, h_blk;
+    int max_diff;
+    int v_pel, h_pel;
+    int max_blk, min_blk;
+    int v0, h0;
+    uint8 *ptr;
+    int sum, sum1, incr;
+    int32 addr_v;
+    int sign_v[10], sum_v[10];
+    int *ptr2, *ptr3;
+    uint8 pelu, pelc, pell;
+    incr = width - BLKSIZE;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* chrominance */
+    /* Do the first line (7 pixels at a time => Don't use MMX)*/
+    for (h_blk = 0; h_blk < width; h_blk += BLKSIZE)
+    {
+        max_diff = (QP_store[h_blk>>3] >> 2) + 4;
+        ptr = &Rec_C[h_blk];
+        max_blk = min_blk = *ptr;
+        FindMaxMin(ptr, &min_blk, &max_blk, width);
+        h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
+
+        if (max_blk - min_blk >= 4)
+        {
+            thres = (max_blk + min_blk + 1) >> 1;
+
+
+            for (v_pel = 1; v_pel < BLKSIZE - 1; v_pel++)
+            {
+                addr_v = (int32)v_pel * width;
+                ptr = &Rec_C[addr_v + h0 - 1];
+                ptr2 = &sum_v[0];
+                ptr3 = &sign_v[0];
+
+                pelu = *(ptr - width);
+                pelc = *ptr;
+                pell = *(ptr + width);
+                ptr++;
+                *ptr2++ = pelu + (pelc << 1) + pell;
+                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                pelu = *(ptr - width);
+                pelc = *ptr;
+                pell = *(ptr + width);
+                ptr++;
+                *ptr2++ = pelu + (pelc << 1) + pell;
+                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                for (h_pel = h0; h_pel < h_blk + BLKSIZE - 1; h_pel++)
+                {
+                    pelu = *(ptr - width);
+                    pelc = *ptr;
+                    pell = *(ptr + width);
+
+                    *ptr2 = pelu + (pelc << 1) + pell;
+                    *ptr3 = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                    sum1 = *(ptr3 - 2) + *(ptr3 - 1) + *ptr3;
+                    if (sum1 == 0 || sum1 == 9)
+                    {
+                        sum = (*(ptr2 - 2) + (*(ptr2 - 1) << 1) + *ptr2 + 8) >> 4;
+
+                        ptr--;
+                        if (PV_ABS(*ptr - sum) > max_diff)
+                        {
+                            if (sum > *ptr)
+                                sum = *ptr + max_diff;
+                            else
+                                sum = *ptr - max_diff;
+                        }
+                        *ptr++ = (uint8) sum;
+                    }
+                    ptr++;
+                    ptr2++;
+                    ptr3++;
+                }
+            }
+        }
+    }
+
+    for (v_blk = BLKSIZE; v_blk < height; v_blk += BLKSIZE)
+    {
+        v0 = v_blk - 1;
+        /* Do the first block (pixels=7 => No MMX) */
+        max_diff = (QP_store[((((int32)v_blk*width)>>3))>>3] >> 2) + 4;
+        ptr = &Rec_C[(int32)v_blk * width];
+        max_blk = min_blk = *ptr;
+        FindMaxMin(ptr, &min_blk, &max_blk, incr);
+
+        if (max_blk - min_blk >= 4)
+        {
+            thres = (max_blk + min_blk + 1) >> 1;
+
+            for (v_pel = v0; v_pel < v_blk + BLKSIZE - 1; v_pel++)
+            {
+                addr_v = v_pel * width;
+                ptr = &Rec_C[addr_v];
+                ptr2 = &sum_v[0];
+                ptr3 = &sign_v[0];
+
+                pelu = *(ptr - width);
+                pelc = *ptr;
+                pell = *(ptr + width);
+                ptr++;
+                *ptr2++ = pelu + (pelc << 1) + pell;
+                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                pelu = *(ptr - width);
+                pelc = *ptr;
+                pell = *(ptr + width);
+                ptr++;
+                *ptr2++ = pelu + (pelc << 1) + pell;
+                *ptr3++ = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                for (h_pel = 1; h_pel < BLKSIZE - 1; h_pel++)
+                {
+                    pelu = *(ptr - width);
+                    pelc = *ptr;
+                    pell = *(ptr + width);
+
+                    *ptr2 = pelu + (pelc << 1) + pell;
+                    *ptr3 = INDEX(pelu, thres) + INDEX(pelc, thres) + INDEX(pell, thres);
+
+                    sum1 = *(ptr3 - 2) + *(ptr3 - 1) + *ptr3;
+                    if (sum1 == 0 || sum1 == 9)
+                    {
+                        sum = (*(ptr2 - 2) + (*(ptr2 - 1) << 1) + *ptr2 + 8) >> 4;
+
+                        ptr--;
+                        if (PV_ABS(*ptr - sum) > max_diff)
+                        {
+                            if (sum > *ptr)
+                                sum = *ptr + max_diff;
+                            else
+                                sum = *ptr - max_diff;
+                        }
+                        *ptr++ = (uint8) sum;
+                    }
+                    ptr++;
+                    ptr2++;
+                    ptr3++;
+                }
+            }
+        }
+
+
+        /* Do the rest in MMX */
+        for (h_blk = BLKSIZE; h_blk < width; h_blk += BLKSIZE)
+        {
+            if ((pp_mod[(v_blk/8)*(width/8)+h_blk/8]&0x4) != 0)
+            {
+                max_diff = (QP_store[((((int32)v_blk*width)>>3)+h_blk)>>3] >> 2) + 4;
+                ptr = &Rec_C[(int32)v_blk * width + h_blk];
+                max_blk = min_blk = *ptr;
+                FindMaxMin(ptr, &min_blk, &max_blk, incr);
+                h0 = h_blk - 1;
+
+                if (max_blk - min_blk >= 4)
+                {
+                    thres = (max_blk + min_blk + 1) >> 1;
+#ifdef NoMMX
+                    AdaptiveSmooth_NoMMX(Rec_C, v0, h0, v_blk, h_blk, thres, width, max_diff);
+#else
+                    DeringAdaptiveSmoothMMX(&Rec_C[(int32)v0*width+h0], width, thres, max_diff);
+#endif
+                }
+            }
+        }
+    } /* macroblock level */
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.cpp
new file mode 100644
index 0000000..b5574b4
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/deringing_luma.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.
+ * -------------------------------------------------------------------
+ */
+#include    "mp4dec_lib.h"
+#include    "post_proc.h"
+
+#ifdef PV_POSTPROC_ON
+
+void Deringing_Luma(
+    uint8 *Rec_Y,
+    int width,
+    int height,
+    int16 *QP_store,
+    int,
+    uint8 *pp_mod)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int thres[4], range[4], max_range_blk, max_thres_blk;
+    int MB_V, MB_H, BLK_V, BLK_H;
+    int v_blk, h_blk;
+    int max_diff;
+    int max_blk, min_blk;
+    int v0, h0;
+    uint8 *ptr;
+    int thr, blks, incr;
+    int mb_indx, blk_indx;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    incr = width - BLKSIZE;
+
+    /* Dering the first line of macro blocks */
+    for (MB_H = 0; MB_H < width; MB_H += MBSIZE)
+    {
+        max_diff = (QP_store[(MB_H)>>4] >> 2) + 4;
+
+        /* threshold determination */
+        max_range_blk = max_thres_blk = 0;
+        blks = 0;
+
+        for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
+        {
+            for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
+            {
+                ptr = &Rec_Y[(int32)(BLK_V) * width + MB_H + BLK_H];
+                FindMaxMin(ptr, &min_blk, &max_blk, incr);
+
+                thres[blks] = (max_blk + min_blk + 1) >> 1;
+                range[blks] = max_blk - min_blk;
+
+                if (range[blks] >= max_range_blk)
+                {
+                    max_range_blk = range[blks];
+                    max_thres_blk = thres[blks];
+                }
+                blks++;
+            }
+        }
+
+        blks = 0;
+        for (v_blk = 0; v_blk < MBSIZE; v_blk += BLKSIZE)
+        {
+            v0 = ((v_blk - 1) >= 1) ? (v_blk - 1) : 1;
+            for (h_blk = MB_H; h_blk < MB_H + MBSIZE; h_blk += BLKSIZE)
+            {
+                h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
+
+                /* threshold rearrangement for flat region adjacent to non-flat region */
+                if (range[blks]<32 && max_range_blk >= 64)
+                    thres[blks] = max_thres_blk;
+
+                /* threshold rearrangement for deblocking
+                (blockiness annoying at DC dominant region) */
+                if (max_range_blk >= 16)
+                {
+                    /* adaptive smoothing */
+                    thr = thres[blks];
+
+                    AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
+                                         thr, width, max_diff);
+                }
+                blks++;
+            } /* block level (Luminance) */
+        }
+    } /* macroblock level */
+
+
+    /* Do the rest of the macro-block-lines */
+    for (MB_V = MBSIZE; MB_V < height; MB_V += MBSIZE)
+    {
+        /* First macro-block */
+        max_diff = (QP_store[((((int32)MB_V*width)>>4))>>4] >> 2) + 4;
+        /* threshold determination */
+        max_range_blk = max_thres_blk = 0;
+        blks = 0;
+        for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
+        {
+            for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
+            {
+                ptr = &Rec_Y[(int32)(MB_V + BLK_V) * width + BLK_H];
+                FindMaxMin(ptr, &min_blk, &max_blk, incr);
+                thres[blks] = (max_blk + min_blk + 1) >> 1;
+                range[blks] = max_blk - min_blk;
+
+                if (range[blks] >= max_range_blk)
+                {
+                    max_range_blk = range[blks];
+                    max_thres_blk = thres[blks];
+                }
+                blks++;
+            }
+        }
+
+        blks = 0;
+        for (v_blk = MB_V; v_blk < MB_V + MBSIZE; v_blk += BLKSIZE)
+        {
+            v0 = v_blk - 1;
+            for (h_blk = 0; h_blk < MBSIZE; h_blk += BLKSIZE)
+            {
+                h0 = ((h_blk - 1) >= 1) ? (h_blk - 1) : 1;
+
+                /* threshold rearrangement for flat region adjacent to non-flat region */
+                if (range[blks]<32 && max_range_blk >= 64)
+                    thres[blks] = max_thres_blk;
+
+                /* threshold rearrangement for deblocking
+                (blockiness annoying at DC dominant region) */
+                if (max_range_blk >= 16)
+                {
+                    /* adaptive smoothing */
+                    thr = thres[blks];
+
+                    AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
+                                         thr, width, max_diff);
+                }
+                blks++;
+            }
+        } /* block level (Luminance) */
+
+        /* Rest of the macro-blocks */
+        for (MB_H = MBSIZE; MB_H < width; MB_H += MBSIZE)
+        {
+            max_diff = (QP_store[((((int32)MB_V*width)>>4)+MB_H)>>4] >> 2) + 4;
+
+            /* threshold determination */
+            max_range_blk = max_thres_blk = 0;
+            blks = 0;
+
+            mb_indx = (MB_V / 8) * (width / 8) + MB_H / 8;
+            for (BLK_V = 0; BLK_V < MBSIZE; BLK_V += BLKSIZE)
+            {
+                for (BLK_H = 0; BLK_H < MBSIZE; BLK_H += BLKSIZE)
+                {
+                    blk_indx = mb_indx + (BLK_V / 8) * width / 8 + BLK_H / 8;
+                    /* Update based on pp_mod only */
+                    if ((pp_mod[blk_indx]&0x4) != 0)
+                    {
+                        ptr = &Rec_Y[(int32)(MB_V + BLK_V) * width + MB_H + BLK_H];
+                        FindMaxMin(ptr, &min_blk, &max_blk, incr);
+                        thres[blks] = (max_blk + min_blk + 1) >> 1;
+                        range[blks] = max_blk - min_blk;
+
+                        if (range[blks] >= max_range_blk)
+                        {
+                            max_range_blk = range[blks];
+                            max_thres_blk = thres[blks];
+                        }
+                    }
+                    blks++;
+                }
+            }
+
+            blks = 0;
+            for (v_blk = MB_V; v_blk < MB_V + MBSIZE; v_blk += BLKSIZE)
+            {
+                v0 = v_blk - 1;
+                mb_indx = (v_blk / 8) * (width / 8);
+                for (h_blk = MB_H; h_blk < MB_H + MBSIZE; h_blk += BLKSIZE)
+                {
+                    h0 = h_blk - 1;
+                    blk_indx = mb_indx + h_blk / 8;
+                    if ((pp_mod[blk_indx]&0x4) != 0)
+                    {
+                        /* threshold rearrangement for flat region adjacent to non-flat region */
+                        if (range[blks]<32 && max_range_blk >= 64)
+                            thres[blks] = max_thres_blk;
+
+                        /* threshold rearrangement for deblocking
+                        (blockiness annoying at DC dominant region) */
+                        if (max_range_blk >= 16)
+                        {
+                            /* adaptive smoothing */
+                            thr = thres[blks];
+#ifdef NoMMX
+                            AdaptiveSmooth_NoMMX(Rec_Y, v0, h0, v_blk, h_blk,
+                                                 thr, width, max_diff);
+#else
+                            DeringAdaptiveSmoothMMX(&Rec_Y[v0*width+h0],
+                                                    width, thr, max_diff);
+#endif
+                        }
+                    }
+                    blks++;
+                }
+            } /* block level (Luminance) */
+        } /* macroblock level */
+    } /* macroblock level */
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp
new file mode 100644
index 0000000..a357ea6
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/find_min_max.cpp
@@ -0,0 +1,176 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    input_ptr = pointer to the buffer containing values of type UChar
+            in a 2D block of data.
+    min_ptr = pointer to the minimum value of type Int to be found in a
+          square block of size BLKSIZE contained in 2D block of data.
+    max_ptr = pointer to the maximum value of type Int to be found in a
+          square block of size BLKSIZE contained in 2D block of data.
+    incr = value of type Int representing the width of 2D block of data.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    min_ptr points to the found minimum value in the square block of
+    size BLKSIZE contained in 2D block of data.
+
+    max_ptr points to the found maximum value in the square block of
+    size BLKSIZE contained in 2D block of data.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function finds the maximum and the minimum values in a square block of
+ data of size BLKSIZE * BLKSIZE. The data is contained in the buffer which
+ represents a 2D block of data that is larger than BLKSIZE * BLKSIZE.
+ This is illustrated below.
+
+    mem loc x + 00h -> o o o o o o o o o o o o o o o o
+    mem loc x + 10h -> o o o o o X X X X X X X X o o o
+    mem loc x + 20h -> o o o o o X X X X X X X X o o o
+    mem loc x + 30h -> o o o o o X X X X X X X X o o o
+    mem loc x + 40h -> o o o o o X X X X X X X X o o o
+    mem loc x + 50h -> o o o o o X X X X X X X X o o o
+    mem loc x + 60h -> o o o o o X X X X X X X X o o o
+    mem loc x + 70h -> o o o o o X X X X X X X X o o o
+    mem loc x + 80h -> o o o o o X X X X X X X X o o o
+    mem loc x + 90h -> o o o o o o o o o o o o o o o o
+    mem loc x + A0h -> o o o o o o o o o o o o o o o o
+    mem loc x + B0h -> o o o o o o o o o o o o o o o o
+
+For illustration purposes, the diagram assumes that BLKSIZE is equal to 8
+but this is not a requirement. In this diagram, the buffer starts at
+location x but the input pointer, input_ptr, passed into this function
+would be the first row of data to be searched which is at x + 15h. The
+value of incr passed onto this function represents the amount the input_ptr
+needs to be incremented to point to the next row of data.
+
+This function compares each value in a row to the current maximum and
+minimum. After each row, input_ptr is incremented to point to the next row.
+This is repeated until all rows have been processed. When the search is
+complete the location pointed to by min_ptr contains the minimum value
+found and the location pointed to by max_ptr contains the maximum value found.
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "mp4dec_lib.h"
+#include    "post_proc.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
+----------------------------------------------------------------------------*/
+
+#ifdef PV_POSTPROC_ON
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void  FindMaxMin(
+    uint8 *input_ptr,
+    int *min_ptr,
+    int *max_ptr,
+    int incr)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    register    uint    i, j;
+    register    int min, max;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    max = min = *input_ptr;
+    /*  incr = incr - BLKSIZE; */   /*  09/06/2001, already passed in as width - BLKSIZE */
+
+    for (i = BLKSIZE; i > 0; i--)
+    {
+        for (j = BLKSIZE; j > 0; j--)
+        {
+            if (*input_ptr > max)
+            {
+                max = *input_ptr;
+            }
+            else if (*input_ptr < min)
+            {
+                min = *input_ptr;
+            }
+            input_ptr += 1;
+        }
+
+        /* set pointer to the beginning of the next row*/
+        input_ptr += incr;
+    }
+
+    *max_ptr = max;
+    *min_ptr = min;
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
new file mode 100644
index 0000000..e23f23d
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_adv_b_add.cpp
@@ -0,0 +1,1190 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xpos = x half-pixel of (x,y) coordinates within a VOP; motion
+           compensated coordinates; native type
+    ypos = y half-pixel of (x,y) coordinates within a VOP; motion
+           compensated coordinates; native type
+    comp = pointer to 8-bit compensated prediction values within a VOP;
+        computed by this module (i/o); full-pel resolution
+    c_prev = pointer to previous 8-bit prediction values within a VOP;
+          values range from (0-255); full-pel resolution
+    sh_d = pointer to residual values used to compensate the predicted
+        value; values range from (-512 to 511); full-pel resolution
+    width = width of the VOP in pixels (x axis); full-pel resolution
+    rnd1 = rounding value for case when one dimension uses half-pel
+           resolution
+    rnd2 = rounding value for case when two dimensions uses half-pel
+           resolution
+    CBP = flag indicating whether residual is all zeros
+          (0 -> all zeros, 1 -> not all zeros)
+        outside_flag = flag indicating whether motion vector is outside the
+               VOP (0 -> inside, 1 -> outside)
+
+ Outputs:
+    returns 1
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Pointers and Buffers Modified:
+    comp = buffer contains newly computed compensated prediction values
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Compute pixel values for a block in the current VOP. The prediction
+ values are generated by averaging pixel values in the previous VOP; the
+ block position in the previous frame is computed from the current block's
+ motion vector. The computed pixel values are then computed by adding the
+ prediction values to the block residual values.
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+#include "motion_comp.h"
+
+#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
+
+int GetPredAdvancedBy0x0(
+    uint8 *prev,        /* i */
+    uint8 *pred_block,      /* i */
+    int width,      /* i */
+    int pred_width_rnd /* i */
+)
+{
+    uint    i;      /* loop variable */
+    int offset, offset2;
+    uint32  pred_word, word1, word2;
+    int tmp;
+
+    /* initialize offset to adjust pixel counter */
+    /*    the next row; full-pel resolution      */
+    offset = width - B_SIZE; /* offset for prev */
+    offset2 = (pred_width_rnd >> 1) - 4; /* offset for pred_block */
+
+    tmp = (uint32)prev & 0x3;
+    pred_block -= offset2; /* preset */
+
+    if (tmp == 0)  /* word-aligned */
+    {
+        for (i = B_SIZE; i > 0; i--)
+        {
+            *((uint32*)(pred_block += offset2)) = *((uint32*)prev);
+            *((uint32*)(pred_block += 4)) = *((uint32*)(prev + 4));
+            prev += width;
+        }
+        return 1;
+    }
+    else if (tmp == 1) /* first position */
+    {
+        prev--; /* word-aligned */
+
+        for (i = B_SIZE; i > 0; i--)
+        {
+            word1 = *((uint32*)prev); /* read 4 bytes, b4 b3 b2 b1 */
+            word2 = *((uint32*)(prev += 4));  /* read 4 bytes, b8 b7 b6 b5 */
+            word1 >>= 8; /* 0 b4 b3 b2 */
+            pred_word = word1 | (word2 << 24);  /* b5 b4 b3 b2 */
+            *((uint32*)(pred_block += offset2)) = pred_word;
+
+            word1 = *((uint32*)(prev += 4)); /* b12 b11 b10 b9 */
+            word2 >>= 8; /* 0 b8 b7 b6 */
+            pred_word = word2 | (word1 << 24); /* b9 b8 b7 b6 */
+            *((uint32*)(pred_block += 4)) = pred_word;
+
+            prev += offset;
+        }
+
+        return 1;
+    }
+    else if (tmp == 2) /* second position */
+    {
+        prev -= 2; /* word1-aligned */
+
+        for (i = B_SIZE; i > 0; i--)
+        {
+            word1 = *((uint32*)prev); /* read 4 bytes, b4 b3 b2 b1 */
+            word2 = *((uint32*)(prev += 4));  /* read 4 bytes, b8 b7 b6 b5 */
+            word1 >>= 16; /* 0 0 b4 b3 */
+            pred_word = word1 | (word2 << 16);  /* b6 b5 b4 b3 */
+            *((uint32*)(pred_block += offset2)) = pred_word;
+
+            word1 = *((uint32*)(prev += 4)); /* b12 b11 b10 b9 */
+            word2 >>= 16; /* 0 0 b8 b7 */
+            pred_word = word2 | (word1 << 16); /* b10 b9 b8 b7 */
+            *((uint32*)(pred_block += 4)) = pred_word;
+
+
+            prev += offset;
+        }
+
+        return 1;
+    }
+    else /* third position */
+    {
+        prev -= 3; /* word1-aligned */
+
+        for (i = B_SIZE; i > 0; i--)
+        {
+            word1 = *((uint32*)prev); /* read 4 bytes, b4 b3 b2 b1 */
+            word2 = *((uint32*)(prev += 4));  /* read 4 bytes, b8 b7 b6 b5 */
+            word1 >>= 24; /* 0 0 0 b4 */
+            pred_word = word1 | (word2 << 8);   /* b7 b6 b5 b4 */
+            *((uint32*)(pred_block += offset2)) = pred_word;
+
+            word1 = *((uint32*)(prev += 4)); /* b12 b11 b10 b9 */
+            word2 >>= 24; /* 0 0 0 b8 */
+            pred_word = word2 | (word1 << 8); /* b11 b10 b9 b8 */
+            *((uint32*)(pred_block += 4)) = pred_word;
+
+            prev += offset;
+        }
+
+        return 1;
+    }
+}
+
+/**************************************************************************/
+int GetPredAdvancedBy0x1(
+    uint8 *prev,        /* i */
+    uint8 *pred_block,      /* i */
+    int width,      /* i */
+    int pred_width_rnd /* i */
+)
+{
+    uint    i;      /* loop variable */
+    int offset, offset2;
+    uint32 word1, word2, word3, word12;
+    int tmp;
+    int rnd1;
+    uint32 mask;
+
+    /* initialize offset to adjust pixel counter */
+    /*    the next row; full-pel resolution      */
+    offset = width - B_SIZE; /* offset for prev */
+    offset2 = (pred_width_rnd >> 1) - 4; /* offset of pred_block */
+
+    rnd1 = pred_width_rnd & 1;
+
+    /* Branch based on pixel location (half-pel or full-pel) for x and y */
+    pred_block -= offset2; /* preset */
+
+    tmp = (uint32)prev & 3;
+    mask = 254;
+    mask |= (mask << 8);
+    mask |= (mask << 16); /* 0xFEFEFEFE */
+
+    if (tmp == 0) /* word-aligned */
+    {
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b4 b3 b2 b1 */
+                word2 = *((uint32*)(prev += 4)); /* b8 b7 b6 b5 */
+                word12 = (word1 >> 8); /* 0 b4 b3 b2 */
+                word12 |= (word2 << 24); /* b5 b4 b3 b2 */
+                word3 = word1 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b12 b11 b10 b9 */
+                word12 = (word2 >> 8); /* 0 b8 b7 b6 */
+                word12 |= (word1 << 24); /* b9 b8 b7 b6 */
+                word3 = word2 | word12;
+                word2 &= mask;
+                word3 &= (~mask);  /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 == 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b4 b3 b2 b1 */
+
+                word2 = *((uint32*)(prev += 4)); /* b8 b7 b6 b5 */
+                word12 = (word1 >> 8); /* 0 b4 b3 b2 */
+                word12 |= (word2 << 24); /* b5 b4 b3 b2 */
+                word3 = word1 & word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b12 b11 b10 b9 */
+                word12 = (word2 >> 8); /* 0 b8 b7 b6 */
+                word12 |= (word1 << 24); /* b9 b8 b7 b6 */
+                word3 = word2 & word12;
+                word2 &= mask;
+                word3 &= (~mask);  /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+
+                prev += offset;
+            }
+            return 1;
+        } /* rnd1 */
+    }
+    else if (tmp == 1)
+    {
+        prev--; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b3 b2 b1 b0 */
+                word2 = *((uint32*)(prev += 4)); /* b7 b6 b5 b4 */
+                word12 = (word1 >> 8); /* 0 b3 b2 b1 */
+                word1 >>= 16; /* 0 0 b3 b2 */
+                word12 |= (word2 << 24); /* b4 b3 b2 b1 */
+                word1 |= (word2 << 16); /* b5 b4 b3 b2 */
+                word3 = word1 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b11 b10 b9 b8 */
+                word12 = (word2 >> 8); /* 0 b7 b6 b5 */
+                word2 >>= 16; /* 0 0 b7 b6 */
+                word12 |= (word1 << 24); /* b8 b7 b6 b5 */
+                word2 |= (word1 << 16); /* b9 b8 b7 b6 */
+                word3 = word2 | word12; // rnd1 = 1; otherwise word3 = word2&word12
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 = 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b3 b2 b1 b0 */
+
+                word2 = *((uint32*)(prev += 4)); /* b7 b6 b5 b4 */
+                word12 = (word1 >> 8); /* 0 b3 b2 b1 */
+                word1 >>= 16; /* 0 0 b3 b2 */
+                word12 |= (word2 << 24); /* b4 b3 b2 b1 */
+                word1 |= (word2 << 16); /* b5 b4 b3 b2 */
+                word3 = word1 & word12;
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b11 b10 b9 b8 */
+                word12 = (word2 >> 8); /* 0 b7 b6 b5 */
+                word2 >>= 16; /* 0 0 b7 b6 */
+                word12 |= (word1 << 24); /* b8 b7 b6 b5 */
+                word2 |= (word1 << 16); /* b9 b8 b7 b6 */
+                word3 = word2 & word12;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+
+                prev += offset;
+            }
+            return 1;
+        } /* rnd1 */
+    }
+    else if (tmp == 2)
+    {
+        prev -= 2; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b2 b1 b0 bN1 */
+                word2 = *((uint32*)(prev += 4)); /* b6 b5 b4 b3 */
+                word12 = (word1 >> 16); /* 0 0 b2 b1 */
+                word1 >>= 24; /* 0 0 0 b2 */
+                word12 |= (word2 << 16); /* b4 b3 b2 b1 */
+                word1 |= (word2 << 8); /* b5 b4 b3 b2 */
+                word3 = word1 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b10 b9 b8 b7 */
+                word12 = (word2 >> 16); /* 0 0 b6 b5 */
+                word2 >>= 24; /* 0 0 0 b6 */
+                word12 |= (word1 << 16); /* b8 b7 b6 b5 */
+                word2 |= (word1 << 8); /* b9 b8 b7 b6 */
+                word3 = word2 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 == 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b2 b1 b0 bN1 */
+                word2 = *((uint32*)(prev += 4)); /* b6 b5 b4 b3 */
+                word12 = (word1 >> 16); /* 0 0 b2 b1 */
+                word1 >>= 24; /* 0 0 0 b2 */
+                word12 |= (word2 << 16); /* b4 b3 b2 b1 */
+                word1 |= (word2 << 8); /* b5 b4 b3 b2 */
+                word3 = word1 & word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b10 b9 b8 b7 */
+                word12 = (word2 >> 16); /* 0 0 b6 b5 */
+                word2 >>= 24; /* 0 0 0 b6 */
+                word12 |= (word1 << 16); /* b8 b7 b6 b5 */
+                word2 |= (word1 << 8); /* b9 b8 b7 b6 */
+                word3 = word2 & word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+                prev += offset;
+            }
+            return 1;
+        }
+    }
+    else /* tmp = 3 */
+    {
+        prev -= 3; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b1 b0 bN1 bN2 */
+                word2 = *((uint32*)(prev += 4)); /* b5 b4 b3 b2 */
+                word12 = (word1 >> 24); /* 0 0 0 b1 */
+                word12 |= (word2 << 8); /* b4 b3 b2 b1 */
+                word1 = word2;
+                word3 = word1 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b9 b8 b7 b6 */
+                word12 = (word2 >> 24); /* 0 0 0 b5 */
+                word12 |= (word1 << 8); /* b8 b7 b6 b5 */
+                word2 = word1; /* b9 b8 b7 b6 */
+                word3 = word2 | word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+                prev += offset;
+            }
+            return 1;
+        }
+        else
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)prev); /* b1 b0 bN1 bN2 */
+                word2 = *((uint32*)(prev += 4)); /* b5 b4 b3 b2 */
+                word12 = (word1 >> 24); /* 0 0 0 b1 */
+                word12 |= (word2 << 8); /* b4 b3 b2 b1 */
+                word1 = word2;
+                word3 = word1 & word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word12 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1; /* write 4 pixels */
+
+                word1 = *((uint32*)(prev += 4)); /* b9 b8 b7 b6 */
+                word12 = (word2 >> 24); /* 0 0 0 b5 */
+                word12 |= (word1 << 8); /* b8 b7 b6 b5 */
+                word2 = word1; /* b9 b8 b7 b6 */
+                word3 = word2 & word12; // rnd1 = 1; otherwise word3 = word1&word12
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 &= mask;
+                word2 >>= 1;
+                word2 = word2 + (word12 >> 1);
+                word2 += word3;
+                *((uint32*)(pred_block += 4)) = word2; /* write 4 pixels */
+                prev += offset;
+            }
+            return 1;
+        }
+    }
+}
+
+/**************************************************************************/
+int GetPredAdvancedBy1x0(
+    uint8 *prev,        /* i */
+    uint8 *pred_block,      /* i */
+    int width,      /* i */
+    int pred_width_rnd /* i */
+)
+{
+    uint    i;      /* loop variable */
+    int offset, offset2;
+    uint32  word1, word2, word3, word12, word22;
+    int tmp;
+    int rnd1;
+    uint32 mask;
+
+    /* initialize offset to adjust pixel counter */
+    /*    the next row; full-pel resolution      */
+    offset = width - B_SIZE; /* offset for prev */
+    offset2 = (pred_width_rnd >> 1) - 4; /* offset for pred_block */
+
+    rnd1 = pred_width_rnd & 1;
+
+    /* Branch based on pixel location (half-pel or full-pel) for x and y */
+    pred_block -= offset2; /* preset */
+
+    tmp = (uint32)prev & 3;
+    mask = 254;
+    mask |= (mask << 8);
+    mask |= (mask << 16); /* 0xFEFEFEFE */
+
+    if (tmp == 0) /* word-aligned */
+    {
+        prev -= 4;
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)(prev += 4));
+                word2 = *((uint32*)(prev + width));
+                word3 = word1 | word2; // rnd1 = 1; otherwise word3 = word1&word2
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word2 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1;
+                word1 = *((uint32*)(prev += 4));
+                word2 = *((uint32*)(prev + width));
+                word3 = word1 | word2; // rnd1 = 1; otherwise word3 = word1&word2
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word2 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+
+                prev += offset;
+            }
+            return 1;
+        }
+        else   /* rnd1 = 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word1 = *((uint32*)(prev += 4));
+                word2 = *((uint32*)(prev + width));
+                word3 = word1 & word2;  /* rnd1 = 0; */
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word2 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += offset2)) = word1;
+                word1 = *((uint32*)(prev += 4));
+                word2 = *((uint32*)(prev + width));
+                word3 = word1 & word2;  /* rnd1 = 0; */
+                word1 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word2 &= mask;
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+
+                prev += offset;
+            }
+            return 1;
+        }
+    }
+    else if (tmp == 1)
+    {
+        prev--; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 8; /* 0 b4 b3 b2 */
+                word22 >>= 8;
+                word12 = word12 | (word1 << 24); /* b5 b4 b3 b2 */
+                word22 = word22 | (word2 << 24);
+                word3 = word12 | word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 8; /* 0 b8 b7 b6 */
+                word2 >>= 8;
+                word1 = word1 | (word12 << 24); /* b9 b8 b7 b6 */
+                word2 = word2 | (word22 << 24);
+                word3 = word1 | word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 = 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 8; /* 0 b4 b3 b2 */
+                word22 >>= 8;
+                word12 = word12 | (word1 << 24); /* b5 b4 b3 b2 */
+                word22 = word22 | (word2 << 24);
+                word3 = word12 & word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 8; /* 0 b8 b7 b6 */
+                word2 >>= 8;
+                word1 = word1 | (word12 << 24); /* b9 b8 b7 b6 */
+                word2 = word2 | (word22 << 24);
+                word3 = word1 & word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+            return 1;
+        }
+    }
+    else if (tmp == 2)
+    {
+        prev -= 2; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 16; /* 0 0 b4 b3 */
+                word22 >>= 16;
+                word12 = word12 | (word1 << 16); /* b6 b5 b4 b3 */
+                word22 = word22 | (word2 << 16);
+                word3 = word12 | word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 16; /* 0 0 b8 b7 */
+                word2 >>= 16;
+                word1 = word1 | (word12 << 16); /* b10 b9 b8 b7 */
+                word2 = word2 | (word22 << 16);
+                word3 = word1 | word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 = 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 16; /* 0 0 b4 b3 */
+                word22 >>= 16;
+                word12 = word12 | (word1 << 16); /* b6 b5 b4 b3 */
+                word22 = word22 | (word2 << 16);
+                word3 = word12 & word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 16; /* 0 0 b8 b7 */
+                word2 >>= 16;
+                word1 = word1 | (word12 << 16); /* b10 b9 b8 b7 */
+                word2 = word2 | (word22 << 16);
+                word3 = word1 & word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+
+            return 1;
+        }
+    }
+    else /* tmp == 3 */
+    {
+        prev -= 3; /* word-aligned */
+        if (rnd1 == 1)
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 24; /* 0 0 0 b4 */
+                word22 >>= 24;
+                word12 = word12 | (word1 << 8); /* b7 b6 b5 b4 */
+                word22 = word22 | (word2 << 8);
+                word3 = word12 | word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 24; /* 0 0 0 b8 */
+                word2 >>= 24;
+                word1 = word1 | (word12 << 8); /* b11 b10 b9 b8 */
+                word2 = word2 | (word22 << 8);
+                word3 = word1 | word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+            return 1;
+        }
+        else /* rnd1 = 0 */
+        {
+            for (i = B_SIZE; i > 0; i--)
+            {
+                word12 = *((uint32*)prev); /* read b4 b3 b2 b1 */
+                word22 = *((uint32*)(prev + width));
+
+                word1 = *((uint32*)(prev += 4)); /* read b8 b7 b6 b5 */
+                word2 = *((uint32*)(prev + width));
+                word12 >>= 24; /* 0 0 0 b4 */
+                word22 >>= 24;
+                word12 = word12 | (word1 << 8); /* b7 b6 b5 b4 */
+                word22 = word22 | (word2 << 8);
+                word3 = word12 & word22;
+                word12 &= mask;
+                word22 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word12 >>= 1;
+                word12 = word12 + (word22 >> 1);
+                word12 += word3;
+                *((uint32*)(pred_block += offset2)) = word12;
+
+                word12 = *((uint32*)(prev += 4)); /* read b12 b11 b10 b9 */
+                word22 = *((uint32*)(prev + width));
+                word1 >>= 24; /* 0 0 0 b8 */
+                word2 >>= 24;
+                word1 = word1 | (word12 << 8); /* b11 b10 b9 b8 */
+                word2 = word2 | (word22 << 8);
+                word3 = word1 & word2;
+                word1 &= mask;
+                word2 &= mask;
+                word3 &= (~mask); /* 0x1010101, check last bit */
+                word1 >>= 1;
+                word1 = word1 + (word2 >> 1);
+                word1 += word3;
+                *((uint32*)(pred_block += 4)) = word1;
+                prev += offset;
+            }
+            return 1;
+        } /* rnd */
+    } /* tmp */
+}
+
+/**********************************************************************************/
+int GetPredAdvancedBy1x1(
+    uint8 *prev,        /* i */
+    uint8 *pred_block,      /* i */
+    int width,      /* i */
+    int pred_width_rnd /* i */
+)
+{
+    uint    i;      /* loop variable */
+    int offset, offset2;
+    uint32  x1, x2, x1m, x2m, y1, y2, y1m, y2m; /* new way */
+    int tmp;
+    int rnd1, rnd2;
+    uint32 mask;
+
+    /* initialize offset to adjust pixel counter */
+    /*    the next row; full-pel resolution      */
+    offset = width - B_SIZE; /* offset for prev */
+    offset2 = (pred_width_rnd >> 1) - 8; /* offset for pred_block */
+
+    rnd1 = pred_width_rnd & 1;
+
+    rnd2 = rnd1 + 1;
+    rnd2 |= (rnd2 << 8);
+    rnd2 |= (rnd2 << 16);
+
+    mask = 0x3F;
+    mask |= (mask << 8);
+    mask |= (mask << 16); /* 0x3f3f3f3f */
+
+    tmp = (uint32)prev & 3;
+
+    pred_block -= 4; /* preset */
+
+    if (tmp == 0) /* word-aligned */
+    {
+        for (i = B_SIZE; i > 0; i--)
+        {
+            x1 = *((uint32*)prev); /* load a3 a2 a1 a0 */
+            x2 = *((uint32*)(prev + width)); /* load b3 b2 b1 b0, another line */
+            y1 = *((uint32*)(prev += 4)); /* a7 a6 a5 a4 */
+            y2 = *((uint32*)(prev + width)); /* b7 b6 b5 b4 */
+
+            x1m = (x1 >> 2) & mask; /* zero out last 2 bits */
+            x2m = (x2 >> 2) & mask;
+            x1 = x1 ^(x1m << 2);
+            x2 = x2 ^(x2m << 2);
+            x1m += x2m;
+            x1 += x2;
+
+            /* x2m, x2 free */
+            y1m = (y1 >> 2) & mask; /* zero out last 2 bits */
+            y2m = (y2 >> 2) & mask;
+            y1 = y1 ^(y1m << 2);
+            y2 = y2 ^(y2m << 2);
+            y1m += y2m;
+            y1 += y2;
+
+            /* y2m, y2 free */
+            /* x2m, x2 free */
+            x2 = *((uint32*)(prev += 4)); /* a11 a10 a9 a8 */
+            y2 = *((uint32*)(prev + width)); /* b11 b10 b9 b8 */
+            x2m = (x2 >> 2) & mask;
+            y2m = (y2 >> 2) & mask;
+            x2 = x2 ^(x2m << 2);
+            y2 = y2 ^(y2m << 2);
+            x2m += y2m;
+            x2 += y2;
+            /* y2m, y2 free */
+
+            /* now operate on x1m, x1, y1m, y1, x2m, x2 */
+            /* x1m = a3+b3, a2+b2, a1+b1, a0+b0 */
+            /* y1m = a7+b7, a6+b6, a5+b5, a4+b4 */
+            /* x2m = a11+b11, a10+b10, a9+b9, a8+b8 */
+            /* x1, y1, x2 */
+
+            y2m = x1m >> 8;
+            y2 = x1 >> 8;
+            y2m |= (y1m << 24);  /* a4+b4, a3+b3, a2+b2, a1+b1 */
+            y2 |= (y1 << 24);
+            x1m += y2m;  /* a3+b3+a4+b4, ....., a0+b0+a1+b1 */
+            x1 += y2;
+            x1 += rnd2;
+            x1 &= (mask << 2);
+            x1m += (x1 >> 2);
+            *((uint32*)(pred_block += 4)) = x1m; /* save x1m */
+
+            y2m = y1m >> 8;
+            y2 = y1 >> 8;
+            y2m |= (x2m << 24); /* a8+b8, a7+b7, a6+b6, a5+b5 */
+            y2 |= (x2 << 24);
+            y1m += y2m;  /* a7+b7+a8+b8, ....., a4+b4+a5+b5 */
+            y1 += y2;
+            y1 += rnd2;
+            y1 &= (mask << 2);
+            y1m += (y1 >> 2);
+            *((uint32*)(pred_block += 4)) = y1m; /* save y1m */
+
+            pred_block += offset2;
+            prev += offset;
+        }
+
+        return 1;
+    }
+    else if (tmp == 1)
+    {
+        prev--; /* to word-aligned */
+        for (i = B_SIZE; i > 0; i--)
+        {
+            x1 = *((uint32*)prev); /* load a3 a2 a1 a0 */
+            x2 = *((uint32*)(prev + width)); /* load b3 b2 b1 b0, another line */
+            y1 = *((uint32*)(prev += 4)); /* a7 a6 a5 a4 */
+            y2 = *((uint32*)(prev + width)); /* b7 b6 b5 b4 */
+
+            x1m = (x1 >> 2) & mask; /* zero out last 2 bits */
+            x2m = (x2 >> 2) & mask;
+            x1 = x1 ^(x1m << 2);
+            x2 = x2 ^(x2m << 2);
+            x1m += x2m;
+            x1 += x2;
+
+            /* x2m, x2 free */
+            y1m = (y1 >> 2) & mask; /* zero out last 2 bits */
+            y2m = (y2 >> 2) & mask;
+            y1 = y1 ^(y1m << 2);
+            y2 = y2 ^(y2m << 2);
+            y1m += y2m;
+            y1 += y2;
+
+            /* y2m, y2 free */
+            /* x2m, x2 free */
+            x2 = *((uint32*)(prev += 4)); /* a11 a10 a9 a8 */
+            y2 = *((uint32*)(prev + width)); /* b11 b10 b9 b8 */
+            x2m = (x2 >> 2) & mask;
+            y2m = (y2 >> 2) & mask;
+            x2 = x2 ^(x2m << 2);
+            y2 = y2 ^(y2m << 2);
+            x2m += y2m;
+            x2 += y2;
+            /* y2m, y2 free */
+
+            /* now operate on x1m, x1, y1m, y1, x2m, x2 */
+            /* x1m = a3+b3, a2+b2, a1+b1, a0+b0 */
+            /* y1m = a7+b7, a6+b6, a5+b5, a4+b4 */
+            /* x2m = a11+b11, a10+b10, a9+b9, a8+b8 */
+            /* x1, y1, x2 */
+
+            x1m >>= 8 ;
+            x1 >>= 8;
+            x1m |= (y1m << 24);  /* a4+b4, a3+b3, a2+b2, a1+b1 */
+            x1 |= (y1 << 24);
+            y2m = (y1m << 16);
+            y2 = (y1 << 16);
+            y2m |= (x1m >> 8); /* a5+b5, a4+b4, a3+b3, a2+b2 */
+            y2 |= (x1 >> 8);
+            x1 += rnd2;
+            x1m += y2m;  /* a4+b4+a5+b5, ....., a1+b1+a2+b2 */
+            x1 += y2;
+            x1 &= (mask << 2);
+            x1m += (x1 >> 2);
+            *((uint32*)(pred_block += 4)) = x1m; /* save x1m */
+
+            y1m >>= 8;
+            y1 >>= 8;
+            y1m |= (x2m << 24); /* a8+b8, a7+b7, a6+b6, a5+b5 */
+            y1 |= (x2 << 24);
+            y2m = (x2m << 16);
+            y2 = (x2 << 16);
+            y2m |= (y1m >> 8); /*  a9+b9, a8+b8, a7+b7, a6+b6,*/
+            y2 |= (y1 >> 8);
+            y1 += rnd2;
+            y1m += y2m;  /* a8+b8+a9+b9, ....., a5+b5+a6+b6 */
+            y1 += y2;
+            y1 &= (mask << 2);
+            y1m += (y1 >> 2);
+            *((uint32*)(pred_block += 4)) = y1m; /* save y1m */
+
+            pred_block += offset2;
+            prev += offset;
+        }
+        return 1;
+    }
+    else if (tmp == 2)
+    {
+        prev -= 2; /* to word-aligned */
+        for (i = B_SIZE; i > 0; i--)
+        {
+            x1 = *((uint32*)prev); /* load a3 a2 a1 a0 */
+            x2 = *((uint32*)(prev + width)); /* load b3 b2 b1 b0, another line */
+            y1 = *((uint32*)(prev += 4)); /* a7 a6 a5 a4 */
+            y2 = *((uint32*)(prev + width)); /* b7 b6 b5 b4 */
+
+            x1m = (x1 >> 2) & mask; /* zero out last 2 bits */
+            x2m = (x2 >> 2) & mask;
+            x1 = x1 ^(x1m << 2);
+            x2 = x2 ^(x2m << 2);
+            x1m += x2m;
+            x1 += x2;
+
+            /* x2m, x2 free */
+            y1m = (y1 >> 2) & mask; /* zero out last 2 bits */
+            y2m = (y2 >> 2) & mask;
+            y1 = y1 ^(y1m << 2);
+            y2 = y2 ^(y2m << 2);
+            y1m += y2m;
+            y1 += y2;
+
+            /* y2m, y2 free */
+            /* x2m, x2 free */
+            x2 = *((uint32*)(prev += 4)); /* a11 a10 a9 a8 */
+            y2 = *((uint32*)(prev + width)); /* b11 b10 b9 b8 */
+            x2m = (x2 >> 2) & mask;
+            y2m = (y2 >> 2) & mask;
+            x2 = x2 ^(x2m << 2);
+            y2 = y2 ^(y2m << 2);
+            x2m += y2m;
+            x2 += y2;
+            /* y2m, y2 free */
+
+            /* now operate on x1m, x1, y1m, y1, x2m, x2 */
+            /* x1m = a3+b3, a2+b2, a1+b1, a0+b0 */
+            /* y1m = a7+b7, a6+b6, a5+b5, a4+b4 */
+            /* x2m = a11+b11, a10+b10, a9+b9, a8+b8 */
+            /* x1, y1, x2 */
+
+            x1m >>= 16 ;
+            x1 >>= 16;
+            x1m |= (y1m << 16);  /* a5+b5, a4+b4, a3+b3, a2+b2 */
+            x1 |= (y1 << 16);
+            y2m = (y1m << 8);
+            y2 = (y1 << 8);
+            y2m |= (x1m >> 8); /* a6+b6, a5+b5, a4+b4, a3+b3 */
+            y2 |= (x1 >> 8);
+            x1 += rnd2;
+            x1m += y2m;  /* a5+b5+a6+b6, ....., a2+b2+a3+b3 */
+            x1 += y2;
+            x1 &= (mask << 2);
+            x1m += (x1 >> 2);
+            *((uint32*)(pred_block += 4)) = x1m; /* save x1m */
+
+            y1m >>= 16;
+            y1 >>= 16;
+            y1m |= (x2m << 16); /* a9+b9, a8+b8, a7+b7, a6+b6 */
+            y1 |= (x2 << 16);
+            y2m = (x2m << 8);
+            y2 = (x2 << 8);
+            y2m |= (y1m >> 8); /*  a10+b10, a9+b9, a8+b8, a7+b7,*/
+            y2 |= (y1 >> 8);
+            y1 += rnd2;
+            y1m += y2m;  /* a9+b9+a10+b10, ....., a6+b6+a7+b7 */
+            y1 += y2;
+            y1 &= (mask << 2);
+            y1m += (y1 >> 2);
+            *((uint32*)(pred_block += 4)) = y1m; /* save y1m */
+
+            pred_block += offset2;
+            prev += offset;
+        }
+        return 1;
+    }
+    else /* tmp == 3 */
+    {
+        prev -= 3; /* to word-aligned */
+        for (i = B_SIZE; i > 0; i--)
+        {
+            x1 = *((uint32*)prev); /* load a3 a2 a1 a0 */
+            x2 = *((uint32*)(prev + width)); /* load b3 b2 b1 b0, another line */
+            y1 = *((uint32*)(prev += 4)); /* a7 a6 a5 a4 */
+            y2 = *((uint32*)(prev + width)); /* b7 b6 b5 b4 */
+
+            x1m = (x1 >> 2) & mask; /* zero out last 2 bits */
+            x2m = (x2 >> 2) & mask;
+            x1 = x1 ^(x1m << 2);
+            x2 = x2 ^(x2m << 2);
+            x1m += x2m;
+            x1 += x2;
+
+            /* x2m, x2 free */
+            y1m = (y1 >> 2) & mask; /* zero out last 2 bits */
+            y2m = (y2 >> 2) & mask;
+            y1 = y1 ^(y1m << 2);
+            y2 = y2 ^(y2m << 2);
+            y1m += y2m;
+            y1 += y2;
+
+            /* y2m, y2 free */
+            /* x2m, x2 free */
+            x2 = *((uint32*)(prev += 4)); /* a11 a10 a9 a8 */
+            y2 = *((uint32*)(prev + width)); /* b11 b10 b9 b8 */
+            x2m = (x2 >> 2) & mask;
+            y2m = (y2 >> 2) & mask;
+            x2 = x2 ^(x2m << 2);
+            y2 = y2 ^(y2m << 2);
+            x2m += y2m;
+            x2 += y2;
+            /* y2m, y2 free */
+
+            /* now operate on x1m, x1, y1m, y1, x2m, x2 */
+            /* x1m = a3+b3, a2+b2, a1+b1, a0+b0 */
+            /* y1m = a7+b7, a6+b6, a5+b5, a4+b4 */
+            /* x2m = a11+b11, a10+b10, a9+b9, a8+b8 */
+            /* x1, y1, x2 */
+
+            x1m >>= 24 ;
+            x1 >>= 24;
+            x1m |= (y1m << 8);  /* a6+b6, a5+b5, a4+b4, a3+b3 */
+            x1 |= (y1 << 8);
+
+            x1m += y1m;  /* a6+b6+a7+b7, ....., a3+b3+a4+b4 */
+            x1 += y1;
+            x1 += rnd2;
+            x1 &= (mask << 2);
+            x1m += (x1 >> 2);
+            *((uint32*)(pred_block += 4)) = x1m; /* save x1m */
+
+            y1m >>= 24;
+            y1 >>= 24;
+            y1m |= (x2m << 8); /* a10+b10, a9+b9, a8+b8, a7+b7 */
+            y1 |= (x2 << 8);
+            y1m += x2m;  /* a10+b10+a11+b11, ....., a7+b7+a8+b8 */
+            y1 += x2;
+            y1 += rnd2;
+            y1 &= (mask << 2);
+            y1m += (y1 >> 2);
+            *((uint32*)(pred_block += 4)) = y1m; /* save y1m */
+
+            pred_block += offset2;
+            prev += offset;
+        }
+        return 1;
+    }
+}
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_outside.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_outside.cpp
new file mode 100644
index 0000000..9cd9022
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/get_pred_outside.cpp
@@ -0,0 +1,514 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xpos = x half-pixel of (x,y) coordinates within a VOP; motion
+           compensated coordinates; native data type
+    ypos = y half-pixel of (x,y) coordinates within a VOP; motion
+           compensated coordinates; native data type
+    comp = pointer to 8-bit compensated prediction values within a VOP;
+           computed by this module (i/o); full-pel resolution; 8-bit data
+    c_prev = pointer to previous 8-bit prediction values within a VOP;
+         values range from (0-255); full-pel resolution; 8-bit data
+    sh_d = pointer to residual values used to compensate the predicted
+           value; values range from (-512 to 511); full-pel resolution;
+           native data type
+    width = width of the VOP in pixels (x axis); full-pel resolution;
+        native data type
+    height = height of the VOP in pixels (y axis); full-pel resolution;
+         native data type
+    rnd1 = rounding value for case when one dimension uses half-pel
+           resolution; native data type
+    rnd2 = rounding value for case when two dimensions uses half-pel
+           resolution; native data type
+
+ Outputs:
+    returns 1
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Pointers and Buffers Modified:
+    comp = buffer contains newly computed compensated prediction values
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ Summary:
+
+ This function performs motion compensated prediction for the case where
+ the motion vector points to a block outside the VOP. The function interpolates
+ the pixels that are outside the VOP using the boundary pixels for the block.
+ Once the values are interpolated, the pixel values are computed for a block
+ in the current VOP. The prediction values are generated by averaging pixel
+ values in the previous VOP; the block position in the previous frame is
+ computed from the current block's motion vector. The computed pixel values
+ are calculated by adding the prediction values to the block residual values.
+
+ Details:
+
+ First, this functions determines which VOP boundary(ies) the motion vector
+ is outside, i.e., left, right, top, bottom. xpos is compared to the left and
+ right boundaries; ypos is compared to the top and bottom boundaries. The number
+ of block pixels inside the the boundary in the x and y directions are stored
+ in endx and endy, respectively. If the entire block is inside the x or y
+ boundary, the respectively end is set to 0.
+
+ After the boundaries are tested, any pixels lying outside a boundary are
+ interpolated from the boundary pixels. For example, if the block is outside the
+ bottom boundary, boundary pixels alone the bottom of the VOP as used to
+ interpolated those pixels lying outside the bottom boundary. The interpolation
+ used is a simple column-wise or row-wise copy of the boundary pixels (inside the
+ block) depending on which boundary the block is outside. In our example, each
+ boundary pixel would be copied column-wise to the pixel beneath it. If the
+ block was outside right boundary, the boundary pixels would be copied row-wise
+ to the pixel to the right of it. If the block was outside both an x and y
+ boundary, the boundary pixels would be copied row-wise for the portion of the
+ block outside the x boundary, and column-wise for the portion of the block
+ outside the y boundary. And so on.
+
+ Once the pixel interpolation is complete, the motion compensated output values
+ (comp[]) are calculed from the motion compensated prediction (pred[])values and
+ the residual values (sh_d[]) of the current frame. The prediction values are
+ generated by averaging pixel values in the previous VOP; the block position in
+ the previous frame is computed from the current block's motion vector. The
+ computed pixel values are calculated by adding the prediction values to the
+ block residual values.
+
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+#include "motion_comp.h"
+
+#define PAD_CORNER {    temp = *prev; \
+            temp |= (temp<<8);  \
+            temp |= (temp<<16); \
+            *((uint32*)ptr) = temp; \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  \
+            *((uint32*)(ptr+=16)) = temp;  \
+            *((uint32*)(ptr+4)) = temp;  }
+
+#define PAD_ROW  {  temp = *((uint32*)prev); \
+                    temp2 = *((uint32*)(prev+4)); \
+            *((uint32*)ptr) =  temp;\
+            *((uint32*)(ptr+4)) =  temp2; \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;\
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp2;}
+
+#define PAD_EXTRA_4x8           {   temp = *((uint32*)(prev+8)); \
+                *((uint32*)ptr) =  temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; \
+                *((uint32*)(ptr+=16)) = temp; }
+
+#define PAD_COL { temp = *prev; \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)ptr) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp; \
+            temp = *(prev+=16); \
+            temp|=(temp<<8);  temp|=(temp<<16); \
+            *((uint32*)(ptr+=16)) = temp; \
+            *((uint32*)(ptr+4)) = temp;}
+
+/* copy 8x8 block */
+#define COPY_BLOCK  {           *((uint32*)ptr) = *((uint32*)prev); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4));  }
+
+#define COPY_12x8       {       *((uint32*)ptr) = *((uint32*)prev); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); \
+            *((uint32*)(ptr+=16)) = *((uint32*)(prev+=width)); \
+            *((uint32*)(ptr+4)) = *((uint32*)(prev+4)); \
+            *((uint32*)(ptr+8)) = *((uint32*)(prev+8)); }
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+int GetPredOutside(
+    int xpos,       /* i */
+    int ypos,       /* i */
+    uint8 *c_prev,      /* i */
+    uint8 *pred_block,      /* i */
+    int width,      /* i */
+    int height,     /* i */
+    int rnd1,       /* i */
+    int pred_width
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    uint8   *prev;      /* pointers to adjacent pixels in the    */
+    uint8   pred[256];  /* storage for padded pixel values, 16x16 */
+    uint8   *ptr;
+    int xoffset;
+    uint32 temp, temp2;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* saturate xpos and ypos */
+    if (xpos < -16) xpos = -16;
+    if (xpos > ((width - 1) << 1)) xpos = (width - 1) << 1;
+    if (ypos < -16) ypos = -16;
+    if (ypos > ((height - 1) << 1)) ypos = (height - 1) << 1;
+
+    if (xpos < 0)
+    {
+        if (ypos < 0) /* pad top left of frame */
+        {
+            /* copy the block */
+            ptr = pred + (8 << 4) + 8;
+            prev = c_prev;
+            COPY_BLOCK
+
+            /* pad the corner */
+            ptr = pred;
+            prev = pred + (8 << 4) + 8;
+            PAD_CORNER
+
+            /* pad top */
+            ptr = pred + 8;
+            prev = pred + (8 << 4) + 8;
+            PAD_ROW
+
+            /* pad left */
+            ptr = pred + (8 << 4);
+            prev = pred + (8 << 4) + 8;
+            PAD_COL
+
+
+            ptr = pred + (((ypos >> 1) + 8) << 4) + (xpos >> 1) + 8;
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+        else if ((ypos >> 1) < (height - B_SIZE)) /* pad left of frame */
+        {
+            /* copy block */
+            ptr = pred + 8;
+            prev = c_prev + (ypos >> 1) * width;
+            COPY_BLOCK
+            /* copy extra line */
+            *((uint32*)(ptr += 16)) = *((uint32*)(prev += width));
+            *((uint32*)(ptr + 4)) = *((uint32*)(prev + 4));
+
+            /* pad left */
+            ptr = pred;
+            prev = pred + 8;
+            PAD_COL
+            /* pad extra line */
+            temp = *(prev += 16);
+            temp |= (temp << 8);
+            temp |= (temp << 16);
+            *((uint32*)(ptr += 16)) = temp;
+            *((uint32*)(ptr + 4)) = temp;
+
+            ptr = pred + 8 + (xpos >> 1);
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+        else /* pad bottom left of frame */
+        {
+            /* copy the block */
+            ptr = pred + 8; /* point to the center */
+            prev = c_prev + width * (height - 8);
+            COPY_BLOCK
+
+            /* pad the corner */
+            ptr = pred + (8 << 4);
+            prev = ptr - 8;
+            PAD_CORNER
+
+            /* pad bottom */
+            ptr = pred + (8 << 4) + 8;
+            prev = ptr - 16;
+            PAD_ROW
+
+            /* pad left */
+            ptr = pred ;
+            prev = ptr + 8;
+            PAD_COL
+
+            ptr = pred + 8 + (((ypos >> 1) - (height - 8)) << 4) + (xpos >> 1);
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+    }
+    else if ((xpos >> 1) < (width - B_SIZE))
+    {
+        if (ypos < 0) /* pad top of frame */
+        {
+            xoffset = xpos >> 1;
+            xoffset = xoffset & 0x3; /* word align ptr */
+
+            /* copy block */
+            ptr = pred + (8 << 4);
+            prev = c_prev + (xpos >> 1) - xoffset;
+
+            if (xoffset || (xpos&1)) /* copy extra 4x8 */
+            {
+                COPY_12x8
+            }
+            else
+            {
+                COPY_BLOCK
+            }
+
+            /* pad top */
+            ptr = pred;
+            prev = pred + (8 << 4);
+            PAD_ROW
+            if (xoffset || (xpos&1)) /* pad extra 4x8 */
+            {
+                ptr = pred + 8;
+                PAD_EXTRA_4x8
+            }
+
+            ptr = pred + (((ypos >> 1) + 8) << 4) + xoffset;
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+        else /* pad bottom of frame */
+        {
+            xoffset = xpos >> 1;
+            xoffset = xoffset & 0x3; /* word align ptr */
+            /* copy block */
+            ptr = pred ;
+            prev = c_prev + width * (height - 8) + (xpos >> 1) - xoffset;
+            if (xoffset  || (xpos&1))
+            {
+                COPY_12x8
+            }
+            else
+            {
+                COPY_BLOCK
+            }
+
+            /* pad bottom */
+            ptr = pred + (8 << 4);
+            prev = ptr - 16;
+            PAD_ROW
+            if (xoffset || (xpos&1))
+            {
+                ptr = pred + (8 << 4) + 8;
+                PAD_EXTRA_4x8
+            }
+
+            ptr = pred + (((ypos >> 1) - (height - 8)) << 4) + xoffset;
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+    }
+    else
+    {
+        if (ypos < 0) /* pad top right of frame */
+        {
+            /* copy block */
+            ptr = pred + (8 << 4);
+            prev = c_prev + width - 8;
+            COPY_BLOCK
+
+            /* pad top-right */
+            ptr = pred + 8;
+            prev = pred + (8 << 4) + 7;
+            PAD_CORNER
+
+            /* pad top */
+            ptr = pred ;
+            prev = pred + (8 << 4);
+            PAD_ROW;
+
+            /* pad right */
+            ptr = pred + (8 << 4) + 8;
+            prev = ptr - 1;
+            PAD_COL;
+
+            ptr = pred + ((8 + (ypos >> 1)) << 4) + (8 - (width - (xpos >> 1)));
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+        else if ((ypos >> 1) < (height - B_SIZE)) /* pad right of frame */
+        {
+            /* copy block */
+            ptr = pred;
+            prev = c_prev + (ypos >> 1) * width + width - 8;
+            COPY_BLOCK
+            /* copy extra line */
+            *((uint32*)(ptr += 16)) = *((uint32*)(prev += width));
+            *((uint32*)(ptr + 4)) = *((uint32*)(prev + 4));
+
+            /* pad right */
+            ptr = pred + 8;
+            prev = ptr - 1;
+            PAD_COL;
+            /* pad extra line */
+            temp = *(prev += 16);
+            temp |= (temp << 8);
+            temp |= (temp << 16);
+            *((uint32*)(ptr += 16)) = temp;
+            *((uint32*)(ptr + 4)) = temp;
+
+
+            ptr = pred + 8 - (width - (xpos >> 1));
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+
+        }
+        else /* pad bottom right of frame */
+        {
+            /* copy block */
+            ptr = pred;
+            prev = c_prev + width * (height - 8) + width - 8;
+            COPY_BLOCK
+
+            /* pad bottom-right */
+            ptr = pred + (8 << 4) + 8;
+            prev = ptr - 17;
+            PAD_CORNER
+
+            /* pad right */
+            ptr = pred + 8;
+            prev = ptr - 1;
+            PAD_COL
+
+            /* pad bottom */
+            ptr = pred + (8 << 4);
+            prev = ptr - 16;
+            PAD_ROW
+
+            ptr = pred + 8 - (width - (xpos >> 1)) + ((8 - (height - (ypos >> 1))) << 4);
+
+            GetPredAdvBTable[ypos&1][xpos&1](ptr, pred_block, 16, (pred_width << 1) | rnd1);
+
+            return 1;
+        }
+    }
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/idct.cpp
new file mode 100644
index 0000000..2e932a4
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/idct.cpp
@@ -0,0 +1,579 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ MODULE DESCRIPTION
+
+ This file contains the functions that transform an 8r8 image block from
+ dequantized DCT coefficients to spatial domain pirel values by calculating
+ inverse discrete cosine transform (IDCT).
+
+------------------------------------------------------------------------------
+*/
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+#include "idct.h"
+#include "motion_comp.h"
+#ifndef FAST_IDCT
+
+/*
+------------------------------------------------------------------------------
+ FUNCTION NAME: idct
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS FOR idct
+
+ Inputs:
+    blk = pointer to the buffer containing the dequantized DCT
+          coefficients of type int for an 8r8 image block;
+          values range from (-2048, 2047) which defined as standard.
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    blk points to the found IDCT values for an 8r8 image block.
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION FOR idct
+
+ This function transforms an 8r8 image block from dequantized DCT coefficients
+ (F(u,v)) to spatial domain pirel values (f(r,y)) by performing the two
+ dimensional inverse discrete cosine transform (IDCT).
+
+         _7_ _7_      C(u) C(v)
+    f(r,y) = \   \  F(u,v)---- ----cos[(2r+1)*u*pi/16]cos[(2y+1)*v*pi/16]
+         /__ /__    2    2
+         u=0 v=0
+
+    where   C(i) = 1/sqrt(2)    if i=0
+        C(i) = 1        otherwise
+
+ 2-D IDCT can be separated as horizontal(row-wise) and vertical(column-wise)
+ 1-D IDCTs. Therefore, 2-D IDCT values are found by the following two steps:
+ 1. Find horizontal 1-D IDCT values for each row from 8r8 dequantized DCT
+    coefficients by row IDCT operation.
+
+          _7_        C(u)
+    g(r,v) =  \   F(u,v) ---- cos[(2r+1)*u*pi/16]
+          /__         2
+          u=0
+
+ 2. Find vertical 1-D IDCT values for each column from the results of 1
+    by column IDCT operation.
+
+              _7_        C(v)
+    f(r,y) =  \   g(r,v) ---- cos[(2y+1)*v*pi/16]
+          /__         2
+          v=0
+
+------------------------------------------------------------------------------
+ REQUIREMENTS FOR idct
+
+ None
+
+------------------------------------------------------------------------------
+*/
+/*  REFERENCES FOR idct */
+/* idct.c, inverse fast discrete cosine transform
+ inverse two dimensional DCT, Chen-Wang algorithm
+ (cf. IEEE ASSP-32, pp. 803-816, Aug. 1984)
+ 32-bit integer arithmetic (8 bit coefficients)
+ 11 mults, 29 adds per DCT
+ sE, 18.8.91
+
+ coefficients ertended to 12 bit for IEEE1180-1990
+ compliance                           sE,  2.1.94
+*/
+
+
+/*----------------------------------------------------------------------------
+; Function Code FOR idct
+----------------------------------------------------------------------------*/
+void idct_intra(
+    int *blk, uint8 *comp, int width
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int i;
+    int32   tmpBLK[64];
+    int32   *tmpBLK32 = &tmpBLK[0];
+    int32   r0, r1, r2, r3, r4, r5, r6, r7, r8; /* butterfly nodes */
+    int32   a;
+    int offset = width - 8;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* two dimensional inverse discrete cosine transform */
+
+
+    /* column (vertical) IDCT */
+    for (i = B_SIZE - 1; i >= 0; i--)
+    {
+        /* initialize butterfly nodes at first stage */
+
+        r1 = blk[B_SIZE * 4 + i] << 11;
+        /* since row IDCT results have net left shift by 3 */
+        /* this left shift by 8 gives net left shift by 11 */
+        /* in order to maintain the same scale as that of  */
+        /* coefficients Wi */
+
+        r2 = blk[B_SIZE * 6 + i];
+        r3 = blk[B_SIZE * 2 + i];
+        r4 = blk[B_SIZE * 1 + i];
+        r5 = blk[B_SIZE * 7 + i];
+        r6 = blk[B_SIZE * 5 + i];
+        r7 = blk[B_SIZE * 3 + i];
+
+        if (!(r1 | r2 | r3 | r4 | r5 | r6 | r7))
+        {
+            /* shortcut */
+            /* execute if values of g(r,1) to g(r,7) in a column*/
+            /* are all zeros */
+
+            /* make output of IDCT >>3 or scaled by 1/8 and */
+            /* with the proper rounding */
+            a = (blk[B_SIZE * 0 + i]) << 3;
+            tmpBLK32[B_SIZE * 0 + i] = a;
+            tmpBLK32[B_SIZE * 1 + i] = a;
+            tmpBLK32[B_SIZE * 2 + i] = a;
+            tmpBLK32[B_SIZE * 3 + i] = a;
+            tmpBLK32[B_SIZE * 4 + i] = a;
+            tmpBLK32[B_SIZE * 5 + i] = a;
+            tmpBLK32[B_SIZE * 6 + i] = a;
+            tmpBLK32[B_SIZE * 7 + i] = a;
+        }
+        else
+        {
+            r0 = (blk[8 * 0 + i] << 11) + 128;
+
+            /* first stage */
+
+            r8 = W7 * (r4 + r5);
+            r4 = (r8 + (W1 - W7) * r4);
+            /* Multiplication with Wi increases the net left */
+            /* shift from 11 to 14,we have to shift back by 3*/
+            r5 = (r8 - (W1 + W7) * r5);
+            r8 = W3 * (r6 + r7);
+            r6 = (r8 - (W3 - W5) * r6);
+            r7 = (r8 - (W3 + W5) * r7);
+
+            /* second stage */
+            r8 = r0 + r1;
+            r0 -= r1;
+
+            r1 = W6 * (r3 + r2);
+            r2 = (r1 - (W2 + W6) * r2);
+            r3 = (r1 + (W2 - W6) * r3);
+
+            r1 = r4 + r6;
+            r4 -= r6;
+            r6 = r5 + r7;
+            r5 -= r7;
+
+            /* third stage */
+            r7 = r8 + r3;
+            r8 -= r3;
+            r3 = r0 + r2;
+            r0 -= r2;
+            r2 = (181 * (r4 + r5) + 128) >> 8;  /* rounding */
+            r4 = (181 * (r4 - r5) + 128) >> 8;
+
+            /* fourth stage */
+            /* net shift of IDCT is >>3 after the following */
+            /* shift operation, it makes output of 2-D IDCT */
+            /* scaled by 1/8, that is scaled twice by       */
+            /* 1/(2*sqrt(2)) for row IDCT and column IDCT.  */
+            /* see detail analysis in design doc.           */
+            tmpBLK32[0 + i] = (r7 + r1) >> 8;
+            tmpBLK32[(1<<3) + i] = (r3 + r2) >> 8;
+            tmpBLK32[(2<<3) + i] = (r0 + r4) >> 8;
+            tmpBLK32[(3<<3) + i] = (r8 + r6) >> 8;
+            tmpBLK32[(4<<3) + i] = (r8 - r6) >> 8;
+            tmpBLK32[(5<<3) + i] = (r0 - r4) >> 8;
+            tmpBLK32[(6<<3) + i] = (r3 - r2) >> 8;
+            tmpBLK32[(7<<3) + i] = (r7 - r1) >> 8;
+        }
+    }
+    /* row (horizontal) IDCT */
+    for (i = 0 ; i < B_SIZE; i++)
+    {
+        /* initialize butterfly nodes at the first stage */
+
+        r1 = ((int32)tmpBLK32[4+(i<<3)]) << 8;
+        /* r1 left shift by 11 is to maintain the same  */
+        /* scale as that of coefficients (W1,...W7) */
+        /* since blk[4] won't multiply with Wi.     */
+        /* see detail diagram in design document.   */
+
+        r2 = tmpBLK32[6+(i<<3)];
+        r3 = tmpBLK32[2+(i<<3)];
+        r4 = tmpBLK32[1+(i<<3)];
+        r5 = tmpBLK32[7+(i<<3)];
+        r6 = tmpBLK32[5+(i<<3)];
+        r7 = tmpBLK32[3+(i<<3)];
+
+        if (!(r1 | r2 | r3 | r4 | r5 | r6 | r7))
+        {
+            /* shortcut */
+            /* execute if values of F(1,v) to F(7,v) in a row*/
+            /* are all zeros */
+
+            /* output of row IDCT scaled by 8 */
+            a = (((int32)tmpBLK32[0+(i<<3)] + 32) >> 6);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+            *comp++ = a;
+
+            comp += offset;
+        }
+
+        else
+        {
+            /* for proper rounding in the fourth stage */
+            r0 = (((int32)tmpBLK32[0+(i<<3)]) << 8) + 8192;
+
+            /* first stage */
+
+            r8 = W7 * (r4 + r5) + 4;
+            r4 = (r8 + (W1 - W7) * r4) >> 3;
+            r5 = (r8 - (W1 + W7) * r5) >> 3;
+
+            r8 = W3 * (r6 + r7) + 4;
+            r6 = (r8 - (W3 - W5) * r6) >> 3;
+            r7 = (r8 - (W3 + W5) * r7) >> 3;
+
+            /* second stage */
+            r8 = r0 + r1;
+            r0 -= r1;
+
+            r1 = W6 * (r3 + r2) + 4;
+            r2 = (r1 - (W2 + W6) * r2) >> 3;
+            r3 = (r1 + (W2 - W6) * r3) >> 3;
+
+            r1 = r4 + r6;
+            r4 -= r6;
+            r6 = r5 + r7;
+            r5 -= r7;
+
+            /* third stage */
+            r7 = r8 + r3;
+            r8 -= r3;
+            r3 = r0 + r2;
+            r0 -= r2;
+            r2 = (181 * (r4 + r5) + 128) >> 8;    /* rounding */
+            r4 = (181 * (r4 - r5) + 128) >> 8;
+
+            /* fourth stage */
+            /* net shift of this function is <<3 after the    */
+            /* following shift operation, it makes output of  */
+            /* row IDCT scaled by 8 to retain 3 bits precision*/
+            a = ((r7 + r1) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r3 + r2) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r0 + r4) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r8 + r6) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r8 - r6) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r0 - r4) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r3 - r2) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+            a = ((r7 - r1) >> 14);
+            CLIP_RESULT(a)
+            *comp++ = a;
+
+            comp += offset;
+        }
+    }
+
+
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+void idct(
+    int *blk, uint8 *pred, uint8 *dst, int width)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int i;
+    int32   tmpBLK[64];
+    int32   *tmpBLK32 = &tmpBLK[0];
+    int32   r0, r1, r2, r3, r4, r5, r6, r7, r8; /* butterfly nodes */
+    int32   a;
+    int res;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* two dimensional inverse discrete cosine transform */
+
+
+    /* column (vertical) IDCT */
+    for (i = B_SIZE - 1; i >= 0; i--)
+    {
+        /* initialize butterfly nodes at first stage */
+
+        r1 = blk[B_SIZE * 4 + i] << 11;
+        /* since row IDCT results have net left shift by 3 */
+        /* this left shift by 8 gives net left shift by 11 */
+        /* in order to maintain the same scale as that of  */
+        /* coefficients Wi */
+
+        r2 = blk[B_SIZE * 6 + i];
+        r3 = blk[B_SIZE * 2 + i];
+        r4 = blk[B_SIZE * 1 + i];
+        r5 = blk[B_SIZE * 7 + i];
+        r6 = blk[B_SIZE * 5 + i];
+        r7 = blk[B_SIZE * 3 + i];
+
+        if (!(r1 | r2 | r3 | r4 | r5 | r6 | r7))
+        {
+            /* shortcut */
+            /* execute if values of g(r,1) to g(r,7) in a column*/
+            /* are all zeros */
+
+            /* make output of IDCT >>3 or scaled by 1/8 and */
+            /* with the proper rounding */
+            a = (blk[B_SIZE * 0 + i]) << 3;
+            tmpBLK32[B_SIZE * 0 + i] = a;
+            tmpBLK32[B_SIZE * 1 + i] = a;
+            tmpBLK32[B_SIZE * 2 + i] = a;
+            tmpBLK32[B_SIZE * 3 + i] = a;
+            tmpBLK32[B_SIZE * 4 + i] = a;
+            tmpBLK32[B_SIZE * 5 + i] = a;
+            tmpBLK32[B_SIZE * 6 + i] = a;
+            tmpBLK32[B_SIZE * 7 + i] = a;
+        }
+        else
+        {
+            r0 = (blk[8 * 0 + i] << 11) + 128;
+
+            /* first stage */
+
+            r8 = W7 * (r4 + r5);
+            r4 = (r8 + (W1 - W7) * r4);
+            /* Multiplication with Wi increases the net left */
+            /* shift from 11 to 14,we have to shift back by 3*/
+            r5 = (r8 - (W1 + W7) * r5);
+            r8 = W3 * (r6 + r7);
+            r6 = (r8 - (W3 - W5) * r6);
+            r7 = (r8 - (W3 + W5) * r7);
+
+            /* second stage */
+            r8 = r0 + r1;
+            r0 -= r1;
+
+            r1 = W6 * (r3 + r2);
+            r2 = (r1 - (W2 + W6) * r2);
+            r3 = (r1 + (W2 - W6) * r3);
+
+            r1 = r4 + r6;
+            r4 -= r6;
+            r6 = r5 + r7;
+            r5 -= r7;
+
+            /* third stage */
+            r7 = r8 + r3;
+            r8 -= r3;
+            r3 = r0 + r2;
+            r0 -= r2;
+            r2 = (181 * (r4 + r5) + 128) >> 8;  /* rounding */
+            r4 = (181 * (r4 - r5) + 128) >> 8;
+
+            /* fourth stage */
+            /* net shift of IDCT is >>3 after the following */
+            /* shift operation, it makes output of 2-D IDCT */
+            /* scaled by 1/8, that is scaled twice by       */
+            /* 1/(2*sqrt(2)) for row IDCT and column IDCT.  */
+            /* see detail analysis in design doc.           */
+            tmpBLK32[0 + i] = (r7 + r1) >> 8;
+            tmpBLK32[(1<<3) + i] = (r3 + r2) >> 8;
+            tmpBLK32[(2<<3) + i] = (r0 + r4) >> 8;
+            tmpBLK32[(3<<3) + i] = (r8 + r6) >> 8;
+            tmpBLK32[(4<<3) + i] = (r8 - r6) >> 8;
+            tmpBLK32[(5<<3) + i] = (r0 - r4) >> 8;
+            tmpBLK32[(6<<3) + i] = (r3 - r2) >> 8;
+            tmpBLK32[(7<<3) + i] = (r7 - r1) >> 8;
+        }
+    }
+    /* row (horizontal) IDCT */
+    for (i = B_SIZE - 1; i >= 0; i--)
+    {
+        /* initialize butterfly nodes at the first stage */
+
+        r1 = ((int32)tmpBLK32[4+(i<<3)]) << 8;
+        /* r1 left shift by 11 is to maintain the same  */
+        /* scale as that of coefficients (W1,...W7) */
+        /* since blk[4] won't multiply with Wi.     */
+        /* see detail diagram in design document.   */
+
+        r2 = tmpBLK32[6+(i<<3)];
+        r3 = tmpBLK32[2+(i<<3)];
+        r4 = tmpBLK32[1+(i<<3)];
+        r5 = tmpBLK32[7+(i<<3)];
+        r6 = tmpBLK32[5+(i<<3)];
+        r7 = tmpBLK32[3+(i<<3)];
+
+        if (!(r1 | r2 | r3 | r4 | r5 | r6 | r7))
+        {
+            /* shortcut */
+            /* execute if values of F(1,v) to F(7,v) in a row*/
+            /* are all zeros */
+
+            /* output of row IDCT scaled by 8 */
+            a = (tmpBLK32[0+(i<<3)] + 32) >> 6;
+            blk[0+(i<<3)] = a;
+            blk[1+(i<<3)] = a;
+            blk[2+(i<<3)] = a;
+            blk[3+(i<<3)] = a;
+            blk[4+(i<<3)] = a;
+            blk[5+(i<<3)] = a;
+            blk[6+(i<<3)] = a;
+            blk[7+(i<<3)] = a;
+
+        }
+
+        else
+        {
+            /* for proper rounding in the fourth stage */
+            r0 = (((int32)tmpBLK32[0+(i<<3)]) << 8) + 8192;
+
+            /* first stage */
+
+            r8 = W7 * (r4 + r5) + 4;
+            r4 = (r8 + (W1 - W7) * r4) >> 3;
+            r5 = (r8 - (W1 + W7) * r5) >> 3;
+
+            r8 = W3 * (r6 + r7) + 4;
+            r6 = (r8 - (W3 - W5) * r6) >> 3;
+            r7 = (r8 - (W3 + W5) * r7) >> 3;
+
+            /* second stage */
+            r8 = r0 + r1;
+            r0 -= r1;
+
+            r1 = W6 * (r3 + r2) + 4;
+            r2 = (r1 - (W2 + W6) * r2) >> 3;
+            r3 = (r1 + (W2 - W6) * r3) >> 3;
+
+            r1 = r4 + r6;
+            r4 -= r6;
+            r6 = r5 + r7;
+            r5 -= r7;
+
+            /* third stage */
+            r7 = r8 + r3;
+            r8 -= r3;
+            r3 = r0 + r2;
+            r0 -= r2;
+            r2 = (181 * (r4 + r5) + 128) >> 8;    /* rounding */
+            r4 = (181 * (r4 - r5) + 128) >> 8;
+
+            /* fourth stage */
+            /* net shift of this function is <<3 after the    */
+            /* following shift operation, it makes output of  */
+            /* row IDCT scaled by 8 to retain 3 bits precision*/
+            blk[0+(i<<3)] = (r7 + r1) >> 14;
+            blk[1+(i<<3)] = (r3 + r2) >> 14;
+            blk[2+(i<<3)] = (r0 + r4) >> 14;
+            blk[3+(i<<3)] = (r8 + r6) >> 14;
+            blk[4+(i<<3)] = (r8 - r6) >> 14;
+            blk[5+(i<<3)] = (r0 - r4) >> 14;
+            blk[6+(i<<3)] = (r3 - r2) >> 14;
+            blk[7+(i<<3)] = (r7 - r1) >> 14;
+        }
+        /*  add with prediction ,  08/03/05 */
+        res = (*pred++ + block[0+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[1+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[2+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[3+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[4+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[5+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[6+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+        res = (*pred++ + block[7+(i<<3)]);
+        CLIP_RESULT(res);
+        *dst++ = res;
+
+        pred += 8;
+        dst += (width - 8);
+    }
+
+
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+#endif
+/*----------------------------------------------------------------------------
+; End Function: idct
+----------------------------------------------------------------------------*/
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct.h b/media/libstagefright/codecs/m4v_h263/dec/src/idct.h
new file mode 100644
index 0000000..8edb654
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/idct.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.
+ * -------------------------------------------------------------------
+ */
+#ifndef idct_h
+#define idct_h
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define INTEGER_IDCT
+
+#ifdef FAST_IDCT
+#ifndef INTEGER_IDCT
+#define INTEGER_IDCT
+#endif
+#endif
+
+#ifdef FAST_IDCT
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+    void idctrow0(int16 *blk, uint8 *pred, uint8 *dst, int width);
+    void idctrow1(int16 *blk, uint8 *pred, uint8 *dst, int width);
+    void idctrow2(int16 *blk, uint8 *pred, uint8 *dst, int width);
+    void idctrow3(int16 *blk, uint8 *pred, uint8 *dst, int width);
+    void idctrow4(int16 *blk, uint8 *pred, uint8 *dst, int width);
+    void idctcol0(int16 *blk);
+    void idctcol1(int16 *blk);
+    void idctcol2(int16 *blk);
+    void idctcol3(int16 *blk);
+    void idctcol4(int16 *blk);
+
+    void idctrow0_intra(int16 *blk, PIXEL *comp, int width);
+    void idctrow1_intra(int16 *blk, PIXEL *comp, int width);
+    void idctrow2_intra(int16 *blk, PIXEL *comp, int width);
+    void idctrow3_intra(int16 *blk, PIXEL *comp, int width);
+    void idctrow4_intra(int16 *blk, PIXEL *comp, int width);
+#ifdef __cplusplus
+}
+#endif
+#endif
+
+/* this code assumes ">>" to be a two's-complement arithmetic */
+/* right shift: (-2)>>1 == -1 , (-3)>>1 == -2                 */
+
+/* a positive real constant is converted to an integer scaled by 2048 */
+/* or equivalent to left shift by 11 */
+
+#define W1 2841                 /* 2048*sqrt(2)*cos(1*pi/16) */
+#define W2 2676                 /* 2048*sqrt(2)*cos(2*pi/16) */
+#define W3 2408                 /* 2048*sqrt(2)*cos(3*pi/16) */
+#define W5 1609                 /* 2048*sqrt(2)*cos(5*pi/16) */
+#define W6 1108                 /* 2048*sqrt(2)*cos(6*pi/16) */
+#define W7 565                  /* 2048*sqrt(2)*cos(7*pi/16) */
+#define W1mW7 2276
+#define W1pW7 3406
+#define W5mW3 -799
+#define mW3mW5 -4017
+#define mW2mW6 -3784
+#define W2mW6 1568
+
+/* left shift by 11 is to maintain the accuracy of the decimal point */
+/* for the transform coefficients (W1,...W7) */
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp
new file mode 100644
index 0000000..f35ce4f
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/idct_vca.cpp
@@ -0,0 +1,660 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4def.h"
+#include "idct.h"
+#include "motion_comp.h"
+
+#ifdef FAST_IDCT
+
+/****************************************************************
+*       vca_idct.c : created 6/1/99 for several options
+*                     of hard-coded reduced idct function (using nz_coefs)
+******************************************************************/
+
+/*****************************************************/
+//pretested version
+void idctrow0(int16 *, uint8 *, uint8 *, int)
+{
+    return ;
+}
+void idctcol0(int16 *)
+{
+    return ;
+}
+
+void idctrow1(int16 *blk, uint8 *pred, uint8 *dst, int width)
+{
+    /* shortcut */
+    int tmp;
+    int i = 8;
+    uint32 pred_word, dst_word;
+    int res, res2;
+
+    /* preset the offset, such that we can take advantage pre-offset addressing mode   */
+    width -= 4;
+    dst -= width;
+    pred -= 12;
+    blk -= 8;
+
+    while (i--)
+    {
+        tmp = (*(blk += 8) + 32) >> 6;
+        *blk = 0;
+
+        pred_word = *((uint32*)(pred += 12)); /* read 4 bytes from pred */
+        res = tmp + (pred_word & 0xFF);
+        CLIP_RESULT(res);
+        res2 = tmp + ((pred_word >> 8) & 0xFF);
+        CLIP_RESULT(res2);
+        dst_word = (res2 << 8) | res;
+        res = tmp + ((pred_word >> 16) & 0xFF);
+        CLIP_RESULT(res);
+        dst_word |= (res << 16);
+        res = tmp + ((pred_word >> 24) & 0xFF);
+        CLIP_RESULT(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += width)) = dst_word; /* save 4 bytes to dst */
+
+        pred_word = *((uint32*)(pred += 4)); /* read 4 bytes from pred */
+        res = tmp + (pred_word & 0xFF);
+        CLIP_RESULT(res);
+        res2 = tmp + ((pred_word >> 8) & 0xFF);
+        CLIP_RESULT(res2);
+        dst_word = (res2 << 8) | res;
+        res = tmp + ((pred_word >> 16) & 0xFF);
+        CLIP_RESULT(res);
+        dst_word |= (res << 16);
+        res = tmp + ((pred_word >> 24) & 0xFF);
+        CLIP_RESULT(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += 4)) = dst_word; /* save 4 bytes to dst */
+    }
+    return;
+}
+
+void idctcol1(int16 *blk)
+{ /* shortcut */
+    blk[0] = blk[8] = blk[16] = blk[24] = blk[32] = blk[40] = blk[48] = blk[56] =
+                                              blk[0] << 3;
+    return;
+}
+
+void idctrow2(int16 *blk, uint8 *pred, uint8 *dst, int width)
+{
+    int32 x0, x1, x2, x4, x5;
+    int i = 8;
+    uint32 pred_word, dst_word;
+    int res, res2;
+
+    /* preset the offset, such that we can take advantage pre-offset addressing mode   */
+    width -= 4;
+    dst -= width;
+    pred -= 12;
+    blk -= 8;
+
+    while (i--)
+    {
+        /* shortcut */
+        x4 = blk[9];
+        blk[9] = 0;
+        x0 = ((*(blk += 8)) << 8) + 8192;
+        *blk = 0;  /* for proper rounding in the fourth stage */
+
+        /* first stage */
+        x5 = (W7 * x4 + 4) >> 3;
+        x4 = (W1 * x4 + 4) >> 3;
+
+        /* third stage */
+        x2 = (181 * (x4 + x5) + 128) >> 8;
+        x1 = (181 * (x4 - x5) + 128) >> 8;
+
+        /* fourth stage */
+        pred_word = *((uint32*)(pred += 12)); /* read 4 bytes from pred */
+        res = (x0 + x4) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x0 + x2) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x0 + x1) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x0 + x5) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += width)) = dst_word; /* save 4 bytes to dst */
+
+        pred_word = *((uint32*)(pred += 4)); /* read 4 bytes from pred */
+        res = (x0 - x5) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x0 - x1) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x0 - x2) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x0 - x4) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += 4)) = dst_word; /* save 4 bytes to dst */
+    }
+    return ;
+}
+
+void idctcol2(int16 *blk)
+{
+    int32 x0, x1, x3, x5, x7;//, x8;
+
+    x1 = blk[8];
+    x0 = ((int32)blk[0] << 11) + 128;
+    /* both upper and lower*/
+
+    x7 = W7 * x1;
+    x1 = W1 * x1;
+
+    x3 = x7;
+    x5 = (181 * (x1 - x7) + 128) >> 8;
+    x7 = (181 * (x1 + x7) + 128) >> 8;
+
+    blk[0] = (x0 + x1) >> 8;
+    blk[8] = (x0 + x7) >> 8;
+    blk[16] = (x0 + x5) >> 8;
+    blk[24] = (x0 + x3) >> 8;
+    blk[56] = (x0 - x1) >> 8;
+    blk[48] = (x0 - x7) >> 8;
+    blk[40] = (x0 - x5) >> 8;
+    blk[32] = (x0 - x3) >> 8;
+
+    return ;
+}
+
+void idctrow3(int16 *blk, uint8 *pred, uint8 *dst, int width)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+    int i = 8;
+    uint32 pred_word, dst_word;
+    int res, res2;
+
+    /* preset the offset, such that we can take advantage pre-offset addressing mode   */
+    width -= 4;
+    dst -= width;
+    pred -= 12;
+    blk -= 8;
+
+    while (i--)
+    {
+        x2 = blk[10];
+        blk[10] = 0;
+        x1 = blk[9];
+        blk[9] = 0;
+        x0 = ((*(blk += 8)) << 8) + 8192;
+        *blk = 0;   /* for proper rounding in the fourth stage */
+        /* both upper and lower*/
+        /* both x2orx6 and x0orx4 */
+
+        x4 = x0;
+        x6 = (W6 * x2 + 4) >> 3;
+        x2 = (W2 * x2 + 4) >> 3;
+        x8 = x0 - x2;
+        x0 += x2;
+        x2 = x8;
+        x8 = x4 - x6;
+        x4 += x6;
+        x6 = x8;
+
+        x7 = (W7 * x1 + 4) >> 3;
+        x1 = (W1 * x1 + 4) >> 3;
+        x3 = x7;
+        x5 = (181 * (x1 - x7) + 128) >> 8;
+        x7 = (181 * (x1 + x7) + 128) >> 8;
+
+        pred_word = *((uint32*)(pred += 12)); /* read 4 bytes from pred */
+        res = (x0 + x1) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x4 + x7) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x6 + x5) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x2 + x3) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += width)) = dst_word; /* save 4 bytes to dst */
+
+        pred_word = *((uint32*)(pred += 4)); /* read 4 bytes from pred */
+        res = (x2 - x3) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x6 - x5) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x4 - x7) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x0 - x1) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += 4)) = dst_word; /* save 4 bytes to dst */
+    }
+
+    return ;
+}
+
+void idctcol3(int16 *blk)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+
+    x2 = blk[16];
+    x1 = blk[8];
+    x0 = ((int32)blk[0] << 11) + 128;
+
+    x4 = x0;
+    x6 = W6 * x2;
+    x2 = W2 * x2;
+    x8 = x0 - x2;
+    x0 += x2;
+    x2 = x8;
+    x8 = x4 - x6;
+    x4 += x6;
+    x6 = x8;
+
+    x7 = W7 * x1;
+    x1 = W1 * x1;
+    x3 = x7;
+    x5 = (181 * (x1 - x7) + 128) >> 8;
+    x7 = (181 * (x1 + x7) + 128) >> 8;
+
+    blk[0] = (x0 + x1) >> 8;
+    blk[8] = (x4 + x7) >> 8;
+    blk[16] = (x6 + x5) >> 8;
+    blk[24] = (x2 + x3) >> 8;
+    blk[56] = (x0 - x1) >> 8;
+    blk[48] = (x4 - x7) >> 8;
+    blk[40] = (x6 - x5) >> 8;
+    blk[32] = (x2 - x3) >> 8;
+
+    return;
+}
+
+
+void idctrow4(int16 *blk, uint8 *pred, uint8 *dst, int width)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+    int i = 8;
+    uint32 pred_word, dst_word;
+    int res, res2;
+
+    /* preset the offset, such that we can take advantage pre-offset addressing mode   */
+    width -= 4;
+    dst -= width;
+    pred -= 12;
+    blk -= 8;
+
+    while (i--)
+    {
+        x2 = blk[10];
+        blk[10] = 0;
+        x1 = blk[9];
+        blk[9] = 0;
+        x3 = blk[11];
+        blk[11] = 0;
+        x0 = ((*(blk += 8)) << 8) + 8192;
+        *blk = 0;    /* for proper rounding in the fourth stage */
+
+        x4 = x0;
+        x6 = (W6 * x2 + 4) >> 3;
+        x2 = (W2 * x2 + 4) >> 3;
+        x8 = x0 - x2;
+        x0 += x2;
+        x2 = x8;
+        x8 = x4 - x6;
+        x4 += x6;
+        x6 = x8;
+
+        x7 = (W7 * x1 + 4) >> 3;
+        x1 = (W1 * x1 + 4) >> 3;
+        x5 = (W3 * x3 + 4) >> 3;
+        x3 = (- W5 * x3 + 4) >> 3;
+        x8 = x1 - x5;
+        x1 += x5;
+        x5 = x8;
+        x8 = x7 - x3;
+        x3 += x7;
+        x7 = (181 * (x5 + x8) + 128) >> 8;
+        x5 = (181 * (x5 - x8) + 128) >> 8;
+
+        pred_word = *((uint32*)(pred += 12)); /* read 4 bytes from pred */
+        res = (x0 + x1) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x4 + x7) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x6 + x5) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x2 + x3) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += width)) = dst_word; /* save 4 bytes to dst */
+
+        pred_word = *((uint32*)(pred += 4)); /* read 4 bytes from pred */
+        res = (x2 - x3) >> 14;
+        ADD_AND_CLIP1(res);
+        res2 = (x6 - x5) >> 14;
+        ADD_AND_CLIP2(res2);
+        dst_word = (res2 << 8) | res;
+        res = (x4 - x7) >> 14;
+        ADD_AND_CLIP3(res);
+        dst_word |= (res << 16);
+        res = (x0 - x1) >> 14;
+        ADD_AND_CLIP4(res);
+        dst_word |= (res << 24);
+        *((uint32*)(dst += 4)) = dst_word; /* save 4 bytes to dst */
+    }
+    return ;
+}
+
+void idctcol4(int16 *blk)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8;
+    x2 = blk[16];
+    x1 = blk[8];
+    x3 = blk[24];
+    x0 = ((int32)blk[0] << 11) + 128;
+
+    x4 = x0;
+    x6 = W6 * x2;
+    x2 = W2 * x2;
+    x8 = x0 - x2;
+    x0 += x2;
+    x2 = x8;
+    x8 = x4 - x6;
+    x4 += x6;
+    x6 = x8;
+
+    x7 = W7 * x1;
+    x1 = W1 * x1;
+    x5 = W3 * x3;
+    x3 = -W5 * x3;
+    x8 = x1 - x5;
+    x1 += x5;
+    x5 = x8;
+    x8 = x7 - x3;
+    x3 += x7;
+    x7 = (181 * (x5 + x8) + 128) >> 8;
+    x5 = (181 * (x5 - x8) + 128) >> 8;
+
+
+    blk[0] = (x0 + x1) >> 8;
+    blk[8] = (x4 + x7) >> 8;
+    blk[16] = (x6 + x5) >> 8;
+    blk[24] = (x2 + x3) >> 8;
+    blk[56] = (x0 - x1) >> 8;
+    blk[48] = (x4 - x7) >> 8;
+    blk[40] = (x6 - x5) >> 8;
+    blk[32] = (x2 - x3) >> 8;
+
+    return ;
+}
+
+void idctrow0_intra(int16 *, PIXEL *, int)
+{
+    return ;
+}
+
+void idctrow1_intra(int16 *blk, PIXEL *comp, int width)
+{
+    /* shortcut */
+    int32 tmp;
+    int i = 8;
+    int offset = width;
+    uint32 word;
+
+    comp -= offset;
+    while (i--)
+    {
+        tmp = ((blk[0] + 32) >> 6);
+        blk[0] = 0;
+        CLIP_RESULT(tmp)
+
+        word = (tmp << 8) | tmp;
+        word = (word << 16) | word;
+
+        *((uint32*)(comp += offset)) = word;
+        *((uint32*)(comp + 4)) = word;
+
+
+
+
+        blk += B_SIZE;
+    }
+    return;
+}
+
+void idctrow2_intra(int16 *blk, PIXEL *comp, int width)
+{
+    int32 x0, x1, x2, x4, x5, temp;
+    int i = 8;
+    int offset = width;
+    int32 word;
+
+    comp -= offset;
+    while (i--)
+    {
+        /* shortcut */
+        x4 = blk[1];
+        blk[1] = 0;
+        x0 = ((int32)blk[0] << 8) + 8192;
+        blk[0] = 0;   /* for proper rounding in the fourth stage */
+
+        /* first stage */
+        x5 = (W7 * x4 + 4) >> 3;
+        x4 = (W1 * x4 + 4) >> 3;
+
+        /* third stage */
+        x2 = (181 * (x4 + x5) + 128) >> 8;
+        x1 = (181 * (x4 - x5) + 128) >> 8;
+
+        /* fourth stage */
+        word = ((x0 + x4) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x0 + x2) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+        temp = ((x0 + x1) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+        temp = ((x0 + x5) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp += offset)) = word;
+
+        word = ((x0 - x5) >> 14);
+        CLIP_RESULT(word)
+        temp = ((x0 - x1) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+        temp = ((x0 - x2) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+        temp = ((x0 - x4) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp + 4)) = word;
+
+        blk += B_SIZE;
+    }
+    return ;
+}
+
+void idctrow3_intra(int16 *blk, PIXEL *comp, int width)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8, temp;
+    int i = 8;
+    int offset = width;
+    int32 word;
+
+    comp -= offset;
+
+    while (i--)
+    {
+        x2 = blk[2];
+        blk[2] = 0;
+        x1 = blk[1];
+        blk[1] = 0;
+        x0 = ((int32)blk[0] << 8) + 8192;
+        blk[0] = 0;/* for proper rounding in the fourth stage */
+        /* both upper and lower*/
+        /* both x2orx6 and x0orx4 */
+
+        x4 = x0;
+        x6 = (W6 * x2 + 4) >> 3;
+        x2 = (W2 * x2 + 4) >> 3;
+        x8 = x0 - x2;
+        x0 += x2;
+        x2 = x8;
+        x8 = x4 - x6;
+        x4 += x6;
+        x6 = x8;
+
+        x7 = (W7 * x1 + 4) >> 3;
+        x1 = (W1 * x1 + 4) >> 3;
+        x3 = x7;
+        x5 = (181 * (x1 - x7) + 128) >> 8;
+        x7 = (181 * (x1 + x7) + 128) >> 8;
+
+        word = ((x0 + x1) >> 14);
+        CLIP_RESULT(word)
+        temp = ((x4 + x7) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+
+        temp = ((x6 + x5) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x2 + x3) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp += offset)) = word;
+
+        word = ((x2 - x3) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x6 - x5) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+        temp = ((x4 - x7) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x0 - x1) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp + 4)) = word;
+
+        blk += B_SIZE;
+    }
+    return ;
+}
+
+void idctrow4_intra(int16 *blk, PIXEL *comp, int width)
+{
+    int32 x0, x1, x2, x3, x4, x5, x6, x7, x8, temp;
+    int i = 8;
+    int offset = width;
+    int32 word;
+
+    comp -= offset;
+
+    while (i--)
+    {
+        x2 = blk[2];
+        blk[2] = 0;
+        x1 = blk[1];
+        blk[1] = 0;
+        x3 = blk[3];
+        blk[3] = 0;
+        x0 = ((int32)blk[0] << 8) + 8192;
+        blk[0] = 0;/* for proper rounding in the fourth stage */
+
+        x4 = x0;
+        x6 = (W6 * x2 + 4) >> 3;
+        x2 = (W2 * x2 + 4) >> 3;
+        x8 = x0 - x2;
+        x0 += x2;
+        x2 = x8;
+        x8 = x4 - x6;
+        x4 += x6;
+        x6 = x8;
+
+        x7 = (W7 * x1 + 4) >> 3;
+        x1 = (W1 * x1 + 4) >> 3;
+        x5 = (W3 * x3 + 4) >> 3;
+        x3 = (- W5 * x3 + 4) >> 3;
+        x8 = x1 - x5;
+        x1 += x5;
+        x5 = x8;
+        x8 = x7 - x3;
+        x3 += x7;
+        x7 = (181 * (x5 + x8) + 128) >> 8;
+        x5 = (181 * (x5 - x8) + 128) >> 8;
+
+        word = ((x0 + x1) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x4 + x7) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+
+        temp = ((x6 + x5) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x2 + x3) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp += offset)) = word;
+
+        word = ((x2 - x3) >> 14);
+        CLIP_RESULT(word)
+
+        temp = ((x6 - x5) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 8);
+
+        temp = ((x4 - x7) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 16);
+
+        temp = ((x0 - x1) >> 14);
+        CLIP_RESULT(temp)
+        word = word | (temp << 24);
+        *((int32*)(comp + 4)) = word;
+
+        blk += B_SIZE;
+    }
+
+    return ;
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/max_level.h b/media/libstagefright/codecs/m4v_h263/dec/src/max_level.h
new file mode 100644
index 0000000..2d59c73
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/max_level.h
@@ -0,0 +1,149 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+*     -------------------------------------------------------------------   *
+*                    MPEG-4 Simple Profile Video Decoder                    *
+*     -------------------------------------------------------------------   *
+*
+* This software module was originally developed by
+*
+*   Michael Wollborn (TUH / ACTS-MoMuSyS)
+*
+* in the course of development of the MPEG-4 Video (ISO/IEC 14496-2) standard.
+* This software module is an implementation of a part of one or more MPEG-4
+* Video (ISO/IEC 14496-2) tools as specified by the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* ISO/IEC gives users of the MPEG-4 Video (ISO/IEC 14496-2) standard free
+* license to this software module or modifications thereof for use in hardware
+* or software products claiming conformance to the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* Those intending to use this software module in hardware or software products
+* are advised that its use may infringe existing patents. The original
+* developer of this software module and his/her company, the subsequent
+* editors and their companies, and ISO/IEC have no liability for use of this
+* software module or modifications thereof in an implementation. Copyright is
+* not released for non MPEG-4 Video (ISO/IEC 14496-2) Standard conforming
+* products.
+*
+* ACTS-MoMuSys partners retain full right to use the code for his/her own
+* purpose, assign or donate the code to a third party and to inhibit third
+* parties from using the code for non MPEG-4 Video (ISO/IEC 14496-2) Standard
+* conforming products. This copyright notice must be included in all copies or
+* derivative works.
+*
+* Copyright (c) 1997
+*
+*****************************************************************************
+
+This is a header file for "vlc_decode.c".  The table data actually resides
+in "vlc_tab.c".
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef max_level_H
+#define max_level_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4def.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    extern const int intra_max_level[2][NCOEFF_BLOCK];
+
+    extern const int inter_max_level[2][NCOEFF_BLOCK];
+
+    extern const int intra_max_run0[28];
+
+
+    extern const int intra_max_run1[9];
+
+    extern const int inter_max_run0[13];
+
+
+    extern const int inter_max_run1[4];
+
+
+    /*----------------------------------------------------------------------------
+    ; 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/m4v_h263/dec/src/mb_motion_comp.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
new file mode 100644
index 0000000..fbc7be1
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mb_motion_comp.cpp
@@ -0,0 +1,623 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    video = pointer to structure of type VideoDecData
+
+ Local Stores/Buffers/Pointers Needed:
+    roundtab16 = rounding table
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    video->currVop->yChan contents are the newly calculated luminance
+      data
+    video->currVop->uChan contents are the newly calculated chrominance
+      b data
+    video->currVop->vChan contents are the newly calculated chrominance
+      r data
+    video->pstprcTypCur contents are the updated semaphore propagation
+      values
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function performs high level motion compensation on the luminance and
+ chrominance data. It sets up all the parameters required by the functions
+ that perform luminance and chrominance prediction and it initializes the
+ pointer to the post processing semaphores of a given block. It also checks
+ the motion compensation mode in order to determine which luminance or
+ chrominance prediction functions to call and determines how the post
+ processing semaphores are updated.
+
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+#include "motion_comp.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
+----------------------------------------------------------------------------*/
+/* 09/29/2000 bring this from mp4def.h */
+// const static int roundtab4[] = {0,1,1,1};
+// const static int roundtab8[] = {0,0,1,1,1,1,1,2};
+/*** 10/30 for TPS */
+// const static int roundtab12[] = {0,0,0,1,1,1,1,1,1,1,2,2};
+/* 10/30 for TPS ***/
+const static int roundtab16[] = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2};
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/** modified 3 August 2005 to do prediction and put the results in
+video->mblock->pred_block, no adding with residue */
+
+void  MBMotionComp(
+    VideoDecData *video,
+    int CBP
+)
+{
+
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    /* Previous Video Object Plane */
+    Vop *prev = video->prevVop;
+
+    /* Current Macroblock (MB) in the VOP */
+    int mbnum = video->mbnum;
+
+    /* Number of MB per data row */
+    int MB_in_width = video->nMBPerRow;
+    int ypos, xpos;
+    PIXEL *c_comp, *c_prev;
+    PIXEL *cu_comp, *cu_prev;
+    PIXEL *cv_comp, *cv_prev;
+    int height, width, pred_width;
+    int imv, mvwidth;
+    int32 offset;
+    uint8 mode;
+    uint8 *pred_block, *pred;
+
+    /* Motion vector (dx,dy) in half-pel resolution */
+    int dx, dy;
+
+    MOT px[4], py[4];
+    int xpred, ypred;
+    int xsum;
+    int round1;
+#ifdef PV_POSTPROC_ON // 2/14/2001      
+    /* Total number of pixels in the VOL */
+    int32 size = (int32) video->nTotalMB << 8;
+    uint8 *pp_dec_y, *pp_dec_u;
+    int ll[4];
+    int tmp = 0;
+    uint8 msk_deblock = 0;
+#endif
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Set rounding type */
+    /* change from array to single 09/29/2000 */
+    round1 = (int)(1 - video->currVop->roundingType);
+
+    /* width of luminance data in pixels (y axis) */
+    width = video->width;
+
+    /* heigth of luminance data in pixels (x axis) */
+    height = video->height;
+
+    /* number of blocks per row */
+    mvwidth = MB_in_width << 1;
+
+    /* starting y position in current MB; origin of MB */
+    ypos = video->mbnum_row << 4 ;
+    /* starting x position in current MB; origin of MB */
+    xpos = video->mbnum_col << 4 ;
+
+    /* offset to (x,y) position in current luminance MB */
+    /* in pixel resolution                              */
+    /* ypos*width -> row, +x -> column */
+    offset = (int32)ypos * width + xpos;
+
+    /* get mode for current MB */
+    mode = video->headerInfo.Mode[mbnum];
+
+    /* block index */
+    /* imv = (xpos/8) + ((ypos/8) * mvwidth) */
+    imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3);
+    if (mode & INTER_1VMASK)
+    {
+        dx = px[0] = px[1] = px[2] = px[3] = video->motX[imv];
+        dy = py[0] = py[1] = py[2] = py[3] = video->motY[imv];
+        if ((dx & 3) == 0)
+        {
+            dx = dx >> 1;
+        }
+        else
+        {
+            /* x component of MV is or'ed for rounding (?) */
+            dx = (dx >> 1) | 1;
+        }
+
+        /* y component of motion vector; divide by 2 for to */
+        /* convert to full-pel resolution.                  */
+        if ((dy & 3) == 0)
+        {
+            dy = dy >> 1;
+        }
+        else
+        {
+            /* y component of MV is or'ed for rounding (?) */
+            dy = (dy >> 1) | 1;
+        }
+    }
+    else
+    {
+        px[0] = video->motX[imv];
+        px[1] = video->motX[imv+1];
+        px[2] = video->motX[imv+mvwidth];
+        px[3] = video->motX[imv+mvwidth+1];
+        xsum = px[0] + px[1] + px[2] + px[3];
+        dx = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] +
+                              (((PV_ABS(xsum)) >> 4) << 1));
+        py[0] = video->motY[imv];
+        py[1] = video->motY[imv+1];
+        py[2] = video->motY[imv+mvwidth];
+        py[3] = video->motY[imv+mvwidth+1];
+        xsum = py[0] + py[1] + py[2] + py[3];
+        dy = PV_SIGN(xsum) * (roundtab16[(PV_ABS(xsum)) & 0xF] +
+                              (((PV_ABS(xsum)) >> 4) << 1));
+    }
+
+    /* Pointer to previous luminance frame */
+    c_prev  = prev->yChan;
+
+    pred_block = video->mblock->pred_block;
+
+    /* some blocks have no residue or INTER4V */
+    /*if (mode == MODE_INTER4V)   05/08/15 */
+    /* Motion Compensation for an 8x8 block within a MB */
+    /* (4 MV per MB) */
+
+
+
+    /* Call function that performs luminance prediction */
+    /*      luminance_pred_mode_inter4v(xpos, ypos, px, py, c_prev,
+                    video->mblock->pred_block, width, height,
+                    round1, mvwidth, &xsum, &ysum);*/
+    c_comp = video->currVop->yChan + offset;
+
+
+    xpred = (int)((xpos << 1) + px[0]);
+    ypred = (int)((ypos << 1) + py[0]);
+
+    if ((CBP >> 5)&1)
+    {
+        pred = pred_block;
+        pred_width = 16;
+    }
+    else
+    {
+        pred = c_comp;
+        pred_width = width;
+    }
+
+    /* check whether the MV points outside the frame */
+    if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) &&
+            ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE)))
+    {   /*****************************/
+        /* (x,y) is inside the frame */
+        /*****************************/
+        ;
+        GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+    }
+    else
+    {   /******************************/
+        /* (x,y) is outside the frame */
+        /******************************/
+        GetPredOutside(xpred, ypred, c_prev,
+                       pred, width, height, round1, pred_width);
+    }
+
+
+    /* Compute prediction values over current luminance MB */
+    /* (blocks 1); add motion vector prior to input;       */
+    /* add 8 to x_pos to advance to next block         */
+    xpred = (int)(((xpos + B_SIZE) << 1) + px[1]);
+    ypred = (int)((ypos << 1) + py[1]);
+
+    if ((CBP >> 4)&1)
+    {
+        pred = pred_block + 8;
+        pred_width = 16;
+    }
+    else
+    {
+        pred = c_comp + 8;
+        pred_width = width;
+    }
+
+    /* check whether the MV points outside the frame */
+    if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) &&
+            ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE)))
+    {   /*****************************/
+        /* (x,y) is inside the frame */
+        /*****************************/
+        GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+    }
+    else
+    {   /******************************/
+        /* (x,y) is outside the frame */
+        /******************************/
+        GetPredOutside(xpred, ypred, c_prev,
+                       pred, width, height, round1, pred_width);
+    }
+
+
+
+    /* Compute prediction values over current luminance MB */
+    /* (blocks 2); add motion vector prior to input        */
+    /* add 8 to y_pos to advance to block on next row      */
+    xpred = (int)((xpos << 1) + px[2]);
+    ypred = (int)(((ypos + B_SIZE) << 1) + py[2]);
+
+    if ((CBP >> 3)&1)
+    {
+        pred = pred_block + 128;
+        pred_width = 16;
+    }
+    else
+    {
+        pred = c_comp + (width << 3);
+        pred_width = width;
+    }
+
+    /* check whether the MV points outside the frame */
+    if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) &&
+            ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE)))
+    {   /*****************************/
+        /* (x,y) is inside the frame */
+        /*****************************/
+        GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+    }
+    else
+    {   /******************************/
+        /* (x,y) is outside the frame */
+        /******************************/
+        GetPredOutside(xpred, ypred, c_prev,
+                       pred, width, height, round1, pred_width);
+    }
+
+
+
+    /* Compute prediction values over current luminance MB */
+    /* (blocks 3); add motion vector prior to input;       */
+    /* add 8 to x_pos and y_pos to advance to next block   */
+    /* on next row                         */
+    xpred = (int)(((xpos + B_SIZE) << 1) + px[3]);
+    ypred = (int)(((ypos + B_SIZE) << 1) + py[3]);
+
+    if ((CBP >> 2)&1)
+    {
+        pred = pred_block + 136;
+        pred_width = 16;
+    }
+    else
+    {
+        pred = c_comp + (width << 3) + 8;
+        pred_width = width;
+    }
+
+    /* check whether the MV points outside the frame */
+    if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) &&
+            ypred >= 0 && ypred <= ((height << 1) - (2*B_SIZE)))
+    {   /*****************************/
+        /* (x,y) is inside the frame */
+        /*****************************/
+        GetPredAdvBTable[ypred&1][xpred&1](c_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+    }
+    else
+    {   /******************************/
+        /* (x,y) is outside the frame */
+        /******************************/
+        GetPredOutside(xpred, ypred, c_prev,
+                       pred, width, height, round1, pred_width);
+    }
+    /* Call function to set de-blocking and de-ringing */
+    /*   semaphores for luminance                      */
+
+#ifdef PV_POSTPROC_ON
+    if (video->postFilterType != PV_NO_POST_PROC)
+    {
+        if (mode&INTER_1VMASK)
+        {
+            pp_dec_y = video->pstprcTypCur + imv;
+            ll[0] = 1;
+            ll[1] = mvwidth - 1;
+            ll[2] = 1;
+            ll[3] = -mvwidth - 1;
+            msk_deblock = pp_semaphore_luma(xpred, ypred, pp_dec_y,
+                                            video->pstprcTypPrv, ll, &tmp, px[0], py[0], mvwidth,
+                                            width, height);
+
+            pp_dec_u = video->pstprcTypCur + (size >> 6) +
+                       ((imv + (xpos >> 3)) >> 2);
+
+            pp_semaphore_chroma_inter(xpred, ypred, pp_dec_u,
+                                      video->pstprcTypPrv, dx, dy, mvwidth, height, size,
+                                      tmp, msk_deblock);
+        }
+        else
+        {
+            /* Post-processing mode (MBM_INTER8) */
+            /* deblocking and deringing) */
+            pp_dec_y = video->pstprcTypCur + imv;
+            *pp_dec_y = 4;
+            *(pp_dec_y + 1) = 4;
+            *(pp_dec_y + mvwidth) = 4;
+            *(pp_dec_y + mvwidth + 1) = 4;
+            pp_dec_u = video->pstprcTypCur + (size >> 6) +
+                       ((imv + (xpos >> 3)) >> 2);
+            *pp_dec_u = 4;
+            pp_dec_u[size>>8] = 4;
+        }
+    }
+#endif
+
+
+    /* xpred and ypred calculation for Chrominance is */
+    /* in full-pel resolution.                        */
+
+    /* Chrominance */
+    /* width of chrominance data in pixels (y axis) */
+    width >>= 1;
+
+    /* heigth of chrominance data in pixels (x axis) */
+    height >>= 1;
+
+    /* Pointer to previous chrominance b frame */
+    cu_prev = prev->uChan;
+
+    /* Pointer to previous chrominance r frame */
+    cv_prev = prev->vChan;
+
+    /* x position in prediction data offset by motion vector */
+    /* xpred calculation for Chrominance is in full-pel      */
+    /* resolution.                                           */
+    xpred = xpos + dx;
+
+    /* y position in prediction data offset by motion vector */
+    /* ypred calculation for Chrominance is in full-pel      */
+    /* resolution.                                           */
+    ypred = ypos + dy;
+
+    cu_comp = video->currVop->uChan + (offset >> 2) + (xpos >> 2);
+    cv_comp = video->currVop->vChan + (offset >> 2) + (xpos >> 2);
+
+    /* Call function that performs chrominance prediction */
+    /*      chrominance_pred(xpred, ypred, cu_prev, cv_prev,
+            pred_block, width_uv, height_uv,
+            round1);*/
+    if (xpred >= 0 && xpred <= ((width << 1) - (2*B_SIZE)) && ypred >= 0 &&
+            ypred <= ((height << 1) - (2*B_SIZE)))
+    {
+        /*****************************/
+        /* (x,y) is inside the frame */
+        /*****************************/
+        if ((CBP >> 1)&1)
+        {
+            pred = pred_block + 256;
+            pred_width = 16;
+        }
+        else
+        {
+            pred = cu_comp;
+            pred_width = width;
+        }
+
+        /* Compute prediction for Chrominance b (block[4]) */
+        GetPredAdvBTable[ypred&1][xpred&1](cu_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+
+        if (CBP&1)
+        {
+            pred = pred_block + 264;
+            pred_width = 16;
+        }
+        else
+        {
+            pred = cv_comp;
+            pred_width = width;
+        }
+        /* Compute prediction for Chrominance r (block[5]) */
+        GetPredAdvBTable[ypred&1][xpred&1](cv_prev + (xpred >> 1) + ((ypred >> 1)*width),
+                                           pred, width, (pred_width << 1) | round1);
+
+        return ;
+    }
+    else
+    {
+        /******************************/
+        /* (x,y) is outside the frame */
+        /******************************/
+        if ((CBP >> 1)&1)
+        {
+            pred = pred_block + 256;
+            pred_width = 16;
+        }
+        else
+        {
+            pred = cu_comp;
+            pred_width = width;
+        }
+
+        /* Compute prediction for Chrominance b (block[4]) */
+        GetPredOutside(xpred, ypred,    cu_prev,
+                       pred, width, height, round1, pred_width);
+
+        if (CBP&1)
+        {
+            pred = pred_block + 264;
+            pred_width = 16;
+        }
+        else
+        {
+            pred = cv_comp;
+            pred_width = width;
+        }
+
+        /* Compute prediction for Chrominance r (block[5]) */
+        GetPredOutside(xpred, ypred,    cv_prev,
+                       pred, width, height, round1, pred_width);
+
+        return ;
+    }
+
+}
+
+/*** special function for skipped macroblock,  Aug 15, 2005 */
+void  SkippedMBMotionComp(
+    VideoDecData *video
+)
+{
+    Vop *prev = video->prevVop;
+    Vop *comp;
+    int ypos, xpos;
+    PIXEL *c_comp, *c_prev;
+    PIXEL *cu_comp, *cu_prev;
+    PIXEL *cv_comp, *cv_prev;
+    int width, width_uv;
+    int32 offset;
+#ifdef PV_POSTPROC_ON // 2/14/2001      
+    int imv;
+    int32 size = (int32) video->nTotalMB << 8;
+    uint8 *pp_dec_y, *pp_dec_u;
+    uint8 *pp_prev1;
+    int mvwidth = video->nMBPerRow << 1;
+#endif
+
+    width = video->width;
+    width_uv  = width >> 1;
+    ypos = video->mbnum_row << 4 ;
+    xpos = video->mbnum_col << 4 ;
+    offset = (int32)ypos * width + xpos;
+
+
+    /* zero motion compensation for previous frame */
+    /*mby*width + mbx;*/
+    c_prev  = prev->yChan + offset;
+    /*by*width_uv + bx;*/
+    cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2);
+    /*by*width_uv + bx;*/
+    cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2);
+
+    comp = video->currVop;
+
+    c_comp  = comp->yChan + offset;
+    cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2);
+    cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2);
+
+
+    /* Copy previous reconstructed frame into the current frame */
+    PutSKIPPED_MB(c_comp,  c_prev, width);
+    PutSKIPPED_B(cu_comp, cu_prev, width_uv);
+    PutSKIPPED_B(cv_comp, cv_prev, width_uv);
+
+    /*  10/24/2000 post_processing semaphore generation */
+#ifdef PV_POSTPROC_ON // 2/14/2001
+    if (video->postFilterType != PV_NO_POST_PROC)
+    {
+        imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3);
+        /* Post-processing mode (copy previous MB) */
+        pp_prev1 = video->pstprcTypPrv + imv;
+        pp_dec_y = video->pstprcTypCur + imv;
+        *pp_dec_y = *pp_prev1;
+        *(pp_dec_y + 1) = *(pp_prev1 + 1);
+        *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth);
+        *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1);
+
+        /* chrominance */
+        /*4*MB_in_width*MB_in_height*/
+        pp_prev1 = video->pstprcTypPrv + (size >> 6) +
+                   ((imv + (xpos >> 3)) >> 2);
+        pp_dec_u = video->pstprcTypCur + (size >> 6) +
+                   ((imv + (xpos >> 3)) >> 2);
+        *pp_dec_u = *pp_prev1;
+        pp_dec_u[size>>8] = pp_prev1[size>>8];
+    }
+#endif
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+
+    return;
+}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mb_utils.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/mb_utils.cpp
new file mode 100644
index 0000000..25a31b7
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mb_utils.cpp
@@ -0,0 +1,133 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+
+/* ====================================================================== /
+    Function : PutSKIPPED_MB()
+    Date     : 04/03/2000
+/ ====================================================================== */
+
+void PutSKIPPED_MB(uint8 *comp, uint8 *prev, int width)
+{
+    int32 *temp0, *temp1;
+    int  row;
+    row = MB_SIZE;
+
+
+    while (row)
+    {
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+        temp1[2] = temp0[2];
+        temp1[3] = temp0[3];
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+        temp1[2] = temp0[2];
+        temp1[3] = temp0[3];
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+        temp1[2] = temp0[2];
+        temp1[3] = temp0[3];
+
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+        temp1[2] = temp0[2];
+        temp1[3] = temp0[3];
+
+        comp += width;
+        prev += width;
+        row -= 4;
+    }
+}
+
+
+/* ====================================================================== /
+    Function : PutSKIPPED_B()
+    Date     : 04/03/2000
+/ ====================================================================== */
+
+void PutSKIPPED_B(uint8 *comp, uint8 *prev, int width)
+{
+    int32 *temp0, *temp1;
+    int  row;
+
+    row = B_SIZE;
+    while (row)
+    {
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+
+        comp += width;
+        prev += width;
+
+        temp0 = (int32 *)prev;
+        temp1 = (int32 *)comp;
+
+        temp1[0] = temp0[0];
+        temp1[1] = temp0[1];
+
+        comp += width;
+        prev += width;
+        row -= 4;
+    }
+}
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mbtype_mode.h b/media/libstagefright/codecs/m4v_h263/dec/src/mbtype_mode.h
new file mode 100644
index 0000000..c45bb5f
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mbtype_mode.h
@@ -0,0 +1,37 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+const static int MBtype_mode[] =
+{
+    MODE_INTER,
+    MODE_INTER_Q,
+    MODE_INTER4V,
+    MODE_INTRA,
+    MODE_INTRA_Q,
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    MODE_INTER4V_Q,
+#endif
+    MODE_SKIPPED
+};
+#ifdef PV_ANNEX_IJKT_SUPPORT
+const static int16 DQ_tab_Annex_T_10[32] = {0, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3, -3};
+const static int16 DQ_tab_Annex_T_11[32] = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, -5};
+const static int16 MQ_chroma_QP_table[32] = {0, 1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13,
+        14, 14, 14, 14, 14, 15, 15, 15, 15, 15
+                                            };
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h b/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
new file mode 100644
index 0000000..0c12f20
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/motion_comp.h
@@ -0,0 +1,108 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef motion_comp_h
+#define motion_comp_h
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4dec_lib.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+/* CBP Mask defines used in chrominance prediction */
+#define CBP_MASK_CHROMA_BLK4    0x2
+#define CBP_MASK_CHROMA_BLK5    0x1
+
+/* CBP Mask defines used in luminance prediction (MODE_INTER4V) */
+#define CBP_MASK_BLK0_MODE_INTER4V  0x20
+#define CBP_MASK_BLK1_MODE_INTER4V  0x10
+#define CBP_MASK_BLK2_MODE_INTER4V  0x08
+#define CBP_MASK_BLK3_MODE_INTER4V  0x04
+
+/* CBP Mask defines used in luminance prediction (MODE_INTER or MODE_INTER_Q) */
+#define CBP_MASK_MB_MODE_INTER  0x3c
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define CLIP_RESULT(x)      if(x & -256){x = 0xFF & (~(x>>31));}
+#define ADD_AND_CLIP1(x)    x += (pred_word&0xFF); CLIP_RESULT(x);
+#define ADD_AND_CLIP2(x)    x += ((pred_word>>8)&0xFF); CLIP_RESULT(x);
+#define ADD_AND_CLIP3(x)    x += ((pred_word>>16)&0xFF); CLIP_RESULT(x);
+#define ADD_AND_CLIP4(x)    x += ((pred_word>>24)&0xFF); CLIP_RESULT(x);
+
+#define ADD_AND_CLIP(x,y)    {  x9 = ~(x>>8); \
+                            if(x9!=-1){ \
+                                x9 = ((uint32)x9)>>24; \
+                                y = x9|(y<<8); \
+                            } \
+                            else \
+                            {    \
+                                y =  x|(y<<8); \
+                            } \
+                            }
+
+
+    static int (*const GetPredAdvBTable[2][2])(uint8*, uint8*, int, int) =
+    {
+        {&GetPredAdvancedBy0x0, &GetPredAdvancedBy0x1},
+        {&GetPredAdvancedBy1x0, &GetPredAdvancedBy1x1}
+    };
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h b/media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h
new file mode 100644
index 0000000..9cd4edc
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mp4dec_lib.h
@@ -0,0 +1,334 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef _MP4DECLIB_H_
+#define _MP4DECLIB_H_
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4def.h" /* typedef */
+#include "mp4lib_int.h" /* main video structure */
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+    /* defined in pvdec_api.c, these function are not supposed to be    */
+    /* exposed to programmers outside PacketVideo.  08/15/2000.    */
+    uint VideoDecoderErrorDetected(VideoDecData *video);
+
+#ifdef ENABLE_LOG
+    void m4vdec_dprintf(char *format, ...);
+#define mp4dec_log(message) m4vdec_dprintf(message)
+#else
+#define mp4dec_log(message)
+#endif
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in frame_buffer.c */
+    PV_STATUS FillFrameBufferNew(BitstreamDecVideo *stream);
+    PV_STATUS FillFrameBuffer(BitstreamDecVideo *stream, int short_header);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in dc_ac_pred.c */
+    int cal_dc_scaler(int QP, int type);
+    PV_STATUS PV_DecodePredictedIntraDC(int compnum, BitstreamDecVideo *stream,
+                                        int16 *IntraDC_delta);
+
+    void    doDCACPrediction(VideoDecData *video, int comp, int16 *q_block,
+                             int *direction);
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    void    doDCACPrediction_I(VideoDecData *video, int comp, int16 *q_block);
+#endif
+    /*--------------------------------------------------------------------------*/
+    /* defined in block_idct.c */
+    void MBlockIDCTAdd(VideoDecData *video, int nz_coefs[]);
+
+    void BlockIDCT(uint8 *dst, uint8 *pred, int16 *blk, int width, int nzcoefs,
+                   uint8 *bitmapcol, uint8 bitmaprow);
+
+    void MBlockIDCT(VideoDecData *video);
+    void BlockIDCT_intra(MacroBlock *mblock, PIXEL *c_comp, int comp, int width_offset);
+    /*--------------------------------------------------------------------------*/
+    /* defined in combined_decode.c */
+    PV_STATUS DecodeFrameCombinedMode(VideoDecData *video);
+    PV_STATUS GetMBheader(VideoDecData *video, int16 *QP);
+    PV_STATUS GetMBData(VideoDecData *video);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in datapart_decode.c */
+    PV_STATUS DecodeFrameDataPartMode(VideoDecData *video);
+    PV_STATUS GetMBheaderDataPart_DQUANT_DC(VideoDecData *video, int16 *QP);
+    PV_STATUS GetMBheaderDataPart_P(VideoDecData *video);
+    PV_STATUS DecodeDataPart_I_VideoPacket(VideoDecData *video, int slice_counter);
+    PV_STATUS DecodeDataPart_P_VideoPacket(VideoDecData *video, int slice_counter);
+    PV_STATUS GetMBData_DataPart(VideoDecData *video);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in packet_util.c */
+    PV_STATUS PV_ReadVideoPacketHeader(VideoDecData *video, int *next_MB);
+    PV_STATUS RecoverPacketError(BitstreamDecVideo *stream, int marker_length, int32 *nextVop);
+    PV_STATUS RecoverGOBError(BitstreamDecVideo *stream, int marker_length, int32 *vopPos);
+    PV_STATUS PV_GobHeader(VideoDecData *video);
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    PV_STATUS PV_H263SliceHeader(VideoDecData *videoInt, int *next_MB);
+#endif
+    /*--------------------------------------------------------------------------*/
+    /* defined in motion_comp.c */
+    void MBMotionComp(VideoDecData *video, int CBP);
+    void  SkippedMBMotionComp(VideoDecData *video);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in chrominance_pred.c */
+    void chrominance_pred(
+        int xpred,          /* i */
+        int ypred,          /* i */
+        uint8 *cu_prev,     /* i */
+        uint8 *cv_prev,     /* i */
+        uint8 *pred_block,  /* i */
+        int width_uv,       /* i */
+        int height_uv,      /* i */
+        int round1
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in luminance_pred_mode_inter.c */
+    void luminance_pred_mode_inter(
+        int xpred,          /* i */
+        int ypred,          /* i */
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,  /* i */
+        int width,          /* i */
+        int height,         /* i */
+        int round1
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in luminance_pred_mode_inter4v.c */
+    void luminance_pred_mode_inter4v(
+        int xpos,           /* i */
+        int ypos,           /* i */
+        MOT *px,            /* i */
+        MOT *py,            /* i */
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,  /* i */
+        int width,          /* i */
+        int height,         /* i */
+        int round1,         /* i */
+        int mvwidth,            /* i */
+        int *xsum_ptr,          /* i/o */
+        int *ysum_ptr           /* i/o */
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in pp_semaphore_chroma_inter.c */
+#ifdef PV_POSTPROC_ON
+    void pp_semaphore_chroma_inter(
+        int xpred,      /* i */
+        int ypred,      /* i */
+        uint8   *pp_dec_u,  /* i/o */
+        uint8   *pstprcTypPrv,  /* i */
+        int dx,     /* i */
+        int dy,     /* i */
+        int mvwidth,    /* i */
+        int height,     /* i */
+        int32   size,       /* i */
+        int mv_loc,     /* i */
+        uint8   msk_deblock /* i */
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in pp_semaphore_luma.c */
+    uint8 pp_semaphore_luma(
+        int xpred,      /* i */
+        int ypred,      /* i */
+        uint8   *pp_dec_y,  /* i/o */
+        uint8   *pstprcTypPrv,  /* i */
+        int *ll,        /* i */
+        int *mv_loc,    /* i/o */
+        int dx,     /* i */
+        int dy,     /* i */
+        int mvwidth,    /* i */
+        int width,      /* i */
+        int height      /* i */
+    );
+#endif
+    /*--------------------------------------------------------------------------*/
+    /* defined in get_pred_adv_mb_add.c */
+    int GetPredAdvancedMB(
+        int xpos,
+        int ypos,
+        uint8 *c_prev,
+        uint8 *pred_block,
+        int width,
+        int rnd1
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in get_pred_adv_b_add.c */
+    int GetPredAdvancedBy0x0(
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,      /* i */
+        int width,      /* i */
+        int pred_width_rnd /* i */
+    );
+
+    int GetPredAdvancedBy0x1(
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,      /* i */
+        int width,      /* i */
+        int pred_width_rnd /* i */
+    );
+
+    int GetPredAdvancedBy1x0(
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,      /* i */
+        int width,      /* i */
+        int pred_width_rnd /* i */
+    );
+
+    int GetPredAdvancedBy1x1(
+        uint8 *c_prev,      /* i */
+        uint8 *pred_block,      /* i */
+        int width,      /* i */
+        int pred_width_rnd /* i */
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in get_pred_outside.c */
+    int GetPredOutside(
+        int xpos,
+        int ypos,
+        uint8 *c_prev,
+        uint8 *pred_block,
+        int width,
+        int height,
+        int rnd1,
+        int pred_width
+    );
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in find_pmvsErrRes.c */
+    void mv_prediction(VideoDecData *video, int block, MOT *mvx, MOT *mvy);
+
+    /*--------------------------------------------------------------------------*/
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in mb_utils.c */
+    void Copy_MB_into_Vop(uint8 *comp, int yChan[][NCOEFF_BLOCK], int width);
+    void Copy_B_into_Vop(uint8 *comp, int cChan[], int width);
+    void PutSKIPPED_MB(uint8 *comp, uint8 *c_prev, int width);
+    void PutSKIPPED_B(uint8 *comp, uint8 *c_prev, int width);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in vop.c */
+    PV_STATUS DecodeGOVHeader(BitstreamDecVideo *stream, uint32 *time_base);
+    PV_STATUS DecodeVOLHeader(VideoDecData *video, int layer);
+    PV_STATUS DecodeVOPHeader(VideoDecData *video, Vop *currVop, Bool use_ext_tiemstamp);
+    PV_STATUS DecodeShortHeader(VideoDecData *video, Vop *currVop);
+    PV_STATUS PV_DecodeVop(VideoDecData *video);
+    uint32 CalcVopDisplayTime(Vol *currVol, Vop *currVop, int shortVideoHeader);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in post_proc.c */
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    void H263_Deblock(uint8 *rec,   int width, int height, int16 *QP_store, uint8 *mode, int chr, int T);
+#endif
+    int  PostProcSemaphore(int16 *q_block);
+    void PostFilter(VideoDecData *video, int filer_type, uint8 *output);
+    void FindMaxMin(uint8 *ptr, int *min, int *max, int incr);
+    void DeringAdaptiveSmoothMMX(uint8 *img, int incr, int thres, int mxdf);
+    void AdaptiveSmooth_NoMMX(uint8 *Rec_Y, int v0, int h0, int v_blk, int h_blk,
+                              int thr, int width, int max_diff);
+    void Deringing_Luma(uint8 *Rec_Y, int width, int height, int16 *QP_store,
+                        int Combined, uint8 *pp_mod);
+    void Deringing_Chroma(uint8 *Rec_C, int width, int height, int16 *QP_store,
+                          int Combined, uint8 *pp_mod);
+    void CombinedHorzVertFilter(uint8 *rec, int width, int height, int16 *QP_store,
+                                int chr, uint8 *pp_mod);
+    void CombinedHorzVertFilter_NoSoftDeblocking(uint8 *rec, int width, int height, int16 *QP_store,
+            int chr, uint8 *pp_mod);
+    void CombinedHorzVertRingFilter(uint8 *rec, int width, int height,
+                                    int16 *QP_store, int chr, uint8 *pp_mod);
+
+    /*--------------------------------------------------------------------------*/
+    /* defined in conceal.c */
+    void ConcealTexture_I(VideoDecData *video, int32 startFirstPartition, int mb_start, int mb_stop,
+                          int slice_counter);
+    void ConcealTexture_P(VideoDecData *video, int mb_start, int mb_stop,
+                          int slice_counter);
+    void ConcealPacket(VideoDecData *video, int mb_start, int mb_stop,
+                       int slice_counter);
+    void CopyVopMB(Vop *curr, uint8 *prev, int mbnum, int width, int height);
+
+    /* define in vlc_dequant.c ,  09/18/2000*/
+#ifdef PV_SUPPORT_MAIN_PROFILE
+    int VlcDequantMpegIntraBlock(void *video, int comp, int switched,
+                                 uint8 *bitmapcol, uint8 *bitmaprow);
+    int VlcDequantMpegInterBlock(void *video, int comp,
+                                 uint8 *bitmapcol, uint8 *bitmaprow);
+#endif
+    int VlcDequantH263IntraBlock(VideoDecData *video, int comp, int switched,
+                                 uint8 *bitmapcol, uint8 *bitmaprow);
+    int VlcDequantH263IntraBlock_SH(VideoDecData *video, int comp,
+                                    uint8 *bitmapcol, uint8 *bitmaprow);
+    int VlcDequantH263InterBlock(VideoDecData *video, int comp,
+                                 uint8 *bitmapcol, uint8 *bitmaprow);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h b/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
new file mode 100644
index 0000000..3388d89
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mp4def.h
@@ -0,0 +1,167 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef _PVDECDEF_H_
+#define _PVDECDEF_H_
+
+#include "mp4dec_api.h"
+
+typedef enum
+{
+    PV_SUCCESS,
+    PV_FAIL,
+    PV_MB_STUFFING,         /* hit Macroblock_Stuffing */
+    PV_END_OF_VOP,          /* hit End_of_Video_Object_Plane */
+    PV_END_OF_MB            /* hit End_of_Macroblock */
+#ifdef PV_TOLERATE_VOL_ERRORS
+    , PV_BAD_VOLHEADER
+#endif
+} PV_STATUS;
+
+typedef uint8 PIXEL;
+typedef int16 MOT;   /*  : "int" type runs faster on RISC machine */
+
+#define TRUE    1
+#define FALSE   0
+
+#define PV_ABS(x)       (((x)<0)? -(x) : (x))
+#define PV_SIGN(x)      (((x)<0)? -1 : 1)
+#define PV_SIGN0(a)     (((a)<0)? -1 : (((a)>0) ? 1 : 0))
+#define PV_MAX(a,b)     ((a)>(b)? (a):(b))
+#define PV_MIN(a,b)     ((a)<(b)? (a):(b))
+#define PV_MEDIAN(A,B,C) ((A) > (B) ? ((A) < (C) ? (A) : (B) > (C) ? (B) : (C)): (B) < (C) ? (B) : (C) > (A) ? (C) : (A))
+/* You don't want to use ((x>UB)?UB:(x<LB)?LB:x) for the clipping */
+/*    because it will use one extra comparison if the compiler is */
+/*    not well-optimized.    04/19/2000.                        */
+#define CLIP_THE_RANGE(x,LB,UB) if (x<LB) x = LB; else if (x>UB) x = UB
+
+#define MODE_INTRA      0x08 //01000
+#define MODE_INTRA_Q    0x09 //01001
+#define MODE_SKIPPED    0x10 //10000
+#define MODE_INTER4V    0x14 //10100
+#define MODE_INTER      0x16 //10110
+#define MODE_INTER_Q    0x17 //10111
+#define MODE_INTER4V_Q  0x15 //10101
+#define INTER_1VMASK    0x2
+#define Q_MASK          0x1
+#define INTRA_MASK      0x8
+#define INTER_MASK      0x4
+
+
+#define I_VOP       0
+#define P_VOP       1
+#define B_VOP       2
+
+#define LUMINANCE_DC_TYPE   1
+#define CHROMINANCE_DC_TYPE 2
+
+#define START_CODE_LENGTH       32
+
+/* 11/30/98 */
+#define NoMarkerFound -1
+#define FoundRM     1   /* Resync Marker */
+#define FoundVSC    2   /* VOP_START_CODE. */
+#define FoundGSC    3   /* GROUP_START_CODE */
+#define FoundEOB    4   /* EOB_CODE */
+
+/* PacketVideo "absolution timestamp" object.   06/13/2000 */
+#define PVTS_START_CODE         0x01C4
+#define PVTS_START_CODE_LENGTH  32
+
+/* session layer and vop layer start codes */
+
+#define VISUAL_OBJECT_SEQUENCE_START_CODE   0x01B0
+#define VISUAL_OBJECT_SEQUENCE_END_CODE     0x01B1
+
+#define VISUAL_OBJECT_START_CODE   0x01B5
+#define VO_START_CODE           0x8
+#define VO_HEADER_LENGTH        32      /* lengtho of VO header: VO_START_CODE +  VO_ID */
+
+#define SOL_START_CODE          0x01BE
+#define SOL_START_CODE_LENGTH   32
+
+#define VOL_START_CODE 0x12
+#define VOL_START_CODE_LENGTH 28
+
+#define VOP_START_CODE 0x1B6
+#define VOP_START_CODE_LENGTH   32
+
+#define GROUP_START_CODE    0x01B3
+#define GROUP_START_CODE_LENGTH  32
+
+#define VOP_ID_CODE_LENGTH      5
+#define VOP_TEMP_REF_CODE_LENGTH    16
+
+#define USER_DATA_START_CODE        0x01B2
+#define USER_DATA_START_CODE_LENGTH 32
+
+#define START_CODE_PREFIX       0x01
+#define START_CODE_PREFIX_LENGTH    24
+
+#define SHORT_VIDEO_START_MARKER         0x20
+#define SHORT_VIDEO_START_MARKER_LENGTH  22
+#define SHORT_VIDEO_END_MARKER            0x3F
+#define GOB_RESYNC_MARKER         0x01
+#define GOB_RESYNC_MARKER_LENGTH  17
+
+/* motion and resync markers used in error resilient mode  */
+
+#define DC_MARKER                      438273
+#define DC_MARKER_LENGTH                19
+
+#define MOTION_MARKER_COMB             126977
+#define MOTION_MARKER_COMB_LENGTH       17
+
+#define MOTION_MARKER_SEP              81921
+#define MOTION_MARKER_SEP_LENGTH        17
+
+#define RESYNC_MARKER           1
+#define RESYNC_MARKER_LENGTH    17
+
+#define SPRITE_NOT_USED     0
+#define STATIC_SPRITE       1
+#define ONLINE_SPRITE       2
+#define GMC_SPRITE      3
+
+/* macroblock and block size */
+#define MB_SIZE 16
+#define NCOEFF_MB (MB_SIZE*MB_SIZE)
+#define B_SIZE 8
+#define NCOEFF_BLOCK (B_SIZE*B_SIZE)
+#define NCOEFF_Y NCOEFF_MB
+#define NCOEFF_U NCOEFF_BLOCK
+#define NCOEFF_V NCOEFF_BLOCK
+#define BLK_PER_MB      4   /* Number of blocks per MB */
+
+/* VLC decoding related definitions */
+#define VLC_ERROR   (-1)
+#define VLC_ESCAPE  7167
+
+
+/* macro utility */
+#define  ZERO_OUT_64BYTES(x)    { *((uint32*)x) = *(((uint32*)(x))+1) =  \
+        *(((uint32*)(x))+2) = *(((uint32*)(x))+3) =  \
+        *(((uint32*)(x))+4) = *(((uint32*)(x))+5) =  \
+        *(((uint32*)(x))+6) = *(((uint32*)(x))+7) =  \
+        *(((uint32*)(x))+8) = *(((uint32*)(x))+9) =  \
+        *(((uint32*)(x))+10) = *(((uint32*)(x))+11) =  \
+        *(((uint32*)(x))+12) = *(((uint32*)(x))+13) =  \
+        *(((uint32*)(x))+14) = *(((uint32*)(x))+15) =  0; }
+
+
+
+#endif /* _PVDECDEF_H_ */
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/mp4lib_int.h b/media/libstagefright/codecs/m4v_h263/dec/src/mp4lib_int.h
new file mode 100644
index 0000000..d6754a7
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/mp4lib_int.h
@@ -0,0 +1,296 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef _MP4LIB_INT_H_
+#define _MP4LIB_INT_H_
+
+#include "mp4def.h"
+#include "mp4dec_api.h" // extra structure
+
+#undef ENABLE_LOG
+#define BITRATE_AVERAGE_WINDOW 4
+#define FRAMERATE_SCALE ((BITRATE_AVERAGE_WINDOW-1)*10000L)
+#define FAST_IDCT            /* , for fast Variable complexity IDCT */
+//#define PV_DEC_EXTERNAL_IDCT  /*  for separate IDCT (i.e. no direct access to output frame) */
+#define PV_ANNEX_IJKT_SUPPORT
+#define mid_gray 1024
+
+typedef struct tagBitstream
+{
+    /* function that reteive data from outside the library.   04/11/2000 */
+    /*    In frame-based decoding mode, this shall be NULL.   08/29/2000 */
+    uint32 curr_word;
+    uint32 next_word;
+    uint8 *bitstreamBuffer; /* pointer to buffer memory */
+    int32  read_point;          /* starting point in the buffer to be read to cache */
+    int  incnt;             /* bit left in cached */
+    int  incnt_next;
+    uint32 bitcnt;          /* total bit read so-far (from inbfr)*/
+    int32  data_end_pos;        /*should be added ,  06/07/2000 */
+    int searched_frame_boundary;
+} BitstreamDecVideo, *LPBitstreamDecVideo;
+
+/* complexity estimation parameters */
+typedef struct tagComplexity_Est
+{
+    uint8   text_1;             /* texture_complexity_estimation_set_1  */
+    uint8   text_2;             /* texture_complexity_estimation_set_2  */
+    uint8   mc;                 /* motion_compensation_complexity       */
+} Complexity_Est;
+
+
+typedef struct tagVop
+{
+    PIXEL   *yChan;             /* The Y component */
+    PIXEL   *uChan;             /* The U component */
+    PIXEL   *vChan;             /* The V component */
+
+    uint32  timeStamp;          /* Vop TimeStamp in msec */
+
+    /* Actual syntax elements for VOP (standard) */
+    int     predictionType;     /* VOP prediction type */
+    uint    timeInc;            /* VOP time increment (relative to last mtb) */
+    int     vopCoded;
+    int     roundingType;
+    int     intraDCVlcThr;
+    int16       quantizer;          /* VOP quantizer */
+    int     fcodeForward;       /* VOP dynamic range of motion vectors */
+    int     fcodeBackward;      /* VOP dynamic range of motion vectors */
+    int     refSelectCode;      /* enhancement layer reference select code */
+
+    /* H.263 parameters */
+    int     gobNumber;
+    int     gobFrameID;
+    int     temporalRef;        /* temporal reference, roll over at 256 */
+    int     ETR;
+} Vop;
+
+typedef struct tagVol
+{
+    int     volID;                  /* VOL identifier (for tracking) */
+    uint    timeIncrementResolution;/* VOL time increment */
+    int     nbitsTimeIncRes;        /* number of bits for time increment  */
+    uint        timeInc_offset;         /* timeInc offset for multiple VOP in a packet  */
+    uint32  moduloTimeBase;         /* internal decoder clock */
+    int     fixedVopRate;
+    BitstreamDecVideo   *bitstream; /* library bitstream buffer (input buffer) */
+
+    int     complexity_estDisable;  /* VOL disable complexity estimation */
+    int     complexity_estMethod;   /* VOL complexity estimation method */
+    Complexity_Est complexity;      /* complexity estimation flags      */
+
+    /* Error Resilience Flags */
+    int     errorResDisable;        /* VOL disable error resilence mode */
+    /*            (Use Resynch markers) */
+    int     useReverseVLC;          /* VOL reversible VLCs */
+    int     dataPartitioning;       /* VOL data partitioning */
+
+    /* Bit depth  */
+    uint    bitsPerPixel;
+//  int     mid_gray;               /* 2^(bits_per_pixel+2) */
+
+    /* Quantization related parameters */
+    int     quantPrecision;         /* Quantizer precision */
+    uint    quantType;              /* MPEG-4 or H.263 Quantization Type */
+    /* Added loaded quant mat,  05/22/2000 */
+    int     loadIntraQuantMat;      /* Load intra quantization matrix */
+    int     loadNonIntraQuantMat;   /* Load nonintra quantization matrix */
+    int     iqmat[64];              /* Intra quant.matrix */
+    int     niqmat[64];             /* Non-intra quant.matrix */
+
+    /* Parameters used for scalability */
+    int     scalability;            /* VOL scalability (flag) */
+    int     scalType;               /* temporal = 0, spatial = 1, both = 2 */
+
+    int     refVolID;               /* VOL id of reference VOL */
+    int     refSampDir;             /* VOL resol. of ref. VOL */
+    int     horSamp_n;              /* VOL hor. resampling of ref. VOL given by */
+    int     horSamp_m;              /*     sampfac = hor_samp_n/hor_samp_m      */
+    int     verSamp_n;              /* VOL ver. resampling of ref. VOL given by */
+    int     verSamp_m;              /*     sampfac = ver_samp_n/ver_samp_m      */
+    int     enhancementType;        /* VOL type of enhancement layer */
+    /* profile and level */
+    int32   profile_level_id;       /* 8-bit profile and level */ //  6/17/04
+
+} Vol;
+
+
+typedef int16 typeMBStore[6][NCOEFF_BLOCK];
+
+typedef struct tagMacroBlock
+{
+    typeMBStore         block;              /* blocks */         /*  ACDC */
+    uint8   pred_block[384];        /* prediction block,  Aug 3,2005 */
+    uint8   bitmapcol[6][8];
+    uint8   bitmaprow[6];
+    int     no_coeff[6];
+    int     DCScalarLum;                        /* Luminance DC Scalar */
+    int     DCScalarChr;                        /* Chrominance DC Scalar */
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    int direction;
+#endif
+} MacroBlock;
+
+typedef struct tagHeaderInfoDecVideo
+{
+    uint8       *Mode;              /* Modes INTRA/INTER/etc. */
+    uint8       *CBP;               /* MCBPC/CBPY stuff */
+} HeaderInfoDecVideo;
+
+
+/************************************************************/
+/*                  VLC structures                          */
+/************************************************************/
+typedef struct tagTcoef
+{
+    uint last;
+    uint run;
+    int level;
+    uint sign;
+} Tcoef, *LPTcoef;
+
+
+
+typedef struct tagVLCtab
+{
+    int32 val;
+    int32 len;
+} VLCtab, *LPVLCtab;
+
+typedef struct tagVLCshorttab
+{
+    int16 val;
+    int16 len;
+} VLCshorttab, *LPVLCshorttab ; /* for space saving, Antoine Nguyen*/
+
+typedef struct tagVLCtab2
+{
+    uint8 run;
+    uint8 level;
+    uint8 last;
+    uint8 len;
+} VLCtab2, *LPVLCtab2;  /* 10/24/2000 */
+
+/* This type is designed for fast access of DC/AC */
+/*    prediction data.  If the compiler is smart  */
+/*    enough, it will use shifting for indexing.  */
+/*     04/14/2000.                              */
+
+typedef int16 typeDCStore[6];   /*  ACDC */
+typedef int16 typeDCACStore[4][8];
+
+
+
+/* Global structure that can be passed around */
+typedef struct tagVideoDecData
+{
+    BitstreamDecVideo   *bitstream; /* library bitstream buffer (input buffer) */
+    /* Data For Layers (Scalability) */
+    Vol             **vol;                  /* Data stored for each VOL */
+
+    /* Data used for reconstructing frames */
+    Vop             *currVop;               /* Current VOP (frame)  */
+    Vop             *prevVop;               /* Previous VOP (frame) */
+    /* Data used to facilitate multiple layer decoding.   05/04/2000 */
+    Vop             *prevEnhcVop;           /* New change to rid of memcpy().  04/24/2001 */
+    Vop             **vopHeader;            /* one for each layer.   08/29/2000 */
+
+    /* I/O structures */
+    MacroBlock      *mblock;                    /* Macroblock data structure */
+    uint8           *acPredFlag;                /*  */
+
+    /* scratch memory used in data partitioned mode */
+    typeDCStore     *predDC;        /*  The DC coeffs for each MB */
+    typeDCACStore   *predDCAC_row;
+    typeDCACStore   *predDCAC_col;
+
+    int             usePrevQP;              /* running QP decision switch */
+    uint8           *sliceNo;               /* Slice indicator for each MB  */
+    /*     changed this to a 1D   */
+    /*    array for optimization    */
+    MOT             *motX;                  /* Motion vector in X direction */
+    MOT             *motY;                  /* Motion vector in Y direction */
+    HeaderInfoDecVideo  headerInfo;         /* MB Header information */
+    int16           *QPMB;                  /* Quantizer value for each MB */
+
+    uint8           *pstprcTypCur;          /* Postprocessing type for current frame */
+    uint8           *pstprcTypPrv;          /* Postprocessing type for previous frame */
+    /* scratch memory used in all modes */
+    int             mbnum;                      /*  Macroblock number */
+    uint            mbnum_row;
+    int             mbnum_col;
+    /* I added these variables since they are used a lot.   04/13/2000 */
+    int     nMBPerRow, nMBPerCol;   /* number of MBs in each row & column    */
+    int     nTotalMB;
+    /* for short video header */
+    int     nMBinGOB;               /* number of MBs in GOB,  05/22/00 */
+    int     nGOBinVop;              /* number of GOB in Vop   05/22/00 */
+    /* VOL Dimensions */
+    int     width;                  /* Width */
+    int     height;                 /* Height */
+    int     displayWidth;               /* Handle image whose size is not a multiple of 16. */
+    int     displayHeight;              /*   This is the actual size.   08/09/2000        */
+    int32   size;
+    /* Miscellaneous data points to be passed */
+    int             frame_idx;              /* Current frame ID */
+    int             frameRate;              /* Output frame Rate (over 10 seconds) */
+    int32           duration;
+    uint32          currTimestamp;
+    int             currLayer;              /* Current frame layer  */
+    int     shortVideoHeader;       /* shortVideoHeader mode */
+    int     intra_acdcPredDisable;  /* VOL disable INTRA DC prediction */
+    int             numberOfLayers;         /* Number of Layers */
+    /* Frame to be used for concealment     07/07/2001 */
+    uint8           *concealFrame;
+    int             vop_coding_type;
+    /* framerate and bitrate statistics counters.   08/23/2000 */
+    int32           nBitsPerVop[BITRATE_AVERAGE_WINDOW];
+    uint32          prevTimestamp[BITRATE_AVERAGE_WINDOW];
+    int     nBitsForMBID;           /* how many bits required for MB number? */
+    /* total data memory used by the docder library.   08/23/2000 */
+    int32           memoryUsage;
+
+    /* flag to turn on/off error concealment or soft decoding */
+    int errorConcealment;
+
+    /* Application controls */
+    VideoDecControls    *videoDecControls;
+    int                 postFilterType;     /* Postfilter mode  04/25/00 */
+
+
+
+    PV_STATUS(*vlcDecCoeffIntra)(BitstreamDecVideo *stream, Tcoef *pTcoef/*, int intra_luma*/);
+    PV_STATUS(*vlcDecCoeffInter)(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    int                 initialized;
+
+    /* Annex IJKT */
+    int     deblocking;
+    int     slice_structure;
+    int     modified_quant;
+    int     advanced_INTRA;
+    int16 QP_CHR;  /* ANNEX_T */
+} VideoDecData;
+
+/* for fast VLC+Dequant  10/12/2000*/
+typedef int (*VlcDequantBlockFuncP)(void *video, int comp, int switched,
+                                    uint8 *bitmaprow, uint8 *bitmapcol);
+
+//////////////////////////////////////////////////////////////
+//                  Decoder structures                      //
+//////////////////////////////////////////////////////////////
+#endif /* _MP4LIB_INT_H_ */
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/packet_util.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/packet_util.cpp
new file mode 100644
index 0000000..48414d7
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/packet_util.cpp
@@ -0,0 +1,252 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+
+
+/***********************************************************CommentBegin******
+*       04/13/2000 : initial modification to the new PV-Decoder
+*                            Lib format.
+*       04/16/2001 : Removed PV_END_OF_BUFFER case, error resilience
+***********************************************************CommentEnd********/
+PV_STATUS PV_ReadVideoPacketHeader(VideoDecData *video, int *next_MB)
+{
+    PV_STATUS status;
+    Vol *currVol = video->vol[video->currLayer];
+    Vop *currVop = video->currVop;
+    BitstreamDecVideo *stream = video->bitstream;
+    int fcode_forward;
+    int resync_marker_length;
+    int nbits = video->nBitsForMBID;
+    uint32 tmpvar32;
+    uint tmpvar16;
+    int16 quantizer;
+    int nTotalMB = video->nTotalMB;
+
+    fcode_forward = currVop->fcodeForward;
+    resync_marker_length = 17;
+
+    if (currVop->predictionType != I_VOP) resync_marker_length = 16 + fcode_forward;
+
+    status = PV_BitstreamShowBitsByteAlign(stream, resync_marker_length, &tmpvar32);
+    /*  if (status != PV_SUCCESS && status != PV_END_OF_BUFFER) return status; */
+    if (tmpvar32 == RESYNC_MARKER)
+    {
+//      DecNextStartCode(stream);
+        PV_BitstreamByteAlign(stream);
+        BitstreamReadBits32(stream, resync_marker_length);
+
+        *next_MB = (int) BitstreamReadBits16(stream, nbits);
+//      if (*next_MB <= video->mbnum)   /*  needs more investigation */
+//          *next_MB = video->mbnum+1;
+
+        if (*next_MB >= nTotalMB)  /* fix  04/05/01 */
+        {
+            *next_MB = video->mbnum + 1;
+            if (*next_MB >= nTotalMB)    /* this check is needed  */
+                *next_MB = nTotalMB - 1;
+        }
+        quantizer = (int16) BitstreamReadBits16(stream, currVol->quantPrecision);
+        if (quantizer == 0) return PV_FAIL;        /*  04/03/01 */
+
+        currVop->quantizer = quantizer;
+
+        /* if we have HEC, read some redundant VOP header information */
+        /* this part needs improvement  04/05/01 */
+        if (BitstreamRead1Bits(stream))
+        {
+            int time_base = -1;
+
+            /* modulo_time_base (? bits) */
+            do
+            {
+                time_base++;
+                tmpvar16 = BitstreamRead1Bits(stream);
+            }
+            while (tmpvar16 == 1);
+
+            /* marker bit */
+            BitstreamRead1Bits(stream);
+
+            /* vop_time_increment (1-15 bits) */
+            BitstreamReadBits16(stream, currVol->nbitsTimeIncRes);
+
+            /* marker bit */
+            BitstreamRead1Bits(stream);
+
+            /* vop_prediction_type (2 bits) */
+            BitstreamReadBits16(stream, 2);
+
+            /* Added intra_dc_vlc_thr reading  */
+            BitstreamReadBits16(stream, 3);
+
+            /* fcodes */
+            if (currVop->predictionType != I_VOP)
+            {
+                fcode_forward = (int) BitstreamReadBits16(stream, 3);
+
+                if (currVop->predictionType == B_VOP)
+                {
+                    BitstreamReadBits16(stream, 3);
+                }
+            }
+
+        }
+    }
+    else
+    {
+        PV_BitstreamByteAlign(stream);  /*  */
+        status = BitstreamCheckEndBuffer(stream);   /* return end_of_VOP  03/30/01 */
+        if (status != PV_SUCCESS)
+        {
+            return status;
+        }
+        status = BitstreamShowBits32HC(stream, &tmpvar32);   /*  07/07/01 */
+        /* -16 = 0xFFFFFFF0*/
+        if ((tmpvar32 & 0xFFFFFFF0) == VISUAL_OBJECT_SEQUENCE_START_CODE) /* start code mask 00 00 01 */
+
+        {
+            /* we don't have to check for legl stuffing here.   05/08/2000 */
+            return PV_END_OF_VOP;
+        }
+        else
+        {
+            return PV_FAIL;
+        }
+    }
+
+    return PV_SUCCESS;
+}
+
+
+
+/***********************************************************CommentBegin******
+*       3/10/00  : initial modification to the
+*                new PV-Decoder Lib format.
+*       04/17/01 : remove PV_END_OF_BUFFER, error checking
+***********************************************************CommentEnd********/
+PV_STATUS PV_GobHeader(VideoDecData *video)
+{
+    uint32 tmpvar;
+    Vop *currVop = video->currVop;
+    BitstreamDecVideo *stream = video->bitstream;
+    int quantPrecision = 5;
+    int16 quantizer;
+
+    BitstreamShowBits32(stream, GOB_RESYNC_MARKER_LENGTH, &tmpvar);
+
+    if (tmpvar != GOB_RESYNC_MARKER)
+    {
+        PV_BitstreamShowBitsByteAlign(stream, GOB_RESYNC_MARKER_LENGTH, &tmpvar);
+
+        if (tmpvar != GOB_RESYNC_MARKER)
+        {
+            return PV_FAIL;
+        }
+        else
+            PV_BitstreamByteAlign(stream);  /* if bytealigned GOBHEADER search is performed */
+        /* then no more noforcestuffing  */
+    }
+
+    /* we've got a GOB header info here */
+    BitstreamShowBits32(stream, GOB_RESYNC_MARKER_LENGTH + 5, &tmpvar);
+    tmpvar &= 0x1F;
+
+    if (tmpvar == 0)
+    {
+        return PV_END_OF_VOP;
+    }
+
+    if (tmpvar == 31)
+    {
+        PV_BitstreamFlushBits(stream, GOB_RESYNC_MARKER_LENGTH + 5);
+        BitstreamByteAlignNoForceStuffing(stream);
+        return PV_END_OF_VOP;
+    }
+
+    PV_BitstreamFlushBits(stream, GOB_RESYNC_MARKER_LENGTH + 5);
+    currVop->gobNumber = (int) tmpvar;
+    if (currVop->gobNumber >= video->nGOBinVop) return PV_FAIL;
+    currVop->gobFrameID = (int) BitstreamReadBits16(stream, 2);
+    quantizer = (int16) BitstreamReadBits16(stream, quantPrecision);
+    if (quantizer == 0)   return PV_FAIL;         /*  04/03/01 */
+
+    currVop->quantizer = quantizer;
+    return PV_SUCCESS;
+}
+#ifdef PV_ANNEX_IJKT_SUPPORT
+PV_STATUS PV_H263SliceHeader(VideoDecData *video, int *next_MB)
+{
+    PV_STATUS status;
+    uint32 tmpvar;
+    Vop *currVop = video->currVop;
+    BitstreamDecVideo *stream = video->bitstream;
+    int nTotalMB = video->nTotalMB;
+    int16 quantizer;
+
+    PV_BitstreamShowBitsByteAlignNoForceStuffing(stream, 17, &tmpvar);
+    if (tmpvar == RESYNC_MARKER)
+    {
+        BitstreamByteAlignNoForceStuffing(stream);
+        PV_BitstreamFlushBits(stream, 17);
+        if (!BitstreamRead1Bits(stream))
+        {
+            return PV_FAIL;
+        }
+        *next_MB = BitstreamReadBits16(stream, video->nBitsForMBID);
+        if (*next_MB >= nTotalMB)  /* fix  04/05/01 */
+        {
+            *next_MB = video->mbnum + 1;
+            if (*next_MB >= nTotalMB)    /* this check is needed  */
+                *next_MB = nTotalMB - 1;
+        }
+        /* we will not parse sebp2 for large pictures 3GPP */
+        quantizer = (int16) BitstreamReadBits16(stream, 5);
+        if (quantizer == 0) return PV_FAIL;
+
+        currVop->quantizer = quantizer;
+        if (!BitstreamRead1Bits(stream))
+        {
+            return PV_FAIL;
+        }
+        currVop->gobFrameID = (int) BitstreamReadBits16(stream, 2);
+    }
+    else
+    {
+        status = BitstreamCheckEndBuffer(stream);   /* return end_of_VOP  03/30/01 */
+        if (status != PV_SUCCESS)
+        {
+            return status;
+        }
+        PV_BitstreamShowBitsByteAlign(stream, SHORT_VIDEO_START_MARKER_LENGTH, &tmpvar);
+
+        if (tmpvar == SHORT_VIDEO_START_MARKER)
+        {
+            /* we don't have to check for legal stuffing here.   05/08/2000 */
+            return PV_END_OF_VOP;
+        }
+        else
+        {
+            return PV_FAIL;
+        }
+    }
+    return PV_SUCCESS;
+}
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp
new file mode 100644
index 0000000..b36050c
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/post_filter.cpp
@@ -0,0 +1,585 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#include    "mp4dec_lib.h"
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+#include    "motion_comp.h"
+#include "mbtype_mode.h"
+const static int STRENGTH_tab[] = {0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12};
+#endif
+
+#ifdef PV_POSTPROC_ON
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void PostFilter(
+    VideoDecData *video,
+    int filter_type,
+    uint8 *output)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    uint8 *pp_mod;
+    int16 *QP_store;
+    int combined_with_deblock_filter;
+    int nTotalMB = video->nTotalMB;
+    int width, height;
+    int32 size;
+    int softDeblocking;
+    uint8 *decodedFrame = video->videoDecControls->outputFrame;
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    width = video->width;
+    height = video->height;
+    size = (int32)width * height;
+
+    oscl_memcpy(output, decodedFrame, size);
+    oscl_memcpy(output + size, decodedFrame + size, (size >> 2));
+    oscl_memcpy(output + size + (size >> 2), decodedFrame + size + (size >> 2), (size >> 2));
+
+    if (filter_type == 0)
+        return;
+
+    /* The softDecoding cutoff corresponds to ~93000 bps for QCIF 15fps clip  */
+    if (PVGetDecBitrate(video->videoDecControls) > (100*video->frameRate*(size >> 12)))  // MC_sofDeblock
+        softDeblocking = FALSE;
+    else
+        softDeblocking = TRUE;
+
+    combined_with_deblock_filter = filter_type & PV_DEBLOCK;
+    QP_store = video->QPMB;
+
+    /* Luma */
+    pp_mod = video->pstprcTypCur;
+
+    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
+    {
+        CombinedHorzVertRingFilter(output, width, height, QP_store, 0, pp_mod);
+    }
+    else
+    {
+        if (filter_type & PV_DEBLOCK)
+        {
+            if (softDeblocking)
+            {
+                CombinedHorzVertFilter(output, width, height,
+                                       QP_store, 0, pp_mod);
+            }
+            else
+            {
+                CombinedHorzVertFilter_NoSoftDeblocking(output, width, height,
+                                                        QP_store, 0, pp_mod);
+            }
+        }
+        if (filter_type & PV_DERING)
+        {
+            Deringing_Luma(output, width, height, QP_store,
+                           combined_with_deblock_filter, pp_mod);
+
+        }
+    }
+
+    /* Chroma */
+
+    pp_mod += (nTotalMB << 2);
+    output += size;
+
+    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
+    {
+        CombinedHorzVertRingFilter(output, (int)(width >> 1), (int)(height >> 1), QP_store, (int) 1, pp_mod);
+    }
+    else
+    {
+        if (filter_type & PV_DEBLOCK)
+        {
+            if (softDeblocking)
+            {
+                CombinedHorzVertFilter(output, (int)(width >> 1),
+                                       (int)(height >> 1), QP_store, (int) 1, pp_mod);
+            }
+            else
+            {
+                CombinedHorzVertFilter_NoSoftDeblocking(output, (int)(width >> 1),
+                                                        (int)(height >> 1), QP_store, (int) 1, pp_mod);
+            }
+        }
+        if (filter_type & PV_DERING)
+        {
+            Deringing_Chroma(output, (int)(width >> 1),
+                             (int)(height >> 1), QP_store,
+                             combined_with_deblock_filter, pp_mod);
+        }
+    }
+
+    pp_mod += nTotalMB;
+    output += (size >> 2);
+
+    if ((filter_type & PV_DEBLOCK) && (filter_type & PV_DERING))
+    {
+        CombinedHorzVertRingFilter(output, (int)(width >> 1), (int)(height >> 1), QP_store, (int) 1, pp_mod);
+    }
+    else
+    {
+        if (filter_type & PV_DEBLOCK)
+        {
+            if (softDeblocking)
+            {
+                CombinedHorzVertFilter(output, (int)(width >> 1),
+                                       (int)(height >> 1), QP_store, (int) 1, pp_mod);
+            }
+            else
+            {
+                CombinedHorzVertFilter_NoSoftDeblocking(output, (int)(width >> 1),
+                                                        (int)(height >> 1), QP_store, (int) 1, pp_mod);
+            }
+        }
+        if (filter_type & PV_DERING)
+        {
+            Deringing_Chroma(output, (int)(width >> 1),
+                             (int)(height >> 1), QP_store,
+                             combined_with_deblock_filter, pp_mod);
+        }
+    }
+
+    /*  swap current pp_mod to prev_frame pp_mod */
+    pp_mod = video->pstprcTypCur;
+    video->pstprcTypCur = video->pstprcTypPrv;
+    video->pstprcTypPrv = pp_mod;
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+#endif
+
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+void H263_Deblock(uint8 *rec,
+                  int width,
+                  int height,
+                  int16 *QP_store,
+                  uint8 *mode,
+                  int chr, int annex_T)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int i, j, k;
+    uint8 *rec_y;
+    int tmpvar;
+    int mbnum, strength, A_D, d1_2, d1, d2, A, B, C, D, b_size;
+    int d, offset, nMBPerRow, nMBPerCol, width2 = (width << 1);
+    /* MAKE SURE I-VOP INTRA MACROBLOCKS ARE SET TO NON-SKIPPED MODE*/
+    mbnum = 0;
+
+    if (chr)
+    {
+        nMBPerRow = width >> 3;
+        nMBPerCol = height >> 3;
+        b_size = 8;
+    }
+    else
+    {
+        nMBPerRow = width >> 4;
+        nMBPerCol = height >> 4;
+        b_size = 16;
+    }
+
+
+    /********************************* VERTICAL FILTERING ****************************/
+    /* vertical filtering of mid sections no need to check neighboring QP's etc */
+    if (!chr)
+    {
+        rec_y = rec + (width << 3);
+        for (i = 0; i < (height >> 4); i++)
+        {
+            for (j = 0; j < (width >> 4); j++)
+            {
+                if (mode[mbnum] != MODE_SKIPPED)
+                {
+                    k = 16;
+                    strength = STRENGTH_tab[QP_store[mbnum]];
+                    while (k--)
+                    {
+                        A =  *(rec_y - width2);
+                        D = *(rec_y + width);
+                        A_D = A - D;
+                        C = *rec_y;
+                        B = *(rec_y - width);
+                        d = (((C - B) << 2) + A_D);
+
+                        if (d < 0)
+                        {
+                            d1 = -(-d >> 3);
+                            if (d1 < -(strength << 1))
+                            {
+                                d1 = 0;
+                            }
+                            else if (d1 < -strength)
+                            {
+                                d1 = -d1 - (strength << 1);
+                            }
+                            d1_2 = -d1 >> 1;
+                        }
+                        else
+                        {
+                            d1 = d >> 3;
+                            if (d1 > (strength << 1))
+                            {
+                                d1 = 0;
+                            }
+                            else if (d1 > strength)
+                            {
+                                d1 = (strength << 1) - d1;
+                            }
+                            d1_2 = d1 >> 1;
+                        }
+
+                        if (A_D < 0)
+                        {
+                            d2 = -(-A_D >> 2);
+                            if (d2 < -d1_2)
+                            {
+                                d2 = -d1_2;
+                            }
+                        }
+                        else
+                        {
+                            d2 = A_D >> 2;
+                            if (d2 > d1_2)
+                            {
+                                d2 = d1_2;
+                            }
+                        }
+
+                        *(rec_y - width2) = A - d2;
+                        tmpvar = B + d1;
+                        CLIP_RESULT(tmpvar)
+                        *(rec_y - width) = tmpvar;
+                        tmpvar = C - d1;
+                        CLIP_RESULT(tmpvar)
+                        *rec_y = tmpvar;
+                        *(rec_y + width) = D + d2;
+                        rec_y++;
+                    }
+                }
+                else
+                {
+                    rec_y += b_size;
+                }
+                mbnum++;
+            }
+            rec_y += (15 * width);
+
+        }
+    }
+
+    /* VERTICAL boundary blocks */
+
+
+    rec_y = rec + width * b_size;
+
+    mbnum = nMBPerRow;
+    for (i = 0; i < nMBPerCol - 1; i++)
+    {
+        for (j = 0; j < nMBPerRow; j++)
+        {
+            if (mode[mbnum] != MODE_SKIPPED || mode[mbnum - nMBPerRow] != MODE_SKIPPED)
+            {
+                k = b_size;
+                if (mode[mbnum] != MODE_SKIPPED)
+                {
+                    strength = STRENGTH_tab[(annex_T ?  MQ_chroma_QP_table[QP_store[mbnum]] : QP_store[mbnum])];
+                }
+                else
+                {
+                    strength = STRENGTH_tab[(annex_T ?  MQ_chroma_QP_table[QP_store[mbnum - nMBPerRow]] : QP_store[mbnum - nMBPerRow])];
+                }
+
+                while (k--)
+                {
+                    A =  *(rec_y - width2);
+                    D =  *(rec_y + width);
+                    A_D = A - D;
+                    C = *rec_y;
+                    B = *(rec_y - width);
+                    d = (((C - B) << 2) + A_D);
+
+                    if (d < 0)
+                    {
+                        d1 = -(-d >> 3);
+                        if (d1 < -(strength << 1))
+                        {
+                            d1 = 0;
+                        }
+                        else if (d1 < -strength)
+                        {
+                            d1 = -d1 - (strength << 1);
+                        }
+                        d1_2 = -d1 >> 1;
+                    }
+                    else
+                    {
+                        d1 = d >> 3;
+                        if (d1 > (strength << 1))
+                        {
+                            d1 = 0;
+                        }
+                        else if (d1 > strength)
+                        {
+                            d1 = (strength << 1) - d1;
+                        }
+                        d1_2 = d1 >> 1;
+                    }
+
+                    if (A_D < 0)
+                    {
+                        d2 = -(-A_D >> 2);
+                        if (d2 < -d1_2)
+                        {
+                            d2 = -d1_2;
+                        }
+                    }
+                    else
+                    {
+                        d2 = A_D >> 2;
+                        if (d2 > d1_2)
+                        {
+                            d2 = d1_2;
+                        }
+                    }
+
+                    *(rec_y - width2) = A - d2;
+                    tmpvar = B + d1;
+                    CLIP_RESULT(tmpvar)
+                    *(rec_y - width) = tmpvar;
+                    tmpvar = C - d1;
+                    CLIP_RESULT(tmpvar)
+                    *rec_y = tmpvar;
+                    *(rec_y + width) = D + d2;
+                    rec_y++;
+                }
+            }
+            else
+            {
+                rec_y += b_size;
+            }
+            mbnum++;
+        }
+        rec_y += ((b_size - 1) * width);
+
+    }
+
+
+    /***************************HORIZONTAL FILTERING ********************************************/
+    mbnum = 0;
+    /* HORIZONTAL INNER */
+    if (!chr)
+    {
+        rec_y = rec + 8;
+        offset = width * b_size - b_size;
+
+        for (i = 0; i < nMBPerCol; i++)
+        {
+            for (j = 0; j < nMBPerRow; j++)
+            {
+                if (mode[mbnum] != MODE_SKIPPED)
+                {
+                    k = 16;
+                    strength = STRENGTH_tab[QP_store[mbnum]];
+                    while (k--)
+                    {
+                        A =  *(rec_y - 2);
+                        D =  *(rec_y + 1);
+                        A_D = A - D;
+                        C = *rec_y;
+                        B = *(rec_y - 1);
+                        d = (((C - B) << 2) + A_D);
+
+                        if (d < 0)
+                        {
+                            d1 = -(-d >> 3);
+                            if (d1 < -(strength << 1))
+                            {
+                                d1 = 0;
+                            }
+                            else if (d1 < -strength)
+                            {
+                                d1 = -d1 - (strength << 1);
+                            }
+                            d1_2 = -d1 >> 1;
+                        }
+                        else
+                        {
+                            d1 = d >> 3;
+                            if (d1 > (strength << 1))
+                            {
+                                d1 = 0;
+                            }
+                            else if (d1 > strength)
+                            {
+                                d1 = (strength << 1) - d1;
+                            }
+                            d1_2 = d1 >> 1;
+                        }
+
+                        if (A_D < 0)
+                        {
+                            d2 = -(-A_D >> 2);
+                            if (d2 < -d1_2)
+                            {
+                                d2 = -d1_2;
+                            }
+                        }
+                        else
+                        {
+                            d2 = A_D >> 2;
+                            if (d2 > d1_2)
+                            {
+                                d2 = d1_2;
+                            }
+                        }
+
+                        *(rec_y - 2) = A - d2;
+                        tmpvar = B + d1;
+                        CLIP_RESULT(tmpvar)
+                        *(rec_y - 1) = tmpvar;
+                        tmpvar = C - d1;
+                        CLIP_RESULT(tmpvar)
+                        *rec_y = tmpvar;
+                        *(rec_y + 1) = D + d2;
+                        rec_y += width;
+                    }
+                    rec_y -= offset;
+                }
+                else
+                {
+                    rec_y += b_size;
+                }
+                mbnum++;
+            }
+            rec_y += (15 * width);
+
+        }
+    }
+
+
+
+    /* HORIZONTAL EDGE */
+    rec_y = rec + b_size;
+    offset = width * b_size - b_size;
+    mbnum = 1;
+    for (i = 0; i < nMBPerCol; i++)
+    {
+        for (j = 0; j < nMBPerRow - 1; j++)
+        {
+            if (mode[mbnum] != MODE_SKIPPED || mode[mbnum-1] != MODE_SKIPPED)
+            {
+                k = b_size;
+                if (mode[mbnum] != MODE_SKIPPED)
+                {
+                    strength = STRENGTH_tab[(annex_T ?  MQ_chroma_QP_table[QP_store[mbnum]] : QP_store[mbnum])];
+                }
+                else
+                {
+                    strength = STRENGTH_tab[(annex_T ?  MQ_chroma_QP_table[QP_store[mbnum - 1]] : QP_store[mbnum - 1])];
+                }
+
+                while (k--)
+                {
+                    A =  *(rec_y - 2);
+                    D =  *(rec_y + 1);
+                    A_D = A - D;
+                    C = *rec_y;
+                    B = *(rec_y - 1);
+                    d = (((C - B) << 2) + A_D);
+
+                    if (d < 0)
+                    {
+                        d1 = -(-d >> 3);
+                        if (d1 < -(strength << 1))
+                        {
+                            d1 = 0;
+                        }
+                        else if (d1 < -strength)
+                        {
+                            d1 = -d1 - (strength << 1);
+                        }
+                        d1_2 = -d1 >> 1;
+                    }
+                    else
+                    {
+                        d1 = d >> 3;
+                        if (d1 > (strength << 1))
+                        {
+                            d1 = 0;
+                        }
+                        else if (d1 > strength)
+                        {
+                            d1 = (strength << 1) - d1;
+                        }
+                        d1_2 = d1 >> 1;
+                    }
+
+                    if (A_D < 0)
+                    {
+                        d2 = -(-A_D >> 2);
+                        if (d2 < -d1_2)
+                        {
+                            d2 = -d1_2;
+                        }
+                    }
+                    else
+                    {
+                        d2 = A_D >> 2;
+                        if (d2 > d1_2)
+                        {
+                            d2 = d1_2;
+                        }
+                    }
+
+                    *(rec_y - 2) = A - d2;
+                    tmpvar = B + d1;
+                    CLIP_RESULT(tmpvar)
+                    *(rec_y - 1) = tmpvar;
+                    tmpvar = C - d1;
+                    CLIP_RESULT(tmpvar)
+                    *rec_y = tmpvar;
+                    *(rec_y + 1) = D + d2;
+                    rec_y += width;
+                }
+                rec_y -= offset;
+            }
+            else
+            {
+                rec_y += b_size;
+            }
+            mbnum++;
+        }
+        rec_y += ((width * (b_size - 1)) + b_size);
+        mbnum++;
+    }
+
+    return;
+}
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
new file mode 100644
index 0000000..091fdaf
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc.h
@@ -0,0 +1,75 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#ifndef post_proc_H
+#define post_proc_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "mp4dec_lib.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define UPDATE_PV_MAXPV_MIN(p,max,min) if ((p) > max) max=(p); else if ((p) < min) min = (p);
+
+#define     INDEX(x,thr)    (((x)>=thr)?1:0)
+#define     BLKSIZE     8
+#define     MBSIZE      16
+#define     DERING_THR  16
+
+/* version for fast Deblock filtering*/
+#define     KTh     4  /*threshold for soft filtering*/
+#define     KThH    4  /*threshold for hard filtering */
+
+#define     NoMMX
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp
new file mode 100644
index 0000000..3abc6be
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/post_proc_semaphore.cpp
@@ -0,0 +1,247 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    q_block = pointer to buffer of inverse quantized DCT coefficients of type
+              int for intra-VOP mode or buffer of residual data of type int
+              for inter-VOP mode
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    postmode = post processing semaphore with the vertical deblocking,
+               horizontal deblocking, and deringing bits set up accordingly
+
+ Pointers and Buffers Modified:
+    None
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This function sets up the postmode semaphore based on the contents of the
+ buffer pointed to by q_block. The function starts out with the assumption
+ that all entries of q_block, except for the first entry (q_block[0]), are
+ zero. This case can induce horizontal and vertical blocking artifacts,
+ therefore, both horizontal and vertical deblocking bits are enabled.
+
+ The following conditions are tested when setting up the horizontal/vertical
+ deblocking and deringing bits:
+ 1. When only the elements of the top row of the B_SIZE x B_SIZE block
+    (q_block[n], n = 0,..., B_SIZE-1) are non-zero, vertical blocking artifacts
+    may result, therefore, only the vertical deblocking bit is enabled.
+    Otherwise, the vertical deblocking bit is disabled.
+ 2. When only the elements of the far left column of the B_SIZE x B_SIZE block
+    (q_block[n*B_SIZE], n = 0, ..., B_SIZE-1) are non-zero, horizontal blocking
+    artifacts may result, therefore, only the horizontal deblocking bit is
+    enabled. Otherwise, the horizontal deblocking bit is disabled.
+ 3. If any non-zero elements exist in positions other than q_block[0],
+    q_block[1], or q_block[B_SIZE], the deringing bit is enabled. Otherwise,
+    it is disabled.
+
+ The 3 least significant bits of postmode defines vertical or horizontal
+ deblocking and deringing.
+
+ The valid values are shown below:
+ -------------------------------------------------------
+ |           Type                 | Enabled | Disabled |
+ -------------------------------------------------------
+ | Vertical Deblocking (Bit #0)   |    1    |     0    |
+ -------------------------------------------------------
+ | Horizontal Deblocking (Bit #1) |    1    |     0    |
+ -------------------------------------------------------
+ | Deringing (Bit #2)             |    1    |     0    |
+ -------------------------------------------------------
+
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "mp4dec_lib.h"
+#include    "mp4def.h"
+#include    "post_proc.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
+----------------------------------------------------------------------------*/
+#ifdef PV_POSTPROC_ON
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+int PostProcSemaphore(
+    int16 *q_block)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int i, j;
+
+    /* Set default value to vertical and horizontal deblocking enabled */
+    /* Initial assumption is that only q_block[0] element is non-zero, */
+    /* therefore, vertical and horizontal deblocking bits are set to 1 */
+    int postmode = 0x3;
+
+    /*----------------------------------------------------------------------------
+    ; Function body here
+    ----------------------------------------------------------------------------*/
+    /* Vertical deblocking bit is enabled when only the entire top row of   */
+    /* the B_SIZE x B_SIZE block, i.e., q_block[n], n = 0,..., B_SIZE-1,    */
+    /* are non-zero. Since initial assumption is that all elements, except  */
+    /* q_block[0], is zero, we need to check the remaining elements in the  */
+    /* top row to  determine if all or some are non-zero.                   */
+    if (q_block[1] != 0)
+    {
+        /* At this point, q_block[0] and q_block[1] are non-zero, while */
+        /* q_block[n], n = 2,..., B_SIZE-1, are zero. Therefore, we     */
+        /* need to disable vertical deblocking                          */
+        postmode &= 0xE;
+    }
+
+    for (i = 2; i < B_SIZE; i++)
+    {
+        if (q_block[i])
+        {
+            /* Check if q_block[n], n = 2,..., B_SIZE-1, are non-zero.*/
+            /* If any of them turn out to be non-zero, we need to     */
+            /* disable vertical deblocking.                           */
+            postmode &= 0xE;
+
+            /* Deringing is enabled if any nonzero elements exist in */
+            /* positions other than q_block[0], q_block[1] or        */
+            /* q_block[B_SIZE].                                      */
+            postmode |= 0x4;
+
+            break;
+        }
+    }
+
+    /* Horizontal deblocking bit is enabled when only the entire far */
+    /* left column, i.e., q_block[n*B_SIZE], n = 0, ..., B_SIZE-1,   */
+    /* are non-zero. Since initial assumption is that all elements,  */
+    /* except q_block[0], is zero, we need to check the remaining    */
+    /* elements in the far left column to determine if all or some   */
+    /* are non-zero.                                                 */
+    if (q_block[B_SIZE])
+    {
+        /* At this point, only q_block[0] and q_block[B_SIZE] are non-zero, */
+        /* while q_block[n*B_SIZE], n = 2, 3,..., B_SIZE-1, are zero.       */
+        /* Therefore, we need to disable horizontal deblocking.             */
+        postmode &= 0xD;
+    }
+
+    for (i = 16; i < NCOEFF_BLOCK; i += B_SIZE)
+    {
+        if (q_block[i])
+        {
+            /* Check if q_block[n], n = 2*B_SIZE,...,(B_SIZE-1)*B_SIZE,  */
+            /* are non-zero. If any of them turn out to be non-zero,     */
+            /* we need to disable horizontal deblocking.                 */
+            postmode &= 0xD;
+
+            /* Deringing is enabled if any nonzero elements exist in */
+            /* positions other than q_block[0], q_block[1] or        */
+            /* q_block[B_SIZE].                                      */
+            postmode |= 0x4;
+
+            break;
+        }
+    }
+
+    /* At this point, only the first row and far left column elements */
+    /* have been tested. If deringing bit is still not set at this    */
+    /* point, check the rest of q_block to determine if the elements  */
+    /* are non-zero. If all elements, besides q_block[0], q_block[1], */
+    /* or q_block[B_SIZE] are non-zero, deringing bit must be set     */
+    if ((postmode & 0x4) == 0)
+    {
+        for (i = 1; i < B_SIZE; i++)
+        {
+            for (j = 1; j < B_SIZE; j++)
+            {
+                if (q_block[(i<<3)+j])
+                {
+                    /* At this point, q_block[0] and another q_block */
+                    /* element are non-zero, therefore, we need to   */
+                    /* disable vertical and horizontal deblocking    */
+                    postmode &= 0xC;
+
+                    /* Deringing is enabled if any nonzero elements exist in */
+                    /* positions other than q_block[0], q_block[1] or        */
+                    /* q_block[B_SIZE].                                      */
+                    postmode |= 0x4;
+
+                    /* Set outer FOR loop count to B_SIZE to get out of */
+                    /* outer FOR loop                                   */
+                    i = B_SIZE;
+
+                    /* Get out of inner FOR loop */
+                    break;
+                }
+            }
+        }
+    }
+
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return (postmode);
+}
+
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp
new file mode 100644
index 0000000..7c20222
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_chroma_inter.cpp
@@ -0,0 +1,262 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xpred = x-axis coordinate of the block used for prediction (int)
+    ypred = y-axis coordinate of the block used for prediction (int)
+    pp_dec_u = pointer to the post processing semaphore for chrominance
+               (uint8)
+    pstprcTypPrv = pointer the previous frame's post processing type
+                   (uint8)
+    dx = horizontal component of the motion vector (int)
+    dy = vertical component of the motion vector (int)
+    mvwidth = number of blocks per row in the luminance VOP (int)
+    height = luminance VOP height in pixels (int)
+    size = total number of pixel in the current luminance VOP (int)
+    mv_loc = flag indicating location of the motion compensated
+         (x,y) position with respect to the luminance MB (int);
+         0 -> inside MB, 1 -> outside MB
+    msk_deblock = flag indicating whether to perform deblocking
+              (msk_deblock = 0) or not (msk_deblock = 1) (uint8)
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    None
+
+ Pointers and Buffers Modified:
+    pp_dec_u contents are the updated semaphore propagation data
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This functions performs post processing semaphore propagation processing
+ after chrominance prediction in interframe processing mode.
+
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "mp4dec_api.h"
+#include    "mp4def.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
+----------------------------------------------------------------------------*/
+#ifdef PV_POSTPROC_ON
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+    /*----------------------------------------------------------------------------
+    ; FUNCTION CODE
+    ----------------------------------------------------------------------------*/
+    void pp_semaphore_chroma_inter(
+        int xpred,      /* i */
+        int ypred,      /* i */
+        uint8   *pp_dec_u,  /* i/o */
+        uint8   *pstprcTypPrv,  /* i */
+        int dx,     /* i */
+        int dy,     /* i */
+        int mvwidth,    /* i */
+        int height,     /* i */
+        int32   size,       /* i */
+        int mv_loc,     /* i */
+        uint8   msk_deblock /* i */
+    )
+    {
+        /*----------------------------------------------------------------------------
+        ; Define all local variables
+        ----------------------------------------------------------------------------*/
+        int mmvy, mmvx, nmvy, nmvx;
+        uint8 *pp_prev1, *pp_prev2, *pp_prev3, *pp_prev4;
+
+        /*----------------------------------------------------------------------------
+        ; Function body here
+        ----------------------------------------------------------------------------*/
+
+        /* 09/28/2000, modify semaphore propagation to */
+        /* accommodate smart indexing */
+        mmvx = xpred >> 4;  /* block x coor */
+        nmvx = mmvx;
+
+        mmvy = ypred >> 4;  /* block y coor */
+        nmvy = mmvy;
+
+        /* Check if MV is outside the frame */
+        if (mv_loc == 1)
+        {
+            /* Perform boundary check */
+            if (nmvx < 0)
+            {
+                nmvx = 0;
+            }
+            else if (nmvx > mvwidth - 1)
+            {
+                nmvx = mvwidth - 1;
+            }
+
+            if (nmvy < 0)
+            {
+                nmvy = 0;
+            }
+            else if (nmvy > (height >> 4) - 1)
+            {
+                nmvy = (height >> 4) - 1;
+            }
+        }
+
+        /* Calculate pointer to first chrominance b semaphores in       */
+        /* pstprcTypPrv, i.e., first chrominance b semaphore is in      */
+        /* (pstprcTypPrv + (size>>6)).                  */
+        /* Since total number of chrominance blocks per row in a VOP    */
+        /* is half of the total number of luminance blocks per row in a */
+        /* VOP, we use (mvwidth >> 1) when calculating the row offset.  */
+        pp_prev1 = pstprcTypPrv + (size >> 6) + nmvx + nmvy * (mvwidth >> 1) ;
+
+        /* Check if MV is a multiple of 16 */
+        /*  1/5/01, make sure it doesn't go out of bound */
+        if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 4) - 1))
+        {   /* dy is not a multiple of 16 */
+
+            /* pp_prev3 is the block below pp_prev1 block */
+            pp_prev3 = pp_prev1 + (mvwidth >> 1);
+        }
+        else
+        {   /* dy is a multiple of 16 */
+            pp_prev3 = pp_prev1;
+        }
+
+        /*  1/5/01, make sure it doesn't go out of bound */
+        if (((dx&0xF) != 0) && (mmvx + 1 < (mvwidth >> 1) - 1))
+        {   /* dx is not a multiple of 16 */
+
+            /* pp_prev2 is the block to the right of pp_prev1 block */
+            pp_prev2 = pp_prev1 + 1;
+
+            /* pp_prev4 is the block to the right of the block */
+            /* below pp_prev1 block                */
+            pp_prev4 = pp_prev3 + 1;
+        }
+        else
+        {   /* dx is a multiple of 16 */
+
+            pp_prev2 = pp_prev1;
+            pp_prev4 = pp_prev3;
+        }
+
+        /* Advance offset to location of first Chrominance R semaphore in */
+        /* pstprcTypPrv. Since the number of pixels in a Chrominance VOP  */
+        /* is (number of pixels in Luminance VOP/4), and there are 64     */
+        /* pixels in an 8x8 Chrominance block, the offset can be      */
+        /* calculated as:                         */
+        /*  mv_loc = (number of pixels in Luminance VOP/(4*64))   */
+        /*         = size/256 = size>>8               */
+        mv_loc = (size >> 8);
+
+        /*  11/3/00, change the propagation for deblocking */
+        if (msk_deblock == 0)
+        {
+
+            /* Deblocking semaphore propagation for Chrominance */
+            /* b semaphores                     */
+            *(pp_dec_u) = 0;
+
+            /* Advance offset to point to Chrominance r semaphores */
+            pp_dec_u += mv_loc;
+
+            /* Deblocking semaphore propagation for Chrominance */
+            /* r semaphores                     */
+            *(pp_dec_u) = 0;
+        }
+        else
+        {
+            /* Deringing semaphore propagation for Chrominance B block */
+            if ((*(pp_dec_u)&4) == 0)
+            {
+                *(pp_dec_u) |= ((*(pp_prev1) | *(pp_prev2) |
+                                 *(pp_prev3) | *(pp_prev4)) & 0x4);
+            }
+
+            /* Advance offset to point to Chrominance r semaphores */
+            pp_dec_u += mv_loc;
+            pp_prev1 += mv_loc;
+            pp_prev2 += mv_loc;
+            pp_prev3 += mv_loc;
+            pp_prev4 += mv_loc;
+
+            /* Deringing semaphore propagation for Chrominance R */
+            if ((*(pp_dec_u)&4) == 0)
+            {
+                *(pp_dec_u) |= ((*(pp_prev1) | *(pp_prev2) |
+                                 *(pp_prev3) | *(pp_prev4)) & 0x4);
+            }
+        }
+
+        /*----------------------------------------------------------------------------
+        ; Return nothing or data or data pointer
+        ----------------------------------------------------------------------------*/
+        return;
+    }
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp
new file mode 100644
index 0000000..b3a1ebd
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/pp_semaphore_luma.cpp
@@ -0,0 +1,378 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    xpred = x-axis coordinate of the MB used for prediction (int)
+    ypred = y-axis coordinate of the MB used for prediction (int)
+    pp_dec_y = pointer to the post processing semaphore for current
+           luminance frame (uint8)
+    pstprcTypPrv = pointer the previous frame's post processing type
+                   (uint8)
+    ll = pointer to the buffer (int)
+    mv_loc = flag indicating location of the motion compensated
+         (x,y) position with respect to the luminance MB (int);
+         0 -> inside MB, 1 -> outside MB
+    dx = horizontal component of the motion vector (int)
+    dy = vertical component of the motion vector (int)
+    mvwidth = number of blocks per row (int)
+    width = luminance VOP width in pixels (int)
+    height = luminance VOP height in pixels (int)
+
+ Local Stores/Buffers/Pointers Needed:
+    None
+
+ Global Stores/Buffers/Pointers Needed:
+    None
+
+ Outputs:
+    msk_deblock = flag that indicates whether deblocking is to be
+              performed (msk_deblock = 0) or not (msk_deblock =
+              1) (uint8)
+
+ Pointers and Buffers Modified:
+    pp_dec_y contents are the updated semapohore propagation data
+
+ Local Stores Modified:
+    None
+
+ Global Stores Modified:
+    None
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ This functions performs post processing semaphore propagation processing
+ after luminance prediction.
+
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include    "mp4dec_api.h"
+#include    "mp4def.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
+----------------------------------------------------------------------------*/
+#ifdef PV_POSTPROC_ON
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+    /*----------------------------------------------------------------------------
+    ; FUNCTION CODE
+    ----------------------------------------------------------------------------*/
+    uint8 pp_semaphore_luma(
+        int xpred,      /* i */
+        int ypred,      /* i */
+        uint8   *pp_dec_y,  /* i/o */
+        uint8   *pstprcTypPrv,  /* i */
+        int *ll,        /* i */
+        int *mv_loc,    /* i/o */
+        int dx,     /* i */
+        int dy,     /* i */
+        int mvwidth,    /* i */
+        int width,      /* i */
+        int height      /* i */
+    )
+    {
+        /*----------------------------------------------------------------------------
+        ; Define all local variables
+        ----------------------------------------------------------------------------*/
+        int kk, mmvy, mmvx, nmvx, nmvy;
+        uint8   *pp_prev1, *pp_prev2, *pp_prev3, *pp_prev4;
+        uint8   msk_deblock = 0;        /*  11/3/00 */
+
+        /*----------------------------------------------------------------------------
+        ; Function body here
+        ----------------------------------------------------------------------------*/
+        /* Interframe Processing - 1 MV per MB */
+
+        /* check whether the MV points outside the frame */
+        if (xpred >= 0 && xpred <= ((width << 1) - (2*MB_SIZE)) && ypred >= 0 &&
+                ypred <= ((height << 1) - (2*MB_SIZE)))
+        {   /*****************************/
+            /* (x,y) is inside the frame */
+            /*****************************/
+
+            /*  10/24/2000 post_processing semaphore */
+            /* generation */
+
+            /*  10/23/2000 no boundary checking*/
+            *mv_loc = 0;
+
+            /* Calculate block x coordinate. Divide by 16 is for  */
+            /* converting half-pixel resolution to block          */
+            mmvx = xpred >> 4;
+
+            /* Calculate block y coordinate. Divide by 16 is for */
+            /* converting half-pixel resolution to block         */
+            mmvy = ypred >> 4;
+
+            /* Find post processing semaphore location for block */
+            /* used for prediction, i.e.,                */
+            /* pp_prev1 = &pstprcTypPrv[mmvy*mvwidth][mmvx]      */
+            pp_prev1 = pstprcTypPrv + mmvx + mmvy * mvwidth;
+
+            /* Check if MV is a multiple of 16 */
+            if ((dx&0xF) != 0)
+            {   /* dx is not a multiple of 16 */
+
+                /* pp_prev2 is the block to the right of */
+                /* pp_prev1 block            */
+                pp_prev2 = pp_prev1 + 1;
+
+                if ((dy&0xF) != 0)
+                {   /* dy is not a multiple of 16 */
+
+                    /* pp_prev3 is the block below */
+                    /* pp_prev1 block          */
+                    pp_prev3 = pp_prev1 + mvwidth;
+                }
+                else
+                {   /* dy is a multiple of 16 */
+
+                    pp_prev3 = pp_prev1;
+                }
+
+                /* pp_prev4 is the block to the right of */
+                /* pp_prev3 block.           */
+                pp_prev4 = pp_prev3 + 1;
+            }
+            else
+            {   /* dx is a multiple of 16 */
+
+                pp_prev2 = pp_prev1;
+
+                if ((dy&0xF) != 0)
+                {   /* dy is not a multiple of 16 */
+
+                    /* pp_prev3 is the block below */
+                    /* pp_prev1 block.         */
+                    pp_prev3 = pp_prev1 + mvwidth;
+                }
+                else
+                {   /* dy is a multiple of 16 */
+
+                    pp_prev3 = pp_prev1;
+                    msk_deblock = 0x3;
+                }
+
+                pp_prev4 = pp_prev3;
+            }
+
+            /* Perform post processing semaphore propagation for each */
+            /* of the 4 blocks in a MB.               */
+            for (kk = 0; kk < 4; kk++)
+            {
+                /* Deringing semaphore propagation */
+                if ((*(pp_dec_y) & 4) == 0)
+                {
+                    *(pp_dec_y) |= ((*(pp_prev1) | *(pp_prev2) |
+                                     *(pp_prev3) | *(pp_prev4)) & 0x4);
+                }
+                /* Deblocking semaphore propagation */
+                /*  11/3/00, change the propagation for deblocking */
+                if (msk_deblock == 0)
+                {
+                    *(pp_dec_y) = 0;
+                }
+
+                pp_dec_y += ll[kk];
+                pp_prev1 += ll[kk];
+                pp_prev2 += ll[kk];
+                pp_prev3 += ll[kk];
+                pp_prev4 += ll[kk];
+            }
+
+        }
+        else
+        {   /******************************/
+            /* (x,y) is outside the frame */
+            /******************************/
+
+            /*  10/24/2000 post_processing semaphore */
+            /* generation */
+
+            /*  10/23/2000 boundary checking*/
+            *mv_loc = 1;
+
+            /* Perform post processing semaphore propagation for each */
+            /* of the 4 blocks in a MB.               */
+            for (kk = 0; kk < 4; kk++)
+            {
+                /* Calculate block x coordinate and round (?).  */
+                /* Divide by 16 is for converting half-pixel    */
+                /* resolution to block.             */
+                mmvx = (xpred + ((kk & 1) << 3)) >> 4;
+                nmvx = mmvx;
+
+                /* Calculate block y coordinate and round (?).  */
+                /* Divide by 16 is for converting half-pixel    */
+                /* resolution to block.             */
+                mmvy = (ypred + ((kk & 2) << 2)) >> 4;
+                nmvy = mmvy;
+
+                /* Perform boundary checking */
+                if (nmvx < 0)
+                {
+                    nmvx = 0;
+                }
+                else if (nmvx > mvwidth - 1)
+                {
+                    nmvx = mvwidth - 1;
+                }
+
+                if (nmvy < 0)
+                {
+                    nmvy = 0;
+                }
+                else if (nmvy > (height >> 3) - 1)
+                {
+                    nmvy = (height >> 3) - 1;
+                }
+
+                /* Find post processing semaphore location for block */
+                /* used for prediction, i.e.,                */
+                /* pp_prev1 = &pstprcTypPrv[nmvy*mvwidth][nmvx]      */
+                pp_prev1 = pstprcTypPrv + nmvx + nmvy * mvwidth;
+
+                /* Check if x component of MV is a multiple of 16    */
+                /* and check if block x coordinate is out of bounds  */
+                if (((dx&0xF) != 0) && (mmvx + 1 < mvwidth - 1))
+                {   /* dx is not a multiple of 16 and the block */
+                    /* x coordinate is within the bounds        */
+
+                    /* pp_prev2 is the block to the right of */
+                    /* pp_prev1 block            */
+                    pp_prev2 = pp_prev1 + 1;
+
+                    /* Check if y component of MV is a multiple */
+                    /* of 16 and check if block y coordinate is */
+                    /* out of bounds                */
+                    if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 3) - 1))
+                    {   /* dy is not a multiple of 16 and */
+                        /* the block y coordinate is      */
+                        /* within the bounds              */
+
+                        /* pp_prev3 is the block below */
+                        /* pp_prev1 block          */
+                        pp_prev3 = pp_prev1 + mvwidth;
+
+                        /* all prediction are from different blocks */
+                        msk_deblock = 0x3;
+                    }
+                    else
+                    {   /* dy is a multiple of 16 or the block */
+                        /* y coordinate is out of bounds       */
+
+                        pp_prev3 = pp_prev1;
+                    }
+
+                    /* pp_prev4 is the block to the right of */
+                    /* pp_prev3 block.           */
+                    pp_prev4 = pp_prev3 + 1;
+                }
+                else
+                {   /* dx is a multiple of 16 or the block x */
+                    /* coordinate is out of bounds           */
+
+                    pp_prev2 = pp_prev1;
+
+                    /* Check if y component of MV is a multiple */
+                    /* of 16 and check if block y coordinate is */
+                    /* out of bounds                */
+                    if (((dy&0xF) != 0) && (mmvy + 1 < (height >> 3) - 1))
+                    {   /* dy is not a multiple of 16 and */
+                        /* the block y coordinate is      */
+                        /* within the bounds              */
+
+                        /* pp_prev3 is the block below */
+                        /* pp_prev1 block.         */
+                        pp_prev3 = pp_prev1 + mvwidth;
+                    }
+                    else
+                    {   /* dy is a multiple of 16 or the block */
+                        /* y coordinate is out of bounds       */
+
+                        pp_prev3 = pp_prev1;
+                    }
+
+                    pp_prev4 = pp_prev3;
+                }
+
+                /* Deringing semaphore propagation */
+                if ((*(pp_dec_y)&4) == 0)
+                {
+                    *(pp_dec_y) |= ((*(pp_prev1) |
+                                     *(pp_prev2) | *(pp_prev3) |
+                                     *(pp_prev4)) & 0x4);
+                }
+                /* Deblocking semaphore propagation */
+                /*  11/3/00, change the propaga= */
+                /* tion for deblocking */
+                if (msk_deblock == 0)
+                {
+                    *(pp_dec_y) = 0;
+                }
+
+                pp_dec_y += ll[kk];
+            }
+        }
+
+        /*----------------------------------------------------------------------------
+        ; Return nothing or data or data pointer
+        ----------------------------------------------------------------------------*/
+        return (msk_deblock);
+    }
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp
new file mode 100644
index 0000000..0c354d9
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/pvdec_api.cpp
@@ -0,0 +1,1696 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+
+#define OSCL_DISABLE_WARNING_CONDITIONAL_IS_CONSTANT
+
+#ifdef DEC_INTERNAL_MEMORY_OPT
+#define QCIF_MBS 99
+#define QCIF_BS (4*QCIF_MBS)
+#define QCIF_MB_ROWS 11
+extern uint8                IMEM_sliceNo[QCIF_MBS];
+extern uint8                IMEM_acPredFlag[QCIF_MBS];
+extern uint8                IMEM_headerInfo_Mode[QCIF_MBS];
+extern uint8                IMEM_headerInfo_CBP[QCIF_MBS];
+extern int                  IMEM_headerInfo_QPMB[QCIF_MBS];
+extern MacroBlock           IMEM_mblock;
+extern MOT                  IMEM_motX[QCIF_BS];
+extern MOT                  IMEM_motY[QCIF_BS];
+extern BitstreamDecVideo    IMEM_BitstreamDecVideo[4];
+extern typeDCStore          IMEM_predDC[QCIF_MBS];
+extern typeDCACStore        IMEM_predDCAC_col[QCIF_MB_ROWS+1];
+
+extern VideoDecData         IMEM_VideoDecData[1];
+extern Vop                  IMEM_currVop[1];
+extern Vop                  IMEM_prevVop[1];
+extern PIXEL                IMEM_currVop_yChan[QCIF_MBS*128*3];
+extern PIXEL                IMEM_prevVop_yChan[QCIF_MBS*128*3];
+extern uint8                IMEM_pstprcTypCur[6*QCIF_MBS];
+extern uint8                IMEM_pstprcTypPrv[6*QCIF_MBS];
+
+
+extern Vop                  IMEM_vopHEADER[2];
+extern Vol                  IMEM_VOL[2];
+extern Vop                  IMEM_vopHeader[2][1];
+extern Vol                  IMEM_vol[2][1];
+
+#endif
+
+/* ======================================================================== */
+/*  Function : PVInitVideoDecoder()                                         */
+/*  Date     : 04/11/2000, 08/29/2000                                       */
+/*  Purpose  : Initialization of the MPEG-4 video decoder library.          */
+/*             The return type is Bool instead of PV_STATUS because         */
+/*             we don't want to expose PV_STATUS to (outside) programmers   */
+/*             that use our decoder library SDK.                            */
+/*  In/out   :                                                              */
+/*  Return   : PV_TRUE if successed, PV_FALSE if failed.                    */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF Bool PVInitVideoDecoder(VideoDecControls *decCtrl, uint8 *volbuf[],
+                                        int32 *volbuf_size, int nLayers, int width, int height, MP4DecodingMode mode)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    Bool status = PV_TRUE;
+    int idx;
+    BitstreamDecVideo *stream;
+
+
+    oscl_memset(decCtrl, 0, sizeof(VideoDecControls)); /* fix a size bug.   03/28/2001 */
+    decCtrl->nLayers = nLayers;
+    for (idx = 0; idx < nLayers; idx++)
+    {
+        decCtrl->volbuf[idx] = volbuf[idx];
+        decCtrl->volbuf_size[idx] = volbuf_size[idx];
+    }
+
+    /* memory allocation & initialization */
+#ifdef DEC_INTERNAL_MEMORY_OPT
+    video = IMEM_VideoDecData;
+#else
+    video = (VideoDecData *) oscl_malloc(sizeof(VideoDecData));
+#endif
+    if (video != NULL)
+    {
+        oscl_memset(video, 0, sizeof(VideoDecData));
+        video->memoryUsage = sizeof(VideoDecData);
+        video->numberOfLayers = nLayers;
+#ifdef DEC_INTERNAL_MEMORY_OPT
+        video->vol = (Vol **) IMEM_VOL;
+#else
+        video->vol = (Vol **) oscl_malloc(nLayers * sizeof(Vol *));
+#endif
+        if (video->vol == NULL) status = PV_FALSE;
+        video->memoryUsage += nLayers * sizeof(Vol *);
+
+
+        /* we need to setup this pointer for the application to */
+        /*    pass it around.                                   */
+        decCtrl->videoDecoderData = (void *) video;
+        video->videoDecControls = decCtrl;  /* yes. we have a cyclic */
+        /* references here :)    */
+
+        /* Allocating Vop space, this has to change when we add */
+        /*    spatial scalability to the decoder                */
+#ifdef DEC_INTERNAL_MEMORY_OPT
+        video->currVop = IMEM_currVop;
+        if (video->currVop == NULL) status = PV_FALSE;
+        else oscl_memset(video->currVop, 0, sizeof(Vop));
+        video->prevVop = IMEM_prevVop;
+        if (video->prevVop == NULL) status = PV_FALSE;
+        else oscl_memset(video->prevVop, 0, sizeof(Vop));
+        video->memoryUsage += (sizeof(Vop) * 2);
+        video->vopHeader = (Vop **) IMEM_vopHEADER;
+#else
+
+        video->currVop = (Vop *) oscl_malloc(sizeof(Vop));
+        if (video->currVop == NULL) status = PV_FALSE;
+        else oscl_memset(video->currVop, 0, sizeof(Vop));
+        video->prevVop = (Vop *) oscl_malloc(sizeof(Vop));
+        if (video->prevVop == NULL) status = PV_FALSE;
+        else oscl_memset(video->prevVop, 0, sizeof(Vop));
+        video->memoryUsage += (sizeof(Vop) * 2);
+
+        video->vopHeader = (Vop **) oscl_malloc(sizeof(Vop *) * nLayers);
+#endif
+        if (video->vopHeader == NULL) status = PV_FALSE;
+        else oscl_memset(video->vopHeader, 0, sizeof(Vop *)*nLayers);
+        video->memoryUsage += (sizeof(Vop *) * nLayers);
+
+        video->initialized = PV_FALSE;
+        /* Decode the header to get all information to allocate data */
+        if (status == PV_TRUE)
+        {
+            /* initialize decoded frame counter.   04/24/2001 */
+            video->frame_idx = -1;
+
+
+            for (idx = 0; idx < nLayers; idx++)
+            {
+
+#ifdef DEC_INTERNAL_MEMORY_OPT
+                video->vopHeader[idx] = IMEM_vopHeader[idx];
+#else
+                video->vopHeader[idx] = (Vop *) oscl_malloc(sizeof(Vop));
+#endif
+                if (video->vopHeader[idx] == NULL)
+                {
+                    status = PV_FALSE;
+                    break;
+                }
+                else
+                {
+                    oscl_memset(video->vopHeader[idx], 0, sizeof(Vop));
+                    video->vopHeader[idx]->timeStamp = 0;
+                    video->memoryUsage += (sizeof(Vop));
+                }
+#ifdef DEC_INTERNAL_MEMORY_OPT
+                video->vol[idx] = IMEM_vol[idx];
+                video->memoryUsage += sizeof(Vol);
+                oscl_memset(video->vol[idx], 0, sizeof(Vol));
+                if (video->vol[idx] == NULL) status = PV_FALSE;
+                stream = IMEM_BitstreamDecVideo;
+#else
+                video->vol[idx] = (Vol *) oscl_malloc(sizeof(Vol));
+                if (video->vol[idx] == NULL)
+                {
+                    status = PV_FALSE;
+                    break;
+                }
+                else
+                {
+                    video->memoryUsage += sizeof(Vol);
+                    oscl_memset(video->vol[idx], 0, sizeof(Vol));
+                }
+
+                stream = (BitstreamDecVideo *) oscl_malloc(sizeof(BitstreamDecVideo));
+#endif
+                video->memoryUsage += sizeof(BitstreamDecVideo);
+                if (stream == NULL)
+                {
+                    status = PV_FALSE;
+                    break;
+                }
+                else
+                {
+                    int32 buffer_size;
+                    if ((buffer_size = BitstreamOpen(stream, idx)) < 0)
+                    {
+                        mp4dec_log("InitVideoDecoder(): Can't allocate bitstream buffer.\n");
+                        status = PV_FALSE;
+                        break;
+                    }
+                    video->memoryUsage += buffer_size;
+                    video->vol[idx]->bitstream = stream;
+                    video->vol[idx]->volID = idx;
+                    video->vol[idx]->timeInc_offset = 0;  /*  11/12/01 */
+                    video->vlcDecCoeffIntra = &VlcDecTCOEFShortHeader;
+                    video->vlcDecCoeffInter = &VlcDecTCOEFShortHeader;
+                    if (mode == MPEG4_MODE)
+                    {
+                        /* Set up VOL header bitstream for frame-based decoding.  08/30/2000 */
+                        BitstreamReset(stream, decCtrl->volbuf[idx], decCtrl->volbuf_size[idx]);
+
+                        switch (DecodeVOLHeader(video, idx))
+                        {
+                            case PV_SUCCESS :
+                                if (status == PV_TRUE)
+                                    status = PV_TRUE;   /*  we want to make sure that if first layer is bad, second layer is good return PV_FAIL */
+                                else
+                                    status = PV_FALSE;
+                                break;
+#ifdef PV_TOLERATE_VOL_ERRORS
+                            case PV_BAD_VOLHEADER:
+                                status = PV_TRUE;
+                                break;
+#endif
+                            default :
+                                status = PV_FALSE;
+                                break;
+                        }
+
+                    }
+                    else
+                    {
+                        video->shortVideoHeader = PV_TRUE;
+                    }
+
+                    if (video->shortVideoHeader == PV_TRUE)
+                    {
+                        mode = H263_MODE;
+                        /* Set max width and height.  In H.263 mode, we use    */
+                        /*  volbuf_size[0] to pass in width and volbuf_size[1] */
+                        /*  to pass in height.                    04/23/2001 */
+                        video->prevVop->temporalRef = 0; /*  11/12/01 */
+                        /* Compute some convenience variables:   04/23/2001 */
+                        video->vol[idx]->quantType = 0;
+                        video->vol[idx]->quantPrecision = 5;
+                        video->vol[idx]->errorResDisable = 1;
+                        video->vol[idx]->dataPartitioning = 0;
+                        video->vol[idx]->useReverseVLC = 0;
+                        video->intra_acdcPredDisable = 1;
+                        video->vol[idx]->scalability = 0;
+                        video->size = (int32)width * height;
+
+                        video->displayWidth = video->width = width;
+                        video->displayHeight = video->height = height;
+#ifdef PV_ANNEX_IJKT_SUPPORT
+                        video->modified_quant = 0;
+                        video->advanced_INTRA = 0;
+                        video->deblocking = 0;
+                        video->slice_structure = 0;
+#endif
+                    }
+
+                }
+            }
+
+        }
+        if (status != PV_FALSE)
+        {
+            status = PVAllocVideoData(decCtrl, width, height, nLayers);
+            video->initialized = PV_TRUE;
+        }
+    }
+    else
+    {
+        status = PV_FALSE;
+    }
+
+    if (status == PV_FALSE) PVCleanUpVideoDecoder(decCtrl);
+
+    return status;
+}
+
+Bool PVAllocVideoData(VideoDecControls *decCtrl, int width, int height, int nLayers)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    Bool status = PV_TRUE;
+    int nTotalMB;
+    int nMBPerRow;
+    int32 size;
+
+    if (video->shortVideoHeader == PV_TRUE)
+    {
+        video->displayWidth = video->width = width;
+        video->displayHeight = video->height = height;
+
+        video->nMBPerRow =
+            video->nMBinGOB  = video->width / MB_SIZE;
+        video->nMBPerCol =
+            video->nGOBinVop = video->height / MB_SIZE;
+        video->nTotalMB =
+            video->nMBPerRow * video->nMBPerCol;
+    }
+
+    size = (int32)sizeof(PIXEL) * video->width * video->height;
+#ifdef PV_MEMORY_POOL
+    decCtrl->size = size;
+#else
+#ifdef DEC_INTERNAL_MEMORY_OPT
+    video->currVop->yChan = IMEM_currVop_yChan; /* Allocate memory for all VOP OKA 3/2/1*/
+    if (video->currVop->yChan == NULL) status = PV_FALSE;
+    video->currVop->uChan = video->currVop->yChan + size;
+    video->currVop->vChan = video->currVop->uChan + (size >> 2);
+
+    video->prevVop->yChan = IMEM_prevVop_yChan; /* Allocate memory for all VOP OKA 3/2/1*/
+    if (video->prevVop->yChan == NULL) status = PV_FALSE;
+    video->prevVop->uChan = video->prevVop->yChan + size;
+    video->prevVop->vChan = video->prevVop->uChan + (size >> 2);
+#else
+    video->currVop->yChan = (PIXEL *) oscl_malloc(size * 3 / 2); /* Allocate memory for all VOP OKA 3/2/1*/
+    if (video->currVop->yChan == NULL) status = PV_FALSE;
+
+    video->currVop->uChan = video->currVop->yChan + size;
+    video->currVop->vChan = video->currVop->uChan + (size >> 2);
+    video->prevVop->yChan = (PIXEL *) oscl_malloc(size * 3 / 2); /* Allocate memory for all VOP OKA 3/2/1*/
+    if (video->prevVop->yChan == NULL) status = PV_FALSE;
+
+    video->prevVop->uChan = video->prevVop->yChan + size;
+    video->prevVop->vChan = video->prevVop->uChan + (size >> 2);
+#endif
+    video->memoryUsage += (size * 3);
+#endif   // MEMORY_POOL
+    /* Note that baseVop, enhcVop is only used to hold enhancement */
+    /*    layer header information.                  05/04/2000  */
+    if (nLayers > 1)
+    {
+        video->prevEnhcVop = (Vop *) oscl_malloc(sizeof(Vop));
+        video->memoryUsage += (sizeof(Vop));
+        if (video->prevEnhcVop == NULL)
+        {
+            status = PV_FALSE;
+        }
+        else
+        {
+            oscl_memset(video->prevEnhcVop, 0, sizeof(Vop));
+#ifndef PV_MEMORY_POOL
+            video->prevEnhcVop->yChan = (PIXEL *) oscl_malloc(size * 3 / 2); /* Allocate memory for all VOP OKA 3/2/1*/
+            if (video->prevEnhcVop->yChan == NULL) status = PV_FALSE;
+            video->prevEnhcVop->uChan = video->prevEnhcVop->yChan + size;
+            video->prevEnhcVop->vChan = video->prevEnhcVop->uChan + (size >> 2);
+            video->memoryUsage += (3 * size / 2);
+#endif
+        }
+    }
+
+    /* Allocating space for slices, AC prediction flag, and */
+    /*    AC/DC prediction storage */
+    nTotalMB = video->nTotalMB;
+    nMBPerRow = video->nMBPerRow;
+
+#ifdef DEC_INTERNAL_MEMORY_OPT
+    video->sliceNo = (uint8 *)(IMEM_sliceNo);
+    if (video->sliceNo == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+    video->acPredFlag = (uint8 *)(IMEM_acPredFlag);
+    if (video->acPredFlag == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB);
+    video->predDC = (typeDCStore *)(IMEM_predDC);
+    if (video->predDC == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB * sizeof(typeDCStore));
+    video->predDCAC_col = (typeDCACStore *)(IMEM_predDCAC_col);
+    if (video->predDCAC_col == NULL) status = PV_FALSE;
+    video->memoryUsage += ((nMBPerRow + 1) * sizeof(typeDCACStore));
+    video->predDCAC_row = video->predDCAC_col + 1;
+    video->headerInfo.Mode = (uint8 *)(IMEM_headerInfo_Mode);
+    if (video->headerInfo.Mode == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+    video->headerInfo.CBP = (uint8 *)(IMEM_headerInfo_CBP);
+    if (video->headerInfo.CBP == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+    video->QPMB = (int *)(IMEM_headerInfo_QPMB);
+    if (video->QPMB == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB * sizeof(int));
+    video->mblock = &IMEM_mblock;
+    if (video->mblock == NULL) status = PV_FALSE;
+    oscl_memset(video->mblock->block, 0, sizeof(int16)*6*NCOEFF_BLOCK); //  Aug 23,2005
+
+    video->memoryUsage += sizeof(MacroBlock);
+    video->motX = (MOT *)(IMEM_motX);
+    if (video->motX == NULL) status = PV_FALSE;
+    video->motY = (MOT *)(IMEM_motY);
+    if (video->motY == NULL) status = PV_FALSE;
+    video->memoryUsage += (sizeof(MOT) * 8 * nTotalMB);
+#else
+    video->sliceNo = (uint8 *) oscl_malloc(nTotalMB);
+    if (video->sliceNo == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+
+    video->acPredFlag = (uint8 *) oscl_malloc(nTotalMB * sizeof(uint8));
+    if (video->acPredFlag == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB);
+
+    video->predDC = (typeDCStore *) oscl_malloc(nTotalMB * sizeof(typeDCStore));
+    if (video->predDC == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB * sizeof(typeDCStore));
+
+    video->predDCAC_col = (typeDCACStore *) oscl_malloc((nMBPerRow + 1) * sizeof(typeDCACStore));
+    if (video->predDCAC_col == NULL) status = PV_FALSE;
+    video->memoryUsage += ((nMBPerRow + 1) * sizeof(typeDCACStore));
+
+    /* element zero will be used for storing vertical (col) AC coefficients */
+    /*  the rest will be used for storing horizontal (row) AC coefficients  */
+    video->predDCAC_row = video->predDCAC_col + 1;        /*  ACDC */
+
+    /* Allocating HeaderInfo structure & Quantizer array */
+    video->headerInfo.Mode = (uint8 *) oscl_malloc(nTotalMB);
+    if (video->headerInfo.Mode == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+    video->headerInfo.CBP = (uint8 *) oscl_malloc(nTotalMB);
+    if (video->headerInfo.CBP == NULL) status = PV_FALSE;
+    video->memoryUsage += nTotalMB;
+    video->QPMB = (int16 *) oscl_malloc(nTotalMB * sizeof(int16));
+    if (video->QPMB == NULL) status = PV_FALSE;
+    video->memoryUsage += (nTotalMB * sizeof(int));
+
+    /* Allocating macroblock space */
+    video->mblock = (MacroBlock *) oscl_malloc(sizeof(MacroBlock));
+    if (video->mblock == NULL)
+    {
+        status = PV_FALSE;
+    }
+    else
+    {
+        oscl_memset(video->mblock->block, 0, sizeof(int16)*6*NCOEFF_BLOCK); //  Aug 23,2005
+
+        video->memoryUsage += sizeof(MacroBlock);
+    }
+    /* Allocating motion vector space */
+    video->motX = (MOT *) oscl_malloc(sizeof(MOT) * 4 * nTotalMB);
+    if (video->motX == NULL) status = PV_FALSE;
+    video->motY = (MOT *) oscl_malloc(sizeof(MOT) * 4 * nTotalMB);
+    if (video->motY == NULL) status = PV_FALSE;
+    video->memoryUsage += (sizeof(MOT) * 8 * nTotalMB);
+#endif
+
+#ifdef PV_POSTPROC_ON
+    /* Allocating space for post-processing Mode */
+#ifdef DEC_INTERNAL_MEMORY_OPT
+    video->pstprcTypCur = IMEM_pstprcTypCur;
+    video->memoryUsage += (nTotalMB * 6);
+    if (video->pstprcTypCur == NULL)
+    {
+        status = PV_FALSE;
+    }
+    else
+    {
+        oscl_memset(video->pstprcTypCur, 0, 4*nTotalMB + 2*nTotalMB);
+    }
+
+    video->pstprcTypPrv = IMEM_pstprcTypPrv;
+    video->memoryUsage += (nTotalMB * 6);
+    if (video->pstprcTypPrv == NULL)
+    {
+        status = PV_FALSE;
+    }
+    else
+    {
+        oscl_memset(video->pstprcTypPrv, 0, nTotalMB*6);
+    }
+
+#else
+    video->pstprcTypCur = (uint8 *) oscl_malloc(nTotalMB * 6);
+    video->memoryUsage += (nTotalMB * 6);
+    if (video->pstprcTypCur == NULL)
+    {
+        status = PV_FALSE;
+    }
+    else
+    {
+        oscl_memset(video->pstprcTypCur, 0, 4*nTotalMB + 2*nTotalMB);
+    }
+
+    video->pstprcTypPrv = (uint8 *) oscl_malloc(nTotalMB * 6);
+    video->memoryUsage += (nTotalMB * 6);
+    if (video->pstprcTypPrv == NULL)
+    {
+        status = PV_FALSE;
+    }
+    else
+    {
+        oscl_memset(video->pstprcTypPrv, 0, nTotalMB*6);
+    }
+
+#endif
+
+#endif
+
+    /* initialize the decoder library */
+    video->prevVop->predictionType = I_VOP;
+    video->prevVop->timeStamp = 0;
+#ifndef PV_MEMORY_POOL
+    oscl_memset(video->prevVop->yChan, 16, sizeof(uint8)*size);     /*  10/31/01 */
+    oscl_memset(video->prevVop->uChan, 128, sizeof(uint8)*size / 2);
+
+    oscl_memset(video->currVop->yChan, 0, sizeof(uint8)*size*3 / 2);
+    if (nLayers > 1)
+    {
+        oscl_memset(video->prevEnhcVop->yChan, 0, sizeof(uint8)*size*3 / 2);
+        video->prevEnhcVop->timeStamp = 0;
+    }
+    video->concealFrame = video->prevVop->yChan;               /*  07/07/2001 */
+    decCtrl->outputFrame = video->prevVop->yChan;              /*  06/19/2002 */
+#endif
+
+    /* always start from base layer */
+    video->currLayer = 0;
+    return status;
+}
+
+/* ======================================================================== */
+/*  Function : PVResetVideoDecoder()                                        */
+/*  Date     : 01/14/2002                                                   */
+/*  Purpose  : Reset video timestamps                                       */
+/*  In/out   :                                                              */
+/*  Return   : PV_TRUE if successed, PV_FALSE if failed.                    */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVResetVideoDecoder(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    int idx;
+
+    for (idx = 0; idx < decCtrl->nLayers; idx++)
+    {
+        video->vopHeader[idx]->timeStamp = 0;
+    }
+    video->prevVop->timeStamp = 0;
+    if (decCtrl->nLayers > 1)
+        video->prevEnhcVop->timeStamp = 0;
+
+    oscl_memset(video->mblock->block, 0, sizeof(int16)*6*NCOEFF_BLOCK); //  Aug 23,2005
+
+    return PV_TRUE;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVCleanUpVideoDecoder()                                      */
+/*  Date     : 04/11/2000, 08/29/2000                                       */
+/*  Purpose  : Cleanup of the MPEG-4 video decoder library.                 */
+/*  In/out   :                                                              */
+/*  Return   : PV_TRUE if successed, PV_FALSE if failed.                    */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF Bool PVCleanUpVideoDecoder(VideoDecControls *decCtrl)
+{
+    int idx;
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+#ifdef DEC_INTERNAL_MEMORY_OPT
+    if (video)
+    {
+#ifdef PV_POSTPROC_ON
+        video->pstprcTypCur = NULL;
+        video->pstprcTypPrv = NULL;
+#endif
+
+        video->acPredFlag       = NULL;
+        video->sliceNo          = NULL;
+        video->motX             = NULL;
+        video->motY             = NULL;
+        video->mblock           = NULL;
+        video->QPMB             = NULL;
+        video->predDC           = NULL;
+        video->predDCAC_row     = NULL;
+        video->predDCAC_col     = NULL;
+        video->headerInfo.Mode  = NULL;
+        video->headerInfo.CBP   = NULL;
+        if (video->numberOfLayers > 1)
+        {
+            if (video->prevEnhcVop)
+            {
+                video->prevEnhcVop->uChan = NULL;
+                video->prevEnhcVop->vChan = NULL;
+                if (video->prevEnhcVop->yChan) oscl_free(video->prevEnhcVop->yChan);
+                oscl_free(video->prevEnhcVop);
+            }
+        }
+        if (video->currVop)
+        {
+            video->currVop->uChan = NULL;
+            video->currVop->vChan = NULL;
+            if (video->currVop->yChan)
+                video->currVop->yChan = NULL;
+            video->currVop = NULL;
+        }
+        if (video->prevVop)
+        {
+            video->prevVop->uChan = NULL;
+            video->prevVop->vChan = NULL;
+            if (video->prevVop->yChan)
+                video->prevVop->yChan = NULL;
+            video->prevVop = NULL;
+        }
+
+        if (video->vol)
+        {
+            for (idx = 0; idx < video->numberOfLayers; idx++)
+            {
+                if (video->vol[idx])
+                {
+                    BitstreamClose(video->vol[idx]->bitstream);
+                    video->vol[idx]->bitstream = NULL;
+                    video->vol[idx] = NULL;
+                }
+                video->vopHeader[idx] = NULL;
+
+            }
+            video->vol = NULL;
+            video->vopHeader = NULL;
+        }
+
+        video = NULL;
+        decCtrl->videoDecoderData = NULL;
+    }
+
+#else
+
+    if (video)
+    {
+#ifdef PV_POSTPROC_ON
+        if (video->pstprcTypCur) oscl_free(video->pstprcTypCur);
+        if (video->pstprcTypPrv) oscl_free(video->pstprcTypPrv);
+#endif
+        if (video->predDC) oscl_free(video->predDC);
+        video->predDCAC_row = NULL;
+        if (video->predDCAC_col) oscl_free(video->predDCAC_col);
+        if (video->motX) oscl_free(video->motX);
+        if (video->motY) oscl_free(video->motY);
+        if (video->mblock) oscl_free(video->mblock);
+        if (video->QPMB) oscl_free(video->QPMB);
+        if (video->headerInfo.Mode) oscl_free(video->headerInfo.Mode);
+        if (video->headerInfo.CBP) oscl_free(video->headerInfo.CBP);
+        if (video->sliceNo) oscl_free(video->sliceNo);
+        if (video->acPredFlag) oscl_free(video->acPredFlag);
+
+        if (video->numberOfLayers > 1)
+        {
+            if (video->prevEnhcVop)
+            {
+                video->prevEnhcVop->uChan = NULL;
+                video->prevEnhcVop->vChan = NULL;
+                if (video->prevEnhcVop->yChan) oscl_free(video->prevEnhcVop->yChan);
+                oscl_free(video->prevEnhcVop);
+            }
+        }
+        if (video->currVop)
+        {
+
+#ifndef PV_MEMORY_POOL
+            video->currVop->uChan = NULL;
+            video->currVop->vChan = NULL;
+            if (video->currVop->yChan)
+                oscl_free(video->currVop->yChan);
+#endif
+            oscl_free(video->currVop);
+        }
+        if (video->prevVop)
+        {
+#ifndef PV_MEMORY_POOL
+            video->prevVop->uChan = NULL;
+            video->prevVop->vChan = NULL;
+            if (video->prevVop->yChan)
+                oscl_free(video->prevVop->yChan);
+#endif
+            oscl_free(video->prevVop);
+        }
+
+        if (video->vol)
+        {
+            for (idx = 0; idx < video->numberOfLayers; idx++)
+            {
+                if (video->vol[idx])
+                {
+                    if (video->vol[idx]->bitstream)
+                    {
+                        BitstreamClose(video->vol[idx]->bitstream);
+                        oscl_free(video->vol[idx]->bitstream);
+                    }
+                    oscl_free(video->vol[idx]);
+                }
+
+            }
+            oscl_free(video->vol);
+        }
+
+        for (idx = 0; idx < video->numberOfLayers; idx++)
+        {
+            if (video->vopHeader[idx]) oscl_free(video->vopHeader[idx]);
+        }
+
+        if (video->vopHeader) oscl_free(video->vopHeader);
+
+        oscl_free(video);
+        decCtrl->videoDecoderData = NULL;
+    }
+#endif
+    return PV_TRUE;
+}
+/* ======================================================================== */
+/*  Function : PVGetVideoDimensions()                                       */
+/*  Date     : 040505                                                       */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : the display_width and display_height of                      */
+/*          the frame in the current layer.                                 */
+/*  Note     : This is not a macro or inline function because we do         */
+/*              not want to expose our internal data structure.             */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF void PVGetVideoDimensions(VideoDecControls *decCtrl, int32 *display_width, int32 *display_height)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    *display_width = video->displayWidth;
+    *display_height = video->displayHeight;
+}
+
+/* ======================================================================== */
+/*  Function : PVGetVideoTimeStamp()                                        */
+/*  Date     : 04/27/2000, 08/29/2000                                       */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : current time stamp in millisecond.                           */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+uint32 PVGetVideoTimeStamp(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    return video->currTimestamp;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVSetPostProcType()                                          */
+/*  Date     : 07/07/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : Set post-processing filter type.                             */
+/*  Note     :                                                              */
+/*  Modified : . 08/29/2000 changes the name for consistency.               */
+/* ======================================================================== */
+OSCL_EXPORT_REF void PVSetPostProcType(VideoDecControls *decCtrl, int mode)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    video->postFilterType = mode;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVGetDecBitrate()                                            */
+/*  Date     : 08/23/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns the average bits per second.           */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int PVGetDecBitrate(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    int     idx;
+    int32   sum = 0;
+
+    for (idx = 0; idx < BITRATE_AVERAGE_WINDOW; idx++)
+    {
+        sum += video->nBitsPerVop[idx];
+    }
+    sum = (sum * video->frameRate) / (10 * BITRATE_AVERAGE_WINDOW);
+    return (int) sum;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVGetDecFramerate()                                          */
+/*  Date     : 08/23/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns the average frame per 10 second.       */
+/*  Note     : The fps can be calculated by PVGetDecFramerate()/10          */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int PVGetDecFramerate(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+
+    return video->frameRate;
+}
+
+/* ======================================================================== */
+/*  Function : PVGetOutputFrame()                                           */
+/*  Date     : 05/07/2001                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns the pointer to the output frame        */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+uint8 *PVGetDecOutputFrame(VideoDecControls *decCtrl)
+{
+    return decCtrl->outputFrame;
+}
+
+/* ======================================================================== */
+/*  Function : PVGetLayerID()                                               */
+/*  Date     : 07/09/2001                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns decoded frame layer id (BASE/ENHANCE)  */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int PVGetLayerID(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    return video->currLayer;
+}
+/* ======================================================================== */
+/*  Function : PVGetDecMemoryUsage()                                        */
+/*  Date     : 08/23/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns the amount of memory used.             */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int32 PVGetDecMemoryUsage(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    return video->memoryUsage;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVGetDecBitstreamMode()                                      */
+/*  Date     : 08/23/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function returns the decoding mode of the baselayer     */
+/*              bitstream.                                                  */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+OSCL_EXPORT_REF MP4DecodingMode PVGetDecBitstreamMode(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    if (video->shortVideoHeader)
+    {
+        return H263_MODE;
+    }
+    else
+    {
+        return MPEG4_MODE;
+    }
+}
+
+
+/* ======================================================================== */
+/*  Function : PVExtractVolHeader()                                         */
+/*  Date     : 08/29/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : Extract vol header of the bitstream from buffer[].           */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVExtractVolHeader(uint8 *video_buffer, uint8 *vol_header, int32 *vol_header_size)
+{
+    int idx = -1;
+    uint8 start_code_prefix[] = { 0x00, 0x00, 0x01 };
+    uint8 h263_prefix[] = { 0x00, 0x00, 0x80 };
+
+    if (oscl_memcmp(h263_prefix, video_buffer, 3) == 0) /* we have short header stream */
+    {
+        oscl_memcpy(vol_header, video_buffer, 32);
+        *vol_header_size = 32;
+        return TRUE;
+    }
+    else
+    {
+        if (oscl_memcmp(start_code_prefix, video_buffer, 3) ||
+                (video_buffer[3] != 0xb0 && video_buffer[3] >= 0x20)) return FALSE;
+
+        do
+        {
+            idx++;
+            while (oscl_memcmp(start_code_prefix, video_buffer + idx, 3))
+            {
+                idx++;
+                if (idx + 3 >= *vol_header_size) goto quit;
+            }
+        }
+        while (video_buffer[idx+3] != 0xb3 && video_buffer[idx+3] != 0xb6);
+
+        oscl_memcpy(vol_header, video_buffer, idx);
+        *vol_header_size = idx;
+        return TRUE;
+    }
+
+quit:
+    oscl_memcpy(vol_header, video_buffer, *vol_header_size);
+    return FALSE;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVLocateFrameHeader()                                        */
+/*  Date     : 04/8/2005                                                    */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : Return the offset to the first SC in the buffer              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int32 PVLocateFrameHeader(uint8 *ptr, int32 size)
+{
+    int count = 0;
+    int32 i = size;
+
+    if (size < 1)
+    {
+        return 0;
+    }
+    while (i--)
+    {
+        if ((count > 1) && (*ptr == 0x01))
+        {
+            i += 2;
+            break;
+        }
+
+        if (*ptr++)
+            count = 0;
+        else
+            count++;
+    }
+    return (size - (i + 1));
+}
+
+
+/* ======================================================================== */
+/*  Function : PVLocateH263FrameHeader()                                    */
+/*  Date     : 04/8/2005                                                    */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : Return the offset to the first SC in the buffer              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int32 PVLocateH263FrameHeader(uint8 *ptr, int32 size)
+{
+    int count = 0;
+    int32 i = size;
+
+    if (size < 1)
+    {
+        return 0;
+    }
+
+    while (i--)
+    {
+        if ((count > 1) && ((*ptr & 0xFC) == 0x80))
+        {
+            i += 2;
+            break;
+        }
+
+        if (*ptr++)
+            count = 0;
+        else
+            count++;
+    }
+    return (size - (i + 1));
+}
+
+
+/* ======================================================================== */
+/*  Function : PVDecodeVideoFrame()                                         */
+/*  Date     : 08/29/2000                                                   */
+/*  Purpose  : Decode one video frame and return a YUV-12 image.            */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified : 04/17/2001 removed PV_EOS, PV_END_OF_BUFFER              */
+/*           : 08/22/2002 break up into 2 functions PVDecodeVopHeader and */
+/*                          PVDecodeVopBody                                 */
+/* ======================================================================== */
+OSCL_EXPORT_REF Bool PVDecodeVideoFrame(VideoDecControls *decCtrl, uint8 *buffer[],
+                                        uint32 timestamp[], int32 buffer_size[], uint use_ext_timestamp[], uint8 *currYUV)
+{
+    PV_STATUS status = PV_FAIL;
+    VopHeaderInfo header_info;
+
+    status = (PV_STATUS)PVDecodeVopHeader(decCtrl, buffer, timestamp, buffer_size, &header_info, use_ext_timestamp, currYUV);
+    if (status != PV_TRUE)
+        return PV_FALSE;
+
+    if (PVDecodeVopBody(decCtrl, buffer_size) != PV_TRUE)
+    {
+        return PV_FALSE;
+    }
+
+    return PV_TRUE;
+}
+
+/* ======================================================================== */
+/*  Function : PVDecodeVopHeader()                                          */
+/*  Date     : 08/22/2002                                                   */
+/*  Purpose  : Determine target layer and decode vop header, modified from  */
+/*              original PVDecodeVideoFrame.                                */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVDecodeVopHeader(VideoDecControls *decCtrl, uint8 *buffer[],
+                       uint32 timestamp[], int32 buffer_size[], VopHeaderInfo *header_info, uint use_ext_timestamp [], uint8 *currYUV)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    Vol *currVol;
+    Vop *currVop = video->currVop;
+    Vop **vopHeader = video->vopHeader;
+    BitstreamDecVideo *stream;
+
+    int target_layer;
+
+#ifdef PV_SUPPORT_TEMPORAL_SCALABILITY
+    PV_STATUS status = PV_FAIL;
+    int idx;
+    int32 display_time;
+
+    /* decide which frame to decode next */
+    if (decCtrl->nLayers > 1)
+    {
+        display_time = target_layer = -1;
+        for (idx = 0; idx < decCtrl->nLayers; idx++)
+        {
+            /* do we have data for this layer? */
+            if (buffer_size[idx] <= 0)
+            {
+                timestamp[idx] = -1;
+                continue;
+            }
+
+            /* did the application provide a timestamp for this vop? */
+            if (timestamp[idx] < 0)
+            {
+                if (vopHeader[idx]->timeStamp < 0)
+                {
+                    /* decode the timestamp in the bitstream */
+                    video->currLayer = idx;
+                    stream = video->vol[idx]->bitstream;
+                    BitstreamReset(stream, buffer[idx], buffer_size[idx]);
+
+                    while ((status = DecodeVOPHeader(video, vopHeader[idx], FALSE)) != PV_SUCCESS)
+                    {
+                        /* Try to find a VOP header in the buffer.   08/30/2000. */
+                        if (PVSearchNextM4VFrame(stream) != PV_SUCCESS)
+                        {
+                            /* if we don't have data for enhancement layer, */
+                            /*    don't just stop.   09/07/2000.          */
+                            buffer_size[idx] = 0;
+                            break;
+                        }
+                    }
+                    if (status == PV_SUCCESS)
+                    {
+                        vopHeader[idx]->timeStamp =
+                            timestamp[idx] = CalcVopDisplayTime(video->vol[idx], vopHeader[idx], video->shortVideoHeader);
+                        if (idx == 0) vopHeader[idx]->refSelectCode = 1;
+                    }
+                }
+                else
+                {
+                    /* We've decoded this vop header in the previous run already. */
+                    timestamp[idx] = vopHeader[idx]->timeStamp;
+                }
+            }
+
+            /* Use timestamps to select the next VOP to be decoded */
+            if (timestamp[idx] >= 0 && (display_time < 0 || display_time > timestamp[idx]))
+            {
+                display_time = timestamp[idx];
+                target_layer = idx;
+            }
+            else if (display_time == timestamp[idx])
+            {
+                /* we have to handle either SNR or spatial scalability here. */
+            }
+        }
+        if (target_layer < 0) return PV_FALSE;
+
+        /* set up for decoding the target layer */
+        video->currLayer = target_layer;
+        currVol = video->vol[target_layer];
+        video->bitstream = stream = currVol->bitstream;
+
+        /* We need to decode the vop header if external timestamp   */
+        /*    is provided.    10/04/2000                            */
+        if (vopHeader[target_layer]->timeStamp < 0)
+        {
+            stream = video->vol[target_layer]->bitstream;
+            BitstreamReset(stream, buffer[target_layer], buffer_size[target_layer]);
+
+            while (DecodeVOPHeader(video, vopHeader[target_layer], TRUE) != PV_SUCCESS)
+            {
+                /* Try to find a VOP header in the buffer.   08/30/2000. */
+                if (PVSearchNextM4VFrame(stream) != PV_SUCCESS)
+                {
+                    /* if we don't have data for enhancement layer, */
+                    /*    don't just stop.   09/07/2000.          */
+                    buffer_size[target_layer] = 0;
+                    break;
+                }
+            }
+            video->vol[target_layer]->timeInc_offset = vopHeader[target_layer]->timeInc;
+            video->vol[target_layer]->moduloTimeBase = timestamp[target_layer];
+            vopHeader[target_layer]->timeStamp = timestamp[target_layer];
+            if (target_layer == 0) vopHeader[target_layer]->refSelectCode = 1;
+        }
+    }
+    else /* base layer only decoding */
+    {
+#endif
+        video->currLayer = target_layer = 0;
+        currVol = video->vol[0];
+        video->bitstream = stream = currVol->bitstream;
+        if (buffer_size[0] <= 0) return PV_FALSE;
+        BitstreamReset(stream, buffer[0], buffer_size[0]);
+
+        if (video->shortVideoHeader)
+        {
+            while (DecodeShortHeader(video, vopHeader[0]) != PV_SUCCESS)
+            {
+                if (PVSearchNextH263Frame(stream) != PV_SUCCESS)
+                {
+                    /* There is no vop header in the buffer,    */
+                    /*   clean bitstream buffer.     2/5/2001   */
+                    buffer_size[0] = 0;
+                    if (video->initialized == PV_FALSE)
+                    {
+                        video->displayWidth = video->width = 0;
+                        video->displayHeight = video->height = 0;
+                    }
+                    return PV_FALSE;
+                }
+            }
+
+            if (use_ext_timestamp[0])
+            {
+                /* MTB for H263 is absolute TR */
+                /* following line is equivalent to  round((timestamp[0]*30)/1001);   11/13/2001 */
+                video->vol[0]->moduloTimeBase = 30 * ((timestamp[0] + 17) / 1001) + (30 * ((timestamp[0] + 17) % 1001) / 1001);
+                vopHeader[0]->timeStamp = timestamp[0];
+            }
+            else
+                vopHeader[0]->timeStamp = CalcVopDisplayTime(currVol, vopHeader[0], video->shortVideoHeader);
+        }
+        else
+        {
+            while (DecodeVOPHeader(video, vopHeader[0], FALSE) != PV_SUCCESS)
+            {
+                /* Try to find a VOP header in the buffer.   08/30/2000. */
+                if (PVSearchNextM4VFrame(stream) != PV_SUCCESS)
+                {
+                    /* There is no vop header in the buffer,    */
+                    /*   clean bitstream buffer.     2/5/2001   */
+                    buffer_size[0] = 0;
+                    return PV_FALSE;
+                }
+            }
+
+            if (use_ext_timestamp[0])
+            {
+                video->vol[0]->timeInc_offset = vopHeader[0]->timeInc;
+                video->vol[0]->moduloTimeBase = timestamp[0];  /*  11/12/2001 */
+                vopHeader[0]->timeStamp = timestamp[0];
+            }
+            else
+            {
+                vopHeader[0]->timeStamp = CalcVopDisplayTime(currVol, vopHeader[0], video->shortVideoHeader);
+            }
+        }
+
+        /* set up some base-layer only parameters */
+        vopHeader[0]->refSelectCode = 1;
+#ifdef PV_SUPPORT_TEMPORAL_SCALABILITY
+    }
+#endif
+    timestamp[target_layer] = video->currTimestamp = vopHeader[target_layer]->timeStamp;
+#ifdef PV_MEMORY_POOL
+    vopHeader[target_layer]->yChan = (PIXEL *)currYUV;
+    vopHeader[target_layer]->uChan = (PIXEL *)currYUV + decCtrl->size;
+    vopHeader[target_layer]->vChan = (PIXEL *)(vopHeader[target_layer]->uChan) + (decCtrl->size >> 2);
+#else
+    vopHeader[target_layer]->yChan = currVop->yChan;
+    vopHeader[target_layer]->uChan = currVop->uChan;
+    vopHeader[target_layer]->vChan = currVop->vChan;
+#endif
+    oscl_memcpy(currVop, vopHeader[target_layer], sizeof(Vop));
+
+#ifdef PV_SUPPORT_TEMPORAL_SCALABILITY
+    vopHeader[target_layer]->timeStamp = -1;
+#endif
+    /* put header info into the structure */
+    header_info->currLayer = target_layer;
+    header_info->timestamp = video->currTimestamp;
+    header_info->frameType = (MP4FrameType)currVop->predictionType;
+    header_info->refSelCode = vopHeader[target_layer]->refSelectCode;
+    header_info->quantizer = currVop->quantizer;
+    /***************************************/
+
+    return PV_TRUE;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVDecodeVopBody()                                            */
+/*  Date     : 08/22/2002                                                   */
+/*  Purpose  : Decode vop body after the header is decoded, modified from   */
+/*              original PVDecodeVideoFrame.                                */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVDecodeVopBody(VideoDecControls *decCtrl, int32 buffer_size[])
+{
+    PV_STATUS status = PV_FAIL;
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    int target_layer = video->currLayer;
+    Vol *currVol = video->vol[target_layer];
+    Vop *currVop = video->currVop;
+    Vop *prevVop = video->prevVop;
+    Vop *tempVopPtr;
+    int bytes_consumed = 0; /* Record how many bits we used in the buffer.   04/24/2001 */
+
+    int idx;
+
+    if (currVop->vopCoded == 0)                  /*  07/03/2001 */
+    {
+        PV_BitstreamByteAlign(currVol->bitstream);
+        /* We should always clear up bitstream buffer.   10/10/2000 */
+        bytes_consumed = (getPointer(currVol->bitstream) + 7) >> 3;
+
+        if (bytes_consumed > currVol->bitstream->data_end_pos)
+        {
+            bytes_consumed = currVol->bitstream->data_end_pos;
+        }
+
+        if (bytes_consumed < buffer_size[target_layer])
+        {
+            /* If we only consume part of the bits in the buffer, take those */
+            /*  out.     04/24/2001 */
+            /*          oscl_memcpy(buffer[target_layer], buffer[target_layer]+bytes_consumed,
+                            (buffer_size[target_layer]-=bytes_consumed)); */
+            buffer_size[target_layer] -= bytes_consumed;
+        }
+        else
+        {
+            buffer_size[target_layer] = 0;
+        }
+#ifdef PV_MEMORY_POOL
+
+        if (target_layer)
+        {
+            if (video->prevEnhcVop->timeStamp > video->prevVop->timeStamp)
+            {
+                video->prevVop = video->prevEnhcVop;
+            }
+        }
+
+        oscl_memcpy(currVop->yChan, video->prevVop->yChan, (decCtrl->size*3) / 2);
+
+        video->prevVop = prevVop;
+
+        video->concealFrame = currVop->yChan;       /*  07/07/2001 */
+
+        video->vop_coding_type = currVop->predictionType; /*  07/09/01 */
+
+        decCtrl->outputFrame = currVop->yChan;
+
+        /* Swap VOP pointers.  No enhc. frame oscl_memcpy() anymore!   04/24/2001 */
+        if (target_layer)
+        {
+            tempVopPtr = video->prevEnhcVop;
+            video->prevEnhcVop = video->currVop;
+            video->currVop = tempVopPtr;
+        }
+        else
+        {
+            tempVopPtr = video->prevVop;
+            video->prevVop = video->currVop;
+            video->currVop = tempVopPtr;
+        }
+#else
+        if (target_layer)       /* this is necessary to avoid flashback problems   06/21/2002*/
+        {
+            video->prevEnhcVop->timeStamp = currVop->timeStamp;
+        }
+        else
+        {
+            video->prevVop->timeStamp = currVop->timeStamp;
+        }
+#endif
+        video->vop_coding_type = currVop->predictionType; /*  07/09/01 */
+        /* the following is necessary to avoid displaying an notCoded I-VOP at the beginning of a session
+        or after random positioning  07/03/02*/
+        if (currVop->predictionType == I_VOP)
+        {
+            video->vop_coding_type = P_VOP;
+        }
+
+
+        return PV_TRUE;
+    }
+    /* ======================================================= */
+    /*  Decode vop body (if there is no error in the header!)  */
+    /* ======================================================= */
+
+    /* first, we need to select a reference frame */
+    if (decCtrl->nLayers > 1)
+    {
+        if (currVop->predictionType == I_VOP)
+        {
+            /* do nothing here */
+        }
+        else if (currVop->predictionType == P_VOP)
+        {
+            switch (currVop->refSelectCode)
+            {
+                case 0 : /* most recently decoded enhancement vop */
+                    /* Setup video->prevVop before we call PV_DecodeVop().   04/24/2001 */
+                    if (video->prevEnhcVop->timeStamp >= video->prevVop->timeStamp)
+                        video->prevVop = video->prevEnhcVop;
+                    break;
+
+                case 1 : /* most recently displayed base-layer vop */
+                    if (target_layer)
+                    {
+                        if (video->prevEnhcVop->timeStamp > video->prevVop->timeStamp)
+                            video->prevVop = video->prevEnhcVop;
+                    }
+                    break;
+
+                case 2 : /* next base-layer vop in display order */
+                    break;
+
+                case 3 : /* temporally coincident base-layer vop (no MV's) */
+                    break;
+            }
+        }
+        else /* we have a B-Vop */
+        {
+            mp4dec_log("DecodeVideoFrame(): B-VOP not supported.\n");
+        }
+    }
+
+    /* This is for the calculation of the frame rate and bitrate. */
+    idx = ++video->frame_idx % BITRATE_AVERAGE_WINDOW;
+
+    /* Calculate bitrate for this layer.   08/23/2000 */
+    status = PV_DecodeVop(video);
+    video->nBitsPerVop[idx] = getPointer(currVol->bitstream);
+    video->prevTimestamp[idx] = currVop->timeStamp;
+
+    /* restore video->prevVop after PV_DecodeVop().   04/24/2001 */
+//  if (currVop->refSelectCode == 0) video->prevVop = prevVop;
+    video->prevVop = prevVop;
+
+    /* Estimate the frame rate.   08/23/2000 */
+    video->duration = video->prevTimestamp[idx];
+    video->duration -= video->prevTimestamp[(++idx)%BITRATE_AVERAGE_WINDOW];
+    if (video->duration > 0)
+    { /* Only update framerate when the timestamp is right */
+        video->frameRate = (int)(FRAMERATE_SCALE) / video->duration;
+    }
+
+    /* We should always clear up bitstream buffer.   10/10/2000 */
+    bytes_consumed = (getPointer(currVol->bitstream) + 7) >> 3; /*  11/4/03 */
+
+    if (bytes_consumed > currVol->bitstream->data_end_pos)
+    {
+        bytes_consumed = currVol->bitstream->data_end_pos;
+    }
+
+    if (bytes_consumed < buffer_size[target_layer])
+    {
+        /* If we only consume part of the bits in the buffer, take those */
+        /*  out.     04/24/2001 */
+        /*      oscl_memcpy(buffer[target_layer], buffer[target_layer]+bytes_consumed,
+                    (buffer_size[target_layer]-=bytes_consumed)); */
+        buffer_size[target_layer] -= bytes_consumed;
+    }
+    else
+    {
+        buffer_size[target_layer] = 0;
+    }
+    switch (status)
+    {
+        case PV_FAIL :
+            return PV_FALSE;        /* this will take care of concealment if we lose whole frame  */
+
+        case PV_END_OF_VOP :
+            /* we may want to differenciate PV_END_OF_VOP and PV_SUCCESS */
+            /*    in the future.     05/10/2000                      */
+
+        case PV_SUCCESS :
+            /* Nohting is wrong :). */
+
+
+            video->concealFrame = video->currVop->yChan;       /*  07/07/2001 */
+
+            video->vop_coding_type = video->currVop->predictionType; /*  07/09/01 */
+
+            decCtrl->outputFrame = video->currVop->yChan;
+
+            /* Swap VOP pointers.  No enhc. frame oscl_memcpy() anymore!   04/24/2001 */
+            if (target_layer)
+            {
+                tempVopPtr = video->prevEnhcVop;
+                video->prevEnhcVop = video->currVop;
+                video->currVop = tempVopPtr;
+            }
+            else
+            {
+                tempVopPtr = video->prevVop;
+                video->prevVop = video->currVop;
+                video->currVop = tempVopPtr;
+            }
+            break;
+
+        default :
+            /* This will never happen */
+            break;
+    }
+
+    return PV_TRUE;
+}
+
+#ifdef PV_MEMORY_POOL
+OSCL_EXPORT_REF void PVSetReferenceYUV(VideoDecControls *decCtrl, uint8 *YUV)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    video->prevVop->yChan = (PIXEL *)YUV;
+    video->prevVop->uChan = (PIXEL *)YUV + video->size;
+    video->prevVop->vChan = (PIXEL *)video->prevVop->uChan + (decCtrl->size >> 2);
+    oscl_memset(video->prevVop->yChan, 16, sizeof(uint8)*decCtrl->size);     /*  10/31/01 */
+    oscl_memset(video->prevVop->uChan, 128, sizeof(uint8)*decCtrl->size / 2);
+    video->concealFrame = video->prevVop->yChan;               /*  07/07/2001 */
+    decCtrl->outputFrame = video->prevVop->yChan;              /*  06/19/2002 */
+}
+#endif
+
+
+/* ======================================================================== */
+/*  Function : VideoDecoderErrorDetected()                                  */
+/*  Date     : 06/20/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : This function will be called everytime an error int the      */
+/*              bitstream is detected.                                      */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+uint VideoDecoderErrorDetected(VideoDecData *)
+{
+    /* This is only used for trapping bitstream error for debuging */
+    return 0;
+}
+
+#ifdef ENABLE_LOG
+#include <stdio.h>
+#include <stdarg.h>
+/* ======================================================================== */
+/*  Function : m4vdec_dprintf()                                             */
+/*  Date     : 08/15/2000                                                   */
+/*  Purpose  : This is a function that logs messages in the mpeg4 video     */
+/*             decoder.  We can call the standard PacketVideo PVMessage     */
+/*             from inside this function if necessary.                      */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     : To turn on the logging, LOG_MP4DEC_MESSAGE must be defined   */
+/*              when compiling this file (only this file).                  */
+/*  Modified :                                                              */
+/* ======================================================================== */
+void m4vdec_dprintf(char *format, ...)
+{
+    FILE *log_fp;
+    va_list args;
+    va_start(args, format);
+
+    /* open the log file */
+    log_fp = fopen("\\mp4dec_log.txt", "a+");
+    if (log_fp == NULL) return;
+    /* output the message */
+    vfprintf(log_fp, format, args);
+    fclose(log_fp);
+
+    va_end(args);
+}
+#endif
+
+
+/* ======================================================================== */
+/*  Function : IsIntraFrame()                                               */
+/*  Date     : 05/29/2000                                                   */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : The most recently decoded frame is an Intra frame.           */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool IsIntraFrame(VideoDecControls *decCtrl)
+{
+    VideoDecData *video = (VideoDecData *)decCtrl->videoDecoderData;
+    return (video->vop_coding_type == I_VOP);
+}
+
+/* ======================================================================== */
+/*  Function : PVDecPostProcess()                                           */
+/*  Date     : 01/09/2002                                                   */
+/*  Purpose  : PostProcess one video frame and return a YUV-12 image.       */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+void PVDecPostProcess(VideoDecControls *decCtrl, uint8 *outputYUV)
+{
+    uint8 *outputBuffer;
+#ifdef PV_POSTPROC_ON
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    int32 tmpvar;
+    if (outputYUV)
+    {
+        outputBuffer = outputYUV;
+    }
+    else
+    {
+        if (video->postFilterType)
+        {
+            outputBuffer = video->currVop->yChan;
+        }
+        else
+        {
+            outputBuffer = decCtrl->outputFrame;
+        }
+    }
+
+    if (video->postFilterType)
+    {
+        /* Post-processing,  */
+        PostFilter(video, video->postFilterType, outputBuffer);
+    }
+    else
+    {
+        if (outputYUV)
+        {
+            /* Copy decoded frame to the output buffer. */
+            tmpvar = (int32)video->width * video->height;
+            oscl_memcpy(outputBuffer, decCtrl->outputFrame, tmpvar*3 / 2);           /*  3/3/01 */
+        }
+    }
+#else
+    outputBuffer = decCtrl->outputFrame;
+    outputYUV;
+#endif
+    decCtrl->outputFrame = outputBuffer;
+    return;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVDecSetReference(VideoDecControls *decCtrl, uint8 *refYUV,  */
+/*                              int32 timestamp)                            */
+/*  Date     : 07/22/2003                                                   */
+/*  Purpose  : Get YUV reference frame from external source.                */
+/*  In/out   : YUV 4-2-0 frame containing new reference frame in the same   */
+/*   : dimension as original, i.e., doesn't have to be multiple of 16 !!!.  */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVDecSetReference(VideoDecControls *decCtrl, uint8 *refYUV, uint32 timestamp)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    Vop *prevVop = video->prevVop;
+    int width = video->width;
+    uint8 *dstPtr, *orgPtr, *dstPtr2, *orgPtr2;
+    int32 size = (int32)width * video->height;
+
+
+    /* set new parameters */
+    prevVop->timeStamp = timestamp;
+    prevVop->predictionType = I_VOP;
+
+    dstPtr = prevVop->yChan;
+    orgPtr = refYUV;
+    oscl_memcpy(dstPtr, orgPtr, size);
+    dstPtr = prevVop->uChan;
+    dstPtr2 = prevVop->vChan;
+    orgPtr = refYUV + size;
+    orgPtr2 = orgPtr + (size >> 2);
+    oscl_memcpy(dstPtr, orgPtr, (size >> 2));
+    oscl_memcpy(dstPtr2, orgPtr2, (size >> 2));
+
+    video->concealFrame = video->prevVop->yChan;
+    video->vop_coding_type = I_VOP;
+    decCtrl->outputFrame = video->prevVop->yChan;
+
+    return PV_TRUE;
+}
+
+/* ======================================================================== */
+/*  Function : PVDecSetEnhReference(VideoDecControls *decCtrl, uint8 *refYUV,   */
+/*                              int32 timestamp)                            */
+/*  Date     : 07/23/2003                                                   */
+/*  Purpose  : Get YUV enhance reference frame from external source.        */
+/*  In/out   : YUV 4-2-0 frame containing new reference frame in the same   */
+/*   : dimension as original, i.e., doesn't have to be multiple of 16 !!!.  */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified :                                                              */
+/* ======================================================================== */
+Bool PVDecSetEnhReference(VideoDecControls *decCtrl, uint8 *refYUV, uint32 timestamp)
+{
+    VideoDecData *video = (VideoDecData *) decCtrl->videoDecoderData;
+    Vop *prevEnhcVop = video->prevEnhcVop;
+    uint8 *dstPtr, *orgPtr, *dstPtr2, *orgPtr2;
+    int32 size = (int32) video->width * video->height;
+
+    if (video->numberOfLayers <= 1)
+        return PV_FALSE;
+
+
+    /* set new parameters */
+    prevEnhcVop->timeStamp = timestamp;
+    prevEnhcVop->predictionType = I_VOP;
+
+    dstPtr = prevEnhcVop->yChan;
+    orgPtr = refYUV;
+    oscl_memcpy(dstPtr, orgPtr, size);
+    dstPtr = prevEnhcVop->uChan;
+    dstPtr2 = prevEnhcVop->vChan;
+    orgPtr = refYUV + size;
+    orgPtr2 = orgPtr + (size >> 2);
+    oscl_memcpy(dstPtr, orgPtr, (size >> 2));
+    oscl_memcpy(dstPtr2, orgPtr2, (size >> 2));
+    video->concealFrame = video->prevEnhcVop->yChan;
+    video->vop_coding_type = I_VOP;
+    decCtrl->outputFrame = video->prevEnhcVop->yChan;
+
+    return PV_TRUE;
+}
+
+
+/* ======================================================================== */
+/*  Function : PVGetVolInfo()                                               */
+/*  Date     : 08/06/2003                                                   */
+/*  Purpose  : Get the vol info(only base-layer).                           */
+/*  In/out   :                                                              */
+/*  Return   :                                                              */
+/*  Note     :                                                              */
+/*  Modified : 06/24/2004                                                   */
+/* ======================================================================== */
+Bool PVGetVolInfo(VideoDecControls *decCtrl, VolInfo *pVolInfo)
+{
+    Vol *currVol;
+
+    if (pVolInfo == NULL || decCtrl == NULL || decCtrl->videoDecoderData == NULL ||
+            ((VideoDecData *)decCtrl->videoDecoderData)->vol[0] == NULL) return PV_FALSE;
+
+    currVol = ((VideoDecData *)(decCtrl->videoDecoderData))->vol[0];
+
+    // get the VOL info
+    pVolInfo->shortVideoHeader = (int32)((VideoDecData *)(decCtrl->videoDecoderData))->shortVideoHeader;
+    pVolInfo->dataPartitioning = (int32)currVol->dataPartitioning;
+    pVolInfo->errorResDisable  = (int32)currVol->errorResDisable;
+    pVolInfo->useReverseVLC    = (int32)currVol->useReverseVLC;
+    pVolInfo->scalability      = (int32)currVol->scalability;
+    pVolInfo->nbitsTimeIncRes  = (int32)currVol->nbitsTimeIncRes;
+    pVolInfo->profile_level_id = (int32)currVol->profile_level_id;
+
+    return PV_TRUE;
+}
+
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/scaling.h b/media/libstagefright/codecs/m4v_h263/dec/src/scaling.h
new file mode 100644
index 0000000..26abbae
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/scaling.h
@@ -0,0 +1,52 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    extern const int32 scale[63];
+
+#define PV_GET_ROW(a,b) ((a) / (b))
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+}
+#endif
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/scaling_tab.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/scaling_tab.cpp
new file mode 100644
index 0000000..a1f95aa
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/scaling_tab.cpp
@@ -0,0 +1,88 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include    "mp4dec_api.h"
+#include    "mp4def.h"
+#include    "scaling.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
+----------------------------------------------------------------------------*/
+
+/* this scaling can be used for dividing values up to 3292             07/10/01 */
+const int32 scale[63] = {0, 262145, 131073, 87382, 65537, 52430, 43692, 37450, 32769, 29128,
+                         26215, 23832, 21846, 20166, 18726, 17477, 16385, 15421, 14565, 13798,
+                         13108, 12484, 11917, 11399, 10924, 10487, 10083, 9710, 9363, 9040,
+                         8739, 8457, 8193, 7945, 7711, 7491, 7283, 7086, 6900, 6723, 6555, 6395,
+                         6243, 6097, 5959, 5826, 5700, 5579, 5462, 5351, 5244, 5141, 5042, 4947, 4856,
+                         4767, 4682, 4600, 4521, 4444, 4370, 4298, 4229
+                        };
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dec_tab.h b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dec_tab.h
new file mode 100644
index 0000000..404cc8b
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dec_tab.h
@@ -0,0 +1,215 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+*     -------------------------------------------------------------------   *
+*                    MPEG-4 Simple Profile Video Decoder                    *
+*     -------------------------------------------------------------------   *
+*
+* This software module was originally developed by
+*
+*   Paulo Nunes (IST / ACTS-MoMuSyS)
+*
+* and edited by
+*
+*   Robert Danielsen (Telenor / ACTS-MoMuSyS)
+*
+* in the course of development of the MPEG-4 Video (ISO/IEC 14496-2) standard.
+* This software module is an implementation of a part of one or more MPEG-4
+* Video (ISO/IEC 14496-2) tools as specified by the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* ISO/IEC gives users of the MPEG-4 Video (ISO/IEC 14496-2) standard free
+* license to this software module or modifications thereof for use in hardware
+* or software products claiming conformance to the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* Those intending to use this software module in hardware or software products
+* are advised that its use may infringe existing patents. The original
+* developer of this software module and his/her company, the subsequent
+* editors and their companies, and ISO/IEC have no liability for use of this
+* software module or modifications thereof in an implementation. Copyright is
+* not released for non MPEG-4 Video (ISO/IEC 14496-2) Standard conforming
+* products.
+*
+* ACTS-MoMuSys partners retain full right to use the code for his/her own
+* purpose, assign or donate the code to a third party and to inhibit third
+* parties from using the code for non MPEG-4 Video (ISO/IEC 14496-2) Standard
+* conforming products. This copyright notice must be included in all copies or
+* derivative works.
+*
+* Copyright (c) 1996
+*
+*****************************************************************************
+***********************************************************HeaderBegin*******
+*
+* File: vlc_dec_tab.h
+*
+* Author:   Paulo Nunes (IST) - Paulo.Nunes@it.ist.utl.pt
+* Created:  1-Mar-96
+*
+* Description: This file contains the VLC tables for module which deals
+*       with VLC decoding.
+*
+* Notes:    This file was created based on tmndecode
+*       Written by Karl Olav Lillevold <kol@nta.no>,
+*       1995 Telenor R&D.
+*       Donated to the Momusys-project as background code by
+*       Telenor.
+*
+*       based on mpeg2decode, (C) 1994, MPEG Software Simulation Group
+*       and mpeg2play, (C) 1994 Stefan Eckart
+*                         <stefan@lis.e-technik.tu-muenchen.de>
+*
+*
+* Modified:  9-May-96 Paulo Nunes: Reformatted. New headers.
+*       14-May-96 Paulo Nunes: Changed TMNMVtabs according to VM2.1.
+*   04.11.96 Robert Danielsen: Added three new tables for coding
+*           of Intra luminance coefficients (VM 4.0)
+*      01.05.97 Luis Ducla-Soares: added VM7.0 Reversible VLC tables (RVLC).
+*      13.05.97 Minhua Zhou: added VlC tables for CBPYtab2 CBPYtab3,
+*   revised  CBPYtab
+*
+***********************************************************HeaderEnd*********
+
+This module is a header file for "vlc_decode.c".  The table data actually
+resides in "vlc_tab.c".
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef vlc_dec_tab_H
+#define vlc_dec_tab_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "mp4def.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    extern const VLCshorttab PV_TMNMVtab0[];
+
+    extern const VLCshorttab PV_TMNMVtab1[];
+
+    extern const VLCshorttab PV_TMNMVtab2[];
+
+    extern const VLCshorttab PV_MCBPCtab[];
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    extern const VLCshorttab PV_MCBPCtab1[];
+#endif
+    extern const VLCshorttab PV_MCBPCtabintra[];
+
+    /* Table for separate mode MCBPC, for coding DQUANT-flag and CBPC */
+
+    extern const VLCshorttab MCBPCtab_sep[32];
+
+    extern const VLCshorttab PV_CBPYtab[48];
+
+    extern const VLCshorttab CBPYtab2[16];
+
+    extern const VLCshorttab CBPYtab3[64];
+
+    extern const VLCtab2 PV_DCT3Dtab0[];
+
+
+    extern const VLCtab2 PV_DCT3Dtab1[];
+
+
+    extern const VLCtab2 PV_DCT3Dtab2[];
+
+    /* New tables for Intra luminance blocks */
+
+    extern const VLCtab2 PV_DCT3Dtab3[];
+
+    extern const VLCtab2 PV_DCT3Dtab4[];
+
+    extern const VLCtab2 PV_DCT3Dtab5[];
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    /* Annex I tables */
+    extern const VLCtab2 PV_DCT3Dtab6[];
+
+    extern const VLCtab2 PV_DCT3Dtab7[];
+
+    extern const VLCtab2 PV_DCT3Dtab8[];
+#endif
+    /* RVLC tables */
+    extern const int ptrRvlcTab[];
+
+    extern const VLCtab2 RvlcDCTtabIntra[];
+
+    extern const VLCtab2 RvlcDCTtabInter[];
+
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+
+
+
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.cpp
new file mode 100644
index 0000000..f7192b1c
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.cpp
@@ -0,0 +1,1636 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+*     -------------------------------------------------------------------       *
+*                    MPEG-4 Simple Profile Video Decoder                        *
+*     -------------------------------------------------------------------       *
+*
+* This software module was originally developed by
+*
+*   Paulo Nunes (IST / ACTS-MoMuSyS)
+*   Robert Danielsen (Telenor / ACTS-MoMuSyS)
+*
+* in the course of development of the MPEG-4 Video (ISO/IEC 14496-2) standard.
+* This software module is an implementation of a part of one or more MPEG-4
+* Video (ISO/IEC 14496-2) tools as specified by the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* ISO/IEC gives users of the MPEG-4 Video (ISO/IEC 14496-2) standard free
+* license to this software module or modifications thereof for use in hardware
+* or software products claiming conformance to the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* Those intending to use this software module in hardware or software products
+* are advised that its use may infringe existing patents. The original
+* developer of this software module and his/her company, the subsequent
+* editors and their companies, and ISO/IEC have no liability for use of this
+* software module or modifications thereof in an implementation. Copyright is
+* not released for non MPEG-4 Video (ISO/IEC 14496-2) Standard conforming
+* products.
+*
+* ACTS-MoMuSys partners retain full right to use the code for his/her own
+* purpose, assign or donate the code to a third party and to inhibit third
+* parties from using the code for non MPEG-4 Video (ISO/IEC 14496-2) Standard
+* conforming products. This copyright notice must be included in all copies or
+* derivative works.
+*
+* Copyright (c) 1996
+*
+*****************************************************************************/
+
+/***********************************************************HeaderBegin*******
+*
+* File: vlc_dec.c
+*
+* Author:   Paulo Nunes (IST) - Paulo.Nunes@lx.it.pt
+* Created:  1-Mar-96
+*
+* Description: This file contains the VLC functions needed to decode a
+*       bitstream.
+*
+* Notes:
+*       The functions contained in this file were adapted from
+*       tmndecode
+*       Written by Karl Olav Lillevold <kol@nta.no>,
+*       1995 Telenor R&D.
+*       Donated to the Momusys-project as background code by
+*       Telenor.
+*
+*       based on mpeg2decode, (C) 1994, MPEG Software Simulation Group
+*       and mpeg2play, (C) 1994 Stefan Eckart
+*                   <stefan@lis.e-technik.tu-muenchen.de>
+*
+*
+* Modified: 9-May-96 Paulo Nunes: Reformatted. New headers.
+*              17-Jan-97 Jan De Lameillieure (HHI) : corrected in
+*              01.05.97 Luis Ducla-Soares: added RvlcDecTCOEF() to allow decoding
+*                                          of Reversible VLCs.
+*       09.03.98 Paulo Nunes: Cleaning.
+*
+***********************************************************HeaderEnd*********/
+
+#include "mp4dec_lib.h"
+#include "vlc_dec_tab.h"
+#include "vlc_decode.h"
+#include "bitstream.h"
+#include "max_level.h"
+
+
+/* ====================================================================== /
+    Function : DecodeUserData()
+    Date     : 04/10/2000
+    History  :
+    Modified : 04/16/2001 : removed status checking of PV_BitstreamFlushBits
+
+        This is simply a realization of the user_data() function
+        in the ISO/IEC 14496-2 manual.
+/ ====================================================================== */
+PV_STATUS DecodeUserData(BitstreamDecVideo *stream)
+{
+    PV_STATUS status;
+    uint32 code;
+
+    BitstreamReadBits32HC(stream);
+    BitstreamShowBits32(stream, 24, &code);
+
+    while (code != 1)
+    {
+        /* Discard user data for now.   04/05/2000 */
+        BitstreamReadBits16(stream, 8);
+        BitstreamShowBits32(stream, 24, &code);
+        status = BitstreamCheckEndBuffer(stream);
+        if (status == PV_END_OF_VOP) return status;    /*  03/19/2002 */
+    }
+    return PV_SUCCESS;
+}
+
+
+
+/***********************************************************CommentBegin******
+*
+*       3/10/00  : initial modification to the
+*                new PV-Decoder Lib format.
+*       3/29/00  : added return code check to some functions and
+*                optimize the code.
+*
+***********************************************************CommentEnd********/
+PV_STATUS PV_GetMBvectors(VideoDecData *video, uint mode)
+{
+    PV_STATUS status;
+    BitstreamDecVideo *stream = video->bitstream;
+    int  f_code_f = video->currVop->fcodeForward;
+    int  vlc_code_mag;
+
+
+    MOT *mot_x = video->motX;
+    MOT *mot_y = video->motY;
+
+    int k, offset;
+    int x_pos = video->mbnum_col;
+    int y_pos = video->mbnum_row;
+    int doubleWidth = video->nMBPerRow << 1;
+    int pos = (x_pos + y_pos * doubleWidth) << 1;
+    MOT mvx = 0, mvy = 0;
+
+
+    if (f_code_f == 1)
+    {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (mode == MODE_INTER4V || mode == MODE_INTER4V_Q)
+#else
+        if (mode == MODE_INTER4V)
+#endif
+        {
+            for (k = 0; k < 4; k++)
+            {
+                offset = (k & 1) + (k >> 1) * doubleWidth;
+                mv_prediction(video, k, &mvx, &mvy);
+                /* decode component x */
+                status = PV_VlcDecMV(stream, &vlc_code_mag);
+                if (status != PV_SUCCESS)
+                {
+                    return status;
+                }
+
+                mvx += (MOT)vlc_code_mag;
+                mvx = (MOT)(((mvx + 32) & 0x3F) - 32);
+
+
+                status = PV_VlcDecMV(stream, &vlc_code_mag);
+                if (status != PV_SUCCESS)
+                {
+                    return status;
+                }
+
+                mvy += (MOT)vlc_code_mag;
+                mvy = (MOT)(((mvy + 32) & 0x3F) - 32);
+
+                mot_x[pos+offset] = (MOT) mvx;
+                mot_y[pos+offset] = (MOT) mvy;
+            }
+        }
+        else
+        {
+            mv_prediction(video, 0, &mvx, &mvy);
+            /* For PVOPs, field  appears only in MODE_INTER & MODE_INTER_Q */
+            status = PV_VlcDecMV(stream, &vlc_code_mag);
+            if (status != PV_SUCCESS)
+            {
+                return status;
+            }
+
+            mvx += (MOT)vlc_code_mag;
+            mvx = (MOT)(((mvx + 32) & 0x3F) - 32);
+
+
+            status = PV_VlcDecMV(stream, &vlc_code_mag);
+            if (status != PV_SUCCESS)
+            {
+                return status;
+            }
+
+
+            mvy += (MOT)vlc_code_mag;
+            mvy = (MOT)(((mvy + 32) & 0x3F) - 32);
+
+
+            mot_x[pos] = mot_x[pos+1] = (MOT) mvx;
+            mot_y[pos] = mot_y[pos+1] = (MOT) mvy;
+            pos += doubleWidth;
+            mot_x[pos] = mot_x[pos+1] = (MOT) mvx;
+            mot_y[pos] = mot_y[pos+1] = (MOT) mvy;
+        }
+    }
+    else
+    {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (mode == MODE_INTER4V || mode == MODE_INTER4V_Q)
+#else
+        if (mode == MODE_INTER4V)
+#endif
+        {
+            for (k = 0; k < 4; k++)
+            {
+                offset = (k & 1) + (k >> 1) * doubleWidth;
+                mv_prediction(video, k, &mvx, &mvy);
+                status = PV_DecodeMBVec(stream, &mvx, &mvy, f_code_f);
+                mot_x[pos+offset] = (MOT) mvx;
+                mot_y[pos+offset] = (MOT) mvy;
+                if (status != PV_SUCCESS)
+                {
+                    return status;
+                }
+            }
+        }
+        else
+        {
+            mv_prediction(video, 0, &mvx, &mvy);
+            /* For PVOPs, field  appears only in MODE_INTER & MODE_INTER_Q */
+            status = PV_DecodeMBVec(stream, &mvx, &mvy, f_code_f);
+            mot_x[pos] = mot_x[pos+1] = (MOT) mvx;
+            mot_y[pos] = mot_y[pos+1] = (MOT) mvy;
+            pos += doubleWidth;
+            mot_x[pos] = mot_x[pos+1] = (MOT) mvx;
+            mot_y[pos] = mot_y[pos+1] = (MOT) mvy;
+            if (status != PV_SUCCESS)
+            {
+                return status;
+            }
+        }
+    }
+    return PV_SUCCESS;
+}
+
+
+/***********************************************************CommentBegin******
+*       3/10/00  : initial modification to the
+*                new PV-Decoder Lib format.
+*       3/29/00  : added return code check to some functions
+*       5/10/00  : check whether the decoded vector is legal.
+*       4/17/01  : use MOT type
+***********************************************************CommentEnd********/
+PV_STATUS PV_DecodeMBVec(BitstreamDecVideo *stream, MOT *mv_x, MOT *mv_y, int f_code_f)
+{
+    PV_STATUS status;
+    int  vlc_code_magx, vlc_code_magy;
+    int  residualx = 0, residualy = 0;
+
+    /* decode component x */
+    status = PV_VlcDecMV(stream, &vlc_code_magx);
+    if (status != PV_SUCCESS)
+    {
+        return status;
+    }
+
+    if (vlc_code_magx)
+    {
+        residualx = (int) BitstreamReadBits16_INLINE(stream, (int)(f_code_f - 1));
+    }
+
+
+    /* decode component y */
+    status = PV_VlcDecMV(stream, &vlc_code_magy);
+    if (status != PV_SUCCESS)
+    {
+        return status;
+    }
+
+    if (vlc_code_magy)
+    {
+        residualy = (int) BitstreamReadBits16_INLINE(stream, (int)(f_code_f - 1));
+    }
+
+
+    if (PV_DeScaleMVD(f_code_f, residualx, vlc_code_magx, mv_x) != PV_SUCCESS)
+    {
+        return PV_FAIL;
+    }
+
+    if (PV_DeScaleMVD(f_code_f, residualy, vlc_code_magy, mv_y) != PV_SUCCESS)
+    {
+        return PV_FAIL;
+    }
+
+    return PV_SUCCESS;
+}
+
+
+/***********************************************************CommentBegin******
+*       3/31/2000 : initial modification to the new PV-Decoder Lib format.
+*       5/10/2000 : check to see if the decoded vector falls within
+*                           the legal fcode range.
+*
+***********************************************************CommentEnd********/
+PV_STATUS PV_DeScaleMVD(
+    int  f_code,       /* <-- MV range in 1/2 units: 1=32,2=64,...,7=2048     */
+    int  residual,     /* <-- part of the MV Diff. FLC coded                  */
+    int  vlc_code_mag, /* <-- part of the MV Diff. VLC coded                  */
+    MOT  *vector       /* --> Obtained MV component in 1/2 units              */
+)
+{
+    int   half_range = (1 << (f_code + 4));
+    int   mask = (half_range << 1) - 1;
+    int   diff_vector;
+
+
+    if (vlc_code_mag == 0)
+    {
+        diff_vector = vlc_code_mag;
+    }
+    else
+    {
+        diff_vector = ((PV_ABS(vlc_code_mag) - 1) << (f_code - 1)) + residual + 1;
+        if (vlc_code_mag < 0)
+        {
+            diff_vector = -diff_vector;
+        }
+    }
+
+    *vector += (MOT)(diff_vector);
+
+    *vector = (MOT)((*vector + half_range) & mask) - half_range;
+
+    return PV_SUCCESS;
+}
+
+
+
+void mv_prediction(
+    VideoDecData *video,
+    int block,
+    MOT *mvx,
+    MOT *mvy
+)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    MOT *motxdata = video->motX;
+    MOT *motydata = video->motY;
+    int mbnum_col = video->mbnum_col;
+    int mbnum_row = video->mbnum_row;
+    uint8 *slice_nb = video->sliceNo;
+    int nMBPerRow = video->nMBPerRow;
+    int nMVPerRow = nMBPerRow << 1;
+    int mbnum = video->mbnum;
+    int p1x = 0, p2x = 0, p3x = 0;
+    int p1y = 0, p2y = 0, p3y = 0;
+    int rule1 = 0, rule2 = 0, rule3 = 0;
+    int     indx;
+
+    indx = ((mbnum_col << 1) + (block & 1)) + ((mbnum_row << 1)  + (block >> 1)) * nMVPerRow - 1; /* left block */
+
+    if (block & 1)           /* block 1, 3 */
+    {
+        p1x = motxdata[indx];
+        p1y = motydata[indx];
+        rule1 = 1;
+    }
+    else                    /* block 0, 2 */
+    {
+        if (mbnum_col > 0 && slice_nb[mbnum] == slice_nb[mbnum-1])
+        {
+            p1x = motxdata[indx];
+            p1y = motydata[indx];
+            rule1 = 1;
+        }
+    }
+
+    indx = indx + 1 - nMVPerRow; /* upper_block */
+    if (block >> 1)
+    {
+        indx -= (block & 1);
+        p2x = motxdata[indx];
+        p2y = motydata[indx];
+        p3x = motxdata[indx + 1];
+        p3y = motydata[indx + 1];
+        rule2 = rule3 = 1;
+    }
+    else
+    {                           /* block 0,1 */
+        if (mbnum_row)
+        {
+            if (slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow])
+            {
+                p2x = motxdata[indx];
+                p2y = motydata[indx];
+                rule2 = 1;
+            }
+            if (mbnum_col < nMBPerRow - 1 && slice_nb[mbnum] == slice_nb[mbnum-nMBPerRow+1])
+            {
+                indx = indx + 2 - (block & 1);
+                p3x = motxdata[indx];
+                p3y = motydata[indx];
+                rule3 = 1;
+            }
+        }
+    }
+
+    if (rule1 + rule2 + rule3 > 1)
+    {
+        *mvx = (MOT)PV_MEDIAN(p1x, p2x, p3x);
+        *mvy = (MOT)PV_MEDIAN(p1y, p2y, p3y);
+    }
+    else if (rule1 + rule2 + rule3 == 1)
+    {
+        /* two of three are zero */
+        *mvx = (MOT)(p1x + p2x + p3x);
+        *mvy = (MOT)(p1y + p2y + p3y);
+    }
+    else
+    {
+        /* all MBs are outside the VOP */
+        *mvx = *mvy = 0;
+    }
+    /*----------------------------------------------------------------------------
+    ; Return nothing or data or data pointer
+    ----------------------------------------------------------------------------*/
+    return;
+}
+
+/***********************************************************CommentBegin******
+*
+*       3/30/2000 : initial modification to the new PV-Decoder Lib format.
+*       4/16/2001 : removed checking of status for PV_BitstreamFlushBits
+***********************************************************CommentEnd********/
+
+PV_STATUS PV_VlcDecMV(BitstreamDecVideo *stream, int *mv)
+{
+    PV_STATUS status = PV_SUCCESS;
+    uint code;
+
+    BitstreamShow13Bits(stream, &code);
+
+    if (code >> 12)
+    {
+        *mv = 0; /* Vector difference = 0 */
+        PV_BitstreamFlushBits(stream, 1);
+        return PV_SUCCESS;
+    }
+
+    if (code >= 512)
+    {
+        code = (code >> 8) - 2;
+        PV_BitstreamFlushBits(stream, PV_TMNMVtab0[code].len + 1);
+        *mv = PV_TMNMVtab0[code].val;
+        return status;
+    }
+
+    if (code >= 128)
+    {
+        code = (code >> 2) - 32;
+        PV_BitstreamFlushBits(stream, PV_TMNMVtab1[code].len + 1);
+        *mv = PV_TMNMVtab1[code].val;
+        return status;
+    }
+
+    if (code < 4)
+    {
+        *mv = -1;
+        return PV_FAIL;
+    }
+
+    code -= 4;
+
+    PV_BitstreamFlushBits(stream, PV_TMNMVtab2[code].len + 1);
+
+    *mv = PV_TMNMVtab2[code].val;
+    return status;
+}
+
+
+/***********************************************************CommentBegin******
+*       3/30/2000 : initial modification to the new PV-Decoder Lib
+*                           format and the change of error-handling method.
+*       4/16/01   : removed status checking of PV_BitstreamFlushBits
+***********************************************************CommentEnd********/
+
+int PV_VlcDecMCBPC_com_intra(BitstreamDecVideo *stream)
+{
+    uint code;
+
+    BitstreamShowBits16(stream, 9, &code);
+
+
+    if (code < 8)
+    {
+        return VLC_CODE_ERROR;
+    }
+
+    code >>= 3;
+
+    if (code >= 32)
+    {
+        PV_BitstreamFlushBits(stream, 1);
+        return 3;
+    }
+
+    PV_BitstreamFlushBits(stream, PV_MCBPCtabintra[code].len);
+
+    return PV_MCBPCtabintra[code].val;
+}
+
+
+/***********************************************************CommentBegin******
+*
+*       3/30/2000 : initial modification to the new PV-Decoder Lib
+*                           format and the change of error-handling method.
+*       4/16/2001 : removed checking of return status of PV_BitstreamFlushBits
+***********************************************************CommentEnd********/
+
+int PV_VlcDecMCBPC_com_inter(BitstreamDecVideo *stream)
+{
+    uint code;
+
+    BitstreamShowBits16(stream, 9, &code);
+
+    if (code == 0)
+    {
+        return VLC_CODE_ERROR;
+    }
+    else if (code >= 256)
+    {
+        PV_BitstreamFlushBits(stream, 1);
+        return 0;
+    }
+
+    PV_BitstreamFlushBits(stream, PV_MCBPCtab[code].len);
+    return PV_MCBPCtab[code].val;
+}
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+int PV_VlcDecMCBPC_com_inter_H263(BitstreamDecVideo *stream)
+{
+    uint code;
+
+    BitstreamShow13Bits(stream, &code);
+
+    if (code == 0)
+    {
+        return VLC_CODE_ERROR;
+    }
+    else if (code >= 4096)
+    {
+        PV_BitstreamFlushBits(stream, 1);
+        return 0;
+    }
+    if (code >= 16)
+    {
+        PV_BitstreamFlushBits(stream, PV_MCBPCtab[code >> 4].len);
+        return PV_MCBPCtab[code >> 4].val;
+    }
+    else
+    {
+        PV_BitstreamFlushBits(stream, PV_MCBPCtab1[code - 8].len);
+        return PV_MCBPCtab1[code - 8].val;
+    }
+}
+#endif
+/***********************************************************CommentBegin******
+*       3/30/2000 : initial modification to the new PV-Decoder Lib
+*                           format and the change of error-handling method.
+*       4/16/2001 : removed status checking for PV_BitstreamFlushBits
+***********************************************************CommentEnd********/
+
+int PV_VlcDecCBPY(BitstreamDecVideo *stream, int intra)
+{
+    int CBPY = 0;
+    uint code;
+
+    BitstreamShowBits16(stream, 6, &code);
+
+
+    if (code < 2)
+    {
+        return -1;
+    }
+    else if (code >= 48)
+    {
+        PV_BitstreamFlushBits(stream, 2);
+        CBPY = 15;
+    }
+    else
+    {
+        PV_BitstreamFlushBits(stream, PV_CBPYtab[code].len);
+        CBPY = PV_CBPYtab[code].val;
+    }
+
+    if (intra == 0) CBPY = 15 - CBPY;
+    CBPY = CBPY & 15;
+    return CBPY;
+}
+
+
+/***********************************************************CommentBegin******
+*       3/31/2000 : initial modification to the new PV-Decoder Lib format.
+*
+*       8/23/2000 : optimize the function by removing unnecessary BitstreamShowBits()
+*                       function calls.
+*
+*       9/6/2000 : change the API to check for end-of-buffer for proper
+*                           termination of decoding process.
+***********************************************************CommentEnd********/
+PV_STATUS PV_VlcDecIntraDCPredSize(BitstreamDecVideo *stream, int compnum, uint *DC_size)
+{
+    PV_STATUS status = PV_FAIL;      /*  07/09/01 */
+    uint  code;
+
+    *DC_size = 0;
+    if (compnum < 4)  /* luminance block */
+    {
+
+        BitstreamShowBits16(stream, 11, &code);
+
+        if (code == 1)
+        {
+            *DC_size = 12;
+            PV_BitstreamFlushBits(stream, 11);
+            return PV_SUCCESS;
+        }
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 11;
+            PV_BitstreamFlushBits(stream, 10);
+            return PV_SUCCESS;
+        }
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 10;
+            PV_BitstreamFlushBits(stream, 9);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 9;
+            PV_BitstreamFlushBits(stream, 8);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 8;
+            PV_BitstreamFlushBits(stream, 7);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 7;
+            PV_BitstreamFlushBits(stream, 6);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 6;
+            PV_BitstreamFlushBits(stream, 5);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 5;
+            PV_BitstreamFlushBits(stream, 4);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 4;
+            PV_BitstreamFlushBits(stream, 3);
+            return PV_SUCCESS;
+        }
+        else if (code == 2)
+        {
+            *DC_size = 3;
+            PV_BitstreamFlushBits(stream, 3);
+            return PV_SUCCESS;
+        }
+        else if (code == 3)
+        {
+            *DC_size = 0;
+            PV_BitstreamFlushBits(stream, 3);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 2)
+        {
+            *DC_size = 2;
+            PV_BitstreamFlushBits(stream, 2);
+            return PV_SUCCESS;
+        }
+        else if (code == 3)
+        {
+            *DC_size = 1;
+            PV_BitstreamFlushBits(stream, 2);
+            return PV_SUCCESS;
+        }
+    }
+    else /* chrominance block */
+    {
+
+        BitstreamShow13Bits(stream, &code);
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 12;
+            PV_BitstreamFlushBits(stream, 12);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 11;
+            PV_BitstreamFlushBits(stream, 11);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 10;
+            PV_BitstreamFlushBits(stream, 10);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 9;
+            PV_BitstreamFlushBits(stream, 9);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 8;
+            PV_BitstreamFlushBits(stream, 8);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 7;
+            PV_BitstreamFlushBits(stream, 7);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 6;
+            PV_BitstreamFlushBits(stream, 6);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 5;
+            PV_BitstreamFlushBits(stream, 5);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 4;
+            PV_BitstreamFlushBits(stream, 4);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        if (code == 1)
+        {
+            *DC_size = 3;
+            PV_BitstreamFlushBits(stream, 3);
+            return PV_SUCCESS;
+        }
+
+        code >>= 1;
+        {
+            *DC_size = (int)(3 - code);
+            PV_BitstreamFlushBits(stream, 2);
+            return PV_SUCCESS;
+        }
+    }
+
+    return status;
+}
+
+/***********************************************************CommentBegin******
+*
+*
+*       3/30/2000 : initial modification to the new PV-Decoder Lib
+*                           format and the change of error-handling method.
+*
+***********************************************************CommentEnd********/
+
+
+
+PV_STATUS VlcDecTCOEFIntra(BitstreamDecVideo *stream, Tcoef *pTcoef)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFIntra */
+    /*  if(GetTcoeffIntra(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+    if (code >= 1024)
+    {
+        tab = &PV_DCT3Dtab3[(code >> 6) - 16];
+    }
+    else
+    {
+        if (code >= 256)
+        {
+            tab = &PV_DCT3Dtab4[(code >> 3) - 32];
+        }
+        else
+        {
+            if (code >= 16)
+            {
+                tab = &PV_DCT3Dtab5[(code>>1) - 8];
+            }
+            else
+            {
+                return PV_FAIL;
+            }
+        }
+    }
+
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint) tab->run; //(tab->val >> 8) & 255;
+    pTcoef->level = (int) tab->level; //tab->val & 255;
+    pTcoef->last = (uint) tab->last; //(tab->val >> 16) & 1;
+
+
+    /* the following is modified for 3-mode escape -- boon */
+    if (tab->level != 0xFF)
+    {
+        return PV_SUCCESS;
+    }
+
+    //if (((tab->run<<8)|(tab->level)|(tab->last<<16)) == VLC_ESCAPE_CODE)
+
+    if (!pTcoef->sign)
+    {
+        /* first escape mode. level is offset */
+        BitstreamShow13Bits(stream, &code);
+
+        /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFIntra */
+        /*          if(GetTcoeffIntra(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+        if (code >= 1024)
+        {
+            tab = &PV_DCT3Dtab3[(code >> 6) - 16];
+        }
+        else
+        {
+            if (code >= 256)
+            {
+                tab = &PV_DCT3Dtab4[(code >> 3) - 32];
+            }
+            else
+            {
+                if (code >= 16)
+                {
+                    tab = &PV_DCT3Dtab5[(code>>1) - 8];
+                }
+                else
+                {
+                    return PV_FAIL;
+                }
+            }
+        }
+
+        PV_BitstreamFlushBits(stream, tab->len + 1);
+
+        /* sign bit */
+        pTcoef->sign = (code >> (12 - tab->len)) & 1;
+        pTcoef->run = (uint)tab->run; //(tab->val >> 8) & 255;
+        pTcoef->level = (int)tab->level; //tab->val & 255;
+        pTcoef->last = (uint)tab->last; //(tab->val >> 16) & 1;
+
+
+        /* need to add back the max level */
+        if ((pTcoef->last == 0 && pTcoef->run > 14) || (pTcoef->last == 1 && pTcoef->run > 20))
+        {
+            return PV_FAIL;
+        }
+        pTcoef->level = pTcoef->level + intra_max_level[pTcoef->last][pTcoef->run];
+
+
+    }
+    else
+    {
+        uint run_offset;
+        run_offset = BitstreamRead1Bits_INLINE(stream);
+
+        if (!run_offset)
+        {
+            /* second escape mode. run is offset */
+            BitstreamShow13Bits(stream, &code);
+
+            /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFIntra */
+            /*              if(GetTcoeffIntra(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+            if (code >= 1024)
+            {
+                tab = &PV_DCT3Dtab3[(code >> 6) - 16];
+            }
+            else
+            {
+                if (code >= 256)
+                {
+                    tab = &PV_DCT3Dtab4[(code >> 3) - 32];
+                }
+                else
+                {
+                    if (code >= 16)
+                    {
+                        tab = &PV_DCT3Dtab5[(code>>1) - 8];
+                    }
+                    else
+                    {
+                        return PV_FAIL;
+                    }
+                }
+            }
+
+            PV_BitstreamFlushBits(stream, tab->len + 1);
+            /* sign bit */
+            pTcoef->sign = (code >> (12 - tab->len)) & 1;
+            pTcoef->run = (uint)tab->run; //(tab->val >> 8) & 255;
+            pTcoef->level = (int)tab->level; //tab->val & 255;
+            pTcoef->last = (uint)tab->last; //(tab->val >> 16) & 1;
+
+
+
+            /* need to add back the max run */
+            if (pTcoef->last)
+            {
+                if (pTcoef->level > 8)
+                {
+                    return PV_FAIL;
+                }
+                pTcoef->run = pTcoef->run + intra_max_run1[pTcoef->level] + 1;
+            }
+            else
+            {
+                if (pTcoef->level > 27)
+                {
+                    return PV_FAIL;
+                }
+                pTcoef->run = pTcoef->run + intra_max_run0[pTcoef->level] + 1;
+            }
+
+
+        }
+        else
+        {
+
+            code = BitstreamReadBits16_INLINE(stream, 8);
+            pTcoef->last = code >> 7;
+            pTcoef->run = (code >> 1) & 0x3F;
+            pTcoef->level = (int)(BitstreamReadBits16_INLINE(stream, 13) >> 1);
+
+            if (pTcoef->level >= 2048)
+            {
+                pTcoef->sign = 1;
+                pTcoef->level = 4096 - pTcoef->level;
+            }
+            else
+            {
+                pTcoef->sign = 0;
+            }
+        } /* flc */
+    }
+
+    return PV_SUCCESS;
+
+} /* VlcDecTCOEFIntra */
+
+PV_STATUS VlcDecTCOEFInter(BitstreamDecVideo *stream, Tcoef *pTcoef)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFInter */
+    /*  if(GetTcoeffInter(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+    if (code >= 1024)
+    {
+        tab = &PV_DCT3Dtab0[(code >> 6) - 16];
+    }
+    else
+    {
+        if (code >= 256)
+        {
+            tab = &PV_DCT3Dtab1[(code >> 3) - 32];
+        }
+        else
+        {
+            if (code >= 16)
+            {
+                tab = &PV_DCT3Dtab2[(code>>1) - 8];
+            }
+            else
+            {
+                return PV_FAIL;
+            }
+        }
+    }
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint)tab->run;     //(tab->val >> 4) & 255;
+    pTcoef->level = (int)tab->level; //tab->val & 15;
+    pTcoef->last = (uint)tab->last;   //(tab->val >> 12) & 1;
+
+    /* the following is modified for 3-mode escape -- boon */
+    if (tab->run != 0xBF)
+    {
+        return PV_SUCCESS;
+    }
+    //if (((tab->run<<4)|(tab->level)|(tab->last<<12)) == VLC_ESCAPE_CODE)
+
+
+    if (!pTcoef->sign)
+    {
+        /* first escape mode. level is offset */
+        BitstreamShow13Bits(stream, &code);
+
+        /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFInter */
+        /*          if(GetTcoeffInter(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+        if (code >= 1024)
+        {
+            tab = &PV_DCT3Dtab0[(code >> 6) - 16];
+        }
+        else
+        {
+            if (code >= 256)
+            {
+                tab = &PV_DCT3Dtab1[(code >> 3) - 32];
+            }
+            else
+            {
+                if (code >= 16)
+                {
+                    tab = &PV_DCT3Dtab2[(code>>1) - 8];
+                }
+                else
+                {
+                    return PV_FAIL;
+                }
+            }
+        }
+        PV_BitstreamFlushBits(stream, tab->len + 1);
+        pTcoef->sign = (code >> (12 - tab->len)) & 1;
+        pTcoef->run = (uint)tab->run;     //(tab->val >> 4) & 255;
+        pTcoef->level = (int)tab->level; //tab->val & 15;
+        pTcoef->last = (uint)tab->last;   //(tab->val >> 12) & 1;
+
+        /* need to add back the max level */
+        if ((pTcoef->last == 0 && pTcoef->run > 26) || (pTcoef->last == 1 && pTcoef->run > 40))
+        {
+            return PV_FAIL;
+        }
+        pTcoef->level = pTcoef->level + inter_max_level[pTcoef->last][pTcoef->run];
+    }
+    else
+    {
+        uint run_offset;
+        run_offset = BitstreamRead1Bits_INLINE(stream);
+
+        if (!run_offset)
+        {
+            /* second escape mode. run is offset */
+            BitstreamShow13Bits(stream, &code);
+
+            /* 10/17/2000, perform a little bit better on ARM by putting the whole function in VlcDecTCOEFFInter */
+            /*if(GetTcoeffInter(code,pTcoef,&tab,stream)!=PV_SUCCESS) return status;*/
+            if (code >= 1024)
+            {
+                tab = &PV_DCT3Dtab0[(code >> 6) - 16];
+            }
+            else
+            {
+                if (code >= 256)
+                {
+                    tab = &PV_DCT3Dtab1[(code >> 3) - 32];
+                }
+                else
+                {
+                    if (code >= 16)
+                    {
+                        tab = &PV_DCT3Dtab2[(code>>1) - 8];
+                    }
+                    else
+                    {
+                        return PV_FAIL;
+                    }
+                }
+            }
+            PV_BitstreamFlushBits(stream, tab->len + 1);
+            pTcoef->sign = (code >> (12 - tab->len)) & 1;
+            pTcoef->run = (uint)tab->run;     //(tab->val >> 4) & 255;
+            pTcoef->level = (int)tab->level; //tab->val & 15;
+            pTcoef->last = (uint)tab->last;   //(tab->val >> 12) & 1;
+
+            /* need to add back the max run */
+            if (pTcoef->last)
+            {
+                if (pTcoef->level > 3)
+                {
+                    return PV_FAIL;
+                }
+                pTcoef->run = pTcoef->run + inter_max_run1[pTcoef->level] + 1;
+            }
+            else
+            {
+                if (pTcoef->level > 12)
+                {
+                    return PV_FAIL;
+                }
+                pTcoef->run = pTcoef->run + inter_max_run0[pTcoef->level] + 1;
+            }
+        }
+        else
+        {
+
+            code = BitstreamReadBits16_INLINE(stream, 8);
+            pTcoef->last = code >> 7;
+            pTcoef->run = (code >> 1) & 0x3F;
+            pTcoef->level = (int)(BitstreamReadBits16_INLINE(stream, 13) >> 1);
+
+
+
+            if (pTcoef->level >= 2048)
+            {
+                pTcoef->sign = 1;
+                pTcoef->level = 4096 - pTcoef->level;
+            }
+            else
+            {
+                pTcoef->sign = 0;
+            }
+        } /* flc */
+    }
+
+    return PV_SUCCESS;
+
+} /* VlcDecTCOEFInter */
+
+/*=======================================================
+    Function:   VlcDecTCOEFShortHeader()
+    Date    :   04/27/99
+    Purpose :   New function used in decoding of video planes
+                with short header
+    Modified:   05/23/2000
+                for new decoder structure.
+=========================================================*/
+PV_STATUS VlcDecTCOEFShortHeader(BitstreamDecVideo *stream, Tcoef *pTcoef/*, int intra*/)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /*intra = 0;*/
+
+    if (code >= 1024) tab = &PV_DCT3Dtab0[(code >> 6) - 16];
+    else
+    {
+        if (code >= 256) tab = &PV_DCT3Dtab1[(code >> 3) - 32];
+        else
+        {
+            if (code >= 16) tab = &PV_DCT3Dtab2[(code>>1) - 8];
+            else return PV_FAIL;
+        }
+    }
+
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint)tab->run;//(tab->val >> 4) & 255;
+    pTcoef->level = (int)tab->level;//tab->val & 15;
+    pTcoef->last = (uint)tab->last;//(tab->val >> 12) & 1;
+
+    /* the following is modified for 3-mode escape -- boon */
+    if (((tab->run << 4) | (tab->level) | (tab->last << 12)) != VLC_ESCAPE_CODE)    /* ESCAPE */
+    {
+        return PV_SUCCESS;
+    }
+
+
+    /* escape mode 4 - H.263 type */
+    pTcoef->last = pTcoef->sign; /* Last */
+    pTcoef->run = BitstreamReadBits16_INLINE(stream, 6); /* Run */
+    pTcoef->level = (int) BitstreamReadBits16_INLINE(stream, 8); /* Level */
+
+    if (pTcoef->level == 0 || pTcoef->level == 128)
+    {
+        return PV_FAIL;
+    }
+
+    if (pTcoef->level > 128)
+    {
+        pTcoef->sign = 1;
+        pTcoef->level = 256 - pTcoef->level;
+    }
+    else
+    {
+        pTcoef->sign = 0;
+    }
+
+
+
+    return PV_SUCCESS;
+
+}   /* VlcDecTCOEFShortHeader */
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+PV_STATUS VlcDecTCOEFShortHeader_AnnexI(BitstreamDecVideo *stream, Tcoef *pTcoef/*, int intra*/)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /*intra = 0;*/
+
+    if (code >= 1024) tab = &PV_DCT3Dtab6[(code >> 6) - 16];
+    else
+    {
+        if (code >= 256) tab = &PV_DCT3Dtab7[(code >> 3) - 32];
+        else
+        {
+            if (code >= 16) tab = &PV_DCT3Dtab8[(code>>1) - 8];
+            else return PV_FAIL;
+        }
+    }
+
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint)tab->run;//(tab->val >> 4) & 255;
+    pTcoef->level = (int)tab->level;//tab->val & 15;
+    pTcoef->last = (uint)tab->last;//(tab->val >> 12) & 1;
+
+    /* the following is modified for 3-mode escape -- boon */
+    if (((tab->run << 6) | (tab->level) | (tab->last << 12)) != VLC_ESCAPE_CODE)    /* ESCAPE */
+    {
+        return PV_SUCCESS;
+    }
+    /* escape mode 4 - H.263 type */
+    pTcoef->last = pTcoef->sign; /* Last */
+    pTcoef->run = BitstreamReadBits16(stream, 6); /* Run */
+    pTcoef->level = (int) BitstreamReadBits16(stream, 8); /* Level */
+
+    if (pTcoef->level == 0 || pTcoef->level == 128)
+    {
+        return PV_FAIL;
+    }
+
+
+    if (pTcoef->level > 128)
+    {
+        pTcoef->sign = 1;
+        pTcoef->level = 256 - pTcoef->level;
+    }
+    else pTcoef->sign = 0;
+
+
+
+    return PV_SUCCESS;
+
+}   /* VlcDecTCOEFShortHeader_AnnexI */
+
+PV_STATUS VlcDecTCOEFShortHeader_AnnexT(BitstreamDecVideo *stream, Tcoef *pTcoef/*, int intra*/)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /*intra = 0;*/
+
+    if (code >= 1024) tab = &PV_DCT3Dtab0[(code >> 6) - 16];
+    else
+    {
+        if (code >= 256) tab = &PV_DCT3Dtab1[(code >> 3) - 32];
+        else
+        {
+            if (code >= 16) tab = &PV_DCT3Dtab2[(code>>1) - 8];
+            else return PV_FAIL;
+        }
+    }
+
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint)tab->run;//(tab->val >> 4) & 255;
+    pTcoef->level = (int)tab->level;//tab->val & 15;
+    pTcoef->last = (uint)tab->last;//(tab->val >> 12) & 1;
+
+    /* the following is modified for 3-mode escape --  */
+    if (((tab->run << 4) | (tab->level) | (tab->last << 12)) != VLC_ESCAPE_CODE)    /* ESCAPE */
+    {
+        return PV_SUCCESS;
+    }
+    /* escape mode 4 - H.263 type */
+    pTcoef->last = pTcoef->sign; /* Last */
+    pTcoef->run = BitstreamReadBits16(stream, 6); /* Run */
+    pTcoef->level = (int) BitstreamReadBits16(stream, 8); /* Level */
+
+    if (pTcoef->level == 0)
+    {
+        return PV_FAIL;
+    }
+
+    if (pTcoef->level >= 128)
+    {
+        pTcoef->sign = 1;
+        pTcoef->level = 256 - pTcoef->level;
+    }
+    else
+    {
+        pTcoef->sign = 0;
+    }
+
+    if (pTcoef->level == 128)
+    {
+        code = BitstreamReadBits16(stream, 11);        /* ANNEX_T */
+
+        code = (code >> 6 & 0x1F) | (code << 5 & 0x7ff);
+        if (code > 1024)
+        {
+            pTcoef->sign = 1;
+            pTcoef->level = (2048 - code);
+        }
+        else
+        {
+            pTcoef->sign = 0;
+            pTcoef->level = code;
+        }
+    }
+
+    return PV_SUCCESS;
+
+}   /* VlcDecTCOEFShortHeader */
+
+
+PV_STATUS VlcDecTCOEFShortHeader_AnnexIT(BitstreamDecVideo *stream, Tcoef *pTcoef/*, int intra*/)
+{
+    uint code;
+    const VLCtab2 *tab;
+
+    BitstreamShow13Bits(stream, &code);
+
+    /*intra = 0;*/
+
+    if (code >= 1024) tab = &PV_DCT3Dtab6[(code >> 6) - 16];
+    else
+    {
+        if (code >= 256) tab = &PV_DCT3Dtab7[(code >> 3) - 32];
+        else
+        {
+            if (code >= 16) tab = &PV_DCT3Dtab8[(code>>1) - 8];
+            else return PV_FAIL;
+        }
+    }
+
+    PV_BitstreamFlushBits(stream, tab->len + 1);
+    pTcoef->sign = (code >> (12 - tab->len)) & 1;
+    pTcoef->run = (uint)tab->run;//(tab->val >> 4) & 255;
+    pTcoef->level = (int)tab->level;//tab->val & 15;
+    pTcoef->last = (uint)tab->last;//(tab->val >> 12) & 1;
+
+    /* the following is modified for 3-mode escape --  */
+    if (((tab->run << 6) | (tab->level) | (tab->last << 12)) != VLC_ESCAPE_CODE)    /* ESCAPE */
+    {
+        return PV_SUCCESS;
+    }
+    /* escape mode 4 - H.263 type */
+    pTcoef->last = pTcoef->sign; /* Last */
+    pTcoef->run = BitstreamReadBits16(stream, 6); /* Run */
+    pTcoef->level = (int) BitstreamReadBits16(stream, 8); /* Level */
+
+    if (pTcoef->level == 0)
+    {
+        return PV_FAIL;
+    }
+
+    if (pTcoef->level >= 128)
+    {
+        pTcoef->sign = 1;
+        pTcoef->level = 256 - pTcoef->level;
+    }
+    else
+    {
+        pTcoef->sign = 0;
+    }
+
+    if (pTcoef->level == 128)
+    {
+        code = BitstreamReadBits16(stream, 11);        /* ANNEX_T */
+
+        code = (code >> 6 & 0x1F) | (code << 5 & 0x7ff);
+        if (code > 1024)
+        {
+            pTcoef->sign = 1;
+            pTcoef->level = (2048 - code);
+        }
+        else
+        {
+            pTcoef->sign = 0;
+            pTcoef->level = code;
+        }
+    }
+
+
+    return PV_SUCCESS;
+
+}   /* VlcDecTCOEFShortHeader_AnnexI */
+#endif
+/***********************************************************CommentBegin******
+*       3/30/2000 : initial modification to the new PV-Decoder Lib
+*                           format and the change of error-handling method.
+*                           The coefficient is now returned thru a pre-
+*                           initialized parameters for speedup.
+*
+***********************************************************CommentEnd********/
+
+
+PV_STATUS RvlcDecTCOEFInter(BitstreamDecVideo *stream, Tcoef *pTcoef)
+{
+    uint code, mask;
+    const VLCtab2 *tab2;
+    int count, len, num[2] = {0, 0} /*  01/30/01 */;
+
+    mask = 0x4000;      /* mask  100000000000000   */
+    BitstreamShow15Bits(stream, &code);   /*  03/07/01 */
+
+    len = 1;
+
+    //  09/20/99 Escape mode
+    /// Bitstream Exchange
+    if (code < 2048)
+    {
+        PV_BitstreamFlushBits(stream, 5);
+        pTcoef->last = BitstreamRead1Bits_INLINE(stream);
+        pTcoef->run = BitstreamReadBits16_INLINE(stream, 6);
+        //  09/20/99 New marker bit
+        PV_BitstreamFlushBits(stream, 1);
+        //  09/20/99 The length for LEVEL used to be 7 in the old version
+        pTcoef->level = (int)(BitstreamReadBits16_INLINE(stream, 12) >> 1);
+        //  09/20/99 Another new marker bit
+//      PV_BitstreamFlushBitsCheck(stream, 1);
+        pTcoef->sign = BitstreamReadBits16_INLINE(stream, 5) & 0x1;  /* fix   3/13/01  */
+        return PV_SUCCESS;
+    }
+
+    if (code & mask)
+    {
+        count = 1;
+        while (mask && count > 0)       /* fix  3/28/01  */
+        {
+            mask = mask >> 1;
+            if (code & mask)
+                count--;
+            else
+                num[0]++; /* number of zeros in the middle */
+            len++;
+        }
+    }
+    else
+    {
+        count = 2;
+        while (mask && count > 0)           /* fix  3/28/01  */
+        {
+            mask = mask >> 1;
+            if (!(code & mask))
+                count--;
+            else
+                num[count-1]++; /* number of ones in the middle */
+            len++;
+        }
+    }
+
+    code = code & 0x7fff;
+    code = code >> (15 - (len + 1));
+
+    /*  1/30/01, add fast decoding algorithm here */
+    /* code is in two forms : 0xxxx0xxx00 or 0xxx0xxx01
+                         num[1] and num[0] x
+                        or  : 1xxxxx10 or 1xxxxx11
+                                num[0]  x      */
+
+    /* len+1 is the length of the above */
+
+    if (num[1] > 10 || num[0] > 11) /* invalid RVLC code */
+        return PV_FAIL;
+
+    if (code&(1 << len))
+        tab2 = RvlcDCTtabInter + 146 + (num[0] << 1) + (code & 1);
+    else
+        tab2 = RvlcDCTtabInter + ptrRvlcTab[num[1]] + (num[0] << 1) + (code & 1);
+
+    PV_BitstreamFlushBits(stream, (int) tab2->len);
+    pTcoef->run = (uint)tab2->run;//(tab->val >> 8) & 255;
+    pTcoef->level = (int)tab2->level;//tab->val & 255;
+    pTcoef->last = (uint)tab2->last;//(tab->val >> 16) & 1;
+
+    pTcoef->sign = BitstreamRead1Bits_INLINE(stream);
+    return PV_SUCCESS;
+}               /* RvlcDecTCOEFInter */
+
+PV_STATUS RvlcDecTCOEFIntra(BitstreamDecVideo *stream, Tcoef *pTcoef)
+{
+    uint code, mask;
+    const VLCtab2 *tab2;
+    int count, len, num[2] = {0, 0} /*  01/30/01 */;
+
+    mask = 0x4000;      /* mask  100000000000000   */
+    BitstreamShow15Bits(stream, &code);
+
+    len = 1;
+
+    //  09/20/99 Escape mode
+    /// Bitstream Exchange
+    if (code < 2048)
+    {
+        PV_BitstreamFlushBits(stream, 5);
+        pTcoef->last = BitstreamRead1Bits_INLINE(stream);
+        pTcoef->run = BitstreamReadBits16_INLINE(stream, 6);
+        //  09/20/99 New marker bit
+        PV_BitstreamFlushBits(stream, 1);
+        //  09/20/99 The length for LEVEL used to be 7 in the old version
+        pTcoef->level = (int)(BitstreamReadBits16_INLINE(stream, 12) >> 1);
+        //  09/20/99 Another new marker bit
+//      PV_BitstreamFlushBitsCheck(stream, 1);
+        pTcoef->sign = BitstreamReadBits16_INLINE(stream, 5) & 0x1; /* fix   03/13/01 */
+        return PV_SUCCESS;
+    }
+
+    if (code & mask)
+    {
+        count = 1;
+        while (mask && count > 0)                          /* fix  03/28/01 */
+        {
+            mask = mask >> 1;
+            if (code & mask)
+                count--;
+            else
+                num[0]++; /* number of zeros in the middle */
+            len++;
+        }
+    }
+    else
+    {
+        count = 2;
+        while (mask && count > 0)              /* fix  03/28/01 */
+        {
+            mask = mask >> 1;
+            if (!(code & mask))
+                count--;
+            else
+                num[count-1]++; /* number of ones in the middle */
+            len++;
+        }
+    }
+
+    code = code & 0x7fff;
+    code = code >> (15 - (len + 1));
+
+    /*  1/30/01, add fast decoding algorithm here */
+    /* code is in two forms : 0xxxx0xxx00 or 0xxx0xxx01
+                         num[1] and num[0] x
+                        or  : 1xxxxx10 or 1xxxxx11
+                                num[0]  x      */
+
+    /* len+1 is the length of the above */
+
+    if (num[1] > 10 || num[0] > 11) /* invalid RVLC code */
+        return PV_FAIL;
+
+    if (code & (1 << len))
+        tab2 = RvlcDCTtabIntra + 146 + (num[0] << 1) + (code & 1);
+    else
+        tab2 = RvlcDCTtabIntra + ptrRvlcTab[num[1]] + (num[0] << 1) + (code & 1);
+
+    PV_BitstreamFlushBits(stream, (int) tab2->len);
+    pTcoef->run = (uint)tab2->run;//(tab->val >> 8) & 255;
+    pTcoef->level = (int)tab2->level;//tab->val & 255;
+    pTcoef->last = (uint)tab2->last;//(tab->val >> 16) & 1;
+
+    pTcoef->sign = BitstreamRead1Bits_INLINE(stream);
+    return PV_SUCCESS;
+}               /* RvlcDecTCOEFIntra */
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.h
new file mode 100644
index 0000000..a804606
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_decode.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.
+ * -------------------------------------------------------------------
+ */
+/*
+-------------------------------------------------------------------
+                    MPEG-4 Simple Profile Video Decoder
+-------------------------------------------------------------------
+*
+* This software module was originally developed by
+*
+*   Paulo Nunes (IST / ACTS-MoMuSyS)
+*
+* in the course of development of the MPEG-4 Video (ISO/IEC 14496-2) standard.
+* This software module is an implementation of a part of one or more MPEG-4
+* Video (ISO/IEC 14496-2) tools as specified by the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* ISO/IEC gives users of the MPEG-4 Video (ISO/IEC 14496-2) standard free
+* license to this software module or modifications thereof for use in hardware
+* or software products claiming conformance to the MPEG-4 Video (ISO/IEC
+* 14496-2) standard.
+*
+* Those intending to use this software module in hardware or software products
+* are advised that its use may infringe existing patents. The original
+* developer of this software module and his/her company, the subsequent
+* editors and their companies, and ISO/IEC have no liability for use of this
+* software module or modifications thereof in an implementation. Copyright is
+* not released for non MPEG-4 Video (ISO/IEC 14496-2) Standard conforming
+* products.
+*
+* ACTS-MoMuSys partners retain full right to use the code for his/her own
+* purpose, assign or donate the code to a third party and to inhibit third
+* parties from using the code for non MPEG-4 Video (ISO/IEC 14496-2) Standard
+* conforming products. This copyright notice must be included in all copies or
+* derivative works.
+*
+* Copyright (c) 1996
+*
+*****************************************************************************/
+
+/***********************************************************HeaderBegin*******
+*
+* File: vlc_dec.h
+*
+* Author:   Paulo Nunes (IST) - Paulo.Nunes@lx.it.pt
+* Created:
+*
+* Description: This is the header file for the "vlcdec" module.
+*
+* Notes:
+*
+* Modified: 9-May-96 Paulo Nunes: Reformatted. New headers.
+*
+* ================= PacketVideo Modification ================================
+*
+*       3/30/00  : initial modification to the
+*                new PV-Decoder Lib format.
+*
+***********************************************************CommentEnd********/
+
+
+#ifndef _VLCDECODE_H_
+#define _VLCDECODE_H_
+
+#include "mp4lib_int.h"
+
+#define VLC_ERROR_DETECTED(x) ((x) < 0)
+#define VLC_IO_ERROR    -1
+#define VLC_CODE_ERROR  -2
+#define VLC_MB_STUFFING -4
+#define VLC_NO_LAST_BIT -5
+
+#define VLC_ESCAPE_CODE  7167
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+    PV_STATUS DecodeUserData(BitstreamDecVideo *stream);
+    PV_STATUS PV_GetMBvectors(VideoDecData *, uint mode);
+    PV_STATUS PV_DecodeMBVec(BitstreamDecVideo *stream, MOT *mv_x, MOT *mv_y, int f_code_f);
+    PV_STATUS PV_DeScaleMVD(int f_code, int residual, int vlc_code_mag,  MOT *vector);
+
+    PV_STATUS PV_VlcDecMV(BitstreamDecVideo *stream, int *mv);
+    int PV_VlcDecMCBPC_com_intra(BitstreamDecVideo *stream);
+    int PV_VlcDecMCBPC_com_inter(BitstreamDecVideo *stream);
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    int PV_VlcDecMCBPC_com_inter_H263(BitstreamDecVideo *stream);
+    PV_STATUS VlcDecTCOEFShortHeader_AnnexI(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS VlcDecTCOEFShortHeader_AnnexT(BitstreamDecVideo *stream, Tcoef *pTcoef); /* ANNEX_T */
+    PV_STATUS VlcDecTCOEFShortHeader_AnnexIT(BitstreamDecVideo *stream, Tcoef *pTcoef);
+#endif
+    int PV_VlcDecCBPY(BitstreamDecVideo *stream, int intra);
+
+    PV_STATUS VlcDecTCOEFIntra(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS VlcDecTCOEFInter(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS VlcDecTCOEFShortHeader(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS RvlcDecTCOEFIntra(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS RvlcDecTCOEFInter(BitstreamDecVideo *stream, Tcoef *pTcoef);
+    PV_STATUS PV_VlcDecIntraDCPredSize(BitstreamDecVideo *stream, int compnum, uint *DC_size);
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus  */
+
+#endif
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dequant.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dequant.cpp
new file mode 100644
index 0000000..db13a48
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_dequant.cpp
@@ -0,0 +1,1152 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "vlc_decode.h"
+#include "zigzag.h"
+
+
+typedef PV_STATUS(*VlcDecFuncP)(BitstreamDecVideo *stream, Tcoef *pTcoef);
+static const uint8 AC_rowcol[64] = {    0, 0, 0, 0, 0, 0, 0, 0,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                        0, 1, 1, 1, 1, 1, 1, 1,
+                                   };
+static const uint8 mask[8] = /*  for fast bitmap */
+    {128, 64, 32, 16, 8, 4, 2, 1};
+
+
+
+/***********************************************************CommentBegin******
+*
+* -- VlcDequantMpegBlock -- Decodes the DCT coefficients of one 8x8 block and perform
+            dequantization using Mpeg mode.
+    Date:       08/08/2000
+
+    Modified:      3/21/01
+                Added pre IDCT clipping, new ACDC prediction structure, ACDC prediction clipping,
+                16-bit int case, removed multiple zigzaging
+******************************************************************************/
+
+#ifdef PV_SUPPORT_MAIN_PROFILE
+int VlcDequantMpegIntraBlock(void *vid, int comp, int switched,
+                             uint8 *bitmapcol, uint8 *bitmaprow)
+{
+    VideoDecData *video = (VideoDecData*) vid;
+    Vol *currVol = video->vol[video->currLayer];
+    BitstreamDecVideo *stream = video->bitstream;
+    int16 *datablock = video->mblock->block[comp]; /* 10/20/2000, assume it has been reset of all-zero !!!*/
+    int mbnum = video->mbnum;
+    uint CBP = video->headerInfo.CBP[mbnum];
+    int QP = video->QPMB[mbnum];
+    typeDCStore *DC = video->predDC + mbnum;
+    int x_pos = video->mbnum_col;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+    uint ACpred_flag = (uint) video->acPredFlag[mbnum];
+
+    /*** VLC *****/
+    int i, j, k;
+    Tcoef run_level;
+    int last, return_status;
+    VlcDecFuncP vlcDecCoeff;
+    int direction;
+    const int *inv_zigzag;
+    /*** Quantizer ****/
+    int dc_scaler;
+    int sum;
+    int *qmat;
+    int32 temp;
+
+    const int B_Xtab[6] = {0, 1, 0, 1, 2, 3};
+    const int B_Ytab[6] = {0, 0, 1, 1, 2, 3};
+
+    int16 *dcac_row, *dcac_col;
+
+    dcac_row = (*DCAC_row)[B_Xtab[comp]];
+    dcac_col = (*DCAC_col)[B_Ytab[comp]];
+
+
+    i = 1 - switched;
+
+#ifdef FAST_IDCT
+    *((uint32*)bitmapcol) = *((uint32*)(bitmapcol + 4)) = 0;
+    *bitmaprow = 0;
+#endif
+
+
+    /* select which Huffman table to be used */
+    vlcDecCoeff = video->vlcDecCoeffIntra;
+
+    dc_scaler = (comp < 4) ? video->mblock->DCScalarLum : video->mblock->DCScalarChr;
+
+    /* enter the zero run decoding loop */
+    sum = 0;
+    qmat = currVol->iqmat;
+
+    /* perform only VLC decoding */
+    /* We cannot do DCACrecon before VLC decoding.  10/17/2000 */
+    doDCACPrediction(video, comp, datablock, &direction);
+    if (!ACpred_flag) direction = 0;
+    inv_zigzag = zigzag_inv + (ACpred_flag << 6) + (direction << 6);
+    if (CBP & (1 << (5 - comp)))
+    {
+        do
+        {
+            return_status = (*vlcDecCoeff)(stream, &run_level);
+            if (return_status != PV_SUCCESS)
+            {
+                last = 1;/*  11/1/2000 let it slips undetected, just like
+                         in original version */
+                i = VLC_ERROR;
+                ACpred_flag = 0;    /* no of coefficients should not get reset   03/07/2002 */
+                break;
+            }
+
+            i += run_level.run;
+            last = run_level.last;
+            if (i >= 64)
+            {
+                /*  i = NCOEFF_BLOCK; */    /*  11/1/00 */
+                ACpred_flag = 0;    /* no of coefficients should not get reset   03/07/2002 */
+                i = VLC_NO_LAST_BIT;
+                last = 1;
+                break;
+            }
+
+            k = inv_zigzag[i];
+
+            if (run_level.sign == 1)
+            {
+                datablock[k] -= run_level.level;
+            }
+            else
+            {
+                datablock[k] += run_level.level;
+            }
+
+            if (AC_rowcol[k])
+            {
+                temp = (int32)datablock[k] * qmat[k] * QP;
+                temp = (temp + (0x7 & (temp >> 31))) >> 3;
+                if (temp > 2047) temp = 2047;
+                else if (temp < -2048) temp = -2048;
+                datablock[k] = (int) temp;
+
+#ifdef FAST_IDCT
+                bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+                sum ^= temp;
+            }
+
+            i++;
+        }
+        while (!last);
+
+    }
+    else
+    {
+        i = 1;       /*  04/26/01  needed for switched case */
+    }
+    ///// NEED TO DEQUANT THOSE PREDICTED AC COEFF
+    /* dequantize the rest of AC predicted coeff that haven't been dequant */
+    if (ACpred_flag)
+    {
+
+        i = NCOEFF_BLOCK; /* otherwise, FAST IDCT won't work correctly,  10/18/2000 */
+
+        if (!direction) /* check vertical */
+        {
+            dcac_row[0]  = datablock[1];
+            dcac_row[1]  = datablock[2];
+            dcac_row[2]  = datablock[3];
+            dcac_row[3]  = datablock[4];
+            dcac_row[4]  = datablock[5];
+            dcac_row[5]  = datablock[6];
+            dcac_row[6]  = datablock[7];
+
+            for (j = 0, k = 8; k < 64; k += 8, j++)
+            {
+                if (dcac_col[j] = datablock[k])
+                {     /* ACDC clipping  03/26/01 */
+                    if (datablock[k] > 2047) dcac_col[j] = 2047;
+                    else if (datablock[k] < -2048) dcac_col[j] = -2048;
+
+                    temp = (int32)dcac_col[j] * qmat[k] * QP;
+                    temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01*/
+                    if (temp > 2047) temp = 2047;
+                    else if (temp < -2048) temp = -2048;
+                    datablock[k] = (int)temp;
+                    sum ^= temp; /*  7/5/01 */
+#ifdef FAST_IDCT
+                    bitmapcol[0] |= mask[k>>3];
+#endif
+
+                }
+            }
+            for (k = 1; k < 8; k++)
+            {
+                if (datablock[k])
+                {
+                    temp = (int32)datablock[k] * qmat[k] * QP;
+                    temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01*/
+                    if (temp > 2047) temp = 2047;
+                    else if (temp < -2048) temp = -2048;
+                    datablock[k] = (int)temp;
+                    sum ^= temp; /*  7/5/01 */
+#ifdef FAST_IDCT
+                    bitmapcol[k] |= 128;
+#endif
+
+                }
+            }
+
+        }
+        else
+        {
+
+            dcac_col[0]  = datablock[8];
+            dcac_col[1]  = datablock[16];
+            dcac_col[2]  = datablock[24];
+            dcac_col[3]  = datablock[32];
+            dcac_col[4]  = datablock[40];
+            dcac_col[5]  = datablock[48];
+            dcac_col[6]  = datablock[56];
+
+
+            for (j = 0, k = 1; k < 8; k++, j++)
+            {
+                if (dcac_row[j] = datablock[k])
+                {     /* ACDC clipping  03/26/01 */
+                    if (datablock[k] > 2047) dcac_row[j] = 2047;
+                    else if (datablock[k] < -2048) dcac_row[j] = -2048;
+
+                    temp = (int32)dcac_row[j] * qmat[k] * QP;
+                    temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01 */
+                    if (temp > 2047) temp = 2047;
+                    else if (temp < -2048) temp = -2048;
+                    datablock[k] = (int)temp;
+                    sum ^= temp;
+#ifdef FAST_IDCT
+                    bitmapcol[k] |= 128;
+#endif
+
+                }
+            }
+
+            for (k = 8; k < 64; k += 8)
+            {
+                if (datablock[k])
+                {
+                    temp = (int32)datablock[k] * qmat[k] * QP;
+                    temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01 */
+                    if (temp > 2047) temp = 2047;
+                    else if (temp < -2048) temp = -2048;
+                    datablock[k] = (int)temp;
+                    sum ^= temp;
+#ifdef FAST_IDCT
+                    bitmapcol[0] |= mask[k>>3];
+#endif
+                }
+            }
+
+        }
+    }
+    else
+    {
+
+        /* Store the qcoeff-values needed later for prediction */
+
+        dcac_row[0] = datablock[1];                /*  ACDC, no need for clipping */
+        dcac_row[1] = datablock[2];
+        dcac_row[2] = datablock[3];
+        dcac_row[3] = datablock[4];
+        dcac_row[4] = datablock[5];
+        dcac_row[5] = datablock[6];
+        dcac_row[6] = datablock[7];
+
+        dcac_col[0] = datablock[8];
+        dcac_col[1] = datablock[16];
+        dcac_col[2] = datablock[24];
+        dcac_col[3] = datablock[32];
+        dcac_col[4] = datablock[40];
+        dcac_col[5] = datablock[48];
+        dcac_col[6] = datablock[56];
+
+        for (k = 1; k < 8; k++)
+        {
+            if (datablock[k])
+            {
+                temp = (int32)datablock[k] * qmat[k] * QP;
+                temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01*/
+                if (temp > 2047) temp = 2047;
+                else if (temp < -2048) temp = -2048;
+                datablock[k] = (int)temp;
+                sum ^= temp; /*  7/5/01 */
+#ifdef FAST_IDCT
+                bitmapcol[k] |= 128;
+#endif
+
+            }
+        }
+        for (k = 8; k < 64; k += 8)
+        {
+            if (datablock[k])
+            {
+                temp = (int32)datablock[k] * qmat[k] * QP;
+                temp = (temp + (0x7 & (temp >> 31))) >> 3;  /*  03/26/01 */
+                if (temp > 2047) temp = 2047;
+                else if (temp < -2048) temp = -2048;
+                datablock[k] = (int)temp;
+                sum ^= temp;
+#ifdef FAST_IDCT
+                bitmapcol[0] |= mask[k>>3];
+#endif
+            }
+        }
+
+    }
+
+
+
+    if (datablock[0])
+    {
+        temp = (int32)datablock[0] * dc_scaler;
+        if (temp > 2047) temp = 2047;            /*  03/14/01 */
+        else if (temp < -2048)  temp = -2048;
+        datablock[0] = (int)temp;
+        sum ^= temp;
+#ifdef FAST_IDCT
+        bitmapcol[0] |= 128;
+#endif
+    }
+
+    if ((sum & 1) == 0)
+    {
+        datablock[63] = datablock[63] ^ 0x1;
+#ifdef FAST_IDCT   /*  7/5/01, need to update bitmap */
+        if (datablock[63])
+            bitmapcol[7] |= 1;
+#endif
+        i = (-64 & i) | NCOEFF_BLOCK;   /*  if i > -1 then i is set to NCOEFF_BLOCK */
+    }
+
+
+#ifdef FAST_IDCT
+    if (i > 10)
+    {
+        for (k = 1; k < 4; k++)
+        {
+            if (bitmapcol[k] != 0)
+            {
+                (*bitmaprow) |= mask[k];
+            }
+        }
+    }
+#endif
+
+    /* Store the qcoeff-values needed later for prediction */
+    (*DC)[comp] = datablock[0];
+    return i;
+
+}
+
+
+/***********************************************************CommentBegin******
+*
+* -- VlcDequantMpegInterBlock -- Decodes the DCT coefficients of one 8x8 block and perform
+            dequantization using Mpeg mode for INTER block.
+    Date:       08/08/2000
+    Modified:              3/21/01
+                clean up, added clipping, 16-bit int case, new ACDC prediction
+******************************************************************************/
+
+
+int VlcDequantMpegInterBlock(void *vid, int comp,
+                             uint8 *bitmapcol, uint8 *bitmaprow)
+{
+    VideoDecData *video = (VideoDecData*) vid;
+    BitstreamDecVideo *stream = video->bitstream;
+    Vol *currVol = video->vol[video->currLayer];
+    int16 *datablock = video->mblock->block[comp]; /* 10/20/2000, assume it has been reset of all-zero !!!*/
+    int mbnum = video->mbnum;
+    int QP = video->QPMB[mbnum];
+    /*** VLC *****/
+    int i, k;
+    Tcoef run_level;
+    int last, return_status;
+    VlcDecFuncP vlcDecCoeff;
+
+    /*** Quantizer ****/
+    int sum;
+    int *qmat;
+
+    int32 temp;
+
+    i = 0 ;
+
+#ifdef FAST_IDCT
+    *((uint32*)bitmapcol) = *((uint32*)(bitmapcol + 4)) = 0;
+    *bitmaprow = 0;
+#endif
+
+    /* select which Huffman table to be used */
+    vlcDecCoeff = video->vlcDecCoeffInter;
+
+    /* enter the zero run decoding loop */
+    sum = 0;
+    qmat = currVol->niqmat;
+    do
+    {
+        return_status = (*vlcDecCoeff)(stream, &run_level);
+        if (return_status != PV_SUCCESS)
+        {
+            last = 1;/*  11/1/2000 let it slips undetected, just like
+                     in original version */
+            i = VLC_ERROR;
+            sum = 1;    /* no of coefficients should not get reset   03/07/2002 */
+            break;
+        }
+
+        i += run_level.run;
+        last = run_level.last;
+        if (i >= 64)
+        {
+            /*  i = NCOEFF_BLOCK; */    /*  11/1/00 */
+            //return VLC_NO_LAST_BIT;
+            i = VLC_NO_LAST_BIT;
+            last = 1;
+            sum = 1;    /* no of coefficients should not get reset   03/07/2002 */
+            break;
+        }
+
+        k = zigzag_inv[i];
+
+        if (run_level.sign == 1)
+        {
+            temp = (-(int32)(2 * run_level.level + 1) * qmat[k] * QP + 15) >> 4; /*  03/23/01 */
+            if (temp < -2048) temp = - 2048;
+        }
+        else
+        {
+            temp = ((int32)(2 * run_level.level + 1) * qmat[k] * QP) >> 4; /*  03/23/01 */
+            if (temp > 2047) temp = 2047;
+        }
+
+        datablock[k] = (int)temp;
+
+#ifdef FAST_IDCT
+        bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+        sum ^= temp;
+
+        i++;
+    }
+    while (!last);
+
+    if ((sum & 1) == 0)
+    {
+        datablock[63] = datablock[63] ^ 0x1;
+#ifdef FAST_IDCT   /*  7/5/01, need to update bitmap */
+        if (datablock[63])
+            bitmapcol[7] |= 1;
+#endif
+        i = NCOEFF_BLOCK;
+    }
+
+
+#ifdef FAST_IDCT
+    if (i > 10)
+    {
+        for (k = 1; k < 4; k++)               /*  07/19/01 */
+        {
+            if (bitmapcol[k] != 0)
+            {
+                (*bitmaprow) |= mask[k];
+            }
+        }
+    }
+#endif
+
+    return i;
+}
+#endif
+/***********************************************************CommentBegin******
+*
+* -- VlcDequantIntraH263Block -- Decodes the DCT coefficients of one 8x8 block and perform
+            dequantization in H.263 mode for INTRA block.
+    Date:       08/08/2000
+    Modified:               3/21/01
+                clean up, added clipping, 16-bit int case, removed multiple zigzaging
+******************************************************************************/
+
+
+int VlcDequantH263IntraBlock(VideoDecData *video, int comp, int switched,
+                             uint8 *bitmapcol, uint8 *bitmaprow)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int16 *datablock = video->mblock->block[comp]; /* 10/20/2000, assume it has been reset of all-zero !!!*/
+    int32 temp;
+    int mbnum = video->mbnum;
+    uint CBP = video->headerInfo.CBP[mbnum];
+    int QP = video->QPMB[mbnum];
+    typeDCStore *DC = video->predDC + mbnum;
+    int x_pos = video->mbnum_col;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+    uint ACpred_flag = (uint) video->acPredFlag[mbnum];
+
+    /*** VLC *****/
+    int i, j, k;
+    Tcoef run_level;
+    int last, return_status;
+    VlcDecFuncP vlcDecCoeff;
+    int direction;
+    const int *inv_zigzag;
+
+    /*** Quantizer ****/
+    int dc_scaler;
+    int sgn_coeff;
+
+
+
+    const int B_Xtab[6] = {0, 1, 0, 1, 2, 3};
+    const int B_Ytab[6] = {0, 0, 1, 1, 2, 3};
+
+    int16 *dcac_row, *dcac_col;
+
+    dcac_row = (*DCAC_row)[B_Xtab[comp]];
+    dcac_col = (*DCAC_col)[B_Ytab[comp]];
+
+#ifdef FAST_IDCT
+    *((uint32*)bitmapcol) = *((uint32*)(bitmapcol + 4)) = 0;
+    *bitmaprow = 0;
+#endif
+    /* select which Huffman table to be used */
+    vlcDecCoeff = video->vlcDecCoeffIntra;
+
+    dc_scaler = (comp < 4) ? video->mblock->DCScalarLum : video->mblock->DCScalarChr;
+
+    /* perform only VLC decoding */
+    doDCACPrediction(video, comp, datablock, &direction);
+    if (!ACpred_flag) direction = 0;
+
+    inv_zigzag = zigzag_inv + (ACpred_flag << 6) + (direction << 6);  /*  04/17/01 */
+
+    i = 1;
+    if (CBP & (1 << (5 - comp)))
+    {
+        i = 1 - switched;
+        do
+        {
+            return_status = (*vlcDecCoeff)(stream, &run_level);
+            if (return_status != PV_SUCCESS)
+            {
+                last = 1;/* 11/1/2000 let it slips undetected, just like
+                         in original version */
+                i = VLC_ERROR;
+                ACpred_flag = 0;   /* no of coefficients should not get reset   03/07/2002 */
+                break;
+            }
+
+            i += run_level.run;
+            last = run_level.last;
+            if (i >= 64)
+            {
+                ACpred_flag = 0;    /* no of coefficients should not get reset   03/07/2002 */
+                i = VLC_NO_LAST_BIT;
+                last = 1;
+                break;
+            }
+
+            k = inv_zigzag[i];
+
+            if (run_level.sign == 1)
+            {
+                datablock[k] -= run_level.level;
+                sgn_coeff = -1;
+            }
+            else
+            {
+                datablock[k] += run_level.level;
+                sgn_coeff = 1;
+            }
+
+
+            if (AC_rowcol[k])   /*  10/25/2000 */
+            {
+                temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                else if (temp < -2048)  temp = -2048;
+                datablock[k] = (int16) temp;
+
+#ifdef FAST_IDCT
+                bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+            }
+
+            i++;
+        }
+        while (!last);
+
+    }
+
+    ///// NEED TO DEQUANT THOSE PREDICTED AC COEFF
+    /* dequantize the rest of AC predicted coeff that haven't been dequant */
+    if (ACpred_flag)
+    {
+
+        i = NCOEFF_BLOCK; /* otherwise, FAST IDCT won't work correctly,  10/18/2000 */
+
+        if (!direction) /* check vertical */
+        {
+
+            dcac_row[0]  = datablock[1];
+            dcac_row[1]  = datablock[2];
+            dcac_row[2]  = datablock[3];
+            dcac_row[3]  = datablock[4];
+            dcac_row[4]  = datablock[5];
+            dcac_row[5]  = datablock[6];
+            dcac_row[6]  = datablock[7];
+
+            for (j = 0, k = 8; k < 64; k += 8, j++)
+            {
+                dcac_col[j] = datablock[k];
+                if (dcac_col[j])
+                {
+                    if (datablock[k] > 0)
+                    {
+                        if (datablock[k] > 2047) dcac_col[j] = 2047;
+                        sgn_coeff = 1;
+                    }
+                    else
+                    {
+                        if (datablock[k] < -2048) dcac_col[j] = -2048;
+                        sgn_coeff = -1;
+                    }
+                    temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                    if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                    else if (temp < -2048)  temp = -2048;
+                    datablock[k] = (int16) temp;
+#ifdef FAST_IDCT
+                    bitmapcol[0] |= mask[k>>3];
+#endif
+
+                }
+            }
+
+            for (k = 1; k < 8; k++)
+            {
+                if (datablock[k])
+                {
+                    sgn_coeff = (datablock[k] > 0) ? 1 : -1;
+                    temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                    if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                    else if (temp < -2048)  temp = -2048;
+                    datablock[k] = (int16) temp;
+#ifdef FAST_IDCT
+                    bitmapcol[k] |= 128;
+#endif
+
+                }
+            }
+        }
+        else
+        {
+
+            dcac_col[0]  = datablock[8];
+            dcac_col[1]  = datablock[16];
+            dcac_col[2]  = datablock[24];
+            dcac_col[3]  = datablock[32];
+            dcac_col[4]  = datablock[40];
+            dcac_col[5]  = datablock[48];
+            dcac_col[6]  = datablock[56];
+
+
+            for (j = 0, k = 1; k < 8; k++, j++)
+            {
+                dcac_row[j] = datablock[k];
+                if (dcac_row[j])
+                {
+                    if (datablock[k] > 0)
+                    {
+                        if (datablock[k] > 2047) dcac_row[j] = 2047;
+                        sgn_coeff = 1;
+                    }
+                    else
+                    {
+                        if (datablock[k] < -2048) dcac_row[j] = -2048;
+                        sgn_coeff = -1;
+                    }
+
+                    temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                    if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                    else if (temp < -2048)  temp = -2048;
+                    datablock[k] = (int) temp;
+#ifdef FAST_IDCT
+                    bitmapcol[k] |= 128;
+#endif
+
+                }
+            }
+            for (k = 8; k < 64; k += 8)
+            {
+                if (datablock[k])
+                {
+                    sgn_coeff = (datablock[k] > 0) ? 1 : -1;
+                    temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                    if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                    else if (temp < -2048)  temp = -2048;
+                    datablock[k] = (int16) temp;
+#ifdef FAST_IDCT
+                    bitmapcol[0] |= mask[k>>3];
+#endif
+                }
+            }
+
+        }
+    }
+    else
+    {
+        dcac_row[0]  = datablock[1];
+        dcac_row[1]  = datablock[2];
+        dcac_row[2]  = datablock[3];
+        dcac_row[3]  = datablock[4];
+        dcac_row[4]  = datablock[5];
+        dcac_row[5]  = datablock[6];
+        dcac_row[6]  = datablock[7];
+
+        dcac_col[0]  = datablock[8];
+        dcac_col[1]  = datablock[16];
+        dcac_col[2]  = datablock[24];
+        dcac_col[3]  = datablock[32];
+        dcac_col[4]  = datablock[40];
+        dcac_col[5]  = datablock[48];
+        dcac_col[6]  = datablock[56];
+
+        for (k = 1; k < 8; k++)
+        {
+            if (datablock[k])
+            {
+                sgn_coeff = (datablock[k] > 0) ? 1 : -1;
+                temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                else if (temp < -2048)  temp = -2048;
+                datablock[k] = (int16) temp;
+#ifdef FAST_IDCT
+                bitmapcol[k] |= 128;
+#endif
+            }
+        }
+        for (k = 8; k < 64; k += 8)
+        {
+            if (datablock[k])
+            {
+                sgn_coeff = (datablock[k] > 0) ? 1 : -1;
+                temp = (int32)QP * (2 * datablock[k] + sgn_coeff) - sgn_coeff + (QP & 1) * sgn_coeff;
+                if (temp > 2047) temp = 2047;            /*  03/14/01 */
+                else if (temp < -2048)  temp = -2048;
+                datablock[k] = (int16) temp;
+#ifdef FAST_IDCT
+                bitmapcol[0] |= mask[k>>3];
+#endif
+            }
+        }
+    }
+    if (datablock[0])
+    {
+#ifdef FAST_IDCT
+        bitmapcol[0] |= 128;
+#endif
+
+        temp = (int32)datablock[0] * dc_scaler;
+        if (temp > 2047) temp = 2047;            /*  03/14/01 */
+        else if (temp < -2048)  temp = -2048;
+        datablock[0] = (int16)temp;
+    }
+
+
+#ifdef FAST_IDCT
+    if (i > 10)
+    {
+        for (k = 1; k < 4; k++)  /* if i > 10 then k = 0 does not matter  */
+        {
+            if (bitmapcol[k] != 0)
+            {
+                (*bitmaprow) |= mask[k]; /* (1<<(7-i)); */
+            }
+        }
+    }
+#endif
+
+    /* Store the qcoeff-values needed later for prediction */
+    (*DC)[comp] = datablock[0];
+    return i;
+}
+
+int VlcDequantH263IntraBlock_SH(VideoDecData *video, int comp, uint8 *bitmapcol, uint8 *bitmaprow)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int16 *datablock = video->mblock->block[comp]; /*, 10/20/2000, assume it has been reset of all-zero !!!*/
+    int32 temp;
+    int mbnum = video->mbnum;
+    uint CBP = video->headerInfo.CBP[mbnum];
+    int16 QP = video->QPMB[mbnum];
+    typeDCStore *DC = video->predDC + mbnum;
+    int x_pos = video->mbnum_col;
+    typeDCACStore *DCAC_row = video->predDCAC_row + x_pos;
+    typeDCACStore *DCAC_col = video->predDCAC_col;
+    uint ACpred_flag = (uint) video->acPredFlag[mbnum];
+
+    /*** VLC *****/
+    int i, k;
+    Tcoef run_level;
+    int last, return_status;
+    VlcDecFuncP vlcDecCoeff;
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    int direction;
+    const int *inv_zigzag;
+#endif
+    /*** Quantizer ****/
+
+
+
+    const int B_Xtab[6] = {0, 1, 0, 1, 2, 3};
+    const int B_Ytab[6] = {0, 0, 1, 1, 2, 3};
+
+    int16 *dcac_row, *dcac_col;
+
+    dcac_row = (*DCAC_row)[B_Xtab[comp]];
+    dcac_col = (*DCAC_col)[B_Ytab[comp]];
+    i = 1;
+
+#ifdef FAST_IDCT
+    *((uint32*)bitmapcol) = *((uint32*)(bitmapcol + 4)) = 0;
+    *bitmaprow = 0;
+#endif
+
+    /* select which Huffman table to be used */
+    vlcDecCoeff = video->vlcDecCoeffIntra;
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    if (comp > 3)        /* ANNEX_T */
+    {
+        QP = video->QP_CHR;
+    }
+    if (!video->advanced_INTRA)
+    {
+#endif
+
+        if ((CBP & (1 << (5 - comp))) == 0)
+        {
+#ifdef FAST_IDCT
+            bitmapcol[0] = 128;
+            bitmapcol[1] = bitmapcol[2] = bitmapcol[3] = bitmapcol[4] = bitmapcol[5] = bitmapcol[6] = bitmapcol[7] = 0;
+#endif
+            datablock[0] <<= 3;  /* no need to clip */
+            return 1;//ncoeffs;
+        }
+        else
+        {
+            /* enter the zero run decoding loop */
+            do
+            {
+                return_status = (*vlcDecCoeff)(stream, &run_level);
+                if (return_status != PV_SUCCESS)
+                {
+                    last = 1;/*  11/1/2000 let it slips undetected, just like
+                             in original version */
+                    i = VLC_ERROR;
+                    break;
+                }
+
+                i += run_level.run;
+                last = run_level.last;
+                if (i >= 64)
+                {
+                    /*  i = NCOEFF_BLOCK; */    /*  11/1/00 */
+                    i = VLC_NO_LAST_BIT;
+                    last = 1;
+                    break;
+                }
+                k = zigzag_inv[i];
+
+                if (run_level.sign == 0)
+                {
+                    temp = (int32)QP * (2 * run_level.level + 1) - 1 + (QP & 1);
+                    if (temp > 2047) temp = 2047;
+                }
+                else
+                {
+                    temp = -(int32)QP * (2 * run_level.level + 1) + 1 - (QP & 1);
+                    if (temp < -2048) temp = -2048;
+                }
+
+
+                datablock[k] = (int16) temp;
+
+#ifdef FAST_IDCT
+                bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+                i++;
+            }
+            while (!last);
+
+        }
+        /* no ACDC prediction when ACDC disable  */
+        if (datablock[0])
+        {
+#ifdef FAST_IDCT
+            bitmapcol[0] |= 128;
+#endif
+            datablock[0] <<= 3;        /* no need to clip  09/18/2001 */
+        }
+#ifdef PV_ANNEX_IJKT_SUPPORT
+    }
+    else  /* advanced_INTRA mode */
+    {
+        i = 1;
+        doDCACPrediction_I(video, comp, datablock);
+        /* perform only VLC decoding */
+        if (!ACpred_flag)
+        {
+            direction = 0;
+        }
+        else
+        {
+            direction = video->mblock->direction;
+        }
+
+        inv_zigzag = zigzag_inv + (ACpred_flag << 6) + (direction << 6);  /*  04/17/01 */
+
+        if (CBP & (1 << (5 - comp)))
+        {
+            i = 0;
+            do
+            {
+                return_status = (*vlcDecCoeff)(stream, &run_level);
+                if (return_status != PV_SUCCESS)
+                {
+                    last = 1;/*  11/1/2000 let it slips undetected, just like
+                                 in original version */
+                    i = VLC_ERROR;
+                    ACpred_flag = 0;   /* no of coefficients should not get reset   03/07/2002 */
+                    break;
+                }
+
+                i += run_level.run;
+                last = run_level.last;
+                if (i >= 64)
+                {
+                    /*                  i = NCOEFF_BLOCK; */    /*  11/1/00 */
+                    ACpred_flag = 0;    /* no of coefficients should not get reset   03/07/2002 */
+                    i = VLC_NO_LAST_BIT;
+                    last = 1;
+                    break;
+                }
+
+                k = inv_zigzag[i];
+
+                if (run_level.sign == 0)
+                {
+                    datablock[k] += (int16)QP * 2 * run_level.level;
+                    if (datablock[k] > 2047) datablock[k] = 2047;
+                }
+                else
+                {
+                    datablock[k] -= (int16)QP * 2 * run_level.level;
+                    if (datablock[k] < -2048) datablock[k] = -2048;
+                }
+#ifdef FAST_IDCT
+                bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+
+                i++;
+            }
+            while (!last);
+
+        }
+        ///// NEED TO DEQUANT THOSE PREDICTED AC COEFF
+        /* dequantize the rest of AC predicted coeff that haven't been dequant */
+
+        if (ACpred_flag)
+        {
+            i = NCOEFF_BLOCK;
+            for (k = 1; k < 8; k++)
+            {
+                if (datablock[k])
+                {
+                    bitmapcol[k] |= 128;
+                }
+
+                if (datablock[k<<3])
+                {
+                    bitmapcol[0] |= mask[k];
+                }
+            }
+        }
+
+        dcac_row[0]  = datablock[1];
+        dcac_row[1]  = datablock[2];
+        dcac_row[2]  = datablock[3];
+        dcac_row[3]  = datablock[4];
+        dcac_row[4]  = datablock[5];
+        dcac_row[5]  = datablock[6];
+        dcac_row[6]  = datablock[7];
+
+        dcac_col[0]  = datablock[8];
+        dcac_col[1]  = datablock[16];
+        dcac_col[2]  = datablock[24];
+        dcac_col[3]  = datablock[32];
+        dcac_col[4]  = datablock[40];
+        dcac_col[5]  = datablock[48];
+        dcac_col[6]  = datablock[56];
+
+        if (datablock[0])
+        {
+#ifdef FAST_IDCT
+            bitmapcol[0] |= 128;
+#endif
+
+            datablock[0] |= 1;
+            if (datablock[0] < 0)
+            {
+                datablock[0] = 0;
+            }
+        }
+    }
+#endif
+
+#ifdef FAST_IDCT
+    if (i > 10)
+    {
+        for (k = 1; k < 4; k++)  /* if i > 10 then k = 0 does not matter  */
+        {
+            if (bitmapcol[k] != 0)
+            {
+                (*bitmaprow) |= mask[k]; /* (1<<(7-i)); */
+            }
+        }
+    }
+#endif
+
+    /* Store the qcoeff-values needed later for prediction */
+    (*DC)[comp] = datablock[0];
+    return i;
+}
+
+/***********************************************************CommentBegin******
+*
+* -- VlcDequantInterH263Block -- Decodes the DCT coefficients of one 8x8 block and perform
+            dequantization in H.263 mode for INTER block.
+    Date:       08/08/2000
+    Modified:             3/21/01
+                clean up, added clipping, 16-bit int case
+******************************************************************************/
+
+
+int VlcDequantH263InterBlock(VideoDecData *video, int comp,
+                             uint8 *bitmapcol, uint8 *bitmaprow)
+{
+    BitstreamDecVideo *stream = video->bitstream;
+    int16 *datablock = video->mblock->block[comp]; /* 10/20/2000, assume it has been reset of all-zero !!!*/
+    int32 temp;
+    int mbnum = video->mbnum;
+    int QP = video->QPMB[mbnum];
+
+    /*** VLC *****/
+    int i, k;
+    Tcoef run_level;
+    int last, return_status;
+    VlcDecFuncP vlcDecCoeff;
+
+    /*** Quantizer ****/
+
+
+    i = 0;
+
+#ifdef FAST_IDCT
+    *((uint32*)bitmapcol) = *((uint32*)(bitmapcol + 4)) = 0;
+    *bitmaprow = 0;
+#endif
+
+    /* select which Huffman table to be used */
+    vlcDecCoeff = video->vlcDecCoeffInter;
+
+    /* enter the zero run decoding loop */
+    do
+    {
+        return_status = (*vlcDecCoeff)(stream, &run_level);
+        if (return_status != PV_SUCCESS)
+        {
+
+
+            last = 1;/*  11/1/2000 let it slips undetected, just like
+                     in original version */
+            i = -1;
+            break;
+        }
+
+        i += run_level.run;
+        last = run_level.last;
+        if (i >= 64)
+        {
+            i = -1;
+            last = 1;
+            break;
+        }
+
+        if (run_level.sign == 0)
+        {
+            temp = (int32)QP * (2 * run_level.level + 1) - 1 + (QP & 1);
+            if (temp > 2047) temp = 2047;
+
+        }
+        else
+        {
+            temp = -(int32)QP * (2 * run_level.level + 1) + 1 - (QP & 1);
+            if (temp < -2048) temp = -2048;
+        }
+
+        k = zigzag_inv[i];
+        datablock[k] = (int16)temp;
+#ifdef FAST_IDCT
+        bitmapcol[k&0x7] |= mask[k>>3];
+#endif
+        i++;
+    }
+    while (!last);
+
+#ifdef FAST_IDCT
+    if (i > 10)         /*  07/19/01 */
+    {
+        for (k = 1; k < 4; k++)       /*  if (i > 10 ) k = 0 does not matter */
+        {
+            if (bitmapcol[k] != 0)
+            {
+                (*bitmaprow) |= mask[k]; /* (1<<(7-i)); */
+            }
+        }
+    }
+#endif
+    return i;
+}
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vlc_tab.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_tab.cpp
new file mode 100644
index 0000000..704992f
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vlc_tab.cpp
@@ -0,0 +1,835 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include    "mp4dec_api.h"
+#include    "mp4def.h"
+#include    "mp4lib_int.h"
+#include    "vlc_dec_tab.h"
+#include    "max_level.h"
+
+
+const int intra_max_level[2][NCOEFF_BLOCK] =
+{
+    {27, 10,  5,  4,  3,  3,  3,  3,
+        2,  2,  1,  1,  1,  1,  1,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+    },
+
+    {8,  3,  2,  2,  2,  2,  2,  1,
+     1,  1,  1,  1,  1,  1,  1,  1,
+     1,  1,  1,  1,  1,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0
+    }
+};
+
+
+const int inter_max_level[2][NCOEFF_BLOCK] =
+{
+    {12,  6,  4,  3,  3,  3,  3,  2,
+        2,  2,  2,  1,  1,  1,  1,  1,
+        1,  1,  1,  1,  1,  1,  1,  1,
+        1,  1,  1,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0,
+        0,  0,  0,  0,  0,  0,  0,  0},
+
+    {3,  2,  1,  1,  1,  1,  1,  1,
+     1,  1,  1,  1,  1,  1,  1,  1,
+     1,  1,  1,  1,  1,  1,  1,  1,
+     1,  1,  1,  1,  1,  1,  1,  1,
+     1,  1,  1,  1,  1,  1,  1,  1,
+     1,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0,
+     0,  0,  0,  0,  0,  0,  0,  0}
+};
+
+
+const int intra_max_run0[28] = { 999, 14,  9,  7,  3,  2,  1,
+                                 1,  1,  1,  1,  0,  0,  0,
+                                 0,  0,  0,  0,  0,  0,  0,
+                                 0,  0,  0,  0,  0,  0,  0
+                               };
+
+
+const int intra_max_run1[9] = { 999, 20,  6,
+                                1,  0,  0,
+                                0,  0,  0
+                              };
+
+const int inter_max_run0[13] = { 999,
+                                 26, 10,  6,  2,  1,  1,
+                                 0,  0,  0,  0,  0,  0
+                               };
+
+
+const int inter_max_run1[4] = { 999, 40,  1,  0 };
+
+const VLCshorttab PV_TMNMVtab0[] =
+{
+    {3, 4}, { -3, 4}, {2, 3}, {2, 3}, { -2, 3}, { -2, 3}, {1, 2}, {1, 2}, {1, 2}, {1, 2},
+    { -1, 2}, { -1, 2}, { -1, 2}, { -1, 2}
+};
+
+const VLCshorttab PV_TMNMVtab1[] =
+{
+    {12, 10}, { -12, 10}, {11, 10}, { -11, 10}, {10, 9}, {10, 9}, { -10, 9}, { -10, 9},
+    {9, 9}, {9, 9}, { -9, 9}, { -9, 9}, {8, 9}, {8, 9}, { -8, 9}, { -8, 9}, {7, 7}, {7, 7},
+    {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, {7, 7}, { -7, 7}, { -7, 7}, { -7, 7}, { -7, 7},
+    { -7, 7}, { -7, 7}, { -7, 7}, { -7, 7}, {6, 7}, {6, 7}, {6, 7}, {6, 7}, {6, 7}, {6, 7},
+    {6, 7}, {6, 7}, { -6, 7}, { -6, 7}, { -6, 7}, { -6, 7}, { -6, 7}, { -6, 7}, { -6, 7},
+    { -6, 7}, {5, 7}, {5, 7}, {5, 7}, {5, 7}, {5, 7}, {5, 7}, {5, 7}, {5, 7}, { -5, 7},
+    { -5, 7}, { -5, 7}, { -5, 7}, { -5, 7}, { -5, 7}, { -5, 7}, { -5, 7}, {4, 6}, {4, 6}, {4, 6},
+    {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6},
+    {4, 6}, {4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6},
+    { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}, { -4, 6}
+};
+
+const VLCshorttab PV_TMNMVtab2[] =
+{
+    {32, 12}, { -32, 12}, {31, 12}, { -31, 12}, {30, 11}, {30, 11}, { -30, 11}, { -30, 11},
+    {29, 11}, {29, 11}, { -29, 11}, { -29, 11}, {28, 11}, {28, 11}, { -28, 11}, { -28, 11},
+    {27, 11}, {27, 11}, { -27, 11}, { -27, 11}, {26, 11}, {26, 11}, { -26, 11}, { -26, 11},
+    {25, 11}, {25, 11}, { -25, 11}, { -25, 11}, {24, 10}, {24, 10}, {24, 10}, {24, 10},
+    { -24, 10}, { -24, 10}, { -24, 10}, { -24, 10}, {23, 10}, {23, 10}, {23, 10}, {23, 10},
+    { -23, 10}, { -23, 10}, { -23, 10}, { -23, 10}, {22, 10}, {22, 10}, {22, 10}, {22, 10},
+    { -22, 10}, { -22, 10}, { -22, 10}, { -22, 10}, {21, 10}, {21, 10}, {21, 10}, {21, 10},
+    { -21, 10}, { -21, 10}, { -21, 10}, { -21, 10}, {20, 10}, {20, 10}, {20, 10}, {20, 10},
+    { -20, 10}, { -20, 10}, { -20, 10}, { -20, 10}, {19, 10}, {19, 10}, {19, 10}, {19, 10},
+    { -19, 10}, { -19, 10}, { -19, 10}, { -19, 10}, {18, 10}, {18, 10}, {18, 10}, {18, 10},
+    { -18, 10}, { -18, 10}, { -18, 10}, { -18, 10}, {17, 10}, {17, 10}, {17, 10}, {17, 10},
+    { -17, 10}, { -17, 10}, { -17, 10}, { -17, 10}, {16, 10}, {16, 10}, {16, 10}, {16, 10},
+    { -16, 10}, { -16, 10}, { -16, 10}, { -16, 10}, {15, 10}, {15, 10}, {15, 10}, {15, 10},
+    { -15, 10}, { -15, 10}, { -15, 10}, { -15, 10}, {14, 10}, {14, 10}, {14, 10}, {14, 10},
+    { -14, 10}, { -14, 10}, { -14, 10}, { -14, 10}, {13, 10}, {13, 10}, {13, 10}, {13, 10},
+    { -13, 10}, { -13, 10}, { -13, 10}, { -13, 10}
+};
+
+const VLCshorttab PV_MCBPCtab[] =
+{
+    {VLC_ERROR, 0},
+    {255, 9}, {52, 9}, {36, 9}, {20, 9}, {49, 9}, {35, 8}, {35, 8}, {19, 8}, {19, 8},
+    {50, 8}, {50, 8}, {51, 7}, {51, 7}, {51, 7}, {51, 7}, {34, 7}, {34, 7}, {34, 7},
+    {34, 7}, {18, 7}, {18, 7}, {18, 7}, {18, 7}, {33, 7}, {33, 7}, {33, 7}, {33, 7},
+    {17, 7}, {17, 7}, {17, 7}, {17, 7}, {4, 6}, {4, 6}, {4, 6}, {4, 6}, {4, 6},
+    {4, 6}, {4, 6}, {4, 6}, {48, 6}, {48, 6}, {48, 6}, {48, 6}, {48, 6}, {48, 6},
+    {48, 6}, {48, 6}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5},
+    {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5}, {3, 5},
+    {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4},
+    {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4},
+    {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4},
+    {32, 4}, {32, 4}, {32, 4}, {32, 4}, {32, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4},
+    {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4},
+    {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4},
+    {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4}, {16, 4},
+    {16, 4}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3}, {2, 3},
+    {2, 3}, {2, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3}, {1, 3},
+    {1, 3}, {1, 3}, {1, 3}
+};
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+const VLCshorttab PV_MCBPCtab1[] =
+{
+    {5, 11}, {5, 11},  {5, 11}, {5, 11}, {21, 13}, {21, 13}, {37, 13}, {53, 13},
+};
+#endif
+const VLCshorttab PV_MCBPCtabintra[] =
+{
+    {VLC_ERROR, 0},
+    {20, 6}, {36, 6}, {52, 6}, {4, 4}, {4, 4}, {4, 4},
+    {4, 4}, {19, 3}, {19, 3}, {19, 3}, {19, 3}, {19, 3},
+    {19, 3}, {19, 3}, {19, 3}, {35, 3}, {35, 3}, {35, 3},
+    {35, 3}, {35, 3}, {35, 3}, {35, 3}, {35, 3}, {51, 3},
+    {51, 3}, {51, 3}, {51, 3}, {51, 3}, {51, 3}, {51, 3},
+    {51, 3}
+};
+
+
+
+const VLCshorttab PV_CBPYtab[48] =
+{
+    {VLC_ERROR, 0}, {VLC_ERROR, 0}, {6, 6}, {9, 6}, {8, 5}, {8, 5}, {4, 5}, {4, 5},
+    {2, 5}, {2, 5}, {1, 5}, {1, 5}, {0, 4}, {0, 4}, {0, 4}, {0, 4},
+    {12, 4}, {12, 4}, {12, 4}, {12, 4}, {10, 4}, {10, 4}, {10, 4}, {10, 4},
+    {14, 4}, {14, 4}, {14, 4}, {14, 4}, {5, 4}, {5, 4}, {5, 4}, {5, 4},
+    {13, 4}, {13, 4}, {13, 4}, {13, 4}, {3, 4}, {3, 4}, {3, 4}, {3, 4},
+    {11, 4}, {11, 4}, {11, 4}, {11, 4}, {7, 4}, {7, 4}, {7, 4}, {7, 4}
+};
+
+
+
+const VLCtab2 PV_DCT3Dtab0[] =
+{
+    {0x8, 1, 1, 7}, {0x7, 1, 1, 7}, {0x6, 1, 1, 7}, {0x5, 1, 1, 7}, {0xc, 1, 0, 7}, {0xb, 1, 0, 7},
+    {0xa, 1, 0, 7}, {0x0, 4, 0, 7}, {0x4, 1, 1, 6}, {0x4, 1, 1, 6}, {0x3, 1, 1, 6}, {0x3, 1, 1, 6},
+    {0x2, 1, 1, 6}, {0x2, 1, 1, 6}, {0x1, 1, 1, 6}, {0x1, 1, 1, 6}, {0x9, 1, 0, 6}, {0x9, 1, 0, 6},
+    {0x8, 1, 0, 6}, {0x8, 1, 0, 6}, {0x7, 1, 0, 6}, {0x7, 1, 0, 6}, {0x6, 1, 0, 6}, {0x6, 1, 0, 6},
+    {0x1, 2, 0, 6}, {0x1, 2, 0, 6}, {0x0, 3, 0, 6}, {0x0, 3, 0, 6}, {0x5, 1, 0, 5}, {0x5, 1, 0, 5},
+    {0x5, 1, 0, 5}, {0x5, 1, 0, 5}, {0x4, 1, 0, 5}, {0x4, 1, 0, 5}, {0x4, 1, 0, 5}, {0x4, 1, 0, 5},
+    {0x3, 1, 0, 5}, {0x3, 1, 0, 5}, {0x3, 1, 0, 5}, {0x3, 1, 0, 5}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3},
+    {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3},
+    {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3}, {0x1, 1, 0, 3},
+    {0x2, 1, 0, 4}, {0x2, 1, 0, 4}, {0x2, 1, 0, 4}, {0x2, 1, 0, 4}, {0x2, 1, 0, 4}, {0x2, 1, 0, 4},
+    {0x2, 1, 0, 4}, {0x2, 1, 0, 4}, {0x0, 2, 0, 4}, {0x0, 2, 0, 4}, {0x0, 2, 0, 4}, {0x0, 2, 0, 4},
+    {0x0, 2, 0, 4}, {0x0, 2, 0, 4}, {0x0, 2, 0, 4}, {0x0, 2, 0, 4}
+};
+
+
+const VLCtab2 PV_DCT3Dtab1[] =
+{
+    {0x0, 9, 0, 10}, {0x0, 8, 0, 10}, {0x18, 1, 1, 9}, {0x18, 1, 1, 9}, {0x17, 1, 1, 9}, {0x17, 1, 1, 9},
+    {0x16, 1, 1, 9}, {0x16, 1, 1, 9}, {0x15, 1, 1, 9}, {0x15, 1, 1, 9}, {0x14, 1, 1, 9}, {0x14, 1, 1, 9},
+    {0x13, 1, 1, 9}, {0x13, 1, 1, 9}, {0x12, 1, 1, 9}, {0x12, 1, 1, 9}, {0x11, 1, 1, 9}, {0x11, 1, 1, 9},
+    {0x0, 2, 1, 9}, {0x0, 2, 1, 9}, {0x16, 1, 0, 9}, {0x16, 1, 0, 9}, {0x15, 1, 0, 9}, {0x15, 1, 0, 9},
+    {0x14, 1, 0, 9}, {0x14, 1, 0, 9}, {0x13, 1, 0, 9}, {0x13, 1, 0, 9}, {0x12, 1, 0, 9}, {0x12, 1, 0, 9},
+    {0x11, 1, 0, 9}, {0x11, 1, 0, 9}, {0x10, 1, 0, 9}, {0x10, 1, 0, 9}, {0xf, 1, 0, 9}, {0xf, 1, 0, 9},
+    {0x4, 2, 0, 9}, {0x4, 2, 0, 9}, {0x3, 2, 0, 9}, {0x3, 2, 0, 9}, {0x0, 7, 0, 9}, {0x0, 7, 0, 9},
+    {0x0, 6, 0, 9}, {0x0, 6, 0, 9}, {0x10, 1, 1, 8}, {0x10, 1, 1, 8}, {0x10, 1, 1, 8}, {0x10, 1, 1, 8},
+    {0xf, 1, 1, 8}, {0xf, 1, 1, 8}, {0xf, 1, 1, 8}, {0xf, 1, 1, 8}, {0xe, 1, 1, 8}, {0xe, 1, 1, 8},
+    {0xe, 1, 1, 8}, {0xe, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8},
+    {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xb, 1, 1, 8}, {0xb, 1, 1, 8},
+    {0xb, 1, 1, 8}, {0xb, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8},
+    {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0xe, 1, 0, 8}, {0xe, 1, 0, 8},
+    {0xe, 1, 0, 8}, {0xe, 1, 0, 8}, {0xd, 1, 0, 8}, {0xd, 1, 0, 8}, {0xd, 1, 0, 8}, {0xd, 1, 0, 8},
+    {0x2, 2, 0, 8}, {0x2, 2, 0, 8}, {0x2, 2, 0, 8}, {0x2, 2, 0, 8}, {0x1, 3, 0, 8}, {0x1, 3, 0, 8},
+    {0x1, 3, 0, 8}, {0x1, 3, 0, 8}, {0x0, 5, 0, 8}, {0x0, 5, 0, 8}, {0x0, 5, 0, 8}, {0x0, 5, 0, 8}
+};
+
+
+const VLCtab2 PV_DCT3Dtab2[] =
+{
+    {0x1, 2, 1, 11}, {0x1, 2, 1, 11}, {0x0, 3, 1, 11}, {0x0, 3, 1, 11}, {0x0, 0xb, 0, 11}, {0x0, 0xb, 0, 11},
+    {0x0, 0xa, 0, 11}, {0x0, 0xa, 0, 11}, {0x1c, 1, 1, 10}, {0x1c, 1, 1, 10}, {0x1c, 1, 1, 10}, {0x1c, 1, 1, 10},
+    {0x1b, 1, 1, 10}, {0x1b, 1, 1, 10}, {0x1b, 1, 1, 10}, {0x1b, 1, 1, 10}, {0x1a, 1, 1, 10}, {0x1a, 1, 1, 10},
+    {0x1a, 1, 1, 10}, {0x1a, 1, 1, 10}, {0x19, 1, 1, 10}, {0x19, 1, 1, 10}, {0x19, 1, 1, 10}, {0x19, 1, 1, 10},
+    {0x9, 2, 0, 10}, {0x9, 2, 0, 10}, {0x9, 2, 0, 10}, {0x9, 2, 0, 10}, {0x8, 2, 0, 10}, {0x8, 2, 0, 10},
+    {0x8, 2, 0, 10}, {0x8, 2, 0, 10}, {0x7, 2, 0, 10}, {0x7, 2, 0, 10}, {0x7, 2, 0, 10}, {0x7, 2, 0, 10},
+    {0x6, 2, 0, 10}, {0x6, 2, 0, 10}, {0x6, 2, 0, 10}, {0x6, 2, 0, 10}, {0x5, 2, 0, 10}, {0x5, 2, 0, 10},
+    {0x5, 2, 0, 10}, {0x5, 2, 0, 10}, {0x3, 3, 0, 10}, {0x3, 3, 0, 10}, {0x3, 3, 0, 10}, {0x3, 3, 0, 10},
+    {0x2, 3, 0, 10}, {0x2, 3, 0, 10}, {0x2, 3, 0, 10}, {0x2, 3, 0, 10}, {0x1, 4, 0, 10}, {0x1, 4, 0, 10},
+    {0x1, 4, 0, 10}, {0x1, 4, 0, 10}, {0x0, 0xc, 0, 11}, {0x0, 0xc, 0, 11}, {0x1, 5, 0, 11}, {0x1, 5, 0, 11},
+    {0x17, 1, 0, 11}, {0x17, 1, 0, 11}, {0x18, 1, 0, 11}, {0x18, 1, 0, 11}, {0x1d, 1, 1, 11}, {0x1d, 1, 1, 11},
+    {0x1e, 1, 1, 11}, {0x1e, 1, 1, 11}, {0x1f, 1, 1, 11}, {0x1f, 1, 1, 11}, {0x20, 1, 1, 11}, {0x20, 1, 1, 11},
+    {0x1, 6, 0, 12}, {0x2, 4, 0, 12}, {0x4, 3, 0, 12}, {0x5, 3, 0, 12}, {0x6, 3, 0, 12}, {0xa, 2, 0, 12},
+    {0x19, 1, 0, 12}, {0x1a, 1, 0, 12}, {0x21, 1, 1, 12}, {0x22, 1, 1, 12}, {0x23, 1, 1, 12}, {0x24, 1, 1, 12},
+    {0x25, 1, 1, 12}, {0x26, 1, 1, 12}, {0x27, 1, 1, 12}, {0x28, 1, 1, 12}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7}, {0xbf, 0xf, 1, 7},
+    {0xbf, 0xf, 1, 7}
+};
+
+/* New tables for Intra luminance blocks */
+
+const VLCtab2 PV_DCT3Dtab3[] =
+{
+    {0x4, 1, 1, 7}, {0x3, 1, 1, 7}, {0x6, 1, 0, 7}, {0x5, 1, 1, 7},
+    {0x7, 1, 0, 7}, {0x2, 2, 0, 7}, {0x1, 3, 0, 7}, {0x0, 9, 0, 7},
+    {0x0, 2, 1, 6}, {0x0, 2, 1, 6}, {0x5, 1, 0, 6}, {0x5, 1, 0, 6},
+    {0x2, 1, 1, 6}, {0x2, 1, 1, 6}, {0x1, 1, 1, 6}, {0x1, 1, 1, 6},
+    {0x4, 1, 0, 6}, {0x4, 1, 0, 6}, {0x3, 1, 0, 6}, {0x3, 1, 0, 6},
+    {0x0, 8, 0, 6}, {0x0, 8, 0, 6}, {0x0, 7, 0, 6}, {0x0, 7, 0, 6},
+    {0x1, 2, 0, 6}, {0x1, 2, 0, 6}, {0x0, 6, 0, 6}, {0x0, 6, 0, 6},
+    {0x2, 1, 0, 5}, {0x2, 1, 0, 5}, {0x2, 1, 0, 5}, {0x2, 1, 0, 5},
+    {0x0, 5, 0, 5}, {0x0, 5, 0, 5}, {0x0, 5, 0, 5}, {0x0, 5, 0, 5},
+    {0x0, 4, 0, 5}, {0x0, 4, 0, 5}, {0x0, 4, 0, 5}, {0x0, 4, 0, 5},
+    {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4},
+    {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4},
+    {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4},
+    {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}
+};
+
+const VLCtab2 PV_DCT3Dtab4[] =
+{
+    {0x0, 0x12, 0, 10}, {0x0, 0x11, 0, 10}, {0xe, 1, 1, 9}, {0xe, 1, 1, 9},
+    {0xd, 1, 1, 9}, {0xd, 1, 1, 9}, {0xc, 1, 1, 9}, {0xc, 1, 1, 9},
+    {0xb, 1, 1, 9}, {0xb, 1, 1, 9}, {0xa, 1, 1, 9}, {0xa, 1, 1, 9},
+    {0x1, 2, 1, 9}, {0x1, 2, 1, 9}, {0x0, 4, 1, 9}, {0x0, 4, 1, 9},
+    {0xc, 1, 0, 9}, {0xc, 1, 0, 9}, {0xb, 1, 0, 9}, {0xb, 1, 0, 9},
+    {0x7, 2, 0, 9}, {0x7, 2, 0, 9}, {0x6, 2, 0, 9}, {0x6, 2, 0, 9},
+    {0x5, 2, 0, 9}, {0x5, 2, 0, 9}, {0x3, 3, 0, 9}, {0x3, 3, 0, 9},
+    {0x2, 3, 0, 9}, {0x2, 3, 0, 9}, {0x1, 6, 0, 9}, {0x1, 6, 0, 9},
+    {0x1, 5, 0, 9}, {0x1, 5, 0, 9}, {0x0, 0x10, 0, 9}, {0x0, 0x10, 0, 9},
+    {0x4, 2, 0, 9}, {0x4, 2, 0, 9}, {0x0, 0xf, 0, 9}, {0x0, 0xf, 0, 9},
+    {0x0, 0xe, 0, 9}, {0x0, 0xe, 0, 9}, {0x0, 0xd, 0, 9}, {0x0, 0xd, 0, 9},
+    {0x8, 1, 1, 8}, {0x8, 1, 1, 8}, {0x8, 1, 1, 8}, {0x8, 1, 1, 8},
+    {0x7, 1, 1, 8}, {0x7, 1, 1, 8}, {0x7, 1, 1, 8}, {0x7, 1, 1, 8},
+    {0x6, 1, 1, 8}, {0x6, 1, 1, 8}, {0x6, 1, 1, 8}, {0x6, 1, 1, 8},
+    {0x0, 3, 1, 8}, {0x0, 3, 1, 8}, {0x0, 3, 1, 8}, {0x0, 3, 1, 8},
+    {0xa, 1, 0, 8}, {0xa, 1, 0, 8}, {0xa, 1, 0, 8}, {0xa, 1, 0, 8},
+    {0x9, 1, 0, 8}, {0x9, 1, 0, 8}, {0x9, 1, 0, 8}, {0x9, 1, 0, 8},
+    {0x8, 1, 0, 8}, {0x8, 1, 0, 8}, {0x8, 1, 0, 8}, {0x8, 1, 0, 8},
+    {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8},
+    {0x3, 2, 0, 8}, {0x3, 2, 0, 8}, {0x3, 2, 0, 8}, {0x3, 2, 0, 8},
+    {0x1, 4, 0, 8}, {0x1, 4, 0, 8}, {0x1, 4, 0, 8}, {0x1, 4, 0, 8},
+    {0x0, 0xc, 0, 8}, {0x0, 0xc, 0, 8}, {0x0, 0xc, 0, 8}, {0x0, 0xc, 0, 8},
+    {0x0, 0xb, 0, 8}, {0x0, 0xb, 0, 8}, {0x0, 0xb, 0, 8}, {0x0, 0xb, 0, 8},
+    {0x0, 0xa, 0, 8}, {0x0, 0xa, 0, 8}, {0x0, 0xa, 0, 8}, {0x0, 0xa, 0, 8}
+};
+
+const VLCtab2 PV_DCT3Dtab5[] =
+{
+    {0x0, 7, 1, 11}, {0x0, 7, 1, 11}, {0x0, 6, 1, 11}, {0x0, 6, 1, 11},
+    {0x0, 0x16, 0, 11}, {0x0, 0x16, 0, 11}, {0x0, 0x15, 0, 11}, {0x0, 0x15, 0, 11},
+    {0x2, 2, 1, 10}, {0x2, 2, 1, 10}, {0x2, 2, 1, 10}, {0x2, 2, 1, 10},
+    {0x1, 3, 1, 10}, {0x1, 3, 1, 10}, {0x1, 3, 1, 10}, {0x1, 3, 1, 10},
+    {0x0, 5, 1, 10}, {0x0, 5, 1, 10}, {0x0, 5, 1, 10}, {0x0, 5, 1, 10},
+    {0xd, 1, 0, 10}, {0xd, 1, 0, 10}, {0xd, 1, 0, 10}, {0xd, 1, 0, 10},
+    {0x5, 3, 0, 10}, {0x5, 3, 0, 10}, {0x5, 3, 0, 10}, {0x5, 3, 0, 10},
+    {0x8, 2, 0, 10}, {0x8, 2, 0, 10}, {0x8, 2, 0, 10}, {0x8, 2, 0, 10},
+    {0x4, 3, 0, 10}, {0x4, 3, 0, 10}, {0x4, 3, 0, 10}, {0x4, 3, 0, 10},
+    {0x3, 4, 0, 10}, {0x3, 4, 0, 10}, {0x3, 4, 0, 10}, {0x3, 4, 0, 10},
+    {0x2, 4, 0, 10}, {0x2, 4, 0, 10}, {0x2, 4, 0, 10}, {0x2, 4, 0, 10},
+    {0x1, 7, 0, 10}, {0x1, 7, 0, 10}, {0x1, 7, 0, 10}, {0x1, 7, 0, 10},
+    {0x0, 0x14, 0, 10}, {0x0, 0x14, 0, 10}, {0x0, 0x14, 0, 10}, {0x0, 0x14, 0, 10},
+    {0x0, 0x13, 0, 10}, {0x0, 0x13, 0, 10}, {0x0, 0x13, 0, 10}, {0x0, 0x13, 0, 10},
+    {0x0, 0x17, 0, 11}, {0x0, 0x17, 0, 11}, {0x0, 0x18, 0, 11}, {0x0, 0x18, 0, 11},
+    {0x1, 8, 0, 11}, {0x1, 8, 0, 11}, {0x9, 2, 0, 11}, {0x9, 2, 0, 11},
+    {0x3, 2, 1, 11}, {0x3, 2, 1, 11}, {0x4, 2, 1, 11}, {0x4, 2, 1, 11},
+    {0xf, 1, 1, 11}, {0xf, 1, 1, 11}, {0x10, 1, 1, 11}, {0x10, 1, 1, 11},
+    {0, 0x19, 0, 12}, {0, 0x1a, 0, 12}, {0, 0x1b, 0, 12}, {1, 9, 0, 12},
+    {0x6, 3, 0, 12}, {0x1, 0xa, 0, 12}, {0x2, 5, 0, 12}, {0x7, 3, 0, 12},
+    {0xe, 1, 0, 12}, {0x0, 8, 1, 12}, {0x5, 2, 1, 12}, {0x6, 2, 1, 12},
+    {0x11, 1, 1, 12}, {0x12, 1, 1, 12}, {0x13, 1, 1, 12}, {0x14, 1, 1, 12},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7},
+    {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}, {0x1b, 0xff, 0, 7}
+};
+
+#ifdef PV_ANNEX_IJKT_SUPPORT
+const VLCtab2 PV_DCT3Dtab6[] =
+{
+    {0x0, 3, 1, 7}, {0x4, 1, 1, 7}, {0x6, 1, 1, 7}, {0x5, 1, 1, 7}, {0x1, 3, 0, 7}, {0x2, 2, 0, 7},
+    {0x0, 9, 0, 7}, {0x5, 1, 0, 7}, {0x0, 2, 1, 6}, {0x0, 2, 1, 6}, {0x3, 1, 1, 6}, {0x3, 1, 1, 6},
+    {0x2, 1, 1, 6}, {0x2, 1, 1, 6}, {0x1, 1, 1, 6}, {0x1, 1, 1, 6}, {0x0, 6, 0, 6}, {0x0, 6, 0, 6},
+    {0x0, 7, 0, 6}, {0x0, 7, 0, 6}, {0x0, 8, 0, 6}, {0x0, 8, 0, 6}, {0x4, 1, 0, 6}, {0x4, 1, 0, 6},
+    {0x1, 2, 0, 6}, {0x1, 2, 0, 6}, {0x3, 1, 0, 6}, {0x3, 1, 0, 6}, {0x2, 1, 0, 5}, {0x2, 1, 0, 5},
+    {0x2, 1, 0, 5}, {0x2, 1, 0, 5}, {0x0, 4, 0, 5}, {0x0, 4, 0, 5}, {0x0, 4, 0, 5}, {0x0, 4, 0, 5},
+    {0x0, 5, 0, 5}, {0x0, 5, 0, 5}, {0x0, 5, 0, 5}, {0x0, 5, 0, 5}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4}, {0x0, 1, 1, 4},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 1, 0, 2},
+    {0x0, 1, 0, 2}, {0x0, 1, 0, 2}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3}, {0x0, 2, 0, 3},
+    {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x0, 3, 0, 4},
+    {0x0, 3, 0, 4}, {0x0, 3, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4},
+    {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}, {0x1, 1, 0, 4}
+};
+
+const VLCtab2 PV_DCT3Dtab7[] =
+{
+    {0xb, 1, 0, 10}, {0xa, 1, 0, 10}, {0x0, 5, 1, 9}, {0x0, 5, 1, 9}, {0x0, 6, 1, 9}, {0x0, 6, 1, 9},
+    {0x1, 2, 1, 9}, {0x1, 2, 1, 9}, {0x2, 2, 1, 9}, {0x2, 2, 1, 9}, {0xf, 1, 1, 9}, {0xf, 1, 1, 9},
+    {0x10, 1, 1, 9}, {0x10, 1, 1, 9}, {0x12, 1, 1, 9}, {0x12, 1, 1, 9}, {0x11, 1, 1, 9}, {0x11, 1, 1, 9},
+    {0xe, 1, 1, 9}, {0xe, 1, 1, 9}, {0x0, 13, 0, 9}, {0x0, 13, 0, 9}, {0x0, 14, 0, 9}, {0x0, 14, 0, 9},
+    {0x0, 15, 0, 9}, {0x0, 15, 0, 9}, {0x0, 16, 0, 9}, {0x0, 16, 0, 9}, {0x0, 17, 0, 9}, {0x0, 17, 0, 9},
+    {0x0, 18, 0, 9}, {0x0, 18, 0, 9}, {0x0, 11, 0, 9}, {0x0, 11, 0, 9}, {0x0, 12, 0, 9}, {0x0, 12, 0, 9},
+    {0x5, 2, 0, 9}, {0x5, 2, 0, 9}, {0x4, 2, 0, 9}, {0x4, 2, 0, 9}, {0x9, 1, 0, 9}, {0x9, 1, 0, 9},
+    {0x8, 1, 0, 9}, {0x8, 1, 0, 9}, {0x0, 4, 1, 8}, {0x0, 4, 1, 8}, {0x0, 4, 1, 8}, {0x0, 4, 1, 8},
+    {0x7, 1, 1, 8}, {0x7, 1, 1, 8}, {0x7, 1, 1, 8}, {0x7, 1, 1, 8}, {0x8, 1, 1, 8}, {0x8, 1, 1, 8},
+    {0x8, 1, 1, 8}, {0x8, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8}, {0xd, 1, 1, 8},
+    {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xc, 1, 1, 8}, {0xb, 1, 1, 8}, {0xb, 1, 1, 8},
+    {0xb, 1, 1, 8}, {0xb, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8}, {0xa, 1, 1, 8},
+    {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x9, 1, 1, 8}, {0x0, 10, 0, 8}, {0x0, 10, 0, 8},
+    {0x0, 10, 0, 8}, {0x0, 10, 0, 8}, {0x6, 1, 0, 8}, {0x6, 1, 0, 8}, {0x6, 1, 0, 8}, {0x6, 1, 0, 8},
+    {0x3, 2, 0, 8}, {0x3, 2, 0, 8}, {0x3, 2, 0, 8}, {0x3, 2, 0, 8}, {0x1, 4, 0, 8}, {0x1, 4, 0, 8},
+    {0x1, 4, 0, 8}, {0x1, 4, 0, 8}, {0x7, 1, 0, 8}, {0x7, 1, 0, 8}, {0x7, 1, 0, 8}, {0x7, 1, 0, 8}
+};
+
+
+const VLCtab2 PV_DCT3Dtab8[] =
+{
+    {0x13, 0x1, 1, 11}, {0x13, 0x1, 1, 11}, {0x14, 0x1, 1, 11}, {0x14, 0x1, 1, 11}, {0x9, 0x2, 0, 11}, {0x9, 0x2, 0, 11},
+    {0x4, 0x3, 0, 11}, {0x4, 0x3, 0, 11}, {0x0, 0x7, 1, 10}, {0x0, 0x7, 1, 10}, {0x0, 0x7, 1, 10}, {0x0, 0x7, 1, 10},
+    {0x1, 0x3, 1, 10}, {0x1, 0x3, 1, 10}, {0x1, 0x3, 1, 10}, {0x1, 0x3, 1, 10}, {0x3, 0x2, 1, 10}, {0x3, 0x2, 1, 10},
+    {0x3, 0x2, 1, 10}, {0x3, 0x2, 1, 10}, {0x4, 0x2, 1, 10}, {0x4, 0x2, 1, 10}, {0x4, 0x2, 1, 10}, {0x4, 0x2, 1, 10},
+    {0xc, 0x1, 0, 10}, {0xc, 0x1, 0, 10}, {0xc, 0x1, 0, 10}, {0xc, 0x1, 0, 10}, {0x2, 0x4, 0, 10}, {0x2, 0x4, 0, 10},
+    {0x2, 0x4, 0, 10}, {0x2, 0x4, 0, 10}, {0x8, 0x2, 0, 10}, {0x8, 0x2, 0, 10}, {0x8, 0x2, 0, 10}, {0x8, 0x2, 0, 10},
+    {0x7, 0x2, 0, 10}, {0x7, 0x2, 0, 10}, {0x7, 0x2, 0, 10}, {0x7, 0x2, 0, 10}, {0x6, 0x2, 0, 10}, {0x6, 0x2, 0, 10},
+    {0x6, 0x2, 0, 10}, {0x6, 0x2, 0, 10}, {0x3, 0x3, 0, 10}, {0x3, 0x3, 0, 10}, {0x3, 0x3, 0, 10}, {0x3, 0x3, 0, 10},
+    {0x2, 0x3, 0, 10}, {0x2, 0x3, 0, 10}, {0x2, 0x3, 0, 10}, {0x2, 0x3, 0, 10}, {0x1, 0x5, 0, 10}, {0x1, 0x5, 0, 10},
+    {0x1, 0x5, 0, 10}, {0x1, 0x5, 0, 10}, {0xd, 0x1, 0, 11}, {0xd, 0x1, 0, 11}, {0x1, 0x6, 0, 11}, {0x1, 0x6, 0, 11},
+    {0x0, 0x14, 0, 11}, {0x0, 0x14, 0, 11}, {0x0, 0x13, 0, 11}, {0x0, 0x13, 0, 11}, {0x2, 0x3, 1, 11}, {0x2, 0x3, 1, 11},
+    {0x1, 0x4, 1, 11}, {0x1, 0x4, 1, 11}, {0x0, 0x9, 1, 11}, {0x0, 0x9, 1, 11}, {0x0, 0x8, 1, 11}, {0x0, 0x8, 1, 11},
+    {0x1, 0x7, 0, 12}, {0x3, 0x4, 0, 12}, {0x5, 0x3, 0, 12}, {0x0, 0x19, 0, 12}, {0x0, 0x18, 0, 12}, {0x0, 0x17, 0, 12},
+    {0x0, 0x16, 0, 12}, {0x0, 0x15, 0, 12}, {0x15, 0x1, 1, 12}, {0x16, 0x1, 1, 12}, {0x17, 0x1, 1, 12}, {0x7, 0x2, 1, 12},
+    {0x6, 0x2, 1, 12}, {0x5, 0x2, 1, 12}, {0x3, 0x3, 1, 12}, {0x0, 0xa, 1, 12}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7},
+    {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7},
+    {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7},
+    {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7},
+    {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7},
+    {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}, {0x2f, 0x3f, 1, 7}
+};
+#endif
+/* RVLC tables */
+const int ptrRvlcTab[11] = {0, 24, 46, 66, 84, 100, 114, 126, 134, 140, 144};
+
+const VLCtab2 RvlcDCTtabIntra[170] = /* 00xxxx00 or 00xxxx01 */
+{
+    {27, 255, 0, 5},    /* 0000 is escape code */
+    {1, 1, 0, 4},
+    {2, 1, 0, 5},
+    {3, 1, 0, 5},
+    {4, 1, 0, 6},
+    {5, 1, 0, 6},
+    {6, 1, 0, 7},
+    {7, 1, 0, 7},
+    {8, 1, 0, 8},
+    {9, 1, 0, 8},
+    {10, 1, 0, 9},
+    {5, 2, 0, 9},
+    {11, 1, 0, 10},
+    {12, 1, 0, 10},
+    {13, 1, 0, 11},
+    {9, 2, 0, 11},
+    {10, 2, 0, 12},
+    {4, 4, 0, 12},
+    {14, 1, 0, 13},
+    {15, 1, 0, 13},
+    {16, 1, 0, 14},
+    {17, 1, 0, 14},
+    {0, 27, 0, 15},
+    {3, 9, 0, 15},
+    /* 010xxxx00 or 010xxxx01 */
+    {1, 2, 0, 5},
+    {0, 4, 0, 5},
+    {0, 5, 0, 6},
+    {0, 6, 0, 6},
+    {2, 2, 0, 7},
+    {1, 3, 0, 7},
+    {3, 2, 0, 8},
+    {4, 2, 0, 8},
+    {2, 3, 0, 9},
+    {3, 3, 0, 9},
+    {6, 2, 0, 10},
+    {7, 2, 0, 10},
+    {5, 3, 0, 11},
+    {6, 3, 0, 11},
+    {5, 4, 0, 12},
+    {6, 4, 0, 12},
+    {11, 2, 0, 13},
+    {8, 3, 0, 13},
+    {18, 1, 0, 14},
+    {8, 4, 0, 14},
+    {6, 5, 0, 15},
+    {7, 5, 0, 15},
+    /* 0110xxxx00 or 0110xxxx01 */
+    {3, 1, 1, 6},
+    {4, 1, 1, 6},
+    {0, 7, 0, 7},
+    {7, 1, 1, 7},
+    {1, 4, 0, 8},
+    {1, 5, 0, 8},
+    {1, 6, 0, 9},
+    {0, 10, 0, 9},
+    {8, 2, 0, 10},
+    {4, 3, 0, 10},
+    {7, 3, 0, 11},
+    {3, 4, 0, 11},
+    {3, 5, 0, 12},
+    {4, 5, 0, 12},
+    {9, 3, 0, 13},
+    {7, 4, 0, 13},
+    {5, 5, 0, 14},
+    {4, 6, 0, 14},
+    {9, 4, 0, 15},
+    {12, 2, 0, 15},
+    /* 01110xxxx00 or 01110xxxx01 */
+    {8, 1, 1, 7},
+    {9, 1, 1, 7},
+    {0, 8, 0, 8},
+    {0, 9, 0, 8},
+    {0, 11, 0, 9},
+    {1, 2, 1, 9},
+    {2, 4, 0, 10},
+    {1, 7, 0, 10},
+    {2, 5, 0, 11},
+    {2, 6, 0, 11},
+    {1, 10, 0, 12},
+    {0, 18, 0, 12},
+    {3, 6, 0, 13},
+    {2, 7, 0, 13},
+    {5, 6, 0, 14},
+    {3, 7, 0, 14},
+    {19, 1, 0, 15},
+    {1, 5, 1, 15},
+    /* 011110xxxx00 or 011110xxxx01 */
+    {0, 2, 1, 8},
+    {12, 1, 1, 8},
+    {15, 1, 1, 9},
+    {16, 1, 1, 9},
+    {0, 12, 0, 10},
+    {0, 13, 0, 10},
+    {1, 8, 0, 11},
+    {1, 9, 0, 11},
+    {0, 19, 0, 12},
+    {0, 22, 0, 12},
+    {2, 8, 0, 13},
+    {2, 9, 0, 13},
+    {3, 8, 0, 14},
+    {2, 10, 0, 14},
+    {2, 3, 1, 15},
+    {13, 2, 1, 15},
+    /* 0111110xxxx00 or 0111110xxxx01 */
+    {17, 1, 1, 9},
+    {18, 1, 1, 9},
+    {0, 14, 0, 10},
+    {21, 1, 1, 10},
+    {0, 15, 0, 11},
+    {0, 16, 0, 11},
+    {1, 3, 1, 12},
+    {3, 2, 1, 12},
+    {1, 11, 0, 13},
+    {0, 20, 0, 13},
+    {2, 11, 0, 14},
+    {1, 12, 0, 14},
+    {41, 1, 1, 15},
+    {42, 1, 1, 15},
+    /* 01111110xxxx00 or 01111110xxxx01 */
+    {22, 1, 1, 10},
+    {23, 1, 1, 10},
+    {0, 17, 0, 11},
+    {0, 3, 1, 11},
+    {4, 2, 1, 12},
+    {29, 1, 1, 12},
+    {0, 21, 0, 13},
+    {0, 23, 0, 13},
+    {1, 13, 0, 14},
+    {0, 24, 0, 14},
+    {43, 1, 1, 15},
+    {44, 1, 1, 15},
+    /* 011111110xxxx00 or 011111110xxxx01 */
+    {2, 2, 1, 11},
+    {26, 1, 1, 11},
+    {30, 1, 1, 12},
+    {31, 1, 1, 12},
+    {0, 4, 1, 13},
+    {5, 2, 1, 13},
+    {0, 25, 0, 14},
+    {0, 26, 0, 14},
+    /* 0111111110xxxx00 or 0111111110xxxx01 */
+    {32, 1, 1, 12},
+    {33, 1, 1, 12},
+    {6, 2, 1, 13},
+    {7, 2, 1, 13},
+    {0, 5, 1, 14},
+    {1, 4, 1, 14},
+    /* 01111111110xxxx00 or 01111111110xxxx01 */
+    {8, 2, 1, 13},
+    {9, 2, 1, 13},
+    {10, 2, 1, 14},
+    {11, 2, 1, 14},
+    /* 011111111110xxxx00 or 011111111110xxxx01 */
+    {12, 2, 1, 14},
+    {38, 1, 1, 14},
+    /* 1xxxx10 or 1xxxx11 from 11 zeros to 0 zeros*/
+    {0, 1, 0, 3},
+    {0, 2, 0, 3},
+    {0, 3, 0, 4},
+    {0, 1, 1, 4},
+    {1, 1, 1, 5},
+    {2, 1, 1, 5},
+    {5, 1, 1, 6},
+    {6, 1, 1, 6},
+    {10, 1, 1, 7},
+    {11, 1, 1, 7},
+    {13, 1, 1, 8},
+    {14, 1, 1, 8},
+    {19, 1, 1, 9},
+    {20, 1, 1, 9},
+    {24, 1, 1, 10},
+    {25, 1, 1, 10},
+    {27, 1, 1, 11},
+    {28, 1, 1, 11},
+    {34, 1, 1, 12},
+    {35, 1, 1, 12},
+    {36, 1, 1, 13},
+    {37, 1, 1, 13},
+    {39, 1, 1, 14},
+    {40, 1, 1, 14}
+};
+
+const VLCtab2 RvlcDCTtabInter[170] = /* 00xxxx00 or 00xxxx01 */
+{
+    {27, 255, 0, 5},    /* 0000 is escape code */
+    {0, 2, 0, 4},
+    {0, 3, 0, 5},
+    {3, 1, 0, 5},
+    {1, 2, 0, 6},
+    {6, 1, 0, 6},
+    {0, 4, 0, 7},
+    {2, 2, 0, 7},
+    {0, 5, 0, 8},
+    {0, 6, 0, 8},
+    {0, 7, 0, 9},
+    {1, 4, 0, 9},
+    {0, 8, 0, 10},
+    {0, 9, 0, 10},
+    {0, 10, 0, 11},
+    {0, 11, 0, 11},
+    {0, 12, 0, 12},
+    {1, 7, 0, 12},
+    {0, 13, 0, 13},
+    {0, 14, 0, 13},
+    {0, 17, 0, 14},
+    {0, 18, 0, 14},
+    {0, 19, 0, 15},
+    {3, 7, 0, 15},
+    /* 010xxxx00 or 010xxxx01 */
+    {4, 1, 0, 5},
+    {5, 1, 0, 5},
+    {7, 1, 0, 6},
+    {8, 1, 0, 6},
+    {9, 1, 0, 7},
+    {10, 1, 0, 7},
+    {1, 3, 0, 8},
+    {3, 2, 0, 8},
+    {2, 3, 0, 9},
+    {5, 2, 0, 9},
+    {1, 5, 0, 10},
+    {3, 3, 0, 10},
+    {1, 6, 0, 11},
+    {2, 4, 0, 11},
+    {2, 5, 0, 12},
+    {3, 4, 0, 12},
+    {0, 15, 0, 13},
+    {0, 16, 0, 13},
+    {1, 9, 0, 14},
+    {1, 10, 0, 14},
+    {4, 5, 0, 15},
+    {7, 4, 0, 15},
+    /* 0110xxxx00 or 0110xxxx01 */
+    {3, 1, 1, 6},
+    {4, 1, 1, 6},
+    {11, 1, 0, 7},
+    {7, 1, 1, 7},
+    {4, 2, 0, 8},
+    {12, 1, 0, 8},
+    {15, 1, 0, 9},
+    {16, 1, 0, 9},
+    {6, 2, 0, 10},
+    {7, 2, 0, 10},
+    {4, 3, 0, 11},
+    {5, 3, 0, 11},
+    {6, 3, 0, 12},
+    {7, 3, 0, 12},
+    {1, 8, 0, 13},
+    {3, 5, 0, 13},
+    {2, 6, 0, 14},
+    {2, 7, 0, 14},
+    {17, 2, 0, 15},
+    {37, 1, 0, 15},
+    /* 01110xxxx00 or 01110xxxx01 */
+    {8, 1, 1, 7},
+    {9, 1, 1, 7},
+    {13, 1, 0, 8},
+    {14, 1, 0, 8},
+    {17, 1, 0, 9},
+    {1, 2, 1, 9},
+    {8, 2, 0, 10},
+    {9, 2, 0, 10},
+    {10, 2, 0, 11},
+    {21, 1, 0, 11},
+    {11, 2, 0, 12},
+    {27, 1, 0, 12},
+    {4, 4, 0, 13},
+    {5, 4, 0, 13},
+    {3, 6, 0, 14},
+    {6, 4, 0, 14},
+    {38, 1, 0, 15},
+    {1, 5, 1, 15},
+    /* 011110xxxx00 or 011110xxxx01 */
+    {0, 2, 1, 8},
+    {12, 1, 1, 8},
+    {15, 1, 1, 9},
+    {16, 1, 1, 9},
+    {18, 1, 0, 10},
+    {19, 1, 0, 10},
+    {22, 1, 0, 11},
+    {23, 1, 0, 11},
+    {28, 1, 0, 12},
+    {29, 1, 0, 12},
+    {8, 3, 0, 13},
+    {12, 2, 0, 13},
+    {9, 3, 0, 14},
+    {13, 2, 0, 14},
+    {2, 3, 1, 15},
+    {13, 2, 1, 15},
+    /* 0111110xxxx00 or 0111110xxxx01 */
+    {17, 1, 1, 9},
+    {18, 1, 1, 9},
+    {20, 1, 0, 10},
+    {21, 1, 1, 10},
+    {24, 1, 0, 11},
+    {25, 1, 0, 11},
+    {1, 3, 1, 12},
+    {3, 2, 1, 12},
+    {30, 1, 0, 13},
+    {31, 1, 0, 13},
+    {14, 2, 0, 14},
+    {15, 2, 0, 14},
+    {41, 1, 1, 15},
+    {42, 1, 1, 15},
+    /* 01111110xxxx00 or 01111110xxxx01 */
+    {22, 1, 1, 10},
+    {23, 1, 1, 10},
+    {26, 1, 0, 11},
+    {0, 3, 1, 11},
+    {4, 2, 1, 12},
+    {29, 1, 1, 12},
+    {32, 1, 0, 13},
+    {33, 1, 0, 13},
+    {16, 2, 0, 14},
+    {34, 1, 0, 14},
+    {43, 1, 1, 15},
+    {44, 1, 1, 15},
+    /* 011111110xxxx00 or 011111110xxxx01 */
+    {2, 2, 1, 11},
+    {26, 1, 1, 11},
+    {30, 1, 1, 12},
+    {31, 1, 1, 12},
+    {0, 4, 1, 13},
+    {5, 2, 1, 13},
+    {35, 1, 0, 14},
+    {36, 1, 0, 14},
+    /* 0111111110xxxx00 or 0111111110xxxx01 */
+    {32, 1, 1, 12},
+    {33, 1, 1, 12},
+    {6, 2, 1, 13},
+    {7, 2, 1, 13},
+    {0, 5, 1, 14},
+    {1, 4, 1, 14},
+    /* 01111111110xxxx00 or 01111111110xxxx01 */
+    {8, 2, 1, 13},
+    {9, 2, 1, 13},
+    {10, 2, 1, 14},
+    {11, 2, 1, 14},
+    /* 011111111110xxxx00 or 011111111110xxxx01 */
+    {12, 2, 1, 14},
+    {38, 1, 1, 14},
+    /* 1xxxx10 or 1xxxx11 from 11 zeros to 0 zeros*/
+    {0, 1, 0, 3},
+    {1, 1, 0, 3},
+    {2, 1, 0, 4},
+    {0, 1, 1, 4},
+    {1, 1, 1, 5},
+    {2, 1, 1, 5},
+    {5, 1, 1, 6},
+    {6, 1, 1, 6},
+    {10, 1, 1, 7},
+    {11, 1, 1, 7},
+    {13, 1, 1, 8},
+    {14, 1, 1, 8},
+    {19, 1, 1, 9},
+    {20, 1, 1, 9},
+    {24, 1, 1, 10},
+    {25, 1, 1, 10},
+    {27, 1, 1, 11},
+    {28, 1, 1, 11},
+    {34, 1, 1, 12},
+    {35, 1, 1, 12},
+    {36, 1, 1, 13},
+    {37, 1, 1, 13},
+    {39, 1, 1, 14},
+    {40, 1, 1, 14}
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp
new file mode 100644
index 0000000..74fe478
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/vop.cpp
@@ -0,0 +1,1643 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+#include "mp4dec_lib.h"
+#include "bitstream.h"
+#include "vlc_decode.h"
+#include "zigzag.h"
+
+#define OSCL_DISABLE_WARNING_CONV_POSSIBLE_LOSS_OF_DATA
+
+#ifdef PV_SUPPORT_MAIN_PROFILE
+/* INTRA */
+const static int mpeg_iqmat_def[NCOEFF_BLOCK] =
+{
+    8, 17, 18, 19, 21, 23, 25, 27,
+    17, 18, 19, 21, 23, 25, 27, 28,
+    20, 21, 22, 23, 24, 26, 28, 30,
+    21, 22, 23, 24, 26, 28, 30, 32,
+    22, 23, 24, 26, 28, 30, 32, 35,
+    23, 24, 26, 28, 30, 32, 35, 38,
+    25, 26, 28, 30, 32, 35, 38, 41,
+    27, 28, 30, 32, 35, 38, 41, 45
+};
+
+/* INTER */
+const static int mpeg_nqmat_def[64]  =
+{
+    16, 17, 18, 19, 20, 21, 22, 23,
+    17, 18, 19, 20, 21, 22, 23, 24,
+    18, 19, 20, 21, 22, 23, 24, 25,
+    19, 20, 21, 22, 23, 24, 26, 27,
+    20, 21, 22, 23, 25, 26, 27, 28,
+    21, 22, 23, 24, 26, 27, 28, 30,
+    22, 23, 24, 26, 27, 28, 30, 31,
+    23, 24, 25, 27, 28, 30, 31, 33
+};
+#endif
+
+/* ======================================================================== */
+/*  Function : CalcNumBits()                                                */
+/*  Purpose  :                                                              */
+/*  In/out   :                                                              */
+/*  Return   : Calculate the minimum number of bits required to             */
+/*              represent x.                                                */
+/*  Note     : This is an equivalent implementation of                      */
+/*                      (long)ceil(log((double)x)/log(2.0))                 */
+/*  Modified :                                                              */
+/* ======================================================================== */
+int CalcNumBits(uint x)
+{
+    int i = 1;
+    while (x >>= 1) i++;
+    return i;
+}
+
+
+
+/***********************************************************CommentBegin******
+*
+* -- DecodeVolHeader -- Decode the header of a VOL
+*
+*   04/10/2000 : initial modification to the new PV-Decoder Lib format.
+*   10/12/2001 : reject non compliant bitstreams
+*
+***********************************************************CommentEnd********/
+PV_STATUS DecodeVOLHeader(VideoDecData *video, int layer)
+{
+    PV_STATUS status;
+    Vol *currVol;
+    BitstreamDecVideo *stream;
+    uint32 tmpvar, vol_shape;
+    uint32 startCode;
+#ifdef PV_SUPPORT_MAIN_PROFILE
+    int *qmat, i, j;
+#endif
+    int version_id = 1;
+#ifdef PV_TOLERATE_VOL_ERRORS
+    uint32 profile = 0x01;
+#endif
+    /*  There's a "currLayer" variable inside videoDecData.          */
+    /*   However, we don't maintain it until we decode frame data.  04/05/2000 */
+    currVol = video->vol[layer];
+    stream  = currVol->bitstream;
+    currVol->moduloTimeBase = 0;
+
+    /* Determine which start code for the decoder to begin with */
+    status = BitstreamShowBits32HC(stream, &startCode);
+
+    if (startCode == VISUAL_OBJECT_SEQUENCE_START_CODE)
+    {   /*  Bitstream Exhchange Fix 9/99 */
+        /* Bitstream Exchange requires we allow start with Video Object Sequence */
+        /* visual_object_sequence_start_code            */
+        (void) BitstreamReadBits32HC(stream);
+        tmpvar = (uint32) BitstreamReadBits16(stream,  8); /* profile */
+#ifndef PV_TOLERATE_VOL_ERRORS
+        if (layer)                                                      /*    */
+        {
+            /* support SSPL0-2  */
+            if (tmpvar != 0x10 && tmpvar != 0x11 && tmpvar != 0x12 &&
+                    tmpvar != 0xA1 && tmpvar != 0xA2  && tmpvar != 0xA3/* Core SP@L1-L3 */)
+                return PV_FAIL;
+        }
+        else
+        {
+            /* support SPL0-3 & SSPL0-2   */
+            if (tmpvar != 0x01 && tmpvar != 0x02 && tmpvar != 0x03 && tmpvar != 0x08 &&
+                    tmpvar != 0x10 && tmpvar != 0x11 && tmpvar != 0x12 &&
+                    tmpvar != 0x21 && tmpvar != 0x22 &&  /* Core Profile Levels */
+                    tmpvar != 0xA1 && tmpvar != 0xA2 && tmpvar != 0xA3 &&
+                    tmpvar != 0xF0 && tmpvar != 0xF1 && /* Advanced Simple Profile Levels*/
+                    tmpvar != 0xF2 && tmpvar != 0xF3 &&
+                    tmpvar != 0xF4 && tmpvar != 0xF5)
+                return PV_FAIL;
+        }
+#else
+        profile = tmpvar;
+#endif
+
+        // save the profile and level for the query
+        currVol->profile_level_id = (uint)tmpvar; //  6/10/04
+
+
+
+        status = BitstreamShowBits32HC(stream, &tmpvar);
+        if (tmpvar == USER_DATA_START_CODE)
+        {
+            /* Something has to be done with user data  11/11/99 */
+            status = DecodeUserData(stream);
+            if (status != PV_SUCCESS) return PV_FAIL;
+        }
+        /* visual_object_start_code                     */
+        BitstreamShowBits32HC(stream, &tmpvar);
+        if (tmpvar != VISUAL_OBJECT_START_CODE)
+        {
+            do
+            {
+                /* Search for VOL_HEADER */
+                status = PVSearchNextM4VFrame(stream); /* search 0x00 0x00 0x01 */
+                if (status != PV_SUCCESS) return PV_FAIL; /* breaks the loop */
+                BitstreamShowBits32(stream, VOL_START_CODE_LENGTH, &tmpvar);
+                PV_BitstreamFlushBits(stream, 8);
+            }
+            while (tmpvar != VOL_START_CODE);
+            goto decode_vol;
+        }
+        else
+        {
+            BitstreamReadBits32HC(stream);
+        }
+
+        /*  is_visual_object_identifier            */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+        if (tmpvar)
+        {
+            /* visual_object_verid                            */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 4);
+            /* visual_object_priority                         */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 3);
+        }
+        /* visual_object_type                                 */
+        BitstreamShowBits32(stream, 4, &tmpvar);
+        if (tmpvar == 1)
+        { /* video_signal_type */
+            PV_BitstreamFlushBits(stream, 4);
+            tmpvar = (uint32) BitstreamRead1Bits(stream);
+            if (tmpvar == 1)
+            {
+                /* video_format */
+                tmpvar = (uint32) BitstreamReadBits16(stream, 3);
+                /* video_range  */
+                tmpvar = (uint32) BitstreamRead1Bits(stream);
+                /* color_description */
+                tmpvar = (uint32) BitstreamRead1Bits(stream);
+                if (tmpvar == 1)
+                {
+                    /* color_primaries */
+                    tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+                    /* transfer_characteristics */
+                    tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+                    /* matrix_coefficients */
+                    tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+                }
+            }
+        }
+        else
+        {
+            do
+            {
+                /* Search for VOL_HEADER */
+                status = PVSearchNextM4VFrame(stream); /* search 0x00 0x00 0x01 */
+                if (status != PV_SUCCESS) return PV_FAIL; /* breaks the loop */
+                BitstreamShowBits32(stream, VOL_START_CODE_LENGTH, &tmpvar);
+                PV_BitstreamFlushBits(stream, 8);
+            }
+            while (tmpvar != VOL_START_CODE);
+            goto decode_vol;
+        }
+
+        /* next_start_code() */
+        status = PV_BitstreamByteAlign(stream);                            /*  10/12/01 */
+        status = BitstreamShowBits32HC(stream, &tmpvar);
+
+        if (tmpvar == USER_DATA_START_CODE)
+        {
+            /* Something has to be done to deal with user data (parse it)  11/11/99 */
+            status = DecodeUserData(stream);
+            if (status != PV_SUCCESS) return PV_FAIL;
+        }
+        status = BitstreamShowBits32(stream, 27, &tmpvar);   /*  10/12/01 */
+    }
+    else
+    {
+        /*      tmpvar = 0;   */                                             /*  10/12/01 */
+        status = BitstreamShowBits32(stream, 27, &tmpvar);     /* uncomment this line if you want
+                                                                     to start decoding with a
+                                                                     video_object_start_code */
+    }
+
+    if (tmpvar == VO_START_CODE)
+    {
+        /*****
+        *
+        *   Read the VOL header entries from the bitstream
+        *
+        *****/
+        /* video_object_start_code                         */
+        tmpvar = BitstreamReadBits32(stream, 27);
+        tmpvar = (uint32) BitstreamReadBits16(stream, 5);
+
+
+        /* video_object_layer_start_code                   */
+        BitstreamShowBits32(stream, VOL_START_CODE_LENGTH, &tmpvar);
+        if (tmpvar != VOL_START_CODE)
+        {
+            status = BitstreamCheckEndBuffer(stream);
+            if (status == PV_END_OF_VOP)
+            {
+                video->shortVideoHeader = TRUE;
+                return PV_SUCCESS;
+            }
+            else
+            {
+                do
+                {
+                    /* Search for VOL_HEADER */
+                    status = PVSearchNextM4VFrame(stream);/* search 0x00 0x00 0x01 */
+                    if (status != PV_SUCCESS) return PV_FAIL; /* breaks the loop */
+                    BitstreamShowBits32(stream, VOL_START_CODE_LENGTH, &tmpvar);
+                    PV_BitstreamFlushBits(stream, 8); /* advance the byte ptr */
+                }
+                while (tmpvar != VOL_START_CODE);
+            }
+        }
+        else
+        {
+            PV_BitstreamFlushBits(stream, 8);
+        }
+
+decode_vol:
+        PV_BitstreamFlushBits(stream, VOL_START_CODE_LENGTH - 8);
+        video->shortVideoHeader = 0;
+
+        /* vol_id (4 bits) */
+        currVol->volID = (int) BitstreamReadBits16(stream, 4);
+
+        /* RandomAccessible flag */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+
+        /* object type */
+        tmpvar = (uint32) BitstreamReadBits16(stream, 8);                /*  */
+
+#ifdef PV_TOLERATE_VOL_ERRORS
+        if (tmpvar == 0)
+        {
+            if (layer)                                                      /*    */
+            {
+                /* support SSPL0-2  */
+                if (profile != 0x10 && profile != 0x11 && profile != 0x12)
+                    return PV_FAIL;
+                tmpvar = 0x02;
+            }
+            else
+            {
+                /* support SPL0-3 & SSPL0-2   */
+                if (profile != 0x01 && profile != 0x02 && profile != 0x03 && profile != 0x08 &&
+                        profile != 0x10 && profile != 0x11 && profile != 0x12)
+                    return PV_FAIL;
+                tmpvar = 0x01;
+            }
+            profile |= 0x0100;
+        }
+#endif
+
+        if (layer)
+        {
+            if (tmpvar != 0x02) return PV_FAIL;
+        }
+        else
+        {
+            if (tmpvar != 0x01) return PV_FAIL;
+        }
+
+        /* version id specified? */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+        if (tmpvar == 1)
+        {
+            /* version ID */
+            version_id = (uint32) BitstreamReadBits16(stream, 4);
+            /* priority */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 3);
+
+        }
+
+        /* aspect ratio info */
+        tmpvar = (uint32) BitstreamReadBits16(stream, 4);
+        if (tmpvar == 0) return PV_FAIL;
+        if (tmpvar == 0xf /* extended_par */)
+        {
+            /* width */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+            /* height */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+        }
+
+
+        /* control parameters present? */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+
+        /*  Get the parameters (skipped) */
+        /*  03/10/99 */
+        if (tmpvar)
+        {
+            /* chroma_format                    */
+            tmpvar = BitstreamReadBits16(stream, 2);
+            if (tmpvar != 1) return PV_FAIL;
+            /* low_delay  */
+            tmpvar = BitstreamRead1Bits(stream);
+
+            /* vbv_parameters present? */
+            tmpvar = (uint32) BitstreamRead1Bits(stream);
+            if (tmpvar)
+            {
+                /* first_half_bit_rate    */
+                BitstreamReadBits16(stream, 15);
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+                /* latter_half_bit_rate   */
+                BitstreamReadBits16(stream, 15);
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+                /* first_half_vbv_buffer_size   */
+                BitstreamReadBits16(stream, 15);
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+                /* latter_half_vbv_buffer_size   */
+                BitstreamReadBits16(stream,  3);
+                /* first_half_vbv_occupancy     */
+                BitstreamReadBits16(stream, 11);
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+                /* latter_half_vbv_occupancy  */
+                BitstreamReadBits16(stream, 15);
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+            }
+        }
+
+        /* video_object_layer_shape (2 bits), only 00 (rect) is supported for now */
+        vol_shape = (uint32) BitstreamReadBits16(stream, 2);
+        if (vol_shape) return PV_FAIL;
+
+        /* marker bit,  03/10/99 */
+        if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+        /* vop_time_increment_resolution   */
+        currVol->timeIncrementResolution = BitstreamReadBits16(stream, 16);
+        if (currVol->timeIncrementResolution == 0) return PV_FAIL;
+
+        /* . since nbitsTimeIncRes will be used over and over again, */
+        /*    we should put it in Vol structure.  04/12/2000.          */
+        currVol->nbitsTimeIncRes = CalcNumBits((uint)currVol->timeIncrementResolution - 1);
+
+        if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+        /* fixed_vop_rate */
+        currVol->fixedVopRate = (int) BitstreamRead1Bits(stream);
+        if (currVol->fixedVopRate)
+        {
+            /* fixed_vop_time_increment */
+            tmpvar = BitstreamReadBits16(stream, currVol->nbitsTimeIncRes);
+        }
+
+        /* marker bit */
+        if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+        /* video_object_layer_width (13 bits) */
+        video->displayWidth = video->width = (int) BitstreamReadBits16(stream, 13);
+
+        /* round up to a multiple of MB_SIZE.   08/09/2000 */
+        video->width = (video->width + 15) & -16;
+//      video->displayWidth += (video->displayWidth & 0x1);  /* displayed image should be even size */
+
+        /* marker bit */
+        if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+        /* video_object_layer_height (13 bits) */
+        video->displayHeight = video->height = (int) BitstreamReadBits16(stream, 13);
+
+        /* round up to a multiple of MB_SIZE.   08/09/2000 */
+        video->height = (video->height + 15) & -16;
+//      video->displayHeight += (video->displayHeight & 0x1); /* displayed image should be even size */
+        if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+        /*  03/10/99 */
+        /* interlaced */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+        if (tmpvar != 0)
+        {
+            mp4dec_log("DecodeVOLHeader(): Interlaced video is not supported.\n");
+            return PV_FAIL;
+        }
+
+        /* obmc_disable */
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+        if (tmpvar == 0) return PV_FAIL;
+
+        if (version_id == 1)
+        {
+            /*  sprite_enable (1 bits) */
+            tmpvar = (uint32) BitstreamRead1Bits(stream);
+            if (tmpvar)
+            {
+                mp4dec_log("DecodeVOLHeader(): Sprite is not supported.\n");
+                return PV_FAIL;
+            }
+        }
+        else
+        {
+            /* For version 2, vol_sprite_usage has two bits. */
+            /* sprite_enable */
+            tmpvar = (uint32) BitstreamReadBits16(stream, 2);
+            if (tmpvar)
+            {
+                mp4dec_log("DecodeVOLHeader(): Sprite is not supported.\n");
+                return PV_FAIL;
+            }
+        }
+
+        /* not_8_bit */
+        if (BitstreamRead1Bits(stream))
+        {
+            /* quant_precision */
+            currVol->quantPrecision = BitstreamReadBits16(stream, 4);
+            /* bits_per_pixel  */
+            currVol->bitsPerPixel = BitstreamReadBits16(stream, 4);
+            mp4dec_log("DecodeVOLHeader(): not an 8-bit stream.\n");    // For the time being we do not support != 8 bits
+
+            return PV_FAIL;
+        }
+        else
+        {
+            currVol->quantPrecision = 5;
+            currVol->bitsPerPixel = 8;
+        }
+
+        /* quant_type (1 bit) */
+        currVol->quantType = BitstreamRead1Bits(stream);
+        if (currVol->quantType)
+        {
+#ifdef PV_SUPPORT_MAIN_PROFILE
+            /* load quantization matrices.   5/22/2000 */
+            /* load_intra_quant_mat (1 bit) */
+            qmat = currVol->iqmat;
+            currVol->loadIntraQuantMat = BitstreamRead1Bits(stream);
+            if (currVol->loadIntraQuantMat)
+            {
+                /* intra_quant_mat (8*64 bits) */
+                i = 0;
+                do
+                {
+                    qmat[*(zigzag_inv+i)] = (int) BitstreamReadBits16(stream, 8);
+                }
+                while ((qmat[*(zigzag_inv+i)] != 0) && (++i < 64));
+
+                for (j = i; j < 64; j++)
+                    qmat[*(zigzag_inv+j)] = qmat[*(zigzag_inv+i-1)];
+            }
+            else
+            {
+                oscl_memcpy(qmat, mpeg_iqmat_def, 64*sizeof(int));
+            }
+
+            qmat[0] = 0;             /* necessary for switched && MPEG quant  07/09/01 */
+
+            /* load_nonintra_quant_mat (1 bit) */
+            qmat = currVol->niqmat;
+            currVol->loadNonIntraQuantMat = BitstreamRead1Bits(stream);
+            if (currVol->loadNonIntraQuantMat)
+            {
+                /* nonintra_quant_mat (8*64 bits) */
+                i = 0;
+                do
+                {
+                    qmat[*(zigzag_inv+i)] = (int) BitstreamReadBits16(stream, 8);
+                }
+                while ((qmat[*(zigzag_inv+i)] != 0) && (++i < 64));
+
+                for (j = i; j < 64; j++)
+                    qmat[*(zigzag_inv+j)] = qmat[*(zigzag_inv+i-1)];
+            }
+            else
+            {
+                oscl_memcpy(qmat, mpeg_nqmat_def, 64*sizeof(int));
+            }
+#else
+            return PV_FAIL;
+#endif
+        }
+
+        if (version_id != 1)
+        {
+            /* quarter_sample enabled */
+            tmpvar = BitstreamRead1Bits(stream);
+            if (tmpvar) return PV_FAIL;
+        }
+
+        /* complexity_estimation_disable */
+        currVol->complexity_estDisable = BitstreamRead1Bits(stream);
+        if (currVol->complexity_estDisable == 0)
+        {
+            currVol->complexity_estMethod = BitstreamReadBits16(stream, 2);
+
+            if (currVol->complexity_estMethod < 2)
+            {
+                /* shape_complexity_estimation_disable */
+                tmpvar = BitstreamRead1Bits(stream);
+                if (tmpvar == 0)
+                {
+                    mp4dec_log("DecodeVOLHeader(): Shape Complexity estimation is not supported.\n");
+                    return PV_FAIL;
+                }
+                /* texture_complexity_estimation_set_1_disable */
+                tmpvar = BitstreamRead1Bits(stream);
+                if (tmpvar == 0)
+                {
+                    currVol->complexity.text_1 = BitstreamReadBits16(stream, 4);
+                }
+                /* marker bit */
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+                /* texture_complexity_estimation_set_2_disable */
+                tmpvar = BitstreamRead1Bits(stream);
+                if (tmpvar == 0)
+                {
+                    currVol->complexity.text_2 = BitstreamReadBits16(stream, 4);
+                }
+                /* motion_compensation_complexity_disable */
+                tmpvar = BitstreamRead1Bits(stream);
+                if (tmpvar == 0)
+                {
+                    currVol->complexity.mc = BitstreamReadBits16(stream, 6);
+                }
+                /* marker bit */
+                if (!BitstreamRead1Bits(stream)) return PV_FAIL;
+
+                if (currVol->complexity_estMethod == 1)
+                {   /* version2_complexity_estimation_disable */
+                    tmpvar = BitstreamRead1Bits(stream);
+                    if (tmpvar == 0)
+                    {
+                        mp4dec_log("DecodeVOLHeader(): sadct, quarter pel not supported.\n");
+                        return PV_FAIL;
+                    }
+                }
+            }
+        }
+
+        /*  03/10/99 */
+        /* resync_marker_disable */
+        currVol->errorResDisable = (int) BitstreamRead1Bits(stream);
+        /* data_partititioned    */
+        currVol->dataPartitioning = (int) BitstreamRead1Bits(stream);
+
+        video->vlcDecCoeffIntra = &VlcDecTCOEFIntra;
+        video->vlcDecCoeffInter = &VlcDecTCOEFInter;
+
+        if (currVol->dataPartitioning)
+        {
+            if (layer) return PV_FAIL;                              /*  */
+            /* reversible_vlc */
+            currVol->useReverseVLC = (int)BitstreamRead1Bits(stream);
+            if (currVol->useReverseVLC)
+            {
+                video->vlcDecCoeffIntra = &RvlcDecTCOEFIntra;
+                video->vlcDecCoeffInter = &RvlcDecTCOEFInter;
+            }
+            currVol->errorResDisable = 0;
+        }
+        else
+        {
+            currVol->useReverseVLC = 0;
+        }
+
+        if (version_id != 1)
+        {
+            /* newpred_enable */
+            tmpvar = BitstreamRead1Bits(stream);
+            if (tmpvar) return PV_FAIL;
+
+            /* reduced_resolution_vop */
+            tmpvar = BitstreamRead1Bits(stream);
+            if (tmpvar) return PV_FAIL;
+
+        }
+
+        /* Intra AC/DC prediction is always true */
+        video->intra_acdcPredDisable = 0;
+        /* scalability */
+        currVol->scalability = (int) BitstreamRead1Bits(stream);
+
+        if (currVol->scalability)
+        {
+            if (layer == 0)  return PV_FAIL;                     /*  */
+            /* hierarchy_type: 1 : temporal, 0 : spatial */
+            /*  03/10/99 */
+            currVol->scalType = (int) BitstreamRead1Bits(stream);              /*  */
+            if (!currVol->scalType) return PV_FAIL;
+
+            /* ref_layer_id (4 bits) */
+            currVol->refVolID = (int) BitstreamReadBits16(stream, 4);
+            if (layer)                                                      /*  */
+            {
+                if (currVol->refVolID != video->vol[0]->volID) return PV_FAIL;
+            }
+            /* ref_layer_sampling_direc (1 bits)              */
+            /*   1 : ref. layer has higher resolution         */
+            /*   0 : ref. layer has equal or lower resolution */
+            currVol->refSampDir = (int) BitstreamRead1Bits(stream);
+            if (currVol->refSampDir) return PV_FAIL;
+
+            /* hor_sampling_factor_n (5 bits) */
+            currVol->horSamp_n = (int) BitstreamReadBits16(stream, 5);
+
+            /* hor_sampling_factor_m (5 bits) */
+            currVol->horSamp_m = (int) BitstreamReadBits16(stream, 5);
+
+            if (currVol->horSamp_m == 0) return PV_FAIL;
+            if (currVol->horSamp_n != currVol->horSamp_m) return PV_FAIL;
+
+            /* ver_sampling_factor_n (5 bits) */
+            currVol->verSamp_n = (int) BitstreamReadBits16(stream, 5);
+
+            /* ver_sampling_factor_m (5 bits) */
+            currVol->verSamp_m = (int) BitstreamReadBits16(stream, 5);
+
+            if (currVol->verSamp_m == 0) return PV_FAIL;
+            if (currVol->verSamp_n != currVol->verSamp_m) return PV_FAIL;
+
+
+            /* enhancement_type: 1 : partial region, 0 : full region */
+            /* 04/10/2000: we only support full region enhancement layer. */
+            if (BitstreamRead1Bits(stream)) return PV_FAIL;
+        }
+
+        PV_BitstreamByteAlign(stream);
+
+        status = BitstreamShowBits32HC(stream, &tmpvar);
+
+        /* if we hit the end of buffer, tmpvar == 0.   08/30/2000 */
+        if (tmpvar == USER_DATA_START_CODE)
+        {
+            status = DecodeUserData(stream);
+            /* you should not check for status here  03/19/2002 */
+            status = PV_SUCCESS;
+        }
+
+        /* Compute some convenience variables:   04/13/2000 */
+        video->nMBPerRow = video->width / MB_SIZE;
+        video->nMBPerCol = video->height / MB_SIZE;
+        video->nTotalMB = video->nMBPerRow * video->nMBPerCol;
+        video->nBitsForMBID = CalcNumBits((uint)video->nTotalMB - 1);
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        video->modified_quant = 0;
+        video->advanced_INTRA = 0;
+        video->deblocking = 0;
+        video->slice_structure = 0;
+#endif
+    }
+    else
+    {
+        /* SHORT_HEADER */
+        status = BitstreamShowBits32(stream, SHORT_VIDEO_START_MARKER_LENGTH, &tmpvar);
+
+        if (tmpvar == SHORT_VIDEO_START_MARKER)
+        {
+            video->shortVideoHeader = TRUE;
+        }
+        else
+        {
+            do
+            {
+                /* Search for VOL_HEADER */
+                status = PVSearchNextM4VFrame(stream); /* search 0x00 0x00 0x01 */
+                if (status != PV_SUCCESS) return PV_FAIL; /* breaks the loop */
+                BitstreamShowBits32(stream, VOL_START_CODE_LENGTH, &tmpvar);
+                PV_BitstreamFlushBits(stream, 8);
+            }
+            while (tmpvar != VOL_START_CODE);
+            goto decode_vol;
+        }
+    }
+#ifdef PV_TOLERATE_VOL_ERRORS
+    if (profile > 0xFF || profile == 0)
+    {
+        return PV_BAD_VOLHEADER;
+    }
+#endif
+
+    return status;
+}
+
+
+/***********************************************************CommentBegin******
+*
+* -- DecodeGOV -- Decodes the Group of VOPs from bitstream
+*
+*   04/20/2000  initial modification to the new PV-Decoder Lib format.
+*
+***********************************************************CommentEnd********/
+PV_STATUS DecodeGOVHeader(BitstreamDecVideo *stream, uint32 *time_base)
+{
+    uint32 tmpvar, time_s;
+    int closed_gov, broken_link;
+
+    /* group_start_code (32 bits) */
+//   tmpvar = BitstreamReadBits32(stream, 32);
+
+    /* hours */
+    tmpvar = (uint32) BitstreamReadBits16(stream, 5);
+    time_s = tmpvar * 3600;
+
+    /* minutes */
+    tmpvar = (uint32) BitstreamReadBits16(stream, 6);
+    time_s += tmpvar * 60;
+
+    /* marker bit */
+    tmpvar = (uint32) BitstreamRead1Bits(stream);
+
+    /* seconds */
+    tmpvar = (uint32) BitstreamReadBits16(stream, 6);
+    time_s += tmpvar;
+
+    /* We have to check the timestamp here.  If the sync timestamp is */
+    /*    earlier than the previous timestamp or longer than 60 sec.  */
+    /*    after the previous timestamp, assume the GOV header is      */
+    /*    corrupted.                                 05/12/2000     */
+    *time_base = time_s;   /*  02/27/2002 */
+//  *time_base = *time_base/1000;
+//  tmpvar = time_s - *time_base;
+//  if (tmpvar <= 60) *time_base = time_s;
+//  else return PV_FAIL;
+
+    tmpvar = (uint32) BitstreamRead1Bits(stream);
+    closed_gov = tmpvar;
+    tmpvar = (uint32) BitstreamRead1Bits(stream);
+    broken_link = tmpvar;
+
+    if ((closed_gov == 0) && (broken_link == 1))
+    {
+        return PV_SUCCESS;        /*  03/15/2002  you can also return PV_FAIL */
+    }
+
+    PV_BitstreamByteAlign(stream);
+
+    BitstreamShowBits32HC(stream, &tmpvar);
+
+    while (tmpvar == USER_DATA_START_CODE)       /*  03/15/2002 */
+    {
+        DecodeUserData(stream);
+        BitstreamShowBits32HC(stream, &tmpvar);
+    }
+
+    return PV_SUCCESS;
+}
+
+/***********************************************************CommentBegin******
+*
+* -- DecodeVopHeader -- Decodes the VOPheader information from the bitstream
+*
+*   04/12/2000  Initial port to the new PV decoder library format.
+*   05/10/2000  Error resilient decoding of vop header.
+*
+***********************************************************CommentEnd********/
+PV_STATUS DecodeVOPHeader(VideoDecData *video, Vop *currVop, Bool use_ext_timestamp)
+{
+    PV_STATUS status = PV_SUCCESS;
+    Vol *currVol = video->vol[video->currLayer];
+    BitstreamDecVideo *stream = currVol->bitstream;
+    uint32 tmpvar;
+    int time_base;
+
+    /*****
+    *   Read the VOP header from the bitstream (No shortVideoHeader Mode here!)
+    *****/
+    BitstreamShowBits32HC(stream, &tmpvar);
+
+    /* check if we have a GOV header here.   08/30/2000 */
+    if (tmpvar == GROUP_START_CODE)
+    {
+        tmpvar = BitstreamReadBits32HC(stream);
+//      rewindBitstream(stream, START_CODE_LENGTH); /* for backward compatibility */
+        status = DecodeGOVHeader(stream, &tmpvar);
+        if (status != PV_SUCCESS)
+        {
+            return status;
+        }
+//      use_ext_timestamp = TRUE;   /*  02/08/2002 */
+        /* We should have a VOP header following the GOV header.  03/15/2001 */
+        BitstreamShowBits32HC(stream, &tmpvar);
+    }
+#ifdef PV_SUPPORT_TEMPORAL_SCALABILITY
+    currVop->timeStamp = -1;
+#endif
+    if (tmpvar == VOP_START_CODE)
+    {
+        tmpvar = BitstreamReadBits32HC(stream);
+    }
+    else
+    {
+        PV_BitstreamFlushBits(stream, 8); // advance by a byte
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+
+
+    /* vop_prediction_type (2 bits) */
+    currVop->predictionType = (int) BitstreamReadBits16(stream, 2);
+
+    /* modulo_time_base (? bits) */
+    time_base = -1;
+    do
+    {
+        time_base++;
+        tmpvar = (uint32) BitstreamRead1Bits(stream);
+    }
+    while (tmpvar == 1);
+
+
+
+    if (!use_ext_timestamp)
+    {
+        currVol->moduloTimeBase += 1000 * time_base; /* milliseconds based MTB  11/12/01 */
+    }
+
+    /* marker_bit (1 bit) */
+    if (!BitstreamRead1Bits(stream))
+    {
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+    /* vop_time_increment (1-15 bits) in Nov_Compliant (1-16 bits) */
+    /*    we always assumes fixed vop rate here */
+    currVop->timeInc = BitstreamReadBits16(stream, currVol->nbitsTimeIncRes);
+
+
+    /* marker_bit (1 bit) */
+    if (!BitstreamRead1Bits(stream))
+    {
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+    /* vop_coded */
+    currVop->vopCoded = (int) BitstreamRead1Bits(stream);
+
+
+    if (currVop->vopCoded == 0)
+    {
+        status = PV_SUCCESS;
+        goto return_point;
+    }
+
+
+    /* read vop_rounding_type */
+    if (currVop->predictionType == P_VOP)
+    {
+        currVop->roundingType = (int) BitstreamRead1Bits(stream);
+    }
+    else
+    {
+        currVop->roundingType = 0;
+    }
+
+    if (currVol->complexity_estDisable == 0)
+    {
+        if (currVol->complexity_estMethod < 2)   /*   OCT 2002 */
+        {
+            if ((currVol->complexity.text_1 >> 3) & 0x1)    /* intra        */
+                BitstreamReadBits16(stream, 8);
+            if (currVol->complexity.text_1 & 0x1)           /* not_coded    */
+                BitstreamReadBits16(stream, 8);
+            if ((currVol->complexity.text_2 >> 3) & 0x1)    /* dct_coefs    */
+                BitstreamReadBits16(stream, 8);
+            if ((currVol->complexity.text_2 >> 2) & 0x1)    /* dct_lines    */
+                BitstreamReadBits16(stream, 8);
+            if ((currVol->complexity.text_2 >> 1) & 0x1)    /* vlc_symbols  */
+                BitstreamReadBits16(stream, 8);
+            if (currVol->complexity.text_2 & 0x1)           /* vlc_bits     */
+                BitstreamReadBits16(stream, 4);
+
+            if (currVop->predictionType != I_VOP)
+            {
+                if ((currVol->complexity.text_1 >> 2) & 0x1)    /* inter    */
+                    BitstreamReadBits16(stream, 8);
+                if ((currVol->complexity.text_1 >> 1) & 0x1)    /* inter_4v */
+                    BitstreamReadBits16(stream, 8);
+                if ((currVol->complexity.mc >> 5) & 0x1)        /* apm      */
+                    BitstreamReadBits16(stream, 8);
+                if ((currVol->complexity.mc >> 4) & 0x1)        /* npm      */
+                    BitstreamReadBits16(stream, 8);
+                /* interpolate_mc_q */
+                if ((currVol->complexity.mc >> 2) & 0x1)        /* forw_back_mc_q */
+                    BitstreamReadBits16(stream, 8);
+                if ((currVol->complexity.mc >> 1) & 0x1)        /* halfpel2 */
+                    BitstreamReadBits16(stream, 8);
+                if (currVol->complexity.mc & 0x1)               /* halfpel4 */
+                    BitstreamReadBits16(stream, 8);
+            }
+            if (currVop->predictionType == B_VOP)
+            {
+                if ((currVol->complexity.mc >> 3) & 0x1)        /* interpolate_mc_q */
+                    BitstreamReadBits16(stream, 8);
+            }
+        }
+    }
+
+    /* read intra_dc_vlc_thr */
+    currVop->intraDCVlcThr = (int) BitstreamReadBits16(stream, 3);
+
+    /* read vop_quant (currVol->quantPrecision bits) */
+    currVop->quantizer = (int16) BitstreamReadBits16(stream, currVol->quantPrecision);
+    if (currVop->quantizer == 0)
+    {
+        currVop->quantizer = video->prevVop->quantizer;
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+
+    /* read vop_fcode_forward */
+    if (currVop->predictionType != I_VOP)
+    {
+        tmpvar = (uint32) BitstreamReadBits16(stream, 3);
+        if (tmpvar < 1)
+        {
+            currVop->fcodeForward = 1;
+            status = PV_FAIL;
+            goto return_point;
+        }
+        currVop->fcodeForward = tmpvar;
+    }
+    else
+    {
+        currVop->fcodeForward = 0;
+    }
+
+    /* read vop_fcode_backward */
+    if (currVop->predictionType == B_VOP)
+    {
+        tmpvar = (uint32) BitstreamReadBits16(stream, 3);
+        if (tmpvar < 1)
+        {
+            currVop->fcodeBackward = 1;
+            status = PV_FAIL;
+            goto return_point;
+        }
+        currVop->fcodeBackward = tmpvar;
+    }
+    else
+    {
+        currVop->fcodeBackward = 0;
+    }
+
+    if (currVol->scalability)
+    {
+        currVop->refSelectCode = (int) BitstreamReadBits16(stream, 2);
+    }
+
+return_point:
+    return status;
+}
+
+
+/***********************************************************CommentBegin******
+*
+* -- VideoPlaneWithShortHeader -- Decodes the short_video_header information from the bitstream
+* Modified :
+             04/23/2001.  Remove the codes related to the
+                 "first pass" decoding.  We use a different function
+                 to set up the decoder now.
+***********************************************************CommentEnd********/
+PV_STATUS DecodeShortHeader(VideoDecData *video, Vop *currVop)
+{
+    PV_STATUS status = PV_SUCCESS;
+    Vol *currVol = video->vol[0];
+    BitstreamDecVideo *stream = currVol->bitstream;
+    uint32 tmpvar;
+    int32 size;
+
+    int extended_PTYPE = FALSE;
+    int UFEP = 0, custom_PFMT = 0, custom_PCF = 0;
+
+    status = BitstreamShowBits32(stream, SHORT_VIDEO_START_MARKER_LENGTH, &tmpvar);
+
+    if (tmpvar !=  SHORT_VIDEO_START_MARKER)
+    {
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+
+    PV_BitstreamFlushBits(stream, SHORT_VIDEO_START_MARKER_LENGTH);
+
+    /* Temporal reference. Using vop_time_increment_resolution = 30000 */
+    tmpvar = (uint32) BitstreamReadBits16(stream, 8);
+    currVop->temporalRef = (int) tmpvar;
+
+
+    currVop->timeInc = 0xff & (256 + currVop->temporalRef - video->prevVop->temporalRef);
+    currVol->moduloTimeBase += currVop->timeInc; /* mseconds   11/12/01 */
+    /* Marker Bit */
+    if (!BitstreamRead1Bits(stream))
+    {
+        mp4dec_log("DecodeShortHeader(): Market bit wrong.\n");
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+    /* Zero Bit */
+    if (BitstreamRead1Bits(stream))
+    {
+        mp4dec_log("DecodeShortHeader(): Zero bit wrong.\n");
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+    /*split_screen_indicator*/
+    if (BitstreamRead1Bits(stream))
+    {
+        mp4dec_log("DecodeShortHeader(): Split Screen not supported.\n");
+        VideoDecoderErrorDetected(video);
+    }
+
+    /*document_freeze_camera*/
+    if (BitstreamRead1Bits(stream))
+    {
+        mp4dec_log("DecodeShortHeader(): Freeze Camera not supported.\n");
+        VideoDecoderErrorDetected(video);
+    }
+
+    /*freeze_picture_release*/
+    if (BitstreamRead1Bits(stream))
+    {
+        mp4dec_log("DecodeShortHeader(): Freeze Release not supported.\n");
+        VideoDecoderErrorDetected(video);
+    }
+    /* source format */
+    switch (BitstreamReadBits16(stream, 3))
+    {
+        case 1:
+            if (video->size < 128*96)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayWidth = video->width =  128;
+            video->displayHeight = video->height  = 96;
+            break;
+
+        case 2:
+            if (video->size < 176*144)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayWidth = video->width  = 176;
+            video->displayHeight = video->height  = 144;
+            break;
+
+        case 3:
+            if (video->size < 352*288)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayWidth = video->width = 352;
+            video->displayHeight = video->height = 288;
+            break;
+
+        case 4:
+            if (video->size < 704*576)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayWidth = video->width = 704;
+            video->displayHeight = video->height = 576;
+            break;
+
+        case 5:
+            if (video->size < 1408*1152)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayWidth = video->width = 1408;
+            video->displayHeight = video->height = 1152;
+            break;
+
+        case 7:
+            extended_PTYPE = TRUE;
+            break;
+
+        default:
+            /* Msg("H.263 source format not legal\n"); */
+            status = PV_FAIL;
+            goto return_point;
+    }
+
+
+    currVop->roundingType = 0;
+
+    if (extended_PTYPE == FALSE)
+    {
+        currVop->predictionType = (int) BitstreamRead1Bits(stream);
+
+        /* four_reserved_zero_bits */
+        if (BitstreamReadBits16(stream, 4))
+        {
+            mp4dec_log("DecodeShortHeader(): Reserved bits wrong.\n");
+            status = PV_FAIL;
+            goto return_point;
+        }
+    }
+    else
+    {
+        UFEP = BitstreamReadBits16(stream, 3);
+        if (UFEP == 1)
+        {
+            /* source format */
+            switch (BitstreamReadBits16(stream, 3))
+            {
+                case 1:
+                    if (video->size < 128*96)
+                    {
+                        status = PV_FAIL;
+                        goto return_point;
+                    }
+                    video->displayWidth = video->width =  128;
+                    video->displayHeight = video->height  = 96;
+                    break;
+
+                case 2:
+                    if (video->size < 176*144)
+                    {
+                        status = PV_FAIL;
+                        goto return_point;
+                    }
+                    video->displayWidth = video->width  = 176;
+                    video->displayHeight = video->height  = 144;
+                    break;
+
+                case 3:
+                    if (video->size < 352*288)
+                    {
+                        status = PV_FAIL;
+                        goto return_point;
+                    }
+                    video->displayWidth = video->width = 352;
+                    video->displayHeight = video->height = 288;
+                    break;
+
+                case 4:
+                    if (video->size < 704*576)
+                    {
+                        status = PV_FAIL;
+                        goto return_point;
+                    }
+                    video->displayWidth = video->width = 704;
+                    video->displayHeight = video->height = 576;
+                    break;
+
+                case 5:
+                    if (video->size < 1408*1152)
+                    {
+                        status = PV_FAIL;
+                        goto return_point;
+                    }
+                    video->displayWidth = video->width = 1408;
+                    video->displayHeight = video->height = 1152;
+                    break;
+
+                case 6:
+                    custom_PFMT = TRUE;
+                    break;
+
+                default:
+                    /* Msg("H.263 source format not legal\n"); */
+                    status = PV_FAIL;
+                    goto return_point;
+            }
+
+            custom_PCF = BitstreamRead1Bits(stream);
+            /* unrestricted MV */
+            if (BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            /* SAC */
+            if (BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+
+            /* AP */
+            if (BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+
+            video->advanced_INTRA = BitstreamRead1Bits(stream);
+
+            video->deblocking = BitstreamRead1Bits(stream);
+
+            video->slice_structure = BitstreamRead1Bits(stream);
+
+            /* RPS, ISD, AIV */
+            if (BitstreamReadBits16(stream, 3))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->modified_quant = BitstreamRead1Bits(stream);
+
+            /* Marker Bit and reserved*/
+            if (BitstreamReadBits16(stream, 4) != 8)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+        }
+#ifndef PV_ANNEX_IJKT_SUPPORT
+        if (video->advanced_INTRA | video->deblocking | video->modified_quant | video->modified_quant)
+        {
+            status = PV_FAIL;
+            goto return_point;
+        }
+#endif
+
+        if (UFEP == 0 || UFEP == 1)
+        {
+            tmpvar = BitstreamReadBits16(stream, 3);
+            if (tmpvar > 1)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            currVop->predictionType = tmpvar;
+            /* RPR */
+            if (BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+
+            /* RRU */
+            if (BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            currVop->roundingType = (int) BitstreamRead1Bits(stream);
+            if (BitstreamReadBits16(stream, 3) != 1)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+        }
+        else
+        {
+            status = PV_FAIL;
+            goto return_point;
+        }
+        /* CPM */
+        if (BitstreamRead1Bits(stream))
+        {
+            status = PV_FAIL;
+            goto return_point;
+        }
+        /* CPFMT */
+        if (custom_PFMT == 1 && UFEP == 1)
+        {
+            /* aspect ratio */
+            tmpvar = BitstreamReadBits16(stream, 4);
+            if (tmpvar == 0)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            /* Extended PAR */
+            if (tmpvar == 0xF)
+            {
+                /* Read par_width and par_height but do nothing */
+                /* par_width */
+                tmpvar = BitstreamReadBits16(stream, 8);
+
+                /* par_height */
+                tmpvar = BitstreamReadBits16(stream, 8);
+            }
+            tmpvar = BitstreamReadBits16(stream, 9);
+
+            video->displayWidth = (tmpvar + 1) << 2;
+            video->width = (video->displayWidth + 15) & -16;
+            /* marker bit */
+            if (!BitstreamRead1Bits(stream))
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            tmpvar = BitstreamReadBits16(stream, 9);
+            if (tmpvar == 0)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+            video->displayHeight = tmpvar << 2;
+            video->height = (video->displayHeight + 15) & -16;
+
+            if (video->height * video->width > video->size)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+
+            video->nTotalMB = video->width / MB_SIZE * video->height / MB_SIZE;
+
+            if (video->nTotalMB <= 48)
+            {
+                video->nBitsForMBID = 6;
+            }
+            else if (video->nTotalMB <= 99)
+            {
+                video->nBitsForMBID = 7;
+            }
+            else if (video->nTotalMB <= 396)
+            {
+                video->nBitsForMBID = 9;
+            }
+            else if (video->nTotalMB <= 1584)
+            {
+                video->nBitsForMBID = 11;
+            }
+            else if (video->nTotalMB <= 6336)
+            {
+                video->nBitsForMBID = 13 ;
+            }
+            else if (video->nTotalMB <= 9216)
+            {
+                video->nBitsForMBID = 14 ;
+            }
+            else
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+        }
+        if (UFEP == 1 && custom_PCF == 1)
+        {
+            BitstreamRead1Bits(stream);
+
+            tmpvar = BitstreamReadBits16(stream, 7);
+            if (tmpvar == 0)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+        }
+
+        if (custom_PCF == 1)
+        {
+            currVop->ETR = BitstreamReadBits16(stream, 2);
+        }
+
+        if (UFEP == 1 && video->slice_structure == 1)
+        {
+            /* SSS */
+            tmpvar = BitstreamReadBits16(stream, 2);
+            if (tmpvar != 0)
+            {
+                status = PV_FAIL;
+                goto return_point;
+            }
+        }
+    }
+
+    /* Recalculate number of macroblocks per row & col since */
+    /*  the frame size can change.           04/23/2001.   */
+    video->nMBinGOB = video->nMBPerRow = video->width / MB_SIZE;
+    video->nGOBinVop = video->nMBPerCol = video->height / MB_SIZE;
+    video->nTotalMB = video->nMBPerRow * video->nMBPerCol;
+    if (custom_PFMT == 0  || UFEP == 0)
+    {
+        video->nBitsForMBID = CalcNumBits((uint)video->nTotalMB - 1); /* otherwise calculate above */
+    }
+    size = (int32)video->width * video->height;
+    if (video->currVop->predictionType == P_VOP && size > video->videoDecControls->size)
+    {
+        status = PV_FAIL;
+        goto return_point;
+    }
+    video->videoDecControls->size = size;
+    video->currVop->uChan = video->currVop->yChan + size;
+    video->currVop->vChan = video->currVop->uChan + (size >> 2);
+    video->prevVop->uChan = video->prevVop->yChan + size;
+    video->prevVop->vChan = video->prevVop->uChan + (size >> 2);
+
+
+    currVop->quantizer = (int16) BitstreamReadBits16(stream, 5);
+
+    if (currVop->quantizer == 0)                          /*  04/03/01 */
+    {
+        currVop->quantizer = video->prevVop->quantizer;
+        status = PV_FAIL;
+        goto return_point;
+    }
+
+
+    /* Zero bit */
+    if (extended_PTYPE == FALSE)
+    {
+        if (BitstreamRead1Bits(stream))
+        {
+            mp4dec_log("DecodeShortHeader(): Zero bit wrong.\n");
+            status = PV_FAIL;
+            goto return_point;
+        }
+    }
+    /* pei */
+    tmpvar = (uint32) BitstreamRead1Bits(stream);
+
+    while (tmpvar)
+    {
+        tmpvar = (uint32) BitstreamReadBits16(stream, 8); /* "PSPARE" */
+        tmpvar = (uint32) BitstreamRead1Bits(stream); /* "PEI" */
+    }
+
+    if (video->slice_structure)  /* ANNEX_K */
+    {
+        if (!BitstreamRead1Bits(stream))  /* SEPB1 */
+        {
+            status = PV_FAIL;
+            goto return_point;
+        }
+
+        //  if (currVol->nBitsForMBID //
+        if (BitstreamReadBits16(stream, video->nBitsForMBID))
+        {
+            status = PV_FAIL;             /* no ASO, RS support for Annex K */
+            goto return_point;
+        }
+
+        if (!BitstreamRead1Bits(stream))  /*SEPB3 */
+        {
+            status = PV_FAIL;
+            goto return_point;
+        }
+
+    }
+    /* Setting of other VOP-header parameters */
+    currVop->gobNumber = 0;
+    currVop->vopCoded = 1;
+
+    currVop->intraDCVlcThr = 0;
+    currVop->gobFrameID = 0; /* initial value,  05/22/00 */
+    currVol->errorResDisable = 0;
+    /*PutVopInterlaced(0,curr_vop); no implemented yet */
+    if (currVop->predictionType != I_VOP)
+        currVop->fcodeForward = 1;
+    else
+        currVop->fcodeForward = 0;
+
+return_point:
+
+    return status;
+}
+/***********************************************************CommentBegin******
+*
+* -- PV_DecodeVop -- Decodes the VOP information from the bitstream
+*
+*   04/12/2000
+*                   Initial port to the new PV decoder library format.
+*                   This function is different from the one in MoMuSys MPEG-4
+*                   visual decoder.  We handle combined mode with or withput
+*                   error resilience and H.263 mode through the sam path now.
+*
+*   05/04/2000
+*                   Added temporal scalability to the decoder.
+*
+***********************************************************CommentEnd********/
+PV_STATUS PV_DecodeVop(VideoDecData *video)
+{
+    Vol *currVol = video->vol[video->currLayer];
+    PV_STATUS status;
+    uint32 tmpvar;
+
+    /*****
+    *   Do scalable or non-scalable decoding of the current VOP
+    *****/
+
+    if (!currVol->scalability)
+    {
+        if (currVol->dataPartitioning)
+        {
+            /* Data partitioning mode comes here */
+            status = DecodeFrameDataPartMode(video);
+        }
+        else
+        {
+            /* Combined mode with or without error resilience */
+            /*    and short video header comes here.          */
+            status = DecodeFrameCombinedMode(video);
+        }
+    }
+    else
+    {
+#ifdef DO_NOT_FOLLOW_STANDARD
+        /* according to the standard, only combined mode is allowed */
+        /*    in the enhancement layer.          06/01/2000.        */
+        if (currVol->dataPartitioning)
+        {
+            /* Data partitioning mode comes here */
+            status = DecodeFrameDataPartMode(video);
+        }
+        else
+        {
+            /* Combined mode with or without error resilience */
+            /*    and short video header comes here.          */
+            status = DecodeFrameCombinedMode(video);
+        }
+#else
+        status = DecodeFrameCombinedMode(video);
+#endif
+    }
+
+    /* This part is for consuming Visual_object_sequence_end_code and EOS Code */   /*  10/15/01 */
+    if (!video->shortVideoHeader)
+    {
+        /* at this point bitstream is expected to be byte aligned */
+        BitstreamByteAlignNoForceStuffing(currVol->bitstream);
+
+        status = BitstreamShowBits32HC(currVol->bitstream, &tmpvar);  /*  07/07/01 */
+        if (tmpvar == VISUAL_OBJECT_SEQUENCE_END_CODE)/* VOS_END_CODE */
+        {
+            PV_BitstreamFlushBits(currVol->bitstream, 16);
+            PV_BitstreamFlushBits(currVol->bitstream, 16);
+        }
+
+    }
+    else
+    {
+#ifdef PV_ANNEX_IJKT_SUPPORT
+        if (video->deblocking)
+        {
+            H263_Deblock(video->currVop->yChan, video->width, video->height, video->QPMB, video->headerInfo.Mode, 0, 0);
+            H263_Deblock(video->currVop->uChan, video->width >> 1, video->height >> 1, video->QPMB, video->headerInfo.Mode, 1, video->modified_quant);
+            H263_Deblock(video->currVop->vChan, video->width >> 1, video->height >> 1, video->QPMB, video->headerInfo.Mode, 1, video->modified_quant);
+        }
+#endif
+        /* Read EOS code for shortheader bitstreams    */
+        status = BitstreamShowBits32(currVol->bitstream, 22, &tmpvar);
+        if (tmpvar == SHORT_VIDEO_END_MARKER)
+        {
+            PV_BitstreamFlushBits(currVol->bitstream, 22);
+        }
+        else
+        {
+            status = PV_BitstreamShowBitsByteAlign(currVol->bitstream, 22, &tmpvar);
+            if (tmpvar == SHORT_VIDEO_END_MARKER)
+            {
+                PV_BitstreamByteAlign(currVol->bitstream);
+                PV_BitstreamFlushBits(currVol->bitstream, 22);
+            }
+        }
+    }
+    return status;
+}
+
+
+/***********************************************************CommentBegin******
+*
+* -- CalcVopDisplayTime -- calculate absolute time when VOP is to be displayed
+*
+*   04/12/2000 Initial port to the new PV decoder library format.
+*
+***********************************************************CommentEnd********/
+uint32 CalcVopDisplayTime(Vol *currVol, Vop *currVop, int shortVideoHeader)
+{
+    uint32 display_time;
+
+
+    /*****
+    *   Calculate the time when the VOP is to be displayed next
+    *****/
+
+    if (!shortVideoHeader)
+    {
+        display_time = (uint32)(currVol->moduloTimeBase + (((int32)currVop->timeInc - (int32)currVol->timeInc_offset) * 1000) / ((int32)currVol->timeIncrementResolution));  /*  11/12/2001 */
+        if (currVop->timeStamp >= display_time)
+        {
+            display_time += 1000;  /* this case is valid if GOVHeader timestamp is ignored */
+        }
+    }
+    else
+    {
+        display_time = (uint32)(currVol->moduloTimeBase * 33 + (currVol->moduloTimeBase * 11) / 30); /*  11/12/2001 */
+    }
+
+    return(display_time);
+}
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/zigzag.h b/media/libstagefright/codecs/m4v_h263/dec/src/zigzag.h
new file mode 100644
index 0000000..4690a18
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/zigzag.h
@@ -0,0 +1,72 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#ifndef zigzag_H
+#define zigzag_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    extern const int zigzag_inv[3*NCOEFF_BLOCK];
+    /*----------------------------------------------------------------------------
+    ; SIMPLE TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; ENUMERATED TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; GLOBAL FUNCTION DEFINITIONS
+    ; Function Prototype declaration
+    ----------------------------------------------------------------------------*/
+
+    /*----------------------------------------------------------------------------
+    ; END
+    ----------------------------------------------------------------------------*/
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/dec/src/zigzag_tab.cpp b/media/libstagefright/codecs/m4v_h263/dec/src/zigzag_tab.cpp
new file mode 100644
index 0000000..33dbb14
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/dec/src/zigzag_tab.cpp
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+#include    "mp4dec_api.h"
+#include    "mp4def.h"
+#include    "zigzag.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
+----------------------------------------------------------------------------*/
+const int zigzag_inv[3*NCOEFF_BLOCK] =
+{
+    0,  1,  8, 16,  9,  2,  3, 10,
+    17, 24, 32, 25, 18, 11,  4,  5,
+    12, 19, 26, 33, 40, 48, 41, 34,
+    27, 20, 13,  6,  7, 14, 21, 28,
+    35, 42, 49, 56, 57, 50, 43, 36,
+    29, 22, 15, 23, 30, 37, 44, 51,
+    58, 59, 52, 45, 38, 31, 39, 46,
+    53, 60, 61, 54, 47, 55, 62, 63,
+//};
+
+    /* Vertical inverse zigzag */
+//const static Int zigzag_v_inv[NCOEFF_BLOCK] = {
+    0, 8, 16, 24, 1, 9, 2, 10,
+    17, 25, 32, 40, 48, 56, 57, 49,
+    41, 33, 26, 18, 3, 11, 4, 12,
+    19, 27, 34, 42, 50, 58, 35, 43,
+    51, 59, 20, 28, 5, 13, 6, 14,
+    21, 29, 36, 44, 52, 60, 37, 45,
+    53, 61, 22, 30, 7, 15, 23, 31,
+    38, 46, 54, 62, 39, 47, 55, 63,
+//};
+    /* Horizontal inverse zigzag*/
+//const static Int zizag_h_inv[NCOEFF_BLOCK] = {
+    0, 1, 2, 3, 8, 9, 16, 17,
+    10, 11, 4, 5, 6, 7, 15, 14,
+    13, 12, 19, 18, 24, 25, 32, 33,
+    26, 27, 20, 21, 22, 23, 28, 29,
+    30, 31, 34, 35, 40, 41, 48, 49,
+    42, 43, 36, 37, 38, 39, 44, 45,
+    46, 47, 50, 51, 56, 57, 58, 59,
+    52, 53, 54, 55, 60, 61, 62, 63
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Define all local variables
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Function body here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; Return nothing or data or data pointer
+----------------------------------------------------------------------------*/
+
+
diff --git a/media/libstagefright/codecs/m4v_h263/patent_disclaimer.txt b/media/libstagefright/codecs/m4v_h263/patent_disclaimer.txt
new file mode 100644
index 0000000..b4bf11d
--- /dev/null
+++ b/media/libstagefright/codecs/m4v_h263/patent_disclaimer.txt
@@ -0,0 +1,9 @@
+
+THIS IS NOT A GRANT OF PATENT RIGHTS.
+
+Google makes no representation or warranty that the codecs for which
+source code is made available hereunder are unencumbered by
+third-party patents.  Those intending to use this source code in
+hardware or software products are advised that implementations of
+these codecs, including in open source software or shareware, may
+require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/mp3dec/Android.mk b/media/libstagefright/codecs/mp3dec/Android.mk
new file mode 100644
index 0000000..fb56a93
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/Android.mk
@@ -0,0 +1,57 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+        MP3Decoder.cpp \
+	src/pvmp3_normalize.cpp \
+ 	src/pvmp3_alias_reduction.cpp \
+ 	src/pvmp3_crc.cpp \
+ 	src/pvmp3_decode_header.cpp \
+ 	src/pvmp3_decode_huff_cw.cpp \
+ 	src/pvmp3_getbits.cpp \
+ 	src/pvmp3_dequantize_sample.cpp \
+ 	src/pvmp3_framedecoder.cpp \
+ 	src/pvmp3_get_main_data_size.cpp \
+ 	src/pvmp3_get_side_info.cpp \
+ 	src/pvmp3_get_scale_factors.cpp \
+ 	src/pvmp3_mpeg2_get_scale_data.cpp \
+ 	src/pvmp3_mpeg2_get_scale_factors.cpp \
+ 	src/pvmp3_mpeg2_stereo_proc.cpp \
+ 	src/pvmp3_huffman_decoding.cpp \
+ 	src/pvmp3_huffman_parsing.cpp \
+ 	src/pvmp3_tables.cpp \
+ 	src/pvmp3_imdct_synth.cpp \
+ 	src/pvmp3_mdct_6.cpp \
+ 	src/pvmp3_dct_6.cpp \
+ 	src/pvmp3_poly_phase_synthesis.cpp \
+ 	src/pvmp3_equalizer.cpp \
+ 	src/pvmp3_seek_synch.cpp \
+ 	src/pvmp3_stereo_proc.cpp \
+ 	src/pvmp3_reorder.cpp \
+
+ifeq ($(TARGET_ARCH),arm)
+LOCAL_SRC_FILES += \
+	src/asm/pvmp3_polyphase_filter_window_gcc.s \
+ 	src/asm/pvmp3_mdct_18_gcc.s \
+ 	src/asm/pvmp3_dct_9_gcc.s \
+	src/asm/pvmp3_dct_16_gcc.s
+else
+LOCAL_SRC_FILES += \
+ 	src/pvmp3_polyphase_filter_window.cpp \
+ 	src/pvmp3_mdct_18.cpp \
+ 	src/pvmp3_dct_9.cpp \
+ 	src/pvmp3_dct_16.cpp
+endif
+
+LOCAL_C_INCLUDES := \
+        frameworks/base/media/libstagefright/include \
+        $(LOCAL_PATH)/src \
+        $(LOCAL_PATH)/include
+
+LOCAL_CFLAGS := \
+        -DOSCL_UNUSED_ARG=
+
+LOCAL_MODULE := libstagefright_mp3dec
+
+include $(BUILD_STATIC_LIBRARY)
+
diff --git a/media/libstagefright/codecs/mp3dec/MP3Decoder.cpp b/media/libstagefright/codecs/mp3dec/MP3Decoder.cpp
new file mode 100644
index 0000000..2f919c2
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/MP3Decoder.cpp
@@ -0,0 +1,189 @@
+/*
+ * 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 "MP3Decoder.h"
+
+#include "include/pvmp3decoder_api.h"
+
+#include <media/stagefright/MediaBufferGroup.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaDefs.h>
+#include <media/stagefright/MetaData.h>
+
+namespace android {
+
+MP3Decoder::MP3Decoder(const sp<MediaSource> &source)
+    : mSource(source),
+      mStarted(false),
+      mBufferGroup(NULL),
+      mConfig(new tPVMP3DecoderExternal),
+      mDecoderBuf(NULL),
+      mAnchorTimeUs(0),
+      mNumSamplesOutput(0),
+      mInputBuffer(NULL) {
+}
+
+MP3Decoder::~MP3Decoder() {
+    if (mStarted) {
+        stop();
+    }
+
+    delete mConfig;
+    mConfig = NULL;
+}
+
+status_t MP3Decoder::start(MetaData *params) {
+    CHECK(!mStarted);
+
+    mBufferGroup = new MediaBufferGroup;
+    mBufferGroup->add_buffer(new MediaBuffer(4608 * 2));
+
+    mConfig->equalizerType = flat;
+    mConfig->crcEnabled = true;
+
+    uint32_t memRequirements = pvmp3_decoderMemRequirements();
+    mDecoderBuf = malloc(memRequirements);
+
+    pvmp3_InitDecoder(mConfig, mDecoderBuf);
+
+    mSource->start();
+
+    mAnchorTimeUs = 0;
+    mNumSamplesOutput = 0;
+    mStarted = true;
+
+    return OK;
+}
+
+status_t MP3Decoder::stop() {
+    CHECK(mStarted);
+
+    if (mInputBuffer) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    free(mDecoderBuf);
+    mDecoderBuf = NULL;
+
+    delete mBufferGroup;
+    mBufferGroup = NULL;
+
+    mSource->stop();
+
+    mStarted = false;
+
+    return OK;
+}
+
+sp<MetaData> MP3Decoder::getFormat() {
+    sp<MetaData> srcFormat = mSource->getFormat();
+
+    int32_t numChannels;
+    int32_t sampleRate;
+    CHECK(srcFormat->findInt32(kKeyChannelCount, &numChannels));
+    CHECK(srcFormat->findInt32(kKeySampleRate, &sampleRate));
+
+    sp<MetaData> meta = new MetaData;
+    meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
+    meta->setInt32(kKeyChannelCount, numChannels);
+    meta->setInt32(kKeySampleRate, sampleRate);
+
+    int64_t durationUs;
+    if (srcFormat->findInt64(kKeyDuration, &durationUs)) {
+        meta->setInt64(kKeyDuration, durationUs);
+    }
+
+    return meta;
+}
+
+status_t MP3Decoder::read(
+        MediaBuffer **out, const ReadOptions *options) {
+    status_t err;
+
+    *out = NULL;
+
+    int64_t seekTimeUs;
+    if (options && options->getSeekTo(&seekTimeUs)) {
+        CHECK(seekTimeUs >= 0);
+
+        mNumSamplesOutput = 0;
+
+        if (mInputBuffer) {
+            mInputBuffer->release();
+            mInputBuffer = NULL;
+        }
+    } else {
+        seekTimeUs = -1;
+    }
+
+    if (mInputBuffer == NULL) {
+        err = mSource->read(&mInputBuffer, options);
+
+        if (err != OK) {
+            return err;
+        }
+
+        int64_t timeUs;
+        if (mInputBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
+            mAnchorTimeUs = timeUs;
+            mNumSamplesOutput = 0;
+        } else {
+            // We must have a new timestamp after seeking.
+            CHECK(seekTimeUs < 0);
+        }
+    }
+
+    MediaBuffer *buffer;
+    CHECK_EQ(mBufferGroup->acquire_buffer(&buffer), OK);
+
+    mConfig->pInputBuffer =
+        (uint8_t *)mInputBuffer->data() + mInputBuffer->range_offset();
+
+    mConfig->inputBufferCurrentLength = mInputBuffer->range_length();
+    mConfig->inputBufferMaxLength = 0;
+    mConfig->inputBufferUsedLength = 0;
+
+    mConfig->outputFrameSize = buffer->size() / sizeof(int16_t);
+    mConfig->pOutputBuffer = static_cast<int16_t *>(buffer->data());
+
+    CHECK_EQ(pvmp3_framedecoder(mConfig, mDecoderBuf), NO_DECODING_ERROR);
+
+    buffer->set_range(
+            0, mConfig->outputFrameSize * sizeof(int16_t));
+
+    mInputBuffer->set_range(
+            mInputBuffer->range_offset() + mConfig->inputBufferUsedLength,
+            mInputBuffer->range_length() - mConfig->inputBufferUsedLength);
+
+    if (mInputBuffer->range_length() == 0) {
+        mInputBuffer->release();
+        mInputBuffer = NULL;
+    }
+
+    buffer->meta_data()->setInt64(
+            kKeyTime,
+            mAnchorTimeUs
+                + (mNumSamplesOutput * 1000000) / mConfig->samplingRate);
+
+    mNumSamplesOutput += mConfig->outputFrameSize / sizeof(int16_t);
+
+    *out = buffer;
+
+    return OK;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/codecs/mp3dec/include/mp3_decoder_selection.h b/media/libstagefright/codecs/mp3dec/include/mp3_decoder_selection.h
new file mode 100644
index 0000000..e287433
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/include/mp3_decoder_selection.h
@@ -0,0 +1,30 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*! \file   mp3_decoder_selection.h
+ *  \brief  select mp3 decoder
+ *
+ */
+
+#ifndef MP3_DECODER_SELECTION_H
+#define MP3_DECODER_SELECTION_H
+
+
+#define NEW_PV_MP3_DECODER 1  //  1 == PV mp3 decoder
+
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/include/pvmp3_audio_type_defs.h b/media/libstagefright/codecs/mp3dec/include/pvmp3_audio_type_defs.h
new file mode 100644
index 0000000..2d94384
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/include/pvmp3_audio_type_defs.h
@@ -0,0 +1,77 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_audio_type_defs.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file was derived from a number of standards bodies. The type
+ definitions below were created from some of the best practices observed
+ in the standards bodies.
+
+ This file is dependent on limits.h for defining the bit widths. In an
+ ANSI C environment limits.h is expected to always be present and contain
+ the following definitions:
+
+     SCHAR_MIN
+     SCHAR_MAX
+     UCHAR_MAX
+
+     INT_MAX
+     INT_MIN
+     UINT_MAX
+
+     SHRT_MIN
+     SHRT_MAX
+     USHRT_MAX
+
+     LONG_MIN
+     LONG_MAX
+     ULONG_MAX
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVMP3_AUDIO_TYPE_DEFS_H
+#define PVMP3_AUDIO_TYPE_DEFS_H
+
+#include <stdint.h>
+
+typedef int8_t int8;
+typedef uint8_t uint8;
+typedef int16_t int16;
+typedef uint16_t uint16;
+typedef int32_t int32;
+typedef uint32_t uint32;
+typedef int64_t int64;
+typedef uint64_t uint64;
+
+typedef int32_t Int32;
+
+#endif  /* PVMP3_AUDIO_TYPE_DEFS_H */
diff --git a/media/libstagefright/codecs/mp3dec/include/pvmp3decoder_api.h b/media/libstagefright/codecs/mp3dec/include/pvmp3decoder_api.h
new file mode 100644
index 0000000..1568e7c
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/include/pvmp3decoder_api.h
@@ -0,0 +1,259 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3decoder_api.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure tPVMP3DecoderExternal
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3DECODER_API_H
+#define PVMP3DECODER_API_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3_dec_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; 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
+    ----------------------------------------------------------------------------*/
+    typedef enum
+    {
+        flat       = 0,
+        bass_boost = 1,
+        rock       = 2,
+        pop        = 3,
+        jazz       = 4,
+        classical  = 5,
+        talk       = 6,
+        flat_      = 7
+
+    } e_equalization;
+
+
+
+    typedef enum ERROR_CODE
+    {
+        NO_DECODING_ERROR         = 0,
+        UNSUPPORTED_LAYER         = 1,
+        UNSUPPORTED_FREE_BITRATE  = 2,
+        FILE_OPEN_ERROR           = 3,          /* error opening file */
+        CHANNEL_CONFIG_ERROR      = 4,     /* error in channel configuration */
+        SYNTHESIS_WINDOW_ERROR    = 5,   /* error in synthesis window table */
+        READ_FILE_ERROR           = 6,          /* error reading input file */
+        SIDE_INFO_ERROR           = 7,          /* error in side info */
+        HUFFMAN_TABLE_ERROR       = 8,      /* error in Huffman table */
+        COMMAND_LINE_ERROR        = 9,       /* error in command line */
+        MEMORY_ALLOCATION_ERROR   = 10,   /* error allocating memory */
+        NO_ENOUGH_MAIN_DATA_ERROR = 11,
+        SYNCH_LOST_ERROR          = 12,
+        OUTPUT_BUFFER_TOO_SMALL   = 13     /* output buffer can't hold output */
+    } ERROR_CODE;
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    typedef struct
+#ifdef __cplusplus
+                tPVMP3DecoderExternal
+#endif
+    {
+
+        /*
+         * INPUT:
+         * Pointer to the input buffer that contains the encoded bistream data.
+         * The data is filled in such that the first bit transmitted is
+         * the most-significant bit (MSB) of the first array element.
+         * The buffer is accessed in a linear fashion for speed, and the number of
+         * bytes consumed varies frame to frame.
+         * The calling environment can change what is pointed to between calls to
+         * the decode function, library, as long as the inputBufferCurrentLength,
+         * and inputBufferUsedLength are updated too. Also, any remaining bits in
+         * the old buffer must be put at the beginning of the new buffer.
+         */
+        uint8      *pInputBuffer;
+
+        /*
+         * INPUT:
+         * Number of valid bytes in the input buffer, set by the calling
+         * function. After decoding the bitstream the library checks to
+         * see if it when past this value; it would be to prohibitive to
+         * check after every read operation. This value is not modified by
+         * the MP3 library.
+         */
+        int32     inputBufferCurrentLength;
+
+        /*
+         * INPUT/OUTPUT:
+         * Number of elements used by the library, initially set to zero by
+         * the function pvmp3_resetDecoder(), and modified by each
+         * call to pvmp3_framedecoder().
+         */
+        int32     inputBufferUsedLength;
+
+        /*
+         * OUTPUT:
+         * holds the predicted frame size. It used on the test console, for parsing
+         * purposes.
+         */
+        uint32     CurrentFrameLength;
+
+        /*
+         * INPUT:
+         * This variable holds the type of equalization used
+         *
+         *
+         */
+        e_equalization     equalizerType;
+
+
+        /*
+         * INPUT:
+         * The actual size of the buffer.
+         * This variable is not used by the library, but is used by the
+         * console test application. This parameter could be deleted
+         * if this value was passed into these function.
+         */
+        int32     inputBufferMaxLength;
+
+        /*
+         * OUTPUT:
+         * The number of channels decoded from the bitstream.
+         */
+        int16       num_channels;
+
+        /*
+         * OUTPUT:
+         * The number of channels decoded from the bitstream.
+         */
+        int16       version;
+
+        /*
+         * OUTPUT:
+         * The sampling rate decoded from the bitstream, in units of
+         * samples/second.
+         */
+        int32       samplingRate;
+
+        /*
+         * OUTPUT:
+         * This value is the bitrate in units of bits/second. IT
+         * is calculated using the number of bits consumed for the current frame,
+         * and then multiplying by the sampling_rate, divided by points in a frame.
+         * This value can changes frame to frame.
+         */
+        int32       bitRate;
+
+        /*
+         * INPUT/OUTPUT:
+         * In: Inform decoder how much more room is available in the output buffer in int16 samples
+         * Out: Size of the output frame in 16-bit words, This value depends on the mp3 version
+         */
+        int32     outputFrameSize;
+
+        /*
+         * INPUT:
+         * Flag to enable/disable crc error checking
+         */
+        int32     crcEnabled;
+
+        /*
+         * OUTPUT:
+         * This value is used to accumulate bit processed and compute an estimate of the
+         * bitrate. For debugging purposes only, as it will overflow for very long clips
+         */
+        uint32     totalNumberOfBitsUsed;
+
+
+        /*
+         * INPUT: (but what is pointed to is an output)
+         * Pointer to the output buffer to hold the 16-bit PCM audio samples.
+         * If the output is stereo, both left and right channels will be stored
+         * in this one buffer.
+         */
+
+        int16       *pOutputBuffer;
+
+    } tPVMP3DecoderExternal;
+
+uint32 pvmp3_decoderMemRequirements(void);
+
+void pvmp3_InitDecoder(tPVMP3DecoderExternal *pExt,
+                       void  *pMem);
+
+void pvmp3_resetDecoder(void  *pMem);
+
+ERROR_CODE pvmp3_framedecoder(tPVMP3DecoderExternal *pExt,
+                              void              *pMem);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/patent_disclaimer.txt b/media/libstagefright/codecs/mp3dec/patent_disclaimer.txt
new file mode 100644
index 0000000..b4bf11d
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/patent_disclaimer.txt
@@ -0,0 +1,9 @@
+
+THIS IS NOT A GRANT OF PATENT RIGHTS.
+
+Google makes no representation or warranty that the codecs for which
+source code is made available hereunder are unencumbered by
+third-party patents.  Those intending to use this source code in
+hardware or software products are advised that implementations of
+these codecs, including in open source software or shareware, may
+require patent licenses from the relevant patent holders.
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s
new file mode 100644
index 0000000..f83732b
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_16_gcc.s
@@ -0,0 +1,474 @@
+@ ------------------------------------------------------------------
+@ 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.
+@ -------------------------------------------------------------------
+
+@
+@
+@   Filename: pvmp3_dct_16_gcc.s
+@
+@
+@------------------------------------------------------------------------------
+@ REVISION HISTORY
+@
+@
+@ Who:                                   Date: MM/DD/YYYY
+@ Description: 
+@
+@------------------------------------------------------------------------------
+
+.arm
+
+.align 4
+
+.text
+
+.extern  pvmp3_dct_16
+.extern  pvmp3_merge_in_place_N32
+.extern  pvmp3_split
+
+
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_dct_16
+
+pvmp3_dct_16:
+        stmfd    sp!,{r0,r1,r4-r11,lr}
+        ldr      r1,[r0]
+        ldr      r3,[r0,#0x3c]
+        ldr      r12,constant1
+        sub      r2,r1,r3
+        smull    lr,r2,r12,r2
+        sub      sp,sp,#0x1c
+        str      r2,[sp,#0x14]
+        ldr      r2,[r0,#0x1c]
+        ldr      r12,[r0,#0x20]
+        add      r1,r1,r3
+        sub      r3,r2,r12
+        ldr      lr,constant2
+        mov      r3,r3,lsl #3
+        smull    r4,r3,lr,r3
+        ldr      r6,constant5
+        str      r3,[sp]
+        add      r3,r2,r12
+        sub      r2,r1,r3
+        ldr      r12,constant3
+        add      r3,r1,r3
+        smull    lr,r2,r12,r2
+        ldr      r12,[r0,#0x38]
+        ldr      r1,[r0,#4]
+        ldr      lr,constant4
+        sub      r4,r1,r12
+        add      r1,r1,r12
+        ldr      r12,[r0,#0x18]
+        smull    r4,r5,lr,r4
+        ldr      lr,[r0,#0x24]
+        ldr      r10,constant10
+        sub      r4,r12,lr
+        mov      r4,r4,lsl #1
+        smull    r7,r4,r6,r4
+        add      r12,r12,lr
+        add      r7,r1,r12
+        sub      r12,r1,r12
+        ldr      r1,constant6
+        str      r4,[sp,#4]
+        smull    r12,r4,r1,r12
+        ldr      r1,[r0,#8]
+        ldr      r12,[r0,#0x34]
+        ldr      r6,constant7
+        sub      lr,r1,r12
+        smull    r8,lr,r6,lr
+        add      r1,r1,r12
+        str      lr,[sp,#0x10]
+        ldr      r12,[r0,#0x14]
+        ldr      lr,[r0,#0x28]
+        ldr      r8,constant8
+        sub      r6,r12,lr
+        mov      r6,r6,lsl #1
+        smull    r9,r6,r8,r6
+        add      r12,r12,lr
+        ldr      r9,constant9
+        add      r8,r1,r12
+        sub      r12,r1,r12
+        smull    r12,lr,r9,r12
+        ldr      r12,[r0,#0x30]
+        ldr      r1,[r0,#0xc]
+        sub      r9,r1,r12
+        smull    r11,r9,r10,r9
+        add      r12,r1,r12
+        str      r9,[sp,#0xc]
+        ldr      r9,[r0,#0x10]
+        ldr      r10,constant11
+        str      r9,[sp,#0x18]
+        ldr      r1,[r0,#0x2c]
+        sub      r9,r9,r1
+        smull    r11,r9,r10,r9
+        ldr      r10,constant12
+        str      r9,[sp,#8]
+        ldr      r9,[sp,#0x18]
+        ldr      r11,constant14
+        add      r9,r9,r1
+        add      r1,r12,r9
+        sub      r12,r12,r9
+        mov      r12,r12,lsl #2
+        smull    r9,r12,r10,r12
+        ldr      r10,constant13
+        add      r9,r3,r1
+        sub      r1,r3,r1
+        smull    r1,r3,r10,r1
+        sub      r1,r7,r8
+        mov      r1,r1,lsl #1
+        smull    r1,r10,r11,r1
+        add      r1,r7,r8
+        add      r8,r9,r1
+        sub      r7,r9,r1
+        mov      r8,r8,asr #1
+        ldr      r1,constant15
+        str      r8,[r0]
+        smull    r7,r8,r1,r7
+        sub      r7,r3,r10
+        str      r8,[r0,#0x20]
+        mov      r7,r7,lsl #1
+        smull    r8,r7,r1,r7
+        add      r3,r3,r10
+        add      r3,r3,r7
+        str      r3,[r0,#0x10]
+        sub      r3,r2,r12
+        str      r7,[r0,#0x30]
+        add      r2,r2,r12
+        ldr      r7,constant13
+        sub      r12,r4,lr
+        mov      r3,r3,lsl #1
+        smull    r8,r3,r7,r3
+        add      lr,r4,lr
+        sub      r4,r2,lr
+        mov      r12,r12,lsl #2
+        smull    r7,r12,r11,r12
+        add      lr,lr,r2
+        sub      r2,r3,r12
+        mov      r2,r2,lsl #1
+        smull    r7,r2,r1,r2
+        mov      r4,r4,lsl #1
+        add      r12,r12,r2
+        add      r3,r12,r3
+        smull    r7,r4,r1,r4
+        add      r12,r3,lr
+        add      r3,r3,r4
+        str      r3,[r0,#0x18]
+        add      r3,r2,r4
+        str      r2,[r0,#0x38]
+        str      r3,[r0,#0x28]
+        str      r12,[r0,#8]
+        ldr      r2,[sp,#0x14]
+        ldr      r3,[sp,#0]
+        ldr      lr,[sp,#4]
+        sub      r2,r2,r3
+        ldr      r3,constant3
+        mov      r2,r2,lsl #1
+        smull    r12,r2,r3,r2
+        ldr      r3,[sp,#0x14]
+        ldr      r12,[sp,#0]
+        ldr      r4,constant6
+        add      r12,r3,r12
+        ldr      r3,[sp,#4]
+        sub      lr,r5,lr
+        mov      lr,lr,lsl #1
+        add      r3,r5,r3
+        smull    r5,lr,r4,lr
+        ldr      r4,[sp,#0x10]
+        ldr      r5,[sp,#0x10]
+        add      r4,r4,r6
+        sub      r5,r5,r6
+        ldr      r6,constant9
+        mov      r5,r5,lsl #1
+        smull    r7,r5,r6,r5
+        ldr      r6,[sp,#8]
+        ldr      r9,[sp,#0xc]
+        ldr      r10,constant12
+        sub      r6,r9,r6
+        mov      r6,r6,lsl #3
+        smull    r7,r6,r10,r6
+        ldr      r8,[sp,#0x20]
+        ldr      r7,[sp,#8]
+        cmp      r8,#0
+        add      r7,r9,r7
+
+        bne      no_flag_proc
+        rsb      r12,r12,#0
+        rsb      r2,r2,#0
+        rsb      r3,r3,#0
+        rsb      lr,lr,#0
+        rsb      r4,r4,#0
+        rsb      r5,r5,#0
+        rsb      r7,r7,#0
+        rsb      r6,r6,#0
+no_flag_proc:
+
+        sub      r8,r2,r6
+        add      r2,r6,r2
+        sub      r6,r12,r7
+        ldr      r9,constant13
+        add      r12,r12,r7
+        sub      r7,r3,r4
+        mov      r6,r6,lsl #1
+        mov      r8,r8,lsl #1
+        smull    r10,r8,r9,r8
+        add      r3,r3,r4
+        smull    r10,r6,r9,r6
+        sub      r4,lr,r5
+        mov      r7,r7,lsl #2
+        smull    r9,r7,r11,r7
+        add      lr,lr,r5
+        sub      r5,r6,r7
+        add      r6,r6,r7
+        sub      r7,r12,r3
+        add      r3,r12,r3
+        sub      r12,r2,lr
+        mov      r4,r4,lsl #2
+        smull    r9,r4,r11,r4
+        add      lr,r2,lr
+        sub      r2,r8,r4
+        mov      r2,r2,lsl #1
+        mov      r5,r5,lsl #1
+        mov      r12,r12,lsl #1
+        mov      r7,r7,lsl #1
+        smull    r9,r5,r1,r5
+        smull    r9,r2,r1,r2
+        add      r6,r6,r5
+        smull    r9,r7,r1,r7
+        smull    r9,r12,r1,r12
+        add      r1,r4,r2
+        add      r1,r1,r8
+        add      lr,lr,r1
+        add      r3,r3,lr
+        str      r3,[r0,#4]
+        add      r3,r6,lr
+        str      r3,[r0,#0xc]
+        add      r1,r1,r12
+        add      r3,r6,r1
+        add      r1,r7,r1
+        str      r1,[r0,#0x1c]
+        str      r3,[r0,#0x14]
+        add      r1,r12,r2
+        add      r3,r7,r1
+        add      r1,r5,r1
+        str      r1,[r0,#0x2c]
+        str      r3,[r0,#0x24]!
+        add      r1,r5,r2
+        str      r1,[r0,#0x10]
+        str      r2,[r0,#0x18]
+        add      sp,sp,#0x24
+        ldmfd    sp!,{r4-r11,pc}
+
+
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_merge_in_place_N32
+
+
+
+pvmp3_merge_in_place_N32:
+        stmfd    sp!,{r4,lr}
+        ldr      r1,[r0,#0x1c]
+        ldr      r2,[r0,#0x38]
+        str      r1,[r0,#0x38]
+        ldr      r1,[r0,#0x18]
+        ldr      r3,[r0,#0x30]
+        str      r1,[r0,#0x30]
+        ldr      r12,[r0,#0x14]
+        ldr      r1,[r0,#0x28]
+        str      r12,[r0,#0x28]
+        ldr      r12,[r0,#0x10]
+        ldr      lr,[r0,#0x20]
+        str      r12,[r0,#0x20]
+        ldr      r12,[r0,#0xc]
+        str      r12,[r0,#0x18]
+        ldr      r12,[r0,#8]
+        str      r12,[r0,#0x10]
+        ldr      r12,[r0,#4]
+        str      r12,[r0,#8]
+        ldr      r4,[r0,#0x40]
+        ldr      r12,[r0,#0x44]
+        add      r4,r4,r12
+        str      r4,[r0,#4]
+        str      lr,[r0,#0x40]
+        ldr      lr,[r0,#0x48]
+        add      r12,lr,r12
+        str      r12,[r0,#0xc]
+        ldr      r12,[r0,#0x4c]
+        add      lr,r12,lr
+        str      lr,[r0,#0x14]
+        ldr      lr,[r0,#0x24]
+        str      lr,[r0,#0x48]
+        ldr      lr,[r0,#0x50]
+        add      r12,lr,r12
+        str      r12,[r0,#0x1c]
+        ldr      r12,[r0,#0x54]
+        str      r1,[r0,#0x50]
+        add      lr,r12,lr
+        str      lr,[r0,#0x24]
+        ldr      r1,[r0,#0x58]
+        ldr      r4,[r0,#0x2c]
+        ldr      lr,[r0,#0x34]
+        add      r12,r1,r12
+        str      r12,[r0,#0x2c]
+        ldr      r12,[r0,#0x5c]
+        add      r1,r12,r1
+        str      r1,[r0,#0x34]
+        str      r4,[r0,#0x58]
+        ldr      r1,[r0,#0x60]
+        ldr      r4,[r0,#0x3c]
+        add      r12,r1,r12
+        str      r12,[r0,#0x3c]
+        ldr      r12,[r0,#0x64]
+        add      r1,r12,r1
+        str      r1,[r0,#0x44]
+        ldr      r1,[r0,#0x68]
+        add      r12,r1,r12
+        str      r12,[r0,#0x4c]
+        ldr      r12,[r0,#0x6c]
+        add      r1,r12,r1
+        str      r1,[r0,#0x54]
+        ldr      r1,[r0,#0x70]
+        str      r3,[r0,#0x60]
+        add      r12,r1,r12
+        str      r12,[r0,#0x5c]
+        ldr      r3,[r0,#0x74]
+        add      r1,r3,r1
+        str      r1,[r0,#0x64]
+        str      lr,[r0,#0x68]
+        ldr      r1,[r0,#0x78]
+        str      r2,[r0,#0x70]
+        add      r3,r1,r3
+        str      r3,[r0,#0x6c]
+        ldr      r2,[r0,#0x7c]
+        add      r1,r1,r2
+        str      r1,[r0,#0x74]
+        str      r4,[r0,#0x78]
+        ldmfd    sp!,{r4,pc}
+
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_split
+
+
+pvmp3_split:
+        stmfd    sp!,{r4,r5,lr}
+        ldr      r2,constant16
+        sub      r1,r0,#4
+        mov      r3,#3
+loop1:
+        ldr      r12,[r0]
+        ldr      lr,[r1]
+        ldr      r4,[r2],#-4
+        add      r5,lr,r12
+        sub      r12,lr,r12
+        smull    r12,lr,r4,r12
+        str      r5,[r1],#-4
+        mov      r12,r12,lsr #27
+        add      r12,r12,lr,lsl #5
+        str      r12,[r0],#4
+        ldr      r12,[r0]
+        ldr      lr,[r1]
+        ldr      r4,[r2],#-4
+        add      r5,lr,r12
+        sub      r12,lr,r12
+        smull    r12,lr,r4,r12
+        str      r5,[r1],#-4
+        mov      r12,r12,lsr #27
+        add      r12,r12,lr,lsl #5
+        str      r12,[r0],#4
+        subs     r3,r3,#1
+        bne      loop1
+        mov      r3,#5
+loop2:
+        ldr      r12,[r0]
+        ldr      lr,[r1]
+        ldr      r4,[r2],#-4
+        add      r5,lr,r12
+        sub      r12,lr,r12
+        mov      r12,r12,lsl #1
+        smull    lr,r12,r4,r12
+        str      r5,[r1],#-4
+        str      r12,[r0],#4
+        ldr      r12,[r0]
+        ldr      lr,[r1]
+        ldr      r4,[r2],#-4
+        add      r5,lr,r12
+        sub      r12,lr,r12
+        mov      r12,r12,lsl #1
+        smull    lr,r12,r4,r12
+        str      r5,[r1],#-4
+        str      r12,[r0],#4
+        subs     r3,r3,#1
+        bne      loop2
+        ldmfd    sp!,{r4,r5,pc}
+constant1:
+        .word      0x404f4680
+constant2:
+        .word      0x519e4e00
+constant3:
+        .word      0x4140fb80
+constant4:
+        .word      0x42e13c00
+constant5:
+        .word      0x6e3c9300
+constant6:
+        .word      0x4cf8de80
+constant7:
+        .word      0x48919f80
+constant8:
+        .word      0x43e22480
+constant9:
+        .word      0x73326b80
+constant10:
+        .word      0x52cb0e80
+constant11:
+        .word      0x64e24000
+constant12:
+        .word      0x52036780
+constant13:
+        .word      0x4545ea00
+constant14:
+        .word      0x539eba80
+constant15:
+        .word      0x5a827980
+constant16:
+        .word      CosTable_dct32 + 60
+
+
+
+CosTable_dct32:
+        .word      0x4013c280
+        .word      0x40b34580
+        .word      0x41fa2d80
+        .word      0x43f93400
+        .word      0x46cc1c00
+        .word      0x4a9d9d00
+        .word      0x4fae3700
+        .word      0x56601e80
+        .word      0x5f4cf700
+        .word      0x6b6fcf00
+        .word      0x07c7d1d8
+        .word      0x095b0350
+        .word      0x0bdf91b0
+        .word      0x107655e0
+        .word      0x1b42c840
+        .word      0x51852300
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_arm.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_arm.s
new file mode 100644
index 0000000..3a6dd4f
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_arm.s
@@ -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.
+; -------------------------------------------------------------------
+
+;
+;
+;   Filename: pvmp3_dct_9.s
+;
+;------------------------------------------------------------------------------
+; REVISION HISTORY
+;
+;
+; Who:                                   Date: MM/DD/YYYY
+; Description: 
+;
+;------------------------------------------------------------------------------
+
+  AREA  |.drectve|, DRECTVE
+
+    DCB "-defaultlib:coredll.lib "
+    DCB "-defaultlib:corelibc.lib "
+
+  IMPORT pvmp3_mdct_18 ; pvmp3_mdct_18.cpp
+
+;------------------------------------------------------------------------------
+
+  AREA  |.rdata|, DATA, READONLY
+  % 4
+
+
+;------------------------------------------------------------------------------
+
+  AREA  |.text|, CODE, READONLY
+
+
+;------------------------------------------------------------------------------
+
+ EXPORT |pvmp3_dct_9|
+
+|pvmp3_dct_9| PROC
+        stmfd    sp!,{r4-r10,lr}
+        ldr      r2, [r0, #0x20]
+        ldr      r3, [r0]
+        ldr      r12,[r0, #4]
+        add      r1,r2,r3
+        sub      lr,r2,r3
+        ldr      r3,[r0, #0x1c]
+        ldr      r4,[r0, #0x18]
+        add      r2,r3,r12
+        ldr      r5,[r0,#8]
+        sub      r3,r3,r12
+        add      r12,r4,r5
+        sub      r4,r4,r5
+        ldr      r5,[r0, #0x14]
+        ldr      r7,[r0, #0xc]
+        ldr      r9,[r0, #0x10]
+        add      r6,r5,r7
+        sub      r5,r5,r7
+        add      r7,r1,r12
+        add      r8,r9,r2
+        add      r7,r7,r6
+        add      r10,r7,r8
+        rsb      r7,r8,r7,asr #1
+        str      r7,[r0, #0x18]
+        rsb      r2,r9,r2,asr #1
+        str      r10,[r0]
+        ldr      r11,|cos_2pi_9|
+        rsb      r7,r2,#0
+
+        mov      r9,r1,lsl #1
+		mov      r1,r9			;;;;;;  !!!!!!
+        mov      r8,r7
+
+;    vec[4]  = fxp_mac32_Q32( vec[4], tmp0<<1, cos_2pi_9); 
+
+        smlal    r1,r8,r11,r9
+        ldr      r10,|cos_4pi_9|
+        ldr      r11,|cos_pi_9|
+
+;    vec[8]  = fxp_mac32_Q32( vec[8], tmp0<<1, cos_4pi_9);
+
+        smlal    r1,r7,r10,r9
+
+
+
+;    vec[2]  = fxp_mac32_Q32( vec[2], tmp0<<1, cos_pi_9);
+
+        smlal    r9,r2,r11,r9
+        mov      r1,r12,lsl #1
+        rsb      r9,r10,#0
+        ldr      r11,|cos_5pi_9|
+
+        smlal    r12,r2,r9,r1
+
+
+
+;    vec[2]  = fxp_mac32_Q32( vec[2], tmp2<<1, cos_5pi_9);
+
+        ldr      r9,|cos_2pi_9|
+        mov      r12,r1			;;;;;;  !!!!!!
+        smlal    r12,r8,r11,r1
+
+
+;    vec[8]  = fxp_mac32_Q32( vec[8], tmp2<<1, cos_2pi_9);
+
+        smlal    r1,r7,r9,r1
+        mov      r1,r6,lsl #1
+        smlal    r12,r7,r11,r1
+        and      r6,r10,r11,asr #14
+        smlal    r12,r8,r6,r1
+        ldr      r10,|cos_11pi_18|
+        add      r12,r11,r6
+        smlal    r1,r2,r12,r1
+        ldr      r9,|cos_8pi_9|
+        str      r2,[r0,#8]
+        mov      r1,r5,lsl #1
+
+;    vec[8]  = fxp_mac32_Q32( vec[8], tmp3<<1, cos_8pi_9);
+
+        smull    r2,r6,r9,r1
+        str      r7,[r0,#0x20]
+        mov      r2,r4,lsl #1
+        ldr      r7,|cos_13pi_18|
+        smlal    r12,r6,r10,r2
+
+        mov      r3,r3,lsl #1
+
+;    vec[5]  = fxp_mac32_Q32( vec[5], tmp8<<1, cos_13pi_18);
+
+        smlal    r12,r6,r7,r3
+        add      r4,r5,r4
+        mov      r12,lr,lsl #1
+        sub      lr,r4,lr
+        ldr      r7,|cos_17pi_18|
+        str      r8,[r0, #0x10]
+        ldr      r4,|cos_pi_6|
+
+        mov      lr,lr,lsl #1
+
+;    vec[1]  = fxp_mac32_Q32( vec[1], tmp8<<1, cos_17pi_18);
+
+        smlal    r8,r6,r7,r12
+
+;    vec[3]  = fxp_mul32_Q32((tmp5 + tmp6  - tmp8)<<1, cos_pi_6);
+
+        smull    r5,lr,r4,lr
+        str      r6,[r0, #4]
+        str      lr,[r0, #0xc]
+
+
+;    vec[5]  = fxp_mul32_Q32(tmp5<<1, cos_17pi_18);
+        smull    r5,lr,r7,r1
+        rsb      r6,r9,#0
+;    vec[5]  = fxp_mac32_Q32( vec[5], tmp6<<1,  cos_7pi_18);
+        smlal    r5,lr,r6,r2
+;    vec[5]  = fxp_mac32_Q32( vec[5], tmp7<<1,    cos_pi_6);
+        smlal    r5,lr,r4,r3
+;    vec[5]  = fxp_mac32_Q32( vec[5], tmp8<<1, cos_13pi_18);
+        smlal    r5,lr,r10,r12
+        str      lr,[r0, #0x14]
+        rsb      lr,r10,#0
+
+;    vec[7]  = fxp_mul32_Q32(tmp5<<1, cos_5pi_18);
+        smull    r5,r1,lr,r1
+;    vec[7]  = fxp_mac32_Q32( vec[7], tmp6<<1, cos_17pi_18);
+        smlal    r2,r1,r7,r2
+;    vec[7]  = fxp_mac32_Q32( vec[7], tmp7<<1,    cos_pi_6);
+        smlal    r3,r1,r4,r3
+;    vec[7]  = fxp_mac32_Q32( vec[7], tmp8<<1, cos_11pi_18);
+        smlal    r12,r1,r9,r12
+        str      r1,[r0, #0x1c]
+        ldmfd    sp!,{r4-r10,pc}
+|cos_2pi_9|
+        DCD      0x620dbe80
+|cos_4pi_9|
+        DCD      0x163a1a80
+|cos_pi_9|
+        DCD      0x7847d900
+|cos_5pi_9|
+        DCD      0x87b82700
+|cos_8pi_9|
+        DCD      0xd438af00
+|cos_11pi_18|
+        DCD      0xadb92280
+|cos_13pi_18|
+        DCD      0x91261480
+|cos_17pi_18|
+        DCD      0x81f1d200
+|cos_pi_6|
+        DCD      0x6ed9eb80
+        ENDP
+
+
+
+
+
+        END
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s
new file mode 100644
index 0000000..618c50e
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_dct_9_gcc.s
@@ -0,0 +1,193 @@
+@ ------------------------------------------------------------------
+@ 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.
+@ -------------------------------------------------------------------
+
+@
+@
+@   Filename: pvmp3_dct_9_gcc.s
+@
+@------------------------------------------------------------------------------
+@ REVISION HISTORY
+@
+@
+@ Who:                                   Date: MM/DD/YYYY
+@ Description: 
+@
+@------------------------------------------------------------------------------
+
+.arm
+
+.align 4
+
+.text
+
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_dct_9
+
+pvmp3_dct_9:
+        stmfd    sp!,{r4-r11,lr}
+        ldr      r2, [r0, #0x20]
+        ldr      r3, [r0, #0]
+        ldr      r12,[r0, #4]
+        add      r1,r2,r3
+        sub      lr,r2,r3
+        ldr      r3,[r0, #0x1c]
+        ldr      r4,[r0, #0x18]
+        add      r2,r3,r12
+        ldr      r5,[r0,#8]
+        sub      r3,r3,r12
+        add      r12,r4,r5
+        sub      r4,r4,r5
+        ldr      r5,[r0, #0x14]
+        ldr      r7,[r0, #0xc]
+        ldr      r9,[r0, #0x10]
+        add      r6,r5,r7
+        sub      r5,r5,r7
+        add      r7,r1,r12
+        add      r8,r9,r2
+        add      r7,r7,r6
+        add      r10,r7,r8
+        rsb      r7,r8,r7,asr #1
+        str      r7,[r0, #0x18]
+        rsb      r2,r9,r2,asr #1
+        str      r10,[r0,#0]
+        ldr      r11,cos_2pi_9
+        rsb      r7,r2,#0
+
+        ldr      r10,cos_4pi_9
+        mov      r9,r1,lsl #1
+        mov      r8,r7
+
+@    vec[4]  = fxp_mac32_Q32( vec[4], tmp0<<1, cos_2pi_9)@ 
+
+        smlal    r1,r8,r11,r9
+        ldr      r11,cos_pi_9
+		mov      r1,r9			@@@@@@  !!!!!!
+
+@    vec[8]  = fxp_mac32_Q32( vec[8], tmp0<<1, cos_4pi_9)@
+
+        smlal    r1,r7,r10,r9
+
+        mov      r1,r12,lsl #1
+
+
+@    vec[2]  = fxp_mac32_Q32( vec[2], tmp0<<1, cos_pi_9)@
+
+        smlal    r9,r2,r11,r9
+        rsb      r9,r10,#0
+        ldr      r11,cos_5pi_9
+
+        smlal    r12,r2,r9,r1
+
+
+
+@    vec[2]  = fxp_mac32_Q32( vec[2], tmp2<<1, cos_5pi_9)@
+
+        ldr      r9,cos_2pi_9
+        mov      r12,r1			@@@@@@  !!!!!!
+        smlal    r12,r8,r11,r1
+
+
+@    vec[8]  = fxp_mac32_Q32( vec[8], tmp2<<1, cos_2pi_9)@
+
+        smlal    r1,r7,r9,r1
+        mov      r1,r6,lsl #1
+        smlal    r12,r7,r11,r1
+        and      r6,r10,r11,asr #14
+        smlal    r12,r8,r6,r1
+        ldr      r10,cos_11pi_18
+        add      r12,r11,r6
+        smlal    r1,r2,r12,r1
+        ldr      r9,cos_8pi_9
+        str      r2,[r0,#8]
+        mov      r1,r5,lsl #1
+
+@    vec[8]  = fxp_mac32_Q32( vec[8], tmp3<<1, cos_8pi_9)@
+
+        smull    r2,r6,r9,r1
+        str      r7,[r0,#0x20]
+        mov      r2,r4,lsl #1
+        ldr      r7,cos_13pi_18
+        smlal    r12,r6,r10,r2
+
+        mov      r3,r3,lsl #1
+
+@    vec[5]  = fxp_mac32_Q32( vec[5], tmp8<<1, cos_13pi_18)@
+
+        smlal    r12,r6,r7,r3
+        add      r4,r5,r4
+        mov      r12,lr,lsl #1
+        sub      lr,r4,lr
+        ldr      r7,cos_17pi_18
+        str      r8,[r0, #0x10]
+        ldr      r4,cos_pi_6
+
+        mov      lr,lr,lsl #1
+
+@    vec[1]  = fxp_mac32_Q32( vec[1], tmp8<<1, cos_17pi_18)@
+
+        smlal    r8,r6,r7,r12
+
+@    vec[3]  = fxp_mul32_Q32((tmp5 + tmp6  - tmp8)<<1, cos_pi_6)@
+
+        smull    r5,lr,r4,lr
+        str      r6,[r0, #4]
+        str      lr,[r0, #0xc]
+
+
+@    vec[5]  = fxp_mul32_Q32(tmp5<<1, cos_17pi_18)@
+        smull    r5,lr,r7,r1
+        rsb      r6,r9,#0
+@    vec[5]  = fxp_mac32_Q32( vec[5], tmp6<<1,  cos_7pi_18)@
+        smlal    r5,lr,r6,r2
+@    vec[5]  = fxp_mac32_Q32( vec[5], tmp7<<1,    cos_pi_6)@
+        smlal    r5,lr,r4,r3
+@    vec[5]  = fxp_mac32_Q32( vec[5], tmp8<<1, cos_13pi_18)@
+        smlal    r5,lr,r10,r12
+        str      lr,[r0, #0x14]
+        rsb      lr,r10,#0
+
+@    vec[7]  = fxp_mul32_Q32(tmp5<<1, cos_5pi_18)@
+        smull    r5,r1,lr,r1
+@    vec[7]  = fxp_mac32_Q32( vec[7], tmp6<<1, cos_17pi_18)@
+        smlal    r2,r1,r7,r2
+@    vec[7]  = fxp_mac32_Q32( vec[7], tmp7<<1,    cos_pi_6)@
+        smlal    r3,r1,r4,r3
+@    vec[7]  = fxp_mac32_Q32( vec[7], tmp8<<1, cos_11pi_18)@
+        smlal    r12,r1,r9,r12
+        str      r1,[r0, #0x1c]
+        ldmfd    sp!,{r4-r11,pc}
+cos_2pi_9:
+        .word      0x620dbe80
+cos_4pi_9:
+        .word      0x163a1a80
+cos_pi_9:
+        .word      0x7847d900
+cos_5pi_9:
+        .word      0x87b82700
+cos_8pi_9:
+        .word      0xd438af00
+cos_11pi_18:
+        .word      0xadb92280
+cos_13pi_18:
+        .word      0x91261480
+cos_17pi_18:
+        .word      0x81f1d200
+cos_pi_6:
+        .word      0x6ed9eb80
+
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_arm.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_arm.s
new file mode 100644
index 0000000..9401d8c
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_arm.s
@@ -0,0 +1,369 @@
+; ------------------------------------------------------------------
+; 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.
+; -------------------------------------------------------------------
+
+;
+;
+;   Filename: pvmp3_dct_18.s
+;
+;------------------------------------------------------------------------------
+; REVISION HISTORY
+;
+;
+; Who:                                   Date: MM/DD/YYYY
+; Description: 
+;
+;------------------------------------------------------------------------------
+
+        EXPORT pvmp3_mdct_18
+
+        IMPORT ||Lib$$Request$$armlib|| [WEAK]
+        IMPORT ||Lib$$Request$$cpplib|| [WEAK]
+        IMPORT pvmp3_dct_9
+
+
+;------------------------------------------------------------------------------
+
+ AREA |.text|, CODE, READONLY, ALIGN=2
+
+
+;------------------------------------------------------------------------------
+
+|pvmp3_mdct_18| PROC
+        stmfd    sp!,{r4-r10,lr}
+        mov      r7,r2
+        ldr      r2,table
+        mov      r6,r1
+        add      r3,r2,#0x24
+        add      r12,r3,#0x44
+        add      r1,r0,#0x44
+        mov      r5,r0
+
+;    for ( i=9; i!=0; i--)
+;    {
+
+        mov      r4,#9
+Loop_1
+
+;       tmp  = *(pt_vec);
+;		tmp1 = *(pt_vec_o);
+
+        ldr      lr,[r0]		;; tmp  == lr
+        ldr      r8,[r3],#4		;; tmp1 == r8
+
+;        tmp  = fxp_mul32_Q32( tmp<<1,  *(pt_cos++  ));
+;        tmp1 = fxp_mul32_Q27( tmp1, *(pt_cos_x--));
+
+        mov      lr,lr,lsl #1
+        smull    r10,lr,r8,lr
+        ldr      r8,[r12],#-4
+        ldr      r9,[r1]
+        subs     r4,r4,#1
+        smull    r9,r10,r8,r9
+        mov      r8,r9,lsr #27
+        add      r8,r8,r10,lsl #5
+
+;        *(pt_vec++)   =   tmp + tmp1 ;
+;        *(pt_vec_o--) = fxp_mul32_Q28( (tmp - tmp1), *(pt_cos_split++));
+
+        add      r9,lr,r8
+        sub      r8,lr,r8
+        ldr      lr,[r2],#4
+        str      r9,[r0],#4
+        smull    r8,r9,lr,r8
+        mov      lr,r8,lsr #28
+        add      lr,lr,r9,lsl #4
+        str      lr,[r1],#-4
+        bne      Loop_1
+
+;		}
+
+        mov      r0,r5			;; r0 = vec
+        bl       pvmp3_dct_9
+        add      r0,r5,#0x24	;; r0 = &vec[9]
+        bl       pvmp3_dct_9
+
+        ldr      r0,[r5,#0x20]
+        ldr      r2,[r5,#0x40]
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x1c]
+        ldr      r3,[r5,#0x38]
+        str      r0,[r5,#0x38]
+        ldr      r1,[r5,#0x18]
+        ldr      r0,[r5,#0x30]
+        str      r1,[r5,#0x30]
+        ldr      r12,[r5,#0x14]
+        ldr      r1,[r5,#0x28]
+        str      r12,[r5,#0x28]
+        ldr      r12,[r5,#0x10]
+        str      r12,[r5,#0x20]
+        ldr      r12,[r5,#0xc]
+        str      r12,[r5,#0x18]
+        ldr      r12,[r5,#8]
+        str      r12,[r5,#0x10]
+        ldr      r12,[r5,#4]
+        str      r12,[r5,#8]
+        ldr      r12,[r5,#0x24]
+        sub      r12,r12,r1
+        str      r12,[r5,#4]
+        ldr      r12,[r5,#0x2c]
+        sub      r1,r12,r1
+        str      r1,[r5,#0xc]
+        sub      r1,r12,r0
+        str      r1,[r5,#0x14]
+        ldr      r1,[r5,#0x34]
+        sub      r0,r1,r0
+        str      r0,[r5,#0x1c]
+        sub      r0,r1,r3
+        str      r0,[r5,#0x24]
+        ldr      r1,[r5,#0x3c]
+        sub      r3,r1,r3
+        sub      r1,r1,r2
+        str      r1,[r5,#0x34]
+        str      r3,[r5,#0x2c]
+        ldr      r1,[r5,#0x44]
+        sub      r1,r1,r2
+        str      r1,[r5,#0x3c]
+        ldr      r12,[r5,#0]
+
+Loop_2
+        add      r1,r5,r4,lsl #2
+        ldr      r2,[r1,#0x28]
+        ldr      r3,[r6,r4,lsl #2]
+        add      r0,r0,r2
+        str      r0,[r1,#0x28]
+        ldr      lr,[r7,r4,lsl #2]
+        ldr      r1,[r1,#4]
+        smlal    r0,r3,lr,r0
+        mov      r0,r2
+        add      r2,r12,r1
+        rsb      r2,r2,#0
+        str      r3,[r5,r4,lsl #2]
+        str      r2,[r6,r4,lsl #2]
+        add      r4,r4,#1
+        cmp      r4,#6
+        mov      r12,r1
+
+        blt      Loop_2
+
+        ldr      r1,[r5,#0x40]
+        ldr      r2,[r6,#0x18]
+        add      r3,r0,r1
+        str      r3,[r5,#0x40]
+        ldr      lr,[r7,r4,lsl #2]
+        mov      r3,r3,lsl #1
+        ldr      r0,[r5,#0x1c]
+        smlal    r3,r2,lr,r3
+        add      r3,r12,r0
+        str      r2,[r5,#0x18]
+        ldr      r2,[r6,#0x1c]
+        rsb      r3,r3,#0
+        str      r3,[r6,#0x18]
+        ldr      r3,[r5,#0x20]
+        add      r0,r3,r0
+        rsb      r0,r0,#0
+        str      r0,[r6,#0x1c]
+        ldr      r3,[r5,#0x44]
+        ldr      r0,[r6,#0x20]
+        add      r3,r3,r1
+        mov      r1,r2
+        ldr      r10,[r7,#0x1c]
+        mov      r2,r3,lsl #1
+        smlal    r12,r1,r10,r2
+        str      r1,[r5,#0x1c]
+        ldr      r1,[r5,#0x20]
+        ldr      r3,[r5,#0x24]
+        add      r1,r1,r3
+        rsb      r1,r1,#0
+        str      r1,[r6,#0x20]
+        ldr      r1,[r5,#0x44]
+        ldr      r3,[r7,#0x20]
+        mov      r1,r1,lsl #1
+        smlal    r12,r0,r3,r1
+        ldr      lr,[r7,#0x24]
+        ldr      r3,[r6,#0x24]
+        str      r0,[r5,#0x20]
+        smlal    r1,r3,lr,r1
+        ldr      r0,[r6,#0x40]
+        ldr      r12,[r6,#0x44]
+        str      r3,[r5,#0x24]
+        ldr      r1,[r5,#0x28]
+        ldr      r3,[r7,#0x44]
+        mov      r1,r1,lsl #1
+        smlal    r1,r12,r3,r1
+        ldr      r1,[r5,#0x40]
+        str      r12,[r5,#0x44]
+        rsb      r8,r1,#0
+        str      r8,[r5,#0x28]
+        ldr      r1,[r5,#0x2c]
+        ldr      r3,[r7,#0x40]
+        mov      r1,r1,lsl #1
+        smlal    r1,r0,r3,r1
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x3c]
+        ldr      r1,[r6,#0x38]
+        ldr      r3,[r6,#0x3c]
+        rsb      r9,r0,#0
+        str      r9,[r5,#0x2c]
+        ldr      r0,[r5,#0x30]
+        ldr      r12,[r7,#0x3c]
+        mov      r0,r0,lsl #1
+        smlal    r0,r3,r12,r0
+        str      r3,[r5,#0x3c]
+        ldr      r0,[r5,#0x38]
+        rsb      r0,r0,#0
+        str      r0,[r5,#0x30]
+        ldr      r3,[r5,#0x34]
+        ldr      r12,[r7,#0x38]
+        mov      r3,r3,lsl #1
+        smlal    r3,r1,r12,r3
+        mov      r0,r0,lsl #1
+        str      r1,[r5,#0x38]
+        ldr      r4,[r7,#0x34]
+        ldr      r1,[r6,#0x34]
+        ldr      r3,[r6,#0x30]
+        smlal    r0,r1,r4,r0
+        ldr      r12,[r6,#0x2c]
+        ldr      lr,[r6,#0x28]
+        str      r1,[r5,#0x34]
+        ldr      r1,[r7,#0x30]
+        mov      r0,r9,lsl #1
+        smlal    r0,r3,r1,r0
+        mov      r0,r8,lsl #1
+        ldr      r1,[r7,#0x2c]
+        str      r3,[r5,#0x30]
+        smlal    r0,r12,r1,r0
+        ldr      r0,[r7,#0x28]
+        str      r12,[r5,#0x2c]
+        smlal    r2,lr,r0,r2
+        str      lr,[r5,#0x28]
+        ldr      r1,[r6,#4]
+        ldr      r12,[r7,#0x48]
+        mov      r2,r1,lsl #1
+        ldr      r1,[r6,#0x20]
+        ldr      r0,[r6]
+        mov      r1,r1,lsl #1
+        smull    r4,lr,r12,r1
+        ldr      r3,[r6,#0x1c]
+        str      lr,[r6]
+        ldr      r12,[r7,#0x4c]
+        mov      r3,r3,lsl #1
+        smull    r4,lr,r12,r3
+        mov      r0,r0,lsl #1
+        ldr      r12,[r7,#0x64]
+        str      lr,[r6,#4]
+        smull    r4,lr,r12,r2
+        ldr      r12,[r7,#0x68]
+        str      lr,[r6,#0x1c]
+        smull    r4,lr,r12,r0
+        ldr      r12,[r7,#0x6c]
+        str      lr,[r6,#0x20]
+        smull    lr,r0,r12,r0
+        ldr      r12,[r7,#0x70]
+        str      r0,[r6,#0x24]
+        smull    r0,r2,r12,r2
+        ldr      r0,[r7,#0x88]
+        str      r2,[r6,#0x28]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x8c]
+        str      r2,[r6,#0x40]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x44]
+        ldr      r0,[r6,#0x18]
+        ldr      lr,[r7,#0x50]
+        mov      r1,r0,lsl #1
+        ldr      r0,[r6,#0x14]
+        smull    r5,r4,lr,r1
+        ldr      r12,[r6,#0x10]
+        mov      r3,r0,lsl #1
+        ldr      r0,[r6,#0xc]
+        mov      r12,r12,lsl #1
+        mov      r2,r0,lsl #1
+        ldr      r0,[r6,#8]
+        str      r4,[r6,#8]
+        ldr      lr,[r7,#0x54]
+        mov      r0,r0,lsl #1
+        smull    r5,r4,lr,r3
+        ldr      lr,[r7,#0x58]
+        str      r4,[r6,#0xc]
+        smull    r5,r4,lr,r12
+        ldr      lr,[r7,#0x5c]
+        str      r4,[r6,#0x10]
+        smull    r5,r4,lr,r2
+        ldr      lr,[r7,#0x60]
+        str      r4,[r6,#0x14]
+        smull    r5,r4,lr,r0
+        ldr      lr,[r7,#0x74]
+        str      r4,[r6,#0x18]
+        smull    r4,r0,lr,r0
+        ldr      lr,[r7,#0x78]
+        str      r0,[r6,#0x2c]
+        smull    r0,r2,lr,r2
+        ldr      r0,[r7,#0x7c]
+        str      r2,[r6,#0x30]
+        smull    r12,r2,r0,r12
+        ldr      r0,[r7,#0x80]
+        str      r2,[r6,#0x34]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x84]
+        str      r2,[r6,#0x38]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x3c]
+        ldmfd    sp!,{r4-r10,pc}
+table
+        DCD      ||.constdata$1||
+        ENDP
+
+;------------------------------------------------------------------------------
+
+ AREA |.constdata|, DATA, READONLY, ALIGN=2
+
+;------------------------------------------------------------------------------
+
+||.constdata$1||
+cosTerms_dct18
+        DCD      0x0807d2b0
+        DCD      0x08483ee0
+        DCD      0x08d3b7d0
+        DCD      0x09c42570
+        DCD      0x0b504f30
+        DCD      0x0df29440
+        DCD      0x12edfb20
+        DCD      0x1ee8dd40
+        DCD      0x5bca2a00
+cosTerms_1_ov_cos_phi
+        DCD      0x400f9c00
+        DCD      0x408d6080
+        DCD      0x418dcb80
+        DCD      0x431b1a00
+        DCD      0x4545ea00
+        DCD      0x48270680
+        DCD      0x4be25480
+        DCD      0x50ab9480
+        DCD      0x56ce4d80
+        DCD      0x05ebb630
+        DCD      0x06921a98
+        DCD      0x0771d3a8
+        DCD      0x08a9a830
+        DCD      0x0a73d750
+        DCD      0x0d4d5260
+        DCD      0x127b1ca0
+        DCD      0x1ea52b40
+        DCD      0x5bb3cc80
+
+
+
+        END
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s
new file mode 100644
index 0000000..96230c5
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_gcc.s
@@ -0,0 +1,359 @@
+@ ------------------------------------------------------------------
+@ 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.
+@ -------------------------------------------------------------------
+
+@
+@
+@   Filename: pvmp3_dct_18_gcc.s
+@
+@------------------------------------------------------------------------------
+@ REVISION HISTORY
+@
+@
+@ Who:                                   Date: MM/DD/YYYY
+@ Description: 
+@
+@------------------------------------------------------------------------------
+
+.arm
+
+.align 4
+
+.text
+
+.extern  pvmp3_dct_9
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_mdct_18
+
+pvmp3_mdct_18:
+        stmfd    sp!,{r4-r11,lr}
+        mov      r7,r2
+        ldr      r2,table
+        mov      r6,r1
+        add      r3,r2,#0x24
+        add      r12,r3,#0x44
+        add      r1,r0,#0x44
+        mov      r5,r0
+
+@    for ( i=9@ i!=0@ i--)
+@    {
+
+        mov      r4,#9
+Loop_1:
+
+@       tmp  = *(pt_vec)
+@		tmp1 = *(pt_vec_o)
+
+        ldr      lr,[r0]		@@ tmp  == lr
+        ldr      r8,[r3],#4		@@ tmp1 == r8
+
+@        tmp  = fxp_mul32_Q32( tmp<<1,  *(pt_cos++  ))
+@        tmp1 = fxp_mul32_Q27( tmp1, *(pt_cos_x--))
+
+        mov      lr,lr,lsl #1
+        smull    r10,lr,r8,lr
+        ldr      r8,[r12],#-4
+        ldr      r9,[r1]
+        subs     r4,r4,#1
+        smull    r9,r10,r8,r9
+        mov      r8,r9,lsr #27
+        add      r8,r8,r10,lsl #5
+
+@        *(pt_vec++)   =   tmp + tmp1 
+@        *(pt_vec_o--) = fxp_mul32_Q28( (tmp - tmp1), *(pt_cos_split++))
+
+        add      r9,lr,r8
+        sub      r8,lr,r8
+        ldr      lr,[r2],#4
+        str      r9,[r0],#4
+        smull    r8,r9,lr,r8
+        mov      lr,r8,lsr #28
+        add      lr,lr,r9,lsl #4
+        str      lr,[r1],#-4
+        bne      Loop_1
+
+@		}
+
+        mov      r0,r5			@@ r0 = vec
+        bl       pvmp3_dct_9
+        add      r0,r5,#0x24	@@ r0 = &vec[9]
+        bl       pvmp3_dct_9
+
+        ldr      r0,[r5,#0x20]
+        ldr      r2,[r5,#0x40]
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x1c]
+        ldr      r3,[r5,#0x38]
+        str      r0,[r5,#0x38]
+        ldr      r1,[r5,#0x18]
+        ldr      r0,[r5,#0x30]
+        str      r1,[r5,#0x30]
+        ldr      r12,[r5,#0x14]
+        ldr      r1,[r5,#0x28]
+        str      r12,[r5,#0x28]
+        ldr      r12,[r5,#0x10]
+        str      r12,[r5,#0x20]
+        ldr      r12,[r5,#0xc]
+        str      r12,[r5,#0x18]
+        ldr      r12,[r5,#8]
+        str      r12,[r5,#0x10]
+        ldr      r12,[r5,#4]
+        str      r12,[r5,#8]
+        ldr      r12,[r5,#0x24]
+        sub      r12,r12,r1
+        str      r12,[r5,#4]
+        ldr      r12,[r5,#0x2c]
+        sub      r1,r12,r1
+        str      r1,[r5,#0xc]
+        sub      r1,r12,r0
+        str      r1,[r5,#0x14]
+        ldr      r1,[r5,#0x34]
+        sub      r0,r1,r0
+        str      r0,[r5,#0x1c]
+        sub      r0,r1,r3
+        str      r0,[r5,#0x24]
+        ldr      r1,[r5,#0x3c]
+        sub      r3,r1,r3
+        sub      r1,r1,r2
+        str      r1,[r5,#0x34]
+        str      r3,[r5,#0x2c]
+        ldr      r1,[r5,#0x44]
+        sub      r1,r1,r2
+        str      r1,[r5,#0x3c]
+        ldr      r12,[r5,#0]
+
+Loop_2:
+        add      r1,r5,r4,lsl #2
+        ldr      r2,[r1,#0x28]
+        ldr      r3,[r6,r4,lsl #2]
+        add      r0,r0,r2
+        str      r0,[r1,#0x28]
+        ldr      lr,[r7,r4,lsl #2]
+        ldr      r1,[r1,#4]
+        smlal    r0,r3,lr,r0
+        mov      r0,r2
+        add      r2,r12,r1
+        rsb      r2,r2,#0
+        str      r3,[r5,r4,lsl #2]
+        str      r2,[r6,r4,lsl #2]
+        add      r4,r4,#1
+        cmp      r4,#6
+        mov      r12,r1
+
+        blt      Loop_2
+
+        ldr      r1,[r5,#0x40]
+        ldr      r2,[r6,#0x18]
+        add      r3,r0,r1
+        str      r3,[r5,#0x40]
+        ldr      lr,[r7,r4,lsl #2]
+        mov      r3,r3,lsl #1
+        ldr      r0,[r5,#0x1c]
+        smlal    r3,r2,lr,r3
+        add      r3,r12,r0
+        str      r2,[r5,#0x18]
+        ldr      r2,[r6,#0x1c]
+        rsb      r3,r3,#0
+        str      r3,[r6,#0x18]
+        ldr      r3,[r5,#0x20]
+        add      r0,r3,r0
+        rsb      r0,r0,#0
+        str      r0,[r6,#0x1c]
+        ldr      r3,[r5,#0x44]
+        ldr      r0,[r6,#0x20]
+        add      r3,r3,r1
+        mov      r1,r2
+        ldr      r10,[r7,#0x1c]
+        mov      r2,r3,lsl #1
+        smlal    r12,r1,r10,r2
+        str      r1,[r5,#0x1c]
+        ldr      r1,[r5,#0x20]
+        ldr      r3,[r5,#0x24]
+        add      r1,r1,r3
+        rsb      r1,r1,#0
+        str      r1,[r6,#0x20]
+        ldr      r1,[r5,#0x44]
+        ldr      r3,[r7,#0x20]
+        mov      r1,r1,lsl #1
+        smlal    r12,r0,r3,r1
+        ldr      lr,[r7,#0x24]
+        ldr      r3,[r6,#0x24]
+        str      r0,[r5,#0x20]
+        smlal    r1,r3,lr,r1
+        ldr      r0,[r6,#0x40]
+        ldr      r12,[r6,#0x44]
+        str      r3,[r5,#0x24]
+        ldr      r1,[r5,#0x28]
+        ldr      r3,[r7,#0x44]
+        mov      r1,r1,lsl #1
+        smlal    r1,r12,r3,r1
+        ldr      r1,[r5,#0x40]
+        str      r12,[r5,#0x44]
+        rsb      r8,r1,#0
+        str      r8,[r5,#0x28]
+        ldr      r1,[r5,#0x2c]
+        ldr      r3,[r7,#0x40]
+        mov      r1,r1,lsl #1
+        smlal    r1,r0,r3,r1
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x3c]
+        ldr      r1,[r6,#0x38]
+        ldr      r3,[r6,#0x3c]
+        rsb      r9,r0,#0
+        str      r9,[r5,#0x2c]
+        ldr      r0,[r5,#0x30]
+        ldr      r12,[r7,#0x3c]
+        mov      r0,r0,lsl #1
+        smlal    r0,r3,r12,r0
+        str      r3,[r5,#0x3c]
+        ldr      r0,[r5,#0x38]
+        rsb      r0,r0,#0
+        str      r0,[r5,#0x30]
+        ldr      r3,[r5,#0x34]
+        ldr      r12,[r7,#0x38]
+        mov      r3,r3,lsl #1
+        smlal    r3,r1,r12,r3
+        mov      r0,r0,lsl #1
+        str      r1,[r5,#0x38]
+        ldr      r4,[r7,#0x34]
+        ldr      r1,[r6,#0x34]
+        ldr      r3,[r6,#0x30]
+        smlal    r0,r1,r4,r0
+        ldr      r12,[r6,#0x2c]
+        ldr      lr,[r6,#0x28]
+        str      r1,[r5,#0x34]
+        ldr      r1,[r7,#0x30]
+        mov      r0,r9,lsl #1
+        smlal    r0,r3,r1,r0
+        mov      r0,r8,lsl #1
+        ldr      r1,[r7,#0x2c]
+        str      r3,[r5,#0x30]
+        smlal    r0,r12,r1,r0
+        ldr      r0,[r7,#0x28]
+        str      r12,[r5,#0x2c]
+        smlal    r2,lr,r0,r2
+        str      lr,[r5,#0x28]
+        ldr      r1,[r6,#4]
+        ldr      r12,[r7,#0x48]
+        mov      r2,r1,lsl #1
+        ldr      r1,[r6,#0x20]
+        ldr      r0,[r6,#0]
+        mov      r1,r1,lsl #1
+        smull    r4,lr,r12,r1
+        ldr      r3,[r6,#0x1c]
+        str      lr,[r6,#0]
+        ldr      r12,[r7,#0x4c]
+        mov      r3,r3,lsl #1
+        smull    r4,lr,r12,r3
+        mov      r0,r0,lsl #1
+        ldr      r12,[r7,#0x64]
+        str      lr,[r6,#4]
+        smull    r4,lr,r12,r2
+        ldr      r12,[r7,#0x68]
+        str      lr,[r6,#0x1c]
+        smull    r4,lr,r12,r0
+        ldr      r12,[r7,#0x6c]
+        str      lr,[r6,#0x20]
+        smull    lr,r0,r12,r0
+        ldr      r12,[r7,#0x70]
+        str      r0,[r6,#0x24]
+        smull    r0,r2,r12,r2
+        ldr      r0,[r7,#0x88]
+        str      r2,[r6,#0x28]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x8c]
+        str      r2,[r6,#0x40]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x44]
+        ldr      r0,[r6,#0x18]
+        ldr      lr,[r7,#0x50]
+        mov      r1,r0,lsl #1
+        ldr      r0,[r6,#0x14]
+        smull    r5,r4,lr,r1
+        mov      r3,r0,lsl #1
+        ldr      r0,[r6,#0x10]
+        mov      r12,r0,lsl #1
+        ldr      r0,[r6,#0xc]
+        mov      r2,r0,lsl #1
+        ldr      r0,[r6,#8]
+        str      r4,[r6,#8]
+        ldr      lr,[r7,#0x54]
+        mov      r0,r0,lsl #1
+        smull    r5,r4,lr,r3
+        ldr      lr,[r7,#0x58]
+        str      r4,[r6,#0xc]
+        smull    r5,r4,lr,r12
+        ldr      lr,[r7,#0x5c]
+        str      r4,[r6,#0x10]
+        smull    r5,r4,lr,r2
+        ldr      lr,[r7,#0x60]
+        str      r4,[r6,#0x14]
+        smull    r5,r4,lr,r0
+        ldr      lr,[r7,#0x74]
+        str      r4,[r6,#0x18]
+        smull    r4,r0,lr,r0
+        ldr      lr,[r7,#0x78]
+        str      r0,[r6,#0x2c]
+        smull    r0,r2,lr,r2
+        ldr      r0,[r7,#0x7c]
+        str      r2,[r6,#0x30]
+        smull    r12,r2,r0,r12
+        ldr      r0,[r7,#0x80]
+        str      r2,[r6,#0x34]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x84]
+        str      r2,[r6,#0x38]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x3c]
+        ldmfd    sp!,{r4-r11,pc}
+table:
+        .word      constdata$1
+
+@------------------------------------------------------------------------------
+
+constdata$1:
+cosTerms_dct18:
+        .word      0x0807d2b0
+        .word      0x08483ee0
+        .word      0x08d3b7d0
+        .word      0x09c42570
+        .word      0x0b504f30
+        .word      0x0df29440
+        .word      0x12edfb20
+        .word      0x1ee8dd40
+        .word      0x5bca2a00
+cosTerms_1_ov_cos_phi:
+        .word      0x400f9c00
+        .word      0x408d6080
+        .word      0x418dcb80
+        .word      0x431b1a00
+        .word      0x4545ea00
+        .word      0x48270680
+        .word      0x4be25480
+        .word      0x50ab9480
+        .word      0x56ce4d80
+        .word      0x05ebb630
+        .word      0x06921a98
+        .word      0x0771d3a8
+        .word      0x08a9a830
+        .word      0x0a73d750
+        .word      0x0d4d5260
+        .word      0x127b1ca0
+        .word      0x1ea52b40
+        .word      0x5bb3cc80
+
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_wm.asm b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_wm.asm
new file mode 100644
index 0000000..5be75d4
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_mdct_18_wm.asm
@@ -0,0 +1,366 @@
+; ------------------------------------------------------------------
+; 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.
+; -------------------------------------------------------------------
+
+;
+;
+;   Filename: pvmp3_dct_18.s
+;
+;------------------------------------------------------------------------------
+; REVISION HISTORY
+;
+;
+; Who:                                   Date: MM/DD/YYYY
+; Description: 
+;
+;------------------------------------------------------------------------------
+
+        EXPORT |pvmp3_mdct_18|
+
+        IMPORT pvmp3_dct_9
+
+
+;------------------------------------------------------------------------------
+
+ AREA |.text|, CODE, READONLY, ALIGN=2
+
+
+;------------------------------------------------------------------------------
+
+|pvmp3_mdct_18| PROC
+        stmfd    sp!,{r4-r10,lr}
+        mov      r7,r2
+        ldr      r2,table
+        mov      r6,r1
+        add      r3,r2,#0x24
+        add      r12,r3,#0x44
+        add      r1,r0,#0x44
+        mov      r5,r0
+
+;    for ( i=9; i!=0; i--)
+;    {
+
+        mov      r4,#9
+Loop_1
+
+;       tmp  = *(pt_vec);
+;		tmp1 = *(pt_vec_o);
+
+        ldr      lr,[r0]		;; tmp  == lr
+        ldr      r8,[r3],#4		;; tmp1 == r8
+
+;        tmp  = fxp_mul32_Q32( tmp<<1,  *(pt_cos++  ));
+;        tmp1 = fxp_mul32_Q27( tmp1, *(pt_cos_x--));
+
+        mov      lr,lr,lsl #1
+        smull    r10,lr,r8,lr
+        ldr      r8,[r12],#-4
+        ldr      r9,[r1]
+        subs     r4,r4,#1
+        smull    r9,r10,r8,r9
+        mov      r8,r9,lsr #27
+        add      r8,r8,r10,lsl #5
+
+;        *(pt_vec++)   =   tmp + tmp1 ;
+;        *(pt_vec_o--) = fxp_mul32_Q28( (tmp - tmp1), *(pt_cos_split++));
+
+        add      r9,lr,r8
+        sub      r8,lr,r8
+        ldr      lr,[r2],#4
+        str      r9,[r0],#4
+        smull    r8,r9,lr,r8
+        mov      lr,r8,lsr #28
+        add      lr,lr,r9,lsl #4
+        str      lr,[r1],#-4
+        bne      Loop_1
+
+;		}
+
+        mov      r0,r5			;; r0 = vec
+        bl       pvmp3_dct_9
+        add      r0,r5,#0x24	;; r0 = &vec[9]
+        bl       pvmp3_dct_9
+
+        ldr      r0,[r5,#0x20]
+        ldr      r2,[r5,#0x40]
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x1c]
+        ldr      r3,[r5,#0x38]
+        str      r0,[r5,#0x38]
+        ldr      r1,[r5,#0x18]
+        ldr      r0,[r5,#0x30]
+        str      r1,[r5,#0x30]
+        ldr      r12,[r5,#0x14]
+        ldr      r1,[r5,#0x28]
+        str      r12,[r5,#0x28]
+        ldr      r12,[r5,#0x10]
+        str      r12,[r5,#0x20]
+        ldr      r12,[r5,#0xc]
+        str      r12,[r5,#0x18]
+        ldr      r12,[r5,#8]
+        str      r12,[r5,#0x10]
+        ldr      r12,[r5,#4]
+        str      r12,[r5,#8]
+        ldr      r12,[r5,#0x24]
+        sub      r12,r12,r1
+        str      r12,[r5,#4]
+        ldr      r12,[r5,#0x2c]
+        sub      r1,r12,r1
+        str      r1,[r5,#0xc]
+        sub      r1,r12,r0
+        str      r1,[r5,#0x14]
+        ldr      r1,[r5,#0x34]
+        sub      r0,r1,r0
+        str      r0,[r5,#0x1c]
+        sub      r0,r1,r3
+        str      r0,[r5,#0x24]
+        ldr      r1,[r5,#0x3c]
+        sub      r3,r1,r3
+        sub      r1,r1,r2
+        str      r1,[r5,#0x34]
+        str      r3,[r5,#0x2c]
+        ldr      r1,[r5,#0x44]
+        sub      r1,r1,r2
+        str      r1,[r5,#0x3c]
+        ldr      r12,[r5,#0]
+
+Loop_2
+        add      r1,r5,r4,lsl #2
+        ldr      r2,[r1,#0x28]
+        ldr      r3,[r6,r4,lsl #2]
+        add      r0,r0,r2
+        str      r0,[r1,#0x28]
+        ldr      lr,[r7,r4,lsl #2]
+        ldr      r1,[r1,#4]
+        smlal    r0,r3,lr,r0
+        mov      r0,r2
+        add      r2,r12,r1
+        rsb      r2,r2,#0
+        str      r3,[r5,r4,lsl #2]
+        str      r2,[r6,r4,lsl #2]
+        add      r4,r4,#1
+        cmp      r4,#6
+        mov      r12,r1
+
+        blt      Loop_2
+
+        ldr      r1,[r5,#0x40]
+        ldr      r2,[r6,#0x18]
+        add      r3,r0,r1
+        str      r3,[r5,#0x40]
+        ldr      lr,[r7,r4,lsl #2]
+        mov      r3,r3,lsl #1
+        ldr      r0,[r5,#0x1c]
+        smlal    r3,r2,lr,r3
+        add      r3,r12,r0
+        str      r2,[r5,#0x18]
+        ldr      r2,[r6,#0x1c]
+        rsb      r3,r3,#0
+        str      r3,[r6,#0x18]
+        ldr      r3,[r5,#0x20]
+        add      r0,r3,r0
+        rsb      r0,r0,#0
+        str      r0,[r6,#0x1c]
+        ldr      r3,[r5,#0x44]
+        ldr      r0,[r6,#0x20]
+        add      r3,r3,r1
+        mov      r1,r2
+        ldr      r10,[r7,#0x1c]
+        mov      r2,r3,lsl #1
+        smlal    r12,r1,r10,r2
+        str      r1,[r5,#0x1c]
+        ldr      r1,[r5,#0x20]
+        ldr      r3,[r5,#0x24]
+        add      r1,r1,r3
+        rsb      r1,r1,#0
+        str      r1,[r6,#0x20]
+        ldr      r1,[r5,#0x44]
+        ldr      r3,[r7,#0x20]
+        mov      r1,r1,lsl #1
+        smlal    r12,r0,r3,r1
+        ldr      lr,[r7,#0x24]
+        ldr      r3,[r6,#0x24]
+        str      r0,[r5,#0x20]
+        smlal    r1,r3,lr,r1
+        ldr      r0,[r6,#0x40]
+        ldr      r12,[r6,#0x44]
+        str      r3,[r5,#0x24]
+        ldr      r1,[r5,#0x28]
+        ldr      r3,[r7,#0x44]
+        mov      r1,r1,lsl #1
+        smlal    r1,r12,r3,r1
+        ldr      r1,[r5,#0x40]
+        str      r12,[r5,#0x44]
+        rsb      r8,r1,#0
+        str      r8,[r5,#0x28]
+        ldr      r1,[r5,#0x2c]
+        ldr      r3,[r7,#0x40]
+        mov      r1,r1,lsl #1
+        smlal    r1,r0,r3,r1
+        str      r0,[r5,#0x40]
+        ldr      r0,[r5,#0x3c]
+        ldr      r1,[r6,#0x38]
+        ldr      r3,[r6,#0x3c]
+        rsb      r9,r0,#0
+        str      r9,[r5,#0x2c]
+        ldr      r0,[r5,#0x30]
+        ldr      r12,[r7,#0x3c]
+        mov      r0,r0,lsl #1
+        smlal    r0,r3,r12,r0
+        str      r3,[r5,#0x3c]
+        ldr      r0,[r5,#0x38]
+        rsb      r0,r0,#0
+        str      r0,[r5,#0x30]
+        ldr      r3,[r5,#0x34]
+        ldr      r12,[r7,#0x38]
+        mov      r3,r3,lsl #1
+        smlal    r3,r1,r12,r3
+        mov      r0,r0,lsl #1
+        str      r1,[r5,#0x38]
+        ldr      r4,[r7,#0x34]
+        ldr      r1,[r6,#0x34]
+        ldr      r3,[r6,#0x30]
+        smlal    r0,r1,r4,r0
+        ldr      r12,[r6,#0x2c]
+        ldr      lr,[r6,#0x28]
+        str      r1,[r5,#0x34]
+        ldr      r1,[r7,#0x30]
+        mov      r0,r9,lsl #1
+        smlal    r0,r3,r1,r0
+        mov      r0,r8,lsl #1
+        ldr      r1,[r7,#0x2c]
+        str      r3,[r5,#0x30]
+        smlal    r0,r12,r1,r0
+        ldr      r0,[r7,#0x28]
+        str      r12,[r5,#0x2c]
+        smlal    r2,lr,r0,r2
+        str      lr,[r5,#0x28]
+        ldr      r1,[r6,#4]
+        ldr      r12,[r7,#0x48]
+        mov      r2,r1,lsl #1
+        ldr      r1,[r6,#0x20]
+        ldr      r0,[r6]
+        mov      r1,r1,lsl #1
+        smull    r4,lr,r12,r1
+        ldr      r3,[r6,#0x1c]
+        str      lr,[r6]
+        ldr      r12,[r7,#0x4c]
+        mov      r3,r3,lsl #1
+        smull    r4,lr,r12,r3
+        mov      r0,r0,lsl #1
+        ldr      r12,[r7,#0x64]
+        str      lr,[r6,#4]
+        smull    r4,lr,r12,r2
+        ldr      r12,[r7,#0x68]
+        str      lr,[r6,#0x1c]
+        smull    r4,lr,r12,r0
+        ldr      r12,[r7,#0x6c]
+        str      lr,[r6,#0x20]
+        smull    lr,r0,r12,r0
+        ldr      r12,[r7,#0x70]
+        str      r0,[r6,#0x24]
+        smull    r0,r2,r12,r2
+        ldr      r0,[r7,#0x88]
+        str      r2,[r6,#0x28]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x8c]
+        str      r2,[r6,#0x40]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x44]
+        ldr      r0,[r6,#0x18]
+        ldr      lr,[r7,#0x50]
+        mov      r1,r0,lsl #1
+        ldr      r0,[r6,#0x14]
+        smull    r5,r4,lr,r1
+        ldr      r12,[r6,#0x10]
+        mov      r3,r0,lsl #1
+        ldr      r0,[r6,#0xc]
+        mov      r12,r12,lsl #1
+        mov      r2,r0,lsl #1
+        ldr      r0,[r6,#8]
+        str      r4,[r6,#8]
+        ldr      lr,[r7,#0x54]
+        mov      r0,r0,lsl #1
+        smull    r5,r4,lr,r3
+        ldr      lr,[r7,#0x58]
+        str      r4,[r6,#0xc]
+        smull    r5,r4,lr,r12
+        ldr      lr,[r7,#0x5c]
+        str      r4,[r6,#0x10]
+        smull    r5,r4,lr,r2
+        ldr      lr,[r7,#0x60]
+        str      r4,[r6,#0x14]
+        smull    r5,r4,lr,r0
+        ldr      lr,[r7,#0x74]
+        str      r4,[r6,#0x18]
+        smull    r4,r0,lr,r0
+        ldr      lr,[r7,#0x78]
+        str      r0,[r6,#0x2c]
+        smull    r0,r2,lr,r2
+        ldr      r0,[r7,#0x7c]
+        str      r2,[r6,#0x30]
+        smull    r12,r2,r0,r12
+        ldr      r0,[r7,#0x80]
+        str      r2,[r6,#0x34]
+        smull    r3,r2,r0,r3
+        ldr      r0,[r7,#0x84]
+        str      r2,[r6,#0x38]
+        smull    r2,r1,r0,r1
+        str      r1,[r6,#0x3c]
+        ldmfd    sp!,{r4-r10,pc}
+table
+        DCD      cosTerms_dct18
+        ENDP
+
+;------------------------------------------------------------------------------
+
+ AREA |.constdata|, DATA, READONLY, ALIGN=2
+
+;------------------------------------------------------------------------------
+
+cosTerms_dct18
+        DCD      0x0807d2b0
+        DCD      0x08483ee0
+        DCD      0x08d3b7d0
+        DCD      0x09c42570
+        DCD      0x0b504f30
+        DCD      0x0df29440
+        DCD      0x12edfb20
+        DCD      0x1ee8dd40
+        DCD      0x5bca2a00
+cosTerms_1_ov_cos_phi
+        DCD      0x400f9c00
+        DCD      0x408d6080
+        DCD      0x418dcb80
+        DCD      0x431b1a00
+        DCD      0x4545ea00
+        DCD      0x48270680
+        DCD      0x4be25480
+        DCD      0x50ab9480
+        DCD      0x56ce4d80
+        DCD      0x05ebb630
+        DCD      0x06921a98
+        DCD      0x0771d3a8
+        DCD      0x08a9a830
+        DCD      0x0a73d750
+        DCD      0x0d4d5260
+        DCD      0x127b1ca0
+        DCD      0x1ea52b40
+        DCD      0x5bb3cc80
+
+
+
+        END
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_arm.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_arm.s
new file mode 100644
index 0000000..abec599
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_arm.s
@@ -0,0 +1,237 @@
+; ------------------------------------------------------------------
+; 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.
+; -------------------------------------------------------------------
+
+;
+;
+;   Filename: pvmp3_polyphase_filter_window.s
+;
+;------------------------------------------------------------------------------
+; REVISION HISTORY
+;
+;
+; Who:                                   Date: MM/DD/YYYY
+; Description: 
+;
+;------------------------------------------------------------------------------
+
+        EXPORT pvmp3_polyphase_filter_window
+
+        IMPORT ||Lib$$Request$$armlib|| [WEAK]
+        IMPORT ||Lib$$Request$$cpplib|| [WEAK]
+        IMPORT pqmfSynthWin
+
+
+
+;------------------------------------------------------------------------------
+
+ AREA |.text|, CODE, READONLY, ALIGN=2
+
+
+;------------------------------------------------------------------------------
+
+|pvmp3_polyphase_filter_window| PROC
+
+        stmfd    sp!,{r0-r2,r4-r11,lr}
+
+        sub      sp,sp,#4
+        ldr      r2,[sp,#0xc]
+        ldr      r1,PolyPh_filter_coeff
+		
+        sub      r2,r2,#1
+        mov      r10,#1
+        str      r2,[sp]
+
+; Accumulators r9, r11::> Initialization
+
+Loop_j
+        mov      r9,  #0x20
+        mov      r11, #0x20
+        mov      r4,  #0x10
+Loop_i
+        add      r2,r4,r10
+        add      r3,r0,r2,lsl #2
+        sub      r2,r4,r10
+        ldr      r5,[r3]
+        ldr      lr,[r1]
+        add      r12,r0,r2,lsl #2
+        ldr      r6,[r12,#0x780]
+        smlal    r2,r9,lr,r5
+        smlal    r2,r11,lr,r6
+        ldr      r2,[r1,#4]
+        ldr      r7,[r12,#0x80]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        sub      r9,r9,r5
+        ldr      r5,[r1,#8]
+        ldr      r8,[r3,#0x700]
+        add      r4,r4,#0x200
+        smlal    r6,r9,r5,r7
+        smull    r6,r2,r5,r8
+        ldr      r5,[r1,#0xc]
+        sub      r11,r11,r2
+        smlal    r8,r9,r5,r8
+        smlal    r7,r11,r5,r7
+        ldr      r5,[r3,#0x100]
+        ldr      r2,[r1,#0x10]
+        ldr      r6,[r12,#0x680]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x14]
+        ldr      r7,[r12,#0x180]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x18]
+        ldr      r8,[r3,#0x600]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x1c]
+        sub      r11,r11,r5
+        smlal    r8,r9,r6,r8
+        ldr      r2,[r1,#0x20]
+        ldr      r5,[r3,#0x200]
+        smlal    r7,r11,r6,r7
+        ldr      r6,[r12,#0x580]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x24]
+        ldr      r7,[r12,#0x280]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x28]
+        ldr      r8,[r3,#0x500]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x2c]
+        sub      r11,r11,r5
+
+        smlal    r8,r9,r6,r8
+        smlal    r7,r11,r6,r7
+        ldr      r5,[r3,#0x300]
+        ldr      r8,[r1,#0x30]
+        ldr      r6,[r12,#0x480]
+        smlal    r7,r9,r8,r5
+        smlal    r7,r11,r8,r6
+        ldr      r8,[r1,#0x34]
+        ldr      r12,[r12,#0x380]
+        smlal    r5,r11,r8,r5
+        smull    r6,r5,r8,r6
+        ldr      r6,[r1,#0x38]
+
+
+        ldr      r3,[r3,#0x400]
+        sub      r9,r9,r5
+        smlal    r7,r9,r6,r12
+        smull    r8,r7,r6,r3
+        cmp      r4,#0x210
+        sub      r11,r11,r7
+
+        ldr      r2,[r1,#0x3c]
+        add      r1,r1,#0x40
+        smlal    r3,r9,r2,r3
+        smlal    r12,r11,r2,r12
+
+        blt      Loop_i
+
+        mov      r3,r9, asr #6
+        mov      r4,r3, asr #15
+        teq      r4,r3, asr #31
+        ldr      r12,LOW_16BITS
+        ldr      r2,[sp]
+        eorne    r3,r12,r3,asr #31
+        ldr      r4,[sp,#8]
+        mov      r2,r10,lsl r2
+        add      r4,r4,r2,lsl #1
+        strh     r3,[r4]
+
+        mov      r3,r11,asr #6
+        mov      r4,r3,asr #15
+        teq      r4,r3,asr #31
+        eorne    r3,r12,r3,asr #31
+        ldr      r12,[sp,#0xc]
+        ldr      r11,[sp,#8]
+        rsb      r2,r2,r12,lsl #5
+        add      r2,r11,r2,lsl #1
+        strh     r3,[r2]
+
+        add      r10,r10,#1
+        cmp      r10,#0x10
+        blt      Loop_j
+
+; Accumulators r4, r5 Initialization
+
+        mov      r4,#0x20
+        mov      r5,#0x20
+        mov      r3,#0x10
+PolyPh_filter_loop2
+        add      r2,r0,r3,lsl #2
+        ldr      r12,[r2]
+        ldr      r8,[r1]
+        ldr      r6,[r2,#0x80]
+        smlal    r12,r4,r8,r12
+        ldr      r12,[r1,#4]
+        ldr      r7,[r2,#0x40]
+        smlal    r6,r4,r12,r6
+
+        ldr      r12,[r1,#8]
+        ldr      r6,[r2,#0x180]
+        smlal    r7,r5,r12,r7
+        ldr      r12,[r2,#0x100]
+        ldr      r7,[r1,#0xc]
+        ldr      r2,[r2,#0x140]
+        smlal    r12,r4,r7,r12
+        ldr      r12,[r1,#0x10]
+        add      r3,r3,#0x80
+        smlal    r6,r4,r12,r6
+        ldr      r6,[r1,#0x14]
+        cmp      r3,#0x210
+        smlal    r2,r5,r6,r2
+        add      r1,r1,#0x18
+
+        blt      PolyPh_filter_loop2
+        mov      r0,r4,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r1,[sp,#8]
+        eorne    r0,r12,r0,asr #31
+        strh     r0,[r1,#0]
+        mov      r0,r5,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r2,[sp]
+        mov      r1,#0x10
+        eorne    r0,r12,r0,asr #31
+        ldr      r12,[sp,#8]
+        mov      r1,r1,lsl r2
+        add      r1,r12,r1,lsl #1
+        strh     r0,[r1]
+        add      sp,sp,#0x10
+        ldmfd    sp!,{r4-r11,pc}
+
+
+PolyPh_filter_coeff
+        DCD      pqmfSynthWin
+LOW_16BITS
+        DCD      0x00007fff
+
+        ENDP
+
+
+        END
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s
new file mode 100644
index 0000000..4f45737
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_gcc.s
@@ -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.
+@ -------------------------------------------------------------------
+
+@
+@
+@   Filename: pvmp3_polyphase_filter_window.s
+@
+@------------------------------------------------------------------------------
+@ REVISION HISTORY
+@
+@
+@ Who:                                   Date: MM/DD/YYYY
+@ Description: 
+@
+@------------------------------------------------------------------------------
+
+.arm
+
+.align 4
+
+.text
+
+.extern pqmfSynthWin
+
+
+
+@------------------------------------------------------------------------------
+
+.global pvmp3_polyphase_filter_window
+
+pvmp3_polyphase_filter_window:
+        stmfd    sp!,{r0-r2,r4-r11,lr}
+
+        sub      sp,sp,#4
+        ldr      r2,[sp,#0xc]
+        ldr      r1,PolyPh_filter_coeff
+		
+        sub      r2,r2,#1
+        mov      r10,#1
+        str      r2,[sp]
+
+@ Accumulators r9, r11::> Initialization
+
+Loop_j:
+        mov      r9,  #0x20
+        mov      r11, #0x20
+        mov      r4,  #0x10
+Loop_i:
+        add      r2,r4,r10
+        add      r3,r0,r2,lsl #2
+        sub      r2,r4,r10
+        ldr      r5,[r3]
+        ldr      lr,[r1]
+        add      r12,r0,r2,lsl #2
+        ldr      r6,[r12,#0x780]
+        smlal    r2,r9,lr,r5
+        smlal    r2,r11,lr,r6
+        ldr      r2,[r1,#4]
+        ldr      r7,[r12,#0x80]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        sub      r9,r9,r5
+        ldr      r5,[r1,#8]
+        ldr      r8,[r3,#0x700]
+        add      r4,r4,#0x200
+        smlal    r6,r9,r5,r7
+        smull    r6,r2,r5,r8
+        ldr      r5,[r1,#0xc]
+        sub      r11,r11,r2
+        smlal    r8,r9,r5,r8
+        smlal    r7,r11,r5,r7
+        ldr      r5,[r3,#0x100]
+        ldr      r2,[r1,#0x10]
+        ldr      r6,[r12,#0x680]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x14]
+        ldr      r7,[r12,#0x180]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x18]
+        ldr      r8,[r3,#0x600]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x1c]
+        sub      r11,r11,r5
+        smlal    r8,r9,r6,r8
+        ldr      r2,[r1,#0x20]
+        ldr      r5,[r3,#0x200]
+        smlal    r7,r11,r6,r7
+        ldr      r6,[r12,#0x580]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x24]
+        ldr      r7,[r12,#0x280]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x28]
+        ldr      r8,[r3,#0x500]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x2c]
+        sub      r11,r11,r5
+
+        smlal    r8,r9,r6,r8
+        smlal    r7,r11,r6,r7
+        ldr      r5,[r3,#0x300]
+        ldr      r8,[r1,#0x30]
+        ldr      r6,[r12,#0x480]
+        smlal    r7,r9,r8,r5
+        smlal    r7,r11,r8,r6
+        ldr      r8,[r1,#0x34]
+        ldr      r12,[r12,#0x380]
+        smlal    r5,r11,r8,r5
+        smull    r6,r5,r8,r6
+        ldr      r6,[r1,#0x38]
+
+
+        ldr      r3,[r3,#0x400]
+        sub      r9,r9,r5
+        smlal    r7,r9,r6,r12
+        smull    r8,r7,r6,r3
+        cmp      r4,#0x210
+        sub      r11,r11,r7
+
+        ldr      r2,[r1,#0x3c]
+        add      r1,r1,#0x40
+        smlal    r3,r9,r2,r3
+        smlal    r12,r11,r2,r12
+
+        blt      Loop_i
+
+        mov      r3,r9, asr #6
+        mov      r4,r3, asr #15
+        teq      r4,r3, asr #31
+        ldr      r12,LOW_16BITS
+        ldr      r2,[sp]
+        eorne    r3,r12,r3,asr #31
+        ldr      r4,[sp,#8]
+        mov      r2,r10,lsl r2
+        add      r4,r4,r2,lsl #1
+        strh     r3,[r4]
+
+        mov      r3,r11,asr #6
+        mov      r4,r3,asr #15
+        teq      r4,r3,asr #31
+        eorne    r3,r12,r3,asr #31
+        ldr      r12,[sp,#0xc]
+        ldr      r11,[sp,#8]
+        rsb      r2,r2,r12,lsl #5
+        add      r2,r11,r2,lsl #1
+        strh     r3,[r2]
+
+        add      r10,r10,#1
+        cmp      r10,#0x10
+        blt      Loop_j
+
+@ Accumulators r4, r5 Initialization
+
+        mov      r4,#0x20
+        mov      r5,#0x20
+        mov      r3,#0x10
+PolyPh_filter_loop2:
+        add      r2,r0,r3,lsl #2
+        ldr      r12,[r2]
+        ldr      r8,[r1]
+        ldr      r6,[r2,#0x80]
+        smlal    r12,r4,r8,r12
+        ldr      r12,[r1,#4]
+        ldr      r7,[r2,#0x40]
+        smlal    r6,r4,r12,r6
+
+        ldr      r12,[r1,#8]
+        ldr      r6,[r2,#0x180]
+        smlal    r7,r5,r12,r7
+        ldr      r12,[r2,#0x100]
+        ldr      r7,[r1,#0xc]
+        ldr      r2,[r2,#0x140]
+        smlal    r12,r4,r7,r12
+        ldr      r12,[r1,#0x10]
+        add      r3,r3,#0x80
+        smlal    r6,r4,r12,r6
+        ldr      r6,[r1,#0x14]
+        cmp      r3,#0x210
+        smlal    r2,r5,r6,r2
+        add      r1,r1,#0x18
+
+        blt      PolyPh_filter_loop2
+        mov      r0,r4,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r1,[sp,#8]
+        eorne    r0,r12,r0,asr #31
+        strh     r0,[r1,#0]
+        mov      r0,r5,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r2,[sp]
+        mov      r1,#0x10
+        eorne    r0,r12,r0,asr #31
+        ldr      r12,[sp,#8]
+        mov      r1,r1,lsl r2
+        add      r1,r12,r1,lsl #1
+        strh     r0,[r1]
+        add      sp,sp,#0x10
+        ldmfd    sp!,{r4-r11,pc}
+
+PolyPh_filter_coeff:
+        .word      pqmfSynthWin
+LOW_16BITS:
+        .word      0x00007fff
+
diff --git a/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_wm.asm b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_wm.asm
new file mode 100644
index 0000000..f957267
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/asm/pvmp3_polyphase_filter_window_wm.asm
@@ -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.
+; -------------------------------------------------------------------
+
+;
+;
+;   Filename: pvmp3_polyphase_filter_window.s
+;
+;------------------------------------------------------------------------------
+; REVISION HISTORY
+;
+;
+; Who:                                   Date: MM/DD/YYYY
+; Description: 
+;
+;------------------------------------------------------------------------------
+
+	CODE32
+
+	AREA	|.drectve|, DRECTVE
+
+	EXPORT	|pvmp3_polyphase_filter_window|
+	IMPORT	|pqmfSynthWin|
+
+	AREA	|.pdata|, PDATA
+
+	AREA	|.text|, CODE, ARM
+
+|pvmp3_polyphase_filter_window| PROC
+        stmfd    sp!,{r0-r2,r4-r11,lr}
+
+        sub      sp,sp,#4
+        ldr      r2,[sp,#0xc]
+        ldr      r1,PolyPh_filter_coeff
+		
+        sub      r2,r2,#1
+        mov      r10,#1
+        str      r2,[sp]
+
+; Accumulators r9, r11::> Initialization
+
+Loop_j
+        mov      r9,  #0x20
+        mov      r11, #0x20
+        mov      r4,  #0x10
+Loop_i
+        add      r2,r4,r10
+        add      r3,r0,r2,lsl #2
+        sub      r2,r4,r10
+        ldr      r5,[r3]
+        ldr      lr,[r1]
+        add      r12,r0,r2,lsl #2
+        ldr      r6,[r12,#0x780]
+        smlal    r2,r9,lr,r5
+        smlal    r2,r11,lr,r6
+        ldr      r2,[r1,#4]
+        ldr      r7,[r12,#0x80]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        sub      r9,r9,r5
+        ldr      r5,[r1,#8]
+        ldr      r8,[r3,#0x700]
+        add      r4,r4,#0x200
+        smlal    r6,r9,r5,r7
+        smull    r6,r2,r5,r8
+        ldr      r5,[r1,#0xc]
+        sub      r11,r11,r2
+        smlal    r8,r9,r5,r8
+        smlal    r7,r11,r5,r7
+        ldr      r5,[r3,#0x100]
+        ldr      r2,[r1,#0x10]
+        ldr      r6,[r12,#0x680]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x14]
+        ldr      r7,[r12,#0x180]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x18]
+        ldr      r8,[r3,#0x600]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x1c]
+        sub      r11,r11,r5
+        smlal    r8,r9,r6,r8
+        ldr      r2,[r1,#0x20]
+        ldr      r5,[r3,#0x200]
+        smlal    r7,r11,r6,r7
+        ldr      r6,[r12,#0x580]
+        smlal    lr,r9,r2,r5
+        smlal    lr,r11,r2,r6
+        ldr      r2,[r1,#0x24]
+        ldr      r7,[r12,#0x280]
+        smlal    r5,r11,r2,r5
+        smull    r6,r5,r2,r6
+        ldr      r6,[r1,#0x28]
+        ldr      r8,[r3,#0x500]
+        sub      r9,r9,r5
+        smlal    r5,r9,r6,r7
+        smull    r2,r5,r6,r8
+        ldr      r6,[r1,#0x2c]
+        sub      r11,r11,r5
+
+        smlal    r8,r9,r6,r8
+        smlal    r7,r11,r6,r7
+        ldr      r5,[r3,#0x300]
+        ldr      r8,[r1,#0x30]
+        ldr      r6,[r12,#0x480]
+        smlal    r7,r9,r8,r5
+        smlal    r7,r11,r8,r6
+        ldr      r8,[r1,#0x34]
+        ldr      r12,[r12,#0x380]
+        smlal    r5,r11,r8,r5
+        smull    r6,r5,r8,r6
+        ldr      r6,[r1,#0x38]
+
+
+        ldr      r3,[r3,#0x400]
+        sub      r9,r9,r5
+        smlal    r7,r9,r6,r12
+        smull    r8,r7,r6,r3
+        cmp      r4,#0x210
+        sub      r11,r11,r7
+
+        ldr      r2,[r1,#0x3c]
+        add      r1,r1,#0x40
+        smlal    r3,r9,r2,r3
+        smlal    r12,r11,r2,r12
+
+        blt      Loop_i
+
+        mov      r3,r9, asr #6
+        mov      r4,r3, asr #15
+        teq      r4,r3, asr #31
+        ldr      r12,LOW_16BITS
+        ldr      r2,[sp]
+        eorne    r3,r12,r3,asr #31
+        ldr      r4,[sp,#8]
+        mov      r2,r10,lsl r2
+        add      r4,r4,r2,lsl #1
+        strh     r3,[r4]
+
+        mov      r3,r11,asr #6
+        mov      r4,r3,asr #15
+        teq      r4,r3,asr #31
+        eorne    r3,r12,r3,asr #31
+        ldr      r12,[sp,#0xc]
+        ldr      r11,[sp,#8]
+        rsb      r2,r2,r12,lsl #5
+        add      r2,r11,r2,lsl #1
+        strh     r3,[r2]
+
+        add      r10,r10,#1
+        cmp      r10,#0x10
+        blt      Loop_j
+
+; Accumulators r4, r5 Initialization
+
+        mov      r4,#0x20
+        mov      r5,#0x20
+        mov      r3,#0x10
+PolyPh_filter_loop2
+        add      r2,r0,r3,lsl #2
+        ldr      r12,[r2]
+        ldr      r8,[r1]
+        ldr      r6,[r2,#0x80]
+        smlal    r12,r4,r8,r12
+        ldr      r12,[r1,#4]
+        ldr      r7,[r2,#0x40]
+        smlal    r6,r4,r12,r6
+
+        ldr      r12,[r1,#8]
+        ldr      r6,[r2,#0x180]
+        smlal    r7,r5,r12,r7
+        ldr      r12,[r2,#0x100]
+        ldr      r7,[r1,#0xc]
+        ldr      r2,[r2,#0x140]
+        smlal    r12,r4,r7,r12
+        ldr      r12,[r1,#0x10]
+        add      r3,r3,#0x80
+        smlal    r6,r4,r12,r6
+        ldr      r6,[r1,#0x14]
+        cmp      r3,#0x210
+        smlal    r2,r5,r6,r2
+        add      r1,r1,#0x18
+
+        blt      PolyPh_filter_loop2
+        mov      r0,r4,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r1,[sp,#8]
+        eorne    r0,r12,r0,asr #31
+        strh     r0,[r1,#0]
+        mov      r0,r5,asr #6
+        mov      r2,r0,asr #15
+        teq      r2,r0,asr #31
+        ldrne    r12,LOW_16BITS
+        ldr      r2,[sp]
+        mov      r1,#0x10
+        eorne    r0,r12,r0,asr #31
+        ldr      r12,[sp,#8]
+        mov      r1,r1,lsl r2
+        add      r1,r12,r1,lsl #1
+        strh     r0,[r1]
+        add      sp,sp,#0x10
+        ldmfd    sp!,{r4-r11,pc}
+
+
+PolyPh_filter_coeff
+        DCD      pqmfSynthWin
+LOW_16BITS
+        DCD      0x00007fff
+	
+		ENDP  ; |pvmp3_polyphase_filter_window|
+		END
+
diff --git a/media/libstagefright/codecs/mp3dec/src/mp3_mem_funcs.h b/media/libstagefright/codecs/mp3dec/src/mp3_mem_funcs.h
new file mode 100644
index 0000000..46e8022
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/mp3_mem_funcs.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: mp3_mem_funcs.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+------------------------------------------------------------------------------
+
+
+----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef MP3_MEM_FUNCS_H
+#define MP3_MEM_FUNCS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include <string.h>
+
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+#define pv_memset(to, c, n)         memset(to, c, n)
+
+
+#define pv_memcpy(to, from, n)      memcpy(to, from, n)
+#define pv_memmove(to, from, n)     memmove(to, from, n)
+#define pv_memcmp(p, q, n)          memcmp(p, q, n)
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+
+#endif
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3_huffman.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3_huffman.h
new file mode 100644
index 0000000..31102ea
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3_huffman.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pv_mp3_huffman.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+*/
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef PV_MP3_HUFFMAN_H
+#define PV_MP3_HUFFMAN_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+#include "s_tmp3dec_file.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int32 pvmp3_huffman_parsing(int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    granuleInfo *grInfo,
+    tmp3dec_file   *pVars,
+    int32 part2_start,
+    mp3Header *info);
+
+
+    void pvmp3_huffman_quad_decoding(struct huffcodetab *h,
+                                     int32 *is,
+                                     tmp3Bits *pMainData);
+
+    void pvmp3_huffman_pair_decoding(struct huffcodetab *h,
+                                     int32 *is,
+                                     tmp3Bits *pMainData);
+
+
+    void pvmp3_huffman_pair_decoding_linbits(struct huffcodetab *h,
+            int32 *is,
+            tmp3Bits *pMainData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op.h
new file mode 100644
index 0000000..f14e2de
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op.h
@@ -0,0 +1,84 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pv_mp3dec_fxd_op.h
+
+     Date: 09/21/2007
+
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file select the associated fixed point functions with the OS/ARCH.
+
+
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_MP3DEC_FXD_OP_H
+#define PV_MP3DEC_FXD_OP_H
+
+#include "pvmp3_audio_type_defs.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#if (defined(PV_ARM_V5)||defined(PV_ARM_V4))
+
+#include "pv_mp3dec_fxd_op_arm.h"
+
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+#include "pv_mp3dec_fxd_op_arm_gcc.h"
+
+#elif (defined(PV_ARM_MSC_EVC_V5)||defined(PV_ARM_MSC_EVC_V4))
+
+#include "pv_mp3dec_fxd_op_msc_evc.h"
+
+#else
+
+#ifndef C_EQUIVALENT
+#define C_EQUIVALENT
+#endif
+
+#include "pv_mp3dec_fxd_op_c_equivalent.h"
+
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+
+#endif  /* PV_MP3DEC_FXD_OP_H */
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h
new file mode 100644
index 0000000..76a8229
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm.h
@@ -0,0 +1,203 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./cpp/include/pv_mp3dec_fxd_op_arm.h
+
+     Date: 08/20/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file select the associated fixed point functions with the OS/ARCH.
+
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_MP3DEC_FXD_OP_ARM
+#define PV_MP3DEC_FXD_OP_ARM
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "pvmp3_audio_type_defs.h"
+
+
+#if (defined(PV_ARM_V5)||defined(PV_ARM_V4))
+
+
+    __inline  Int32 fxp_mul32_Q30(const Int32 L_var1, const Int32 L_var2)
+    {
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov   result64_lo, result64_lo, lsr #30
+            add   result64_hi, result64_lo, result64_hi, asl  #2
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mac32_Q30(const Int32 L_var1, const Int32 L_var2, Int32 L_add)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            add L_add, L_add, result64_hi, asl  #2
+            add L_add, L_add, result64_lo, lsr  #30
+        }
+        return (L_add);
+    }
+
+
+
+#define Qfmt_31(a)   (Int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+
+
+    __inline  Int32 fxp_mul32_Q32(Int32 L_var1, const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        __asm
+        {
+            smull L_var1, result64_hi, L_var2, L_var1
+        }
+        return (result64_hi);
+    }
+
+    __inline  Int32 fxp_mul32_Q28(const Int32 L_var1, const Int32 L_var2)
+    {
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov   result64_lo, result64_lo, lsr #28
+            add   result64_hi, result64_lo, result64_hi, asl  #4
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q27(const Int32 L_var1, const Int32 L_var2)
+    {
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov   result64_lo, result64_lo, lsr #27
+            add   result64_hi, result64_lo, result64_hi, asl  #5
+        }
+        return (result64_hi);
+    }
+
+
+    __inline  Int32 fxp_mul32_Q26(Int32 L_var1,  Int32 L_var2)
+    {
+
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov   result64_lo, result64_lo, lsr #26
+            add   result64_hi, result64_lo, result64_hi, asl  #6
+        }
+        return (result64_hi);
+    }
+
+
+
+    __inline  Int32 fxp_mac32_Q32(Int32 L_add,  Int32 L_var1, const Int32 L_var2)
+    {
+        __asm
+        {
+            smlal L_var1, L_add, L_var2, L_var1
+        }
+        return L_add;
+    }
+
+
+    __inline  Int32 fxp_msb32_Q32(Int32 L_sub,  Int32 L_var1, Int32 L_var2)
+    {
+
+        __asm
+        {
+            smull  L_var2, L_var1, L_var2, L_var1
+            sub  L_sub, L_sub, L_var1
+        }
+        return L_sub;
+    }
+
+
+    __inline  Int32 fxp_mul32_Q29(const Int32 L_var1,  const Int32 L_var2)
+    {
+        Int32 result64_hi;
+        Int32 result64_lo;
+        __asm
+        {
+            smull result64_lo, result64_hi, L_var2, L_var1
+            mov   result64_lo, result64_lo, lsr #29
+            add   result64_hi, result64_lo, result64_hi, asl  #3
+        }
+        return (result64_hi);
+    }
+
+
+    __inline int32 pv_abs(int32 a)
+    {
+        Int32 b;
+        /*
+            b = a - (a<0);
+            a = b ^ sign(b)
+         */
+        __asm
+        {
+            sub  b, a, a, lsr #31
+            eor  a, b, b, asr #31
+        }
+        return (a);
+    }
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  PV_MP3DEC_FXD_OP_ARM  */
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h
new file mode 100644
index 0000000..71fbd20
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_arm_gcc.h
@@ -0,0 +1,252 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./cpp/include/pv_mp3dec_fxd_op_arm_gcc.h
+
+     Date: 08/20/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file select the associated fixed point functions with the OS/ARCH.
+
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_MP3DEC_FXD_OP_ARM_GCC_H
+#define PV_MP3DEC_FXD_OP_ARM_GCC_H
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "pvmp3_audio_type_defs.h"
+
+
+#if (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+#define Qfmt_31(a)   (int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+#define Qfmt15(x)   (Int16)(x*((int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+    static inline int32 fxp_mul32_Q30(const int32 a, const int32 b)
+    {
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov   %1, %1, lsr #30\n\t"
+                     "add   %0, %1, %0, asl #2"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+    }
+
+
+    static inline int32 fxp_mac32_Q30(const int32 a, const int32 b, int32 L_add)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        register int32 rc = (int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %4, %4, %0, asl #2\n\t"
+                     "add %0, %4, %1, lsr #30"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+
+
+    static inline int32 fxp_mul32_Q32(const int32 a, const int32 b)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile(
+            "smull %1, %0, %2, %3"
+    : "=&r*i"(result64_hi),
+            "=&r*i"(result64_lo)
+                    : "r"(ra),
+                    "r"(rb));
+
+        return (result64_hi);
+    }
+
+
+    static inline int32 fxp_mul32_Q29(const int32 a, const int32 b)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov   %1, %1, lsr #29\n\t"
+                     "add   %0, %1, %0, asl #3"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+
+    }
+
+    static inline int32 fxp_mul32_Q28(const int32 a, const int32 b)
+{
+
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov   %1, %1, lsr #28\n\t"
+                     "add   %0, %1, %0, asl #4"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+
+    }
+
+
+    static inline int32 fxp_mul32_Q27(const int32 a, const int32 b)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov   %1, %1, lsr #27\n\t"
+                     "add   %0, %1, %0, asl #5"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+
+    }
+
+
+    static inline int32 fxp_mul32_Q26(const int32 a, const int32 b)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "mov   %1, %1, lsr #26\n\t"
+                     "add   %0, %1, %0, asl #6"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb));
+        return (result64_hi);
+
+    }
+
+
+
+    static inline int32 fxp_mac32_Q32(int32 L_add, const int32 a, const int32 b)
+{
+
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        register int32 rc = (int32)L_add;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "add %0, %0, %4"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+        return (result64_hi);
+    }
+
+    static inline int32 fxp_msb32_Q32(int32 L_sub, const int32 a, const int32 b)
+{
+        int32 result64_hi;
+        int32 result64_lo;
+        register int32 ra = (int32)a;
+        register int32 rb = (int32)b;
+        register int32 rc = (int32)L_sub;
+
+        asm volatile("smull %1, %0, %2, %3\n\t"
+                     "sub %0, %4, %0"
+             : "=&r*i"(result64_hi),
+                     "=&r*i"(result64_lo)
+                             : "r"(ra),
+                             "r"(rb),
+                             "r"(rc));
+
+
+        return (result64_hi);
+    }
+
+
+    __inline int32 pv_abs(int32 x)
+{
+        register int32 z;
+        register int32 y;
+        register int32 ra = x;
+        asm volatile(
+            "sub  %0, %2, %2, lsr #31\n\t"
+            "eor  %1, %0, %0, asr #31"
+    : "=&r*i"(z),
+            "=&r*i"(y)
+                    : "r"(ra));
+
+        return (y);
+    }
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  PV_MP3DEC_FXD_OP_ARM_GCC_H  */
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.h
new file mode 100644
index 0000000..ba43820
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_c_equivalent.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./cpp/include/pv_mp3dec_fxd_op_c_equivalent.h
+
+     Date: 12/06/2005
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_MP3DEC_FXD_OP_C_EQUIVALENT
+#define PV_MP3DEC_FXD_OP_C_EQUIVALENT
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "pvmp3_audio_type_defs.h"
+#define Qfmt_31(a)   (Int32)((float)a*0x7FFFFFFF)
+
+#define Qfmt15(x)   (Int16)(x*((Int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+
+
+    __inline int32 pv_abs(int32 a)
+    {
+        int32 b = (a < 0) ? -a : a;
+        return b;
+    }
+
+
+
+
+    __inline Int32 fxp_mul32_Q30(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 30);
+    }
+
+    __inline Int32 fxp_mac32_Q30(const Int32 a, const Int32 b, Int32 L_add)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 30));
+    }
+
+    __inline Int32 fxp_mul32_Q32(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 32);
+    }
+
+
+    __inline Int32 fxp_mul32_Q28(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 28);
+    }
+
+    __inline Int32 fxp_mul32_Q27(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 27);
+    }
+
+    __inline Int32 fxp_mul32_Q26(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 26);
+    }
+
+
+    __inline Int32 fxp_mac32_Q32(Int32 L_add, const Int32 a, const Int32 b)
+    {
+        return (L_add + (Int32)(((int64)(a) * b) >> 32));
+    }
+
+    __inline Int32 fxp_msb32_Q32(Int32 L_sub, const Int32 a, const Int32 b)
+    {
+        return (L_sub - ((Int32)(((int64)(a) * b) >> 32)));
+    }
+
+
+    __inline Int32 fxp_mul32_Q29(const Int32 a, const Int32 b)
+    {
+        return (Int32)(((int64)(a) * b) >> 29);
+    }
+
+
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  PV_MP3DEC_FXD_OP_C_EQUIVALENT  */
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h
new file mode 100644
index 0000000..271e6b7
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pv_mp3dec_fxd_op_msc_evc.h
@@ -0,0 +1,132 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./cpp/include/pv_mp3dec_fxd_op_msc_evc.h
+
+     Date: 08/20/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This file select the associated fixed point functions with the OS/ARCH.
+
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PV_MP3DEC_FXD_OP_MSC_EVC_H
+#define PV_MP3DEC_FXD_OP_MSC_EVC_H
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#include "pvmp3_audio_type_defs.h"
+
+
+#if (defined(PV_ARM_MSC_EVC_V5)||defined(PV_ARM_MSC_EVC_V4))
+#include "armintr.h"
+#include "cmnintrin.h"
+
+
+    __inline int32 fxp_mul32_Q30(const int32 a, const int32 b)
+    {
+        return (int32)(((int64)(a) * b) >> 30);
+    }
+
+
+    __inline int32 fxp_mac32_Q30(const int32 a, const int32 b, int32 L_add)
+    {
+        return (L_add + (int32)(((int64)(a) * b) >> 30));
+    }
+
+
+#define Qfmt_31(a)   (int32)(a*0x7FFFFFFF + (a>=0?0.5F:-0.5F))
+
+#define Qfmt15(x)   (Int16)(x*((int32)1<<15) + (x>=0?0.5F:-0.5F))
+
+#define fxp_mul32_Q32( a,  b)   _MulHigh( b, a)
+
+
+
+    __inline int32 fxp_mul32_Q28(const int32 a, const int32 b)
+    {
+        return (int32)(((int64)(a) * b) >> 28);
+    }
+
+
+    __inline int32 fxp_mul32_Q27(const int32 a, const int32 b)
+    {
+        return (int32)(((int64)(a) * b) >> 27);
+    }
+
+
+
+    __inline int32 fxp_mul32_Q26(const int32 a, const int32 b)
+    {
+        return (int32)(((int64)(a) * b) >> 26);
+    }
+
+
+    __inline int32 fxp_mac32_Q32(int32 L_add, const int32 a, const int32 b)
+    {
+        return (L_add + _MulHigh(b, a));
+    }
+
+
+    __inline int32 fxp_msb32_Q32(int32 L_sub, const int32 a, const int32 b)
+    {
+        return (L_sub - _MulHigh(b, a));
+    }
+
+
+
+    __inline int32 fxp_mul32_Q29(const int32 a, const int32 b)
+    {
+        return (int32)(((int64)(a) * b) >> 29);
+    }
+
+
+
+    __inline int32 pv_abs(int32 a)
+    {
+        int32 b = (a < 0) ? -a : a;
+        return b;
+    }
+
+
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif   /*  PV_MP3DEC_FXD_OP_MSC_EVC_H  */
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
new file mode 100644
index 0000000..32c76c6
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.cpp
@@ -0,0 +1,261 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_alias_reduction.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    int32 *input_buffer,          Ptr to fequency lines of current channel
+    struct gr_info_s *gr_info,    structure with granuke information for the
+                                  input
+    mp3Header *info               mp3 header information
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Alias Reduction
+
+
+
+    Alias reduction before processing by the IMDCT
+
+                   Csi  +
+     >---------0---------0-------->
+                \       / -
+             Cai \     /
+                  \   /
+                   \ /
+                    \
+                  /  \
+             Cai /    \
+               /       \  +
+     >--------0---------0---------->
+                  Csi  +
+
+      Aliasing Butterfly
+      Alias reduction is not applied to short blocks
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+                1                                ci
+  csi = ----------------           csi = ----------------
+        sqrt( 1 + (ci^2))                sqrt( 1 + (ci^2))
+
+
+  ci = -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037
+
+ ------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_alias_reduction.h"
+#include "pv_mp3dec_fxd_op.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define NUM_BUTTERFLIES 8
+
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int32 c_signal [ NUM_BUTTERFLIES ] =
+{
+
+    Q31_fmt(0.85749292571254f), Q31_fmt(0.88174199731771f),
+    Q31_fmt(0.94962864910273f), Q31_fmt(0.98331459249179f),
+    Q31_fmt(0.99551781606759f), Q31_fmt(0.99916055817815f),
+    Q31_fmt(0.99989919524445f), Q31_fmt(0.99999315507028f)
+
+};
+
+
+const int32 c_alias [ NUM_BUTTERFLIES ] =
+{
+
+    Q31_fmt(-0.51449575542753f), Q31_fmt(-0.47173196856497f),
+    Q31_fmt(-0.31337745420390f), Q31_fmt(-0.18191319961098f),
+    Q31_fmt(-0.09457419252642f), Q31_fmt(-0.04096558288530f),
+    Q31_fmt(-0.01419856857247f), Q31_fmt(-0.00369997467376f)
+};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_alias_reduction(int32 *input_buffer,         /* Ptr to spec values of current channel */
+                           granuleInfo *gr_info,
+                           int32  *used_freq_lines,
+                           mp3Header *info)
+{
+    int32 *ptr1;
+    int32 *ptr2;
+    int32 *ptr3;
+    int32 *ptr4;
+    const int32 *ptr_csi;
+    const int32 *ptr_csa;
+    int32  sblim;
+
+    int32 i, j;
+
+    *used_freq_lines = fxp_mul32_Q32(*used_freq_lines << 16, (int32)(0x7FFFFFFF / (float)18 - 1.0f)) >> 15;
+
+
+    if (gr_info->window_switching_flag &&  gr_info->block_type == 2)
+    {
+        if (gr_info->mixed_block_flag)
+        {
+            sblim = ((info->version_x == MPEG_2_5) && (info->sampling_frequency == 2)) ? 3 : 1;
+        }
+        else
+        {
+            return;  /* illegal parameter */
+        }
+    }
+    else
+    {
+        sblim = *used_freq_lines + 1;
+
+        if (sblim > SUBBANDS_NUMBER - 1)
+        {
+            sblim = SUBBANDS_NUMBER - 1;  /* default */
+        }
+
+    }
+
+
+    ptr3 = &input_buffer[17];
+    ptr4 = &input_buffer[18];
+    ptr_csi = c_signal;
+    ptr_csa = c_alias;
+
+    /*   NUM_BUTTERFLIES (=8) butterflies between each pair of sub-bands*/
+
+    for (i = NUM_BUTTERFLIES >> 1; i != 0; i--)
+    {
+        int32 csi1  = *ptr_csi++;
+        int32 csi2  = *ptr_csi++;
+        int32 csa1  = *ptr_csa++;
+        int32 csa2  = *ptr_csa++;
+
+        ptr1 = ptr3;
+        ptr3 -= 2;
+        ptr2 = ptr4;
+        ptr4 += 2;
+
+        /*
+         *  "sblim"  alias-reduction operations between each
+         *  pair of sub-bands
+         */
+
+        for (j = sblim >> 1; j != 0; j--)
+        {
+            int32 y = *ptr2;
+            int32 x = *ptr1 << 1;
+            *ptr1--  = fxp_msb32_Q32(fxp_mul32_Q32(x, csi1), y << 1, csa1);
+            *ptr2++  = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi1), x, csa1);
+            y = *ptr2;
+            x = *ptr1 << 1;
+            *ptr1    = fxp_msb32_Q32(fxp_mul32_Q32(x, csi2), y << 1, csa2);
+            *ptr2    = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi2), x, csa2);
+            ptr1 += 19;
+            ptr2 += 17;
+            y = *ptr2;
+            x = *ptr1 << 1;
+            *ptr1--  = fxp_msb32_Q32(fxp_mul32_Q32(x, csi1), y << 1, csa1);
+            *ptr2++  = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi1), x, csa1);
+            y = *ptr2;
+            x = *ptr1 << 1;
+            *ptr1    = fxp_msb32_Q32(fxp_mul32_Q32(x, csi2), y << 1, csa2);
+            *ptr2    = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi2), x, csa2);
+            ptr1 += 19;
+            ptr2 += 17;
+
+        }
+
+        if (sblim & 1)
+        {
+            int32 x = *ptr1 << 1;
+            int32 y = *ptr2;
+            *ptr1--  = fxp_msb32_Q32(fxp_mul32_Q32(x, csi1), y << 1, csa1);
+            *ptr2++  = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi1), x, csa1);
+
+            x = *ptr1 << 1;
+            y = *ptr2;
+            *ptr1    = fxp_msb32_Q32(fxp_mul32_Q32(x, csi2), y << 1, csa2);
+            *ptr2    = fxp_mac32_Q32(fxp_mul32_Q32(y << 1, csi2), x, csa2);
+        }
+    }
+
+}
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.h
new file mode 100644
index 0000000..2292d5f
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_alias_reduction.h
@@ -0,0 +1,100 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_alias_reduction.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_ALIAS_REDUCTION_H
+#define PVMP3_ALIAS_REDUCTION_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_alias_reduction(int32 *input_buffer,
+    granuleInfo *gr_info,
+    int32 *used_freq_lines,
+    mp3Header *info);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.cpp
new file mode 100644
index 0000000..20d0d82
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.cpp
@@ -0,0 +1,161 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_crc.cpp
+
+   Functions:
+        getbits_crc
+        calculate_crc
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+getbits_crc
+
+Input
+    tbits *inputStream,     bit stream structure
+    int32 neededBits,       number of bits to read from the bit stream
+    uint32 *crc,            memory location holding calculated crc value
+    uint32 crc_enabled      flag to enable/disable crc checking
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+calculate_crc
+
+Input
+    uint32 data,            data vector
+    uint32 length,          number of element upon the crc will be calculated
+    uint32 *crc,            memory location holding calculated crc value
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+ ------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_getbits.h"
+#include "pvmp3_crc.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
+----------------------------------------------------------------------------*/
+
+uint32 getbits_crc(tmp3Bits *inputStream,  /* bit stream structure */
+                   int32 neededBits, /* number of bits to read from the bit stream */
+                   uint32 *crc,
+                   uint32 crc_enabled)
+{
+    uint32 bits = getNbits(inputStream, neededBits);
+
+    if (crc_enabled)
+    {
+        calculate_crc(bits, neededBits, crc);
+    }
+    return(bits);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void calculate_crc(uint32 data,
+                   uint32 length,
+                   uint32 *crc)
+{
+    uint32  carry;
+    uint32  masking = 1 << length;
+
+    while ((masking >>= 1))
+    {
+        carry = *crc & 0x8000;
+        *crc <<= 1;
+        if (!carry ^ !(data & masking))
+        {
+            *crc ^= CRC16_POLYNOMIAL;
+        }
+    }
+    *crc &= 0xffff;
+}
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.h
new file mode 100644
index 0000000..b7c277a
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_crc.h
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_crc.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_CRC_H
+#define PVMP3_CRC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+#include "pvmp3decoder_api.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define         CRC16_POLYNOMIAL        0x8005
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    uint32 getbits_crc(tmp3Bits *inputStream,
+    int32 neededBits,
+    uint32 *crc,
+    uint32 crc_enabled);
+
+
+    void calculate_crc(uint32 data,
+                       uint32 length,
+                       uint32 *crc);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
new file mode 100644
index 0000000..a71efc4
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.cpp
@@ -0,0 +1,410 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dct_16.cpp
+
+   Functions:
+    dct_16
+    pv_merge_in_place_N32
+    pv_split
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    dct_16
+
+Input
+    int32 vec[],        input vector length 16
+    Int flag            processing direction: forward (1), backward ( 0)
+ Returns
+
+    int32 vec[],        dct length 16
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    pv_merge_in_place_N32
+
+Input
+    int32 vec[],        input vector length 16
+
+ Returns
+
+    int32 vec[],        merged  output of two dct 16 to create a dct 32
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+    pv_split
+
+Input
+    int32 vec[],        input vector length 16
+
+ Returns
+
+    int32 vec[],        splitted even/odd and pre processing rotation
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    dct 16 and tools to assemble a dct32 output
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#if ( !defined(PV_ARM_GCC_V5) && !defined(PV_ARM_GCC_V4) )
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dct_16.h"
+#include "pv_mp3dec_fxd_op.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define Qfmt(a)   (int32)(a*((int32)1<<27))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int32 CosTable_dct32[16] =
+{
+    Qfmt_31(0.50060299823520F) ,  Qfmt_31(0.50547095989754F) ,
+    Qfmt_31(0.51544730992262F) ,  Qfmt_31(0.53104259108978F) ,
+    Qfmt_31(0.55310389603444F) ,  Qfmt_31(0.58293496820613F) ,
+    Qfmt_31(0.62250412303566F) ,  Qfmt_31(0.67480834145501F) ,
+    Qfmt_31(0.74453627100230F) ,  Qfmt_31(0.83934964541553F) ,
+
+    Qfmt(0.97256823786196F) ,  Qfmt(1.16943993343288F) ,
+    Qfmt(1.48416461631417F) ,  Qfmt(2.05778100995341F) ,
+    Qfmt(3.40760841846872F) ,  Qfmt(10.19000812354803F)
+};
+
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_dct_16(int32 vec[], int32 flag)
+{
+    int32 tmp0;
+    int32 tmp1;
+    int32 tmp2;
+    int32 tmp3;
+    int32 tmp4;
+    int32 tmp5;
+    int32 tmp6;
+    int32 tmp7;
+    int32 tmp_o0;
+    int32 tmp_o1;
+    int32 tmp_o2;
+    int32 tmp_o3;
+    int32 tmp_o4;
+    int32 tmp_o5;
+    int32 tmp_o6;
+    int32 tmp_o7;
+    int32 itmp_e0;
+    int32 itmp_e1;
+    int32 itmp_e2;
+
+    /*  split input vector */
+
+    tmp_o0 = fxp_mul32_Q32((vec[ 0] - vec[15]), Qfmt_31(0.50241928618816F));
+    tmp0   =  vec[ 0] + vec[15];
+
+    tmp_o7 = fxp_mul32_Q32((vec[ 7] - vec[ 8]) << 3, Qfmt_31(0.63764357733614F));
+    tmp7   =  vec[ 7] + vec[ 8];
+
+    itmp_e0    = fxp_mul32_Q32((tmp0 - tmp7), Qfmt_31(0.50979557910416F));
+    tmp7 = (tmp0 + tmp7);
+
+    tmp_o1 = fxp_mul32_Q32((vec[ 1] - vec[14]), Qfmt_31(0.52249861493969F));
+    tmp1   =  vec[ 1] + vec[14];
+
+    tmp_o6 = fxp_mul32_Q32((vec[ 6] - vec[ 9]) << 1, Qfmt_31(0.86122354911916F));
+    tmp6   =  vec[ 6] + vec[ 9];
+
+
+
+    itmp_e1 = (tmp1 + tmp6);
+    tmp6    = fxp_mul32_Q32((tmp1 - tmp6), Qfmt_31(0.60134488693505F));
+
+
+
+    tmp_o2 = fxp_mul32_Q32((vec[ 2] - vec[13]), Qfmt_31(0.56694403481636F));
+    tmp2   =  vec[ 2] + vec[13];
+    tmp_o5 = fxp_mul32_Q32((vec[ 5] - vec[10]) << 1, Qfmt_31(0.53033884299517F));
+    tmp5   =  vec[ 5] + vec[10];
+
+    itmp_e2 = (tmp2 + tmp5);
+    tmp5    = fxp_mul32_Q32((tmp2 - tmp5), Qfmt_31(0.89997622313642F));
+
+    tmp_o3 = fxp_mul32_Q32((vec[ 3] - vec[12]), Qfmt_31(0.64682178335999F));
+    tmp3   =  vec[ 3] + vec[12];
+    tmp_o4 = fxp_mul32_Q32((vec[ 4] - vec[11]), Qfmt_31(0.78815462345125F));
+    tmp4   =  vec[ 4] + vec[11];
+
+    tmp1   = (tmp3 + tmp4);
+    tmp4   =  fxp_mul32_Q32((tmp3 - tmp4) << 2, Qfmt_31(0.64072886193538F));
+
+    /*  split even part of tmp_e */
+
+    tmp0 = (tmp7 + tmp1);
+    tmp1 = fxp_mul32_Q32((tmp7 - tmp1), Qfmt_31(0.54119610014620F));
+
+    tmp3 = fxp_mul32_Q32((itmp_e1 - itmp_e2) << 1, Qfmt_31(0.65328148243819F));
+    tmp7 = (itmp_e1 + itmp_e2);
+
+    vec[ 0]  = (tmp0 + tmp7) >> 1;
+    vec[ 8]  = fxp_mul32_Q32((tmp0 - tmp7), Qfmt_31(0.70710678118655F));
+    tmp0     = fxp_mul32_Q32((tmp1 - tmp3) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 4]  =  tmp1 + tmp3 + tmp0;
+    vec[12]  =  tmp0;
+
+    /*  split odd part of tmp_e */
+
+    tmp1 = fxp_mul32_Q32((itmp_e0 - tmp4) << 1, Qfmt_31(0.54119610014620F));
+    tmp7 = itmp_e0 + tmp4;
+
+    tmp3  = fxp_mul32_Q32((tmp6 - tmp5) << 2, Qfmt_31(0.65328148243819F));
+    tmp6 += tmp5;
+
+    tmp4  = fxp_mul32_Q32((tmp7 - tmp6) << 1, Qfmt_31(0.70710678118655F));
+    tmp6 += tmp7;
+    tmp7  = fxp_mul32_Q32((tmp1 - tmp3) << 1, Qfmt_31(0.70710678118655F));
+
+    tmp1    +=  tmp3 + tmp7;
+    vec[ 2]  =  tmp1 + tmp6;
+    vec[ 6]  =  tmp1 + tmp4;
+    vec[10]  =  tmp7 + tmp4;
+    vec[14]  =  tmp7;
+
+
+    // dct8;
+
+    tmp1 = fxp_mul32_Q32((tmp_o0 - tmp_o7) << 1, Qfmt_31(0.50979557910416F));
+    tmp7 = tmp_o0 + tmp_o7;
+
+    tmp6   = tmp_o1 + tmp_o6;
+    tmp_o1 = fxp_mul32_Q32((tmp_o1 - tmp_o6) << 1, Qfmt_31(0.60134488693505F));
+
+    tmp5   = tmp_o2 + tmp_o5;
+    tmp_o5 = fxp_mul32_Q32((tmp_o2 - tmp_o5) << 1, Qfmt_31(0.89997622313642F));
+
+    tmp0 = fxp_mul32_Q32((tmp_o3 - tmp_o4) << 3, Qfmt_31(0.6407288619354F));
+    tmp4 = tmp_o3 + tmp_o4;
+
+    if (!flag)
+    {
+        tmp7   = -tmp7;
+        tmp1   = -tmp1;
+        tmp6   = -tmp6;
+        tmp_o1 = -tmp_o1;
+        tmp5   = -tmp5;
+        tmp_o5 = -tmp_o5;
+        tmp4   = -tmp4;
+        tmp0   = -tmp0;
+    }
+
+
+    tmp2     =  fxp_mul32_Q32((tmp1 -   tmp0) << 1, Qfmt_31(0.54119610014620F));
+    tmp0    +=  tmp1;
+    tmp1     =  fxp_mul32_Q32((tmp7 -   tmp4) << 1, Qfmt_31(0.54119610014620F));
+    tmp7    +=  tmp4;
+    tmp4     =  fxp_mul32_Q32((tmp6 -   tmp5) << 2, Qfmt_31(0.65328148243819F));
+    tmp6    +=  tmp5;
+    tmp5     =  fxp_mul32_Q32((tmp_o1 - tmp_o5) << 2, Qfmt_31(0.65328148243819F));
+    tmp_o1  += tmp_o5;
+
+
+    vec[13]  =  fxp_mul32_Q32((tmp1 -   tmp4) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 5]  =  tmp1 + tmp4 + vec[13];
+
+    vec[ 9]  =  fxp_mul32_Q32((tmp7 -   tmp6) << 1, Qfmt_31(0.70710678118655F));
+    vec[ 1]  =  tmp7 + tmp6;
+
+    tmp4     =  fxp_mul32_Q32((tmp0 - tmp_o1) << 1, Qfmt_31(0.70710678118655F));
+    tmp0    +=  tmp_o1;
+    tmp6     =  fxp_mul32_Q32((tmp2 -   tmp5) << 1, Qfmt_31(0.70710678118655F));
+    tmp2    +=  tmp5 + tmp6;
+    tmp0    +=  tmp2;
+
+    vec[ 1] += tmp0;
+    vec[ 3]  = tmp0 + vec[ 5];
+    tmp2    += tmp4;
+    vec[ 5]  = tmp2 + vec[ 5];
+    vec[ 7]  = tmp2 + vec[ 9];
+    tmp4    += tmp6;
+    vec[ 9]  = tmp4 + vec[ 9];
+    vec[11]  = tmp4 + vec[13];
+    vec[13]  = tmp6 + vec[13];
+    vec[15]  = tmp6;
+
+}
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void pvmp3_merge_in_place_N32(int32 vec[])
+{
+
+
+    int32 temp0;
+    int32 temp1;
+    int32 temp2;
+    int32 temp3;
+
+    temp0   = vec[14];
+    vec[14] = vec[ 7];
+    temp1   = vec[12];
+    vec[12] = vec[ 6];
+    temp2   = vec[10];
+    vec[10] = vec[ 5];
+    temp3   = vec[ 8];
+    vec[ 8] = vec[ 4];
+    vec[ 6] = vec[ 3];
+    vec[ 4] = vec[ 2];
+    vec[ 2] = vec[ 1];
+
+    vec[ 1] = (vec[16] + vec[17]);
+    vec[16] = temp3;
+    vec[ 3] = (vec[18] + vec[17]);
+    vec[ 5] = (vec[19] + vec[18]);
+    vec[18] = vec[9];
+
+    vec[ 7] = (vec[20] + vec[19]);
+    vec[ 9] = (vec[21] + vec[20]);
+    vec[20] = temp2;
+    temp2   = vec[13];
+    temp3   = vec[11];
+    vec[11] = (vec[22] + vec[21]);
+    vec[13] = (vec[23] + vec[22]);
+    vec[22] = temp3;
+    temp3   = vec[15];
+
+    vec[15] = (vec[24] + vec[23]);
+    vec[17] = (vec[25] + vec[24]);
+    vec[19] = (vec[26] + vec[25]);
+    vec[21] = (vec[27] + vec[26]);
+    vec[23] = (vec[28] + vec[27]);
+    vec[24] = temp1;
+    vec[25] = (vec[29] + vec[28]);
+    vec[26] = temp2;
+    vec[27] = (vec[30] + vec[29]);
+    vec[28] = temp0;
+    vec[29] = (vec[30] + vec[31]);
+    vec[30] = temp3;
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+
+void pvmp3_split(int32 *vect)
+{
+
+    int32 i;
+    const int32 *pt_cosTerms = &CosTable_dct32[15];
+    int32 *pt_vect   = vect;
+    int32 *pt_vect_2 = pt_vect - 1;
+
+    for (i = 3; i != 0; i--)
+    {
+        int32 tmp2 = *(pt_vect);
+        int32 tmp1 = *(pt_vect_2);
+        int32 cosx = *(pt_cosTerms--);
+        *(pt_vect_2--) = (tmp1  + tmp2);
+        *(pt_vect++)   = fxp_mul32_Q27((tmp1 - tmp2), cosx);
+
+        tmp2 = *(pt_vect);
+        tmp1 = *(pt_vect_2);
+        cosx = *(pt_cosTerms--);
+        *(pt_vect_2--) = (tmp1  + tmp2);
+        *(pt_vect++)   = fxp_mul32_Q27((tmp1 - tmp2), cosx);
+
+    }
+
+    for (i = 5; i != 0; i--)
+    {
+        int32 tmp2 = *(pt_vect);
+        int32 tmp1 = *(pt_vect_2);
+        int32 cosx = *(pt_cosTerms--);
+        *(pt_vect_2--) = (tmp1  + tmp2);
+        *(pt_vect++) = fxp_mul32_Q32((tmp1 - tmp2) << 1, cosx);
+
+        tmp2 = *(pt_vect);
+        tmp1 = *(pt_vect_2);
+        cosx = *(pt_cosTerms--);
+        *(pt_vect_2--) = (tmp1  + tmp2);
+        *(pt_vect++) = fxp_mul32_Q32((tmp1 - tmp2) << 1, cosx);
+    }
+
+}
+
+#endif
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.h
new file mode 100644
index 0000000..e8bf76e
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_16.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dct_16.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_DCT_16_H
+#define PVMP3_DCT_16_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_dct_16(int32 vec[], int32 flag);
+
+    void pvmp3_merge_in_place_N32(int32 vec[]);
+
+    void pvmp3_split(int32 *vect);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
new file mode 100644
index 0000000..4c5fb03
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_6.cpp
@@ -0,0 +1,152 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dct6.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    Int32  vec[]             vector of 6  32-bit integers
+Returns
+    Int32  vec[]             dct computation in-place
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns the dct of length 6 of the input vector
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_mdct_6.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define Qfmt30(a)   (Int32)(a*((Int32)1<<30) + (a>=0?0.5F:-0.5F))
+
+#define cos_pi_6     Qfmt30(  0.86602540378444f)
+#define cos_2_pi_6   Qfmt30(  0.5f)
+#define cos_7_pi_12  Qfmt30( -0.25881904510252f)
+#define cos_3_pi_12  Qfmt30(  0.70710678118655f)
+#define cos_11_pi_12 Qfmt30( -0.96592582628907f)
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_dct_6(int32 vec[])
+{
+
+    Int32 tmp0;
+    Int32 tmp1;
+    Int32 tmp2;
+    Int32 tmp3;
+    Int32 tmp4;
+    Int32 tmp5;
+
+
+    /*  split input vector */
+
+    tmp0 =  vec[5] + vec[0];
+    tmp5 =  vec[5] - vec[0];
+    tmp1 =  vec[4] + vec[1];
+    tmp4 =  vec[4] - vec[1];
+    tmp2 =  vec[3] + vec[2];
+    tmp3 =  vec[3] - vec[2];
+
+    vec[0]  = tmp0 + tmp2 ;
+    vec[2]  = fxp_mul32_Q30(tmp0 - tmp2,   cos_pi_6);
+    vec[4]  = (vec[0] >> 1) - tmp1;
+    vec[0] += tmp1;
+
+    tmp0    =  fxp_mul32_Q30(tmp3,  cos_7_pi_12);
+    tmp0    =  fxp_mac32_Q30(tmp4,  -cos_3_pi_12, tmp0);
+    vec[1]  =  fxp_mac32_Q30(tmp5,  cos_11_pi_12, tmp0);
+
+    vec[3]  =  fxp_mul32_Q30((tmp3 + tmp4  - tmp5), cos_3_pi_12);
+    tmp0    =  fxp_mul32_Q30(tmp3, cos_11_pi_12);
+    tmp0    =  fxp_mac32_Q30(tmp4,  cos_3_pi_12, tmp0);
+    vec[5]  =  fxp_mac32_Q30(tmp5,  cos_7_pi_12, tmp0);
+
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
new file mode 100644
index 0000000..ce3ec64
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dct_9.cpp
@@ -0,0 +1,167 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dct_9.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    int32  vec[]             vector of 9  32-bit integers
+Returns
+    int32  vec[]             dct computation in-place
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns the dct of length 9 of the input vector
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#if ( !defined(PV_ARM_GCC_V5) && !defined(PV_ARM_GCC_V4) && !defined(PV_ARM_V5) && !defined(PV_ARM_V4) )
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_mdct_18.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define Qfmt31(a)   (int32)(a*(0x7FFFFFFF))
+
+#define cos_pi_9    Qfmt31( 0.93969262078591f)
+#define cos_2pi_9   Qfmt31( 0.76604444311898f)
+#define cos_4pi_9   Qfmt31( 0.17364817766693f)
+#define cos_5pi_9   Qfmt31(-0.17364817766693f)
+#define cos_7pi_9   Qfmt31(-0.76604444311898f)
+#define cos_8pi_9   Qfmt31(-0.93969262078591f)
+#define cos_pi_6    Qfmt31( 0.86602540378444f)
+#define cos_5pi_6   Qfmt31(-0.86602540378444f)
+#define cos_5pi_18  Qfmt31( 0.64278760968654f)
+#define cos_7pi_18  Qfmt31( 0.34202014332567f)
+#define cos_11pi_18 Qfmt31(-0.34202014332567f)
+#define cos_13pi_18 Qfmt31(-0.64278760968654f)
+#define cos_17pi_18 Qfmt31(-0.98480775301221f)
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_dct_9(int32 vec[])
+{
+
+    /*  split input vector */
+
+    int32 tmp0 =  vec[8] + vec[0];
+    int32 tmp8 =  vec[8] - vec[0];
+    int32 tmp1 =  vec[7] + vec[1];
+    int32 tmp7 =  vec[7] - vec[1];
+    int32 tmp2 =  vec[6] + vec[2];
+    int32 tmp6 =  vec[6] - vec[2];
+    int32 tmp3 =  vec[5] + vec[3];
+    int32 tmp5 =  vec[5] - vec[3];
+
+    vec[0]  = (tmp0 + tmp2 + tmp3)     + (tmp1 + vec[4]);
+    vec[6]  = ((tmp0 + tmp2 + tmp3) >> 1) - (tmp1 + vec[4]);
+    vec[2]  = (tmp1 >> 1) - vec[4];
+    vec[4]  =  -vec[2];
+    vec[8]  =  -vec[2];
+    vec[4]  = fxp_mac32_Q32(vec[4], tmp0 << 1, cos_2pi_9);
+    vec[8]  = fxp_mac32_Q32(vec[8], tmp0 << 1, cos_4pi_9);
+    vec[2]  = fxp_mac32_Q32(vec[2], tmp0 << 1, cos_pi_9);
+    vec[2]  = fxp_mac32_Q32(vec[2], tmp2 << 1, cos_5pi_9);
+    vec[4]  = fxp_mac32_Q32(vec[4], tmp2 << 1, cos_8pi_9);
+    vec[8]  = fxp_mac32_Q32(vec[8], tmp2 << 1, cos_2pi_9);
+    vec[8]  = fxp_mac32_Q32(vec[8], tmp3 << 1, cos_8pi_9);
+    vec[4]  = fxp_mac32_Q32(vec[4], tmp3 << 1, cos_4pi_9);
+    vec[2]  = fxp_mac32_Q32(vec[2], tmp3 << 1, cos_7pi_9);
+
+    vec[1]  = fxp_mul32_Q32(tmp5 << 1, cos_11pi_18);
+    vec[1]  = fxp_mac32_Q32(vec[1], tmp6 << 1, cos_13pi_18);
+    vec[1]  = fxp_mac32_Q32(vec[1], tmp7 << 1,   cos_5pi_6);
+    vec[1]  = fxp_mac32_Q32(vec[1], tmp8 << 1, cos_17pi_18);
+    vec[3]  = fxp_mul32_Q32((tmp5 + tmp6  - tmp8) << 1, cos_pi_6);
+    vec[5]  = fxp_mul32_Q32(tmp5 << 1, cos_17pi_18);
+    vec[5]  = fxp_mac32_Q32(vec[5], tmp6 << 1,  cos_7pi_18);
+    vec[5]  = fxp_mac32_Q32(vec[5], tmp7 << 1,    cos_pi_6);
+    vec[5]  = fxp_mac32_Q32(vec[5], tmp8 << 1, cos_13pi_18);
+    vec[7]  = fxp_mul32_Q32(tmp5 << 1, cos_5pi_18);
+    vec[7]  = fxp_mac32_Q32(vec[7], tmp6 << 1, cos_17pi_18);
+    vec[7]  = fxp_mac32_Q32(vec[7], tmp7 << 1,    cos_pi_6);
+    vec[7]  = fxp_mac32_Q32(vec[7], tmp8 << 1, cos_11pi_18);
+
+}
+
+
+
+#endif // If not assembly
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
new file mode 100644
index 0000000..6cf8e3e
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dec_defs.h
@@ -0,0 +1,199 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dec_defs.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file has the mp3 decoder common defines.
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_DEC_DEFS_H
+#define PVMP3_DEC_DEFS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3decoder_api.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+#define module(x, POW2)   ((x)&(POW2-1))
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define BUFSIZE   8192   // big enough to hold 4608 bytes == biggest mp3 frame
+
+#define CHAN           2
+#define GRAN           2
+
+
+#define SUBBANDS_NUMBER        32
+#define FILTERBANK_BANDS       18
+#define HAN_SIZE              512
+
+
+/* MPEG Header Definitions - ID Bit Values */
+
+#define MPEG_1              0
+#define MPEG_2              1
+#define MPEG_2_5            2
+#define INVALID_VERSION     -1
+
+/* MPEG Header Definitions - Mode Values */
+
+#define MPG_MD_STEREO           0
+#define MPG_MD_JOINT_STEREO     1
+#define MPG_MD_DUAL_CHANNEL     2
+#define MPG_MD_MONO             3
+
+
+
+#define LEFT        0
+#define RIGHT       1
+
+
+#define SYNC_WORD         (int32)0x7ff
+#define SYNC_WORD_LNGTH   11
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    /*----------------------------------------------------------------------------
+    ; STRUCTURES TYPEDEF'S
+    ----------------------------------------------------------------------------*/
+
+    /* Header Information Structure */
+
+    typedef struct
+    {
+        int32 version_x;
+        int32 layer_description;
+        int32 error_protection;
+        int32 bitrate_index;
+        int32 sampling_frequency;
+        int32 padding;
+        int32 extension;
+        int32 mode;
+        int32 mode_ext;
+        int32 copyright;
+        int32 original;
+        int32 emphasis;
+    } mp3Header;
+
+
+    /* Layer III side information. */
+
+    typedef  struct
+    {
+        uint32 part2_3_length;
+        uint32 big_values;
+        int32 global_gain;
+        uint32 scalefac_compress;
+        uint32 window_switching_flag;
+        uint32 block_type;
+        uint32 mixed_block_flag;
+        uint32 table_select[3];
+        uint32 subblock_gain[3];
+        uint32 region0_count;
+        uint32 region1_count;
+        uint32 preflag;
+        uint32 scalefac_scale;
+        uint32 count1table_select;
+
+    } granuleInfo;
+
+    typedef  struct
+    {
+        uint32      scfsi[4];
+        granuleInfo gran[2];
+
+    } channelInfo;
+
+    /* Layer III side info. */
+
+    typedef struct
+    {
+        uint32      main_data_begin;
+        uint32      private_bits;
+        channelInfo ch[2];
+
+    } mp3SideInfo;
+
+    /* Layer III scale factors. */
+    typedef struct
+    {
+        int32 l[23];            /* [cb] */
+        int32 s[3][13];         /* [window][cb] */
+
+    } mp3ScaleFactors;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
new file mode 100644
index 0000000..8b0250a
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_decode_header.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    tbits  *inputStream,        bit stream
+    mp3Header  *info,
+    uint32 *crc
+ Returns
+
+    mp3Header  *info,           structure holding the parsed mp3 header info
+    uint32 *crc                 initialized crc computation
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    gets mp3 header information
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_decode_header.h"
+#include "pvmp3_crc.h"
+#include "pvmp3_getbits.h"
+#include "pvmp3_seek_synch.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
+----------------------------------------------------------------------------*/
+
+ERROR_CODE pvmp3_decode_header(tmp3Bits  *inputStream,
+                               mp3Header  *info,
+                               uint32 *crc)
+{
+
+    ERROR_CODE err = NO_DECODING_ERROR;
+    uint32  temp;
+
+    /*
+     *  Verify that at least the header is complete
+     */
+    if (inputStream->inputBufferCurrentLength < (SYNC_WORD_LNGTH + 21))
+    {
+        return NO_ENOUGH_MAIN_DATA_ERROR;
+    }
+
+    /*
+     *  MPEG Audio Version ID
+     */
+    temp = getUpTo17bits(inputStream, SYNC_WORD_LNGTH);
+    if ((temp & SYNC_WORD) != SYNC_WORD)
+    {
+        err = pvmp3_header_sync(inputStream);
+
+        if (err != NO_DECODING_ERROR)
+        {
+            return err;
+        }
+    }
+
+    temp = getNbits(inputStream, 21);   // to avoid multiple bitstream accesses
+
+
+    switch (temp >> 19)  /* 2 */
+    {
+        case 0:
+            info->version_x = MPEG_2_5;
+            break;
+        case 2:
+            info->version_x = MPEG_2;
+            break;
+        case 3:
+            info->version_x = MPEG_1;
+            break;
+        default:
+            info->version_x = INVALID_VERSION;
+            err = UNSUPPORTED_LAYER;
+            break;
+    }
+
+    info->layer_description  = 4 - ((temp << 13) >> 30);  /* 2 */
+    info->error_protection   =  !((temp << 15) >> 31);  /* 1 */
+
+    if (info->error_protection)
+    {
+        *crc = 0xffff;           /* CRC start value */
+        calculate_crc((temp << 16) >> 16, 16, crc);
+    }
+
+    info->bitrate_index      = (temp << 16) >> 28;  /* 4 */
+    info->sampling_frequency = (temp << 20) >> 30;  /* 2 */
+    info->padding            = (temp << 22) >> 31;  /* 1 */
+    info->extension          = (temp << 23) >> 31;  /* 1 */
+    info->mode               = (temp << 24) >> 30;  /* 2 */
+    info->mode_ext           = (temp << 26) >> 30;  /* 2 */
+    info->copyright          = (temp << 27) >> 31;  /* 1 */
+    info->original           = (temp << 28) >> 31;  /* 1 */
+    info->emphasis           = (temp << 30) >> 30;  /* 2 */
+
+
+    if (!info->bitrate_index || info->sampling_frequency == 3)
+    {
+        err = UNSUPPORTED_FREE_BITRATE;
+    }
+
+    return(err);
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.h
new file mode 100644
index 0000000..2c2e89e
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_header.h
@@ -0,0 +1,101 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_decode_header.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_DECODE_HEADER_H
+#define PVMP3_DECODE_HEADER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3_dec_defs.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    ERROR_CODE pvmp3_decode_header(tmp3Bits  *inputStream,
+    mp3Header  *info,
+    uint32 *crc);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp
new file mode 100644
index 0000000..6e45a18
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.cpp
@@ -0,0 +1,758 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_decode_huff_cw.cpp
+
+ Funtions:
+    pvmp3_decode_huff_cw_tab0
+    pvmp3_decode_huff_cw_tab1
+    pvmp3_decode_huff_cw_tab2
+    pvmp3_decode_huff_cw_tab3
+    pvmp3_decode_huff_cw_tab5
+    pvmp3_decode_huff_cw_tab6
+    pvmp3_decode_huff_cw_tab7
+    pvmp3_decode_huff_cw_tab8
+    pvmp3_decode_huff_cw_tab9
+    pvmp3_decode_huff_cw_tab10
+    pvmp3_decode_huff_cw_tab11
+    pvmp3_decode_huff_cw_tab12
+    pvmp3_decode_huff_cw_tab13
+    pvmp3_decode_huff_cw_tab15
+    pvmp3_decode_huff_cw_tab16
+    pvmp3_decode_huff_cw_tab24
+    pvmp3_decode_huff_cw_tab32
+    pvmp3_decode_huff_cw_tab33
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    BITS          *pMainData = pointer to input mp3 Main data bit stream
+
+
+ Outputs:
+    cw = bit field extracted from a leaf entry of packed mp3 Huffman Tables
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   These functions are used to decode huffman codewords from the input
+   bitstream using combined binary search and look-up table approach.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+ [2] Introduction to Algorithms,
+     Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest.
+     The MIT press, 1990
+
+ [3] "Selecting an Optimal Huffman Decoder for AAC",
+     Vladimir Z. Mesarovic, et al.
+     AES 111th Convention, September 21-24, 2001, New York, USA
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_tables.h"
+#include "pvmp3_getbits.h"
+#include "pvmp3_decode_huff_cw.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
+----------------------------------------------------------------------------*/
+
+uint16 pvmp3_decode_huff_cw_tab0(tmp3Bits *pMainData)
+{
+    OSCL_UNUSED_ARG(pMainData);
+    return(0);
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab1(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 3);    /*  hufftable1  */
+
+    cw = *(huffTable_1 + tmp);
+    pMainData->usedBits -= (3 - (cw & 0xFF));
+    return(cw >> 8);
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab2(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 6);    /*  huffTable_2,3  */
+
+    if (tmp >> 3)
+    {
+        tmp = (tmp >> 3) - 1;
+    }
+    else
+    {
+        tmp = tmp + 7;
+    }
+
+    cw = *(huffTable_2 + tmp);
+    pMainData->usedBits -= (6 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab3(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 6);    /*  huffTable_2,3  */
+
+    if (tmp >> 3)
+    {
+        tmp = (tmp >> 3) - 1;
+    }
+    else
+    {
+        tmp = tmp + 7;
+    }
+
+    cw = *(huffTable_3 + tmp);
+    pMainData->usedBits -= (6 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab5(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 8);    /*  huffTable_5  */
+
+    if ((tmp >> 5))
+    {
+        tmp = (tmp >> 5) - 1;
+    }
+    else if ((tmp >> 1) >= 2)
+    {
+        tmp = (tmp >> 1) - 2 + 7;
+    }
+    else
+    {
+        tmp = (tmp & 3) + 21;
+    }
+
+    cw = *(huffTable_5 + tmp);
+    pMainData->usedBits -= (8 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab6(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 7);    /*  huffTable_6  */
+    if ((tmp >> 3) >= 3)
+    {
+        tmp = (tmp >> 3) - 3;
+    }
+    else if (tmp >> 1)
+    {
+        tmp = (tmp >> 1) - 1 + 13;
+    }
+    else
+    {
+        tmp = tmp + 24;
+    }
+
+    cw = *(huffTable_6 + tmp);
+    pMainData->usedBits -= (7 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab7(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 10);    /*  huffTable_7  */
+    if ((tmp >> 7) >= 2)
+    {
+        tmp = (tmp >> 7) - 2;
+    }
+    else if ((tmp >> 4) >= 7)
+    {
+        tmp = (tmp >> 4) - 7 + 6;
+    }
+    else if ((tmp >> 1) >=  2)
+    {
+        tmp = (tmp >> 1) - 2 + 15;
+    }
+    else
+    {
+        tmp = (tmp & 3) + 69;
+    }
+
+    cw = *(huffTable_7 + tmp);
+    pMainData->usedBits -= (10 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab8(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 11);    /*  huffTable_8  */
+    if ((tmp >> 7) >= 2)
+    {
+        tmp = (tmp >> 7) - 2;
+    }
+    else if ((tmp >> 5) >= 5)
+    {
+        tmp = (tmp >> 5) - 5 + 14;
+    }
+    else if ((tmp >> 2) >= 3)
+    {
+        tmp = (tmp >> 2) - 3 + 17;
+    }
+    else
+    {
+        tmp = (tmp) + 54;
+    }
+
+    cw = *(huffTable_8 + tmp);
+    pMainData->usedBits -= (11 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab9(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo9bits(pMainData, 9);    /*  huffTable_9  */
+    if ((tmp >> 5) >= 5)
+    {
+        tmp = (tmp >> 5) - 5;
+    }
+    else if ((tmp >> 3) >= 6)
+    {
+        tmp = (tmp >> 3) - 6 + 11;
+    }
+    else if ((tmp >> 1) >= 4)
+    {
+        tmp = (tmp >> 1) - 4 + 25;
+    }
+    else
+    {
+        tmp = tmp + 45;
+    }
+
+    cw = *(huffTable_9 + tmp);
+    pMainData->usedBits -= (9 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab10(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 11);    /*  huffTable_10  */
+    if (tmp >> 10)
+    {
+        tmp = (tmp >> 10) - 1;
+    }
+    else if ((tmp >> 7) >= 3)
+    {
+        tmp = (tmp >> 7) - 3 + 1;
+    }
+    else if ((tmp >> 5) >= 8)
+    {
+        tmp = (tmp >> 5) - 8 + 6;
+    }
+    else if ((tmp >> 3) >= 18)
+    {
+        tmp = (tmp >> 3) - 18 + 10;
+    }
+    else if ((tmp >> 2) >= 24)
+    {
+        tmp = (tmp >> 2) - 24 + 24;
+    }
+    else if ((tmp >> 1) >= 12)
+    {
+        tmp = (tmp >> 1) - 12 + 36;
+    }
+    else
+    {
+        tmp = (tmp) + 72;
+    }
+
+    cw = *(huffTable_10 + tmp);
+    pMainData->usedBits -= (11 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab11(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 11);    /*  huffTable_11  */
+    if ((tmp >> 8) >= 3)
+    {
+        tmp = (tmp >> 8) - 3;
+    }
+    else if ((tmp >> 6) >= 7)
+    {
+        tmp = (tmp >> 6) - 7 + 5;
+    }
+    else if ((tmp >> 3) >= 32)
+    {
+        tmp = (tmp >> 3) - 32 + 10;
+    }
+    else if ((tmp >> 2) >= 10)
+    {
+        tmp = (tmp >> 2) - 10 + 34;
+    }
+    else if ((tmp >> 1) >= 8)
+    {
+        tmp = (tmp >> 1) - 8 + 88;
+    }
+    else
+    {
+        tmp = (tmp & 0xFF) + 100;
+    }
+    cw = *(huffTable_11 + tmp);
+    pMainData->usedBits -= (11 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab12(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 10);    /*  huffTable_12  */
+    if ((tmp >> 7) >= 5)
+    {
+        tmp = (tmp >> 7) - 5;
+    }
+    else if ((tmp >> 5) >= 12)
+    {
+        tmp = (tmp >> 5) - 12 + 3;
+    }
+    else if ((tmp >> 4) >= 17)
+    {
+        tmp = (tmp >> 4) - 17 + 11;
+    }
+    else if ((tmp >> 2) >= 32)
+    {
+        tmp = (tmp >> 2) - 32 + 18;
+    }
+    else if ((tmp >> 1) >= 16)
+    {
+        tmp = (tmp >> 1) - 16 + 54;
+    }
+    else
+    {
+        tmp = (tmp & 0x1F) + 102;
+
+    }
+    cw = *(huffTable_12 + tmp);
+    pMainData->usedBits -= (10 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab13(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getNbits(pMainData, 19);    /*  huffTable_13  */
+    if (tmp >> 18)
+    {
+        tmp = 0;
+    }
+    else if ((tmp >> 15) >= 4)
+    {
+        tmp = (tmp >> 15) - 4 + 1;
+    }
+    else if ((tmp >> 11) >= 32)
+    {
+        tmp = (tmp >> 11) - 32 + 5;
+    }
+    else if ((tmp >> 9) >= 64)
+    {
+        tmp = (tmp >> 9) - 64 + 37;
+    }
+    else if ((tmp >> 8) >= 64)
+    {
+        tmp = (tmp >> 8) - 64 + 101;
+    }
+    else if ((tmp >> 7) >= 64)
+    {
+        tmp = (tmp >> 7) - 64 + 165;
+    }
+    else if ((tmp >> 6) >= 32)
+    {
+        tmp = (tmp >> 6) - 32 + 229;
+    }
+    else if ((tmp >> 5) >= 32)
+    {
+        tmp = (tmp >> 5) - 32 + 325;
+    }
+    else if ((tmp >> 4) >= 32)
+    {
+        tmp = (tmp >> 4) - 32 + 357;
+    }
+    else if ((tmp >> 3) >= 32)
+    {
+        tmp = (tmp >> 3) - 32 + 389;
+    }
+    else if ((tmp >> 2) >= 2)
+    {
+        tmp = (tmp >> 2) - 2 + 421;
+    }
+    else
+    {
+        tmp = (tmp & 0x7) + 483;
+    }
+
+    cw = *(huffTable_13 + tmp);
+    pMainData->usedBits -= (19 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab15(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 13);    /*  huffTable_15  */
+    if ((tmp >> 9) >= 10)
+    {
+        tmp = (tmp >> 9) - 10;
+    }
+    else if ((tmp >> 6) >= 39)
+    {
+        tmp = (tmp >> 6) - 39 + 6;
+    }
+    else if ((tmp >> 4) >= 62)
+    {
+        tmp = (tmp >> 4) - 62 + 47;
+    }
+    else if ((tmp >> 3) >= 60)
+    {
+        tmp = (tmp >> 3) - 60 + 141;
+    }
+    else if ((tmp >> 2) >= 64)
+    {
+        tmp = (tmp >> 2) - 64 + 205;
+    }
+    else if ((tmp >> 1) >= 32)
+    {
+        tmp = (tmp >> 1) - 32 + 261;
+    }
+    else
+    {
+        tmp = (tmp & 0x3f) + 357;
+    }
+
+    cw = *(huffTable_15 + tmp);
+    pMainData->usedBits -= (13 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab16(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 17);    /*  huffTable_16  */
+    if (tmp >> 16)
+    {
+        tmp = 0;
+    }
+    else if ((tmp >> 13) >= 4)
+    {
+        tmp = (tmp >> 13) - 4 + 1;
+    }
+    else if ((tmp >> 9) >= 38)
+    {
+        tmp = (tmp >> 9) - 38 + 5;
+    }
+    else if ((tmp >> 7) >= 94)
+    {
+        tmp = (tmp >> 7) - 94 + 31;
+    }
+    else if ((tmp >> 5) >= 214)
+    {
+        tmp = (tmp >> 5) - 214 + 89;
+    }
+    else if ((tmp >> 3) >= 704)
+    {
+        if ((tmp >> 4) >= 384)
+        {
+            tmp = (tmp >> 4) - 384 + 315;
+        }
+        else
+        {
+            tmp = (tmp >> 3) - 704 + 251;
+        }
+    }
+    else if ((tmp >> 8) >= 14)
+    {
+        tmp = (tmp >> 8) - 14 + 359;
+    }
+    else if ((tmp) >= 3456)
+    {
+        if ((tmp >> 2) >= 868)
+        {
+            tmp = (tmp >> 2) - 868 + 383;
+        }
+        else
+        {
+            tmp = (tmp) - 3456 + 367;
+        }
+    }
+    else
+    {
+        tmp = ((tmp >> 6) & 0x3f) + 411;
+    }
+
+    cw = *(huffTable_16 + tmp);
+    pMainData->usedBits -= (17 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab24(tmp3Bits *pMainData)
+{
+    uint32 tmp;
+    uint16 cw;
+
+    tmp = getUpTo17bits(pMainData, 12);    /*  huffTable_24  */
+    if ((tmp >> 6) >= 41)
+    {
+        tmp = (tmp >> 6) - 41;
+    }
+    else if ((tmp >> 3) >= 218)
+    {
+        tmp = (tmp >> 3) - 218 + 23;
+    }
+    else if ((tmp >> 2) >= 336)
+    {
+        tmp = (tmp >> 2) - 336 + 133;
+    }
+    else if ((tmp >> 1) >= 520)
+    {
+        tmp = (tmp >> 1) - 520 + 233;
+    }
+    else if ((tmp) >= 1024)
+    {
+        tmp = (tmp) - 1024 + 385;
+    }
+    else if ((tmp >> 1) >= 352)
+    {
+        if ((tmp >> 8) == 3)
+        {
+            tmp = (tmp >> 8) - 3 + 433;
+        }
+        else
+        {
+            tmp = (tmp >> 1) - 352 + 401;
+        }
+    }
+    else
+    {
+        tmp = ((tmp >> 4) & 0x3f) + 434;
+    }
+
+    cw = *(huffTable_24 + tmp);
+    pMainData->usedBits -= (12 - (cw & 0xFF));
+
+    return(cw >> 8);
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+uint16 pvmp3_decode_huff_cw_tab32(tmp3Bits *pMainData)
+{
+    uint32 tmp = getUpTo9bits(pMainData, 6);    /*  huffTable_32  */
+    if ((tmp >> 5))
+    {
+        pMainData->usedBits -= 5;
+        return(0);
+    }
+    else
+    {
+        uint16 cw = *(huffTable_32 + (tmp & 0x1f));
+        pMainData->usedBits -= (6 - (cw & 0xFF));
+
+        return(cw >> 8);
+    }
+
+}
+
+
+uint16 pvmp3_decode_huff_cw_tab33(tmp3Bits *pMainData)
+{
+
+    uint16 tmp = getUpTo9bits(pMainData, 4);    /*  huffTable_33  */
+
+    return((0x0f - tmp));
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.h
new file mode 100644
index 0000000..941ca6d
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_decode_huff_cw.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_decode_huff_cw.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_DECODE_HUFF_CW_H
+#define PVMP3_DECODE_HUFF_CW_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3_dec_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    uint16 pvmp3_decode_huff_cw_tab0(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab1(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab2(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab3(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab5(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab6(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab7(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab8(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab9(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab10(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab11(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab12(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab13(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab15(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab16(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab24(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab32(tmp3Bits *);
+    uint16 pvmp3_decode_huff_cw_tab33(tmp3Bits *);
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
new file mode 100644
index 0000000..69e1987
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.cpp
@@ -0,0 +1,452 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dequantize_sample.cpp
+
+   Functions:
+      power_1_third
+      pvmp3_dequantize_sample
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+power_1_third
+int32 power_1_third( int32 xx)
+
+Input
+    int32           xx,                     int32 in the [0, 8192] range
+
+ Returns
+
+    int32           xx^(1/3)                int32 Q26 number representing
+                                            the 1/3 power of the input
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+pvmp3_dequantize_sample
+
+Input
+    int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    mp3ScaleFactors *scalefac,                 scale factor structure
+    struct gr_info_s *gr_info,                 granule structure informatiom
+    mp3Header *info                            mp3 header info
+
+ Returns
+
+    int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS], dequantize output as (.)^(4/3)
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    dequantize sample
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_dequantize_sample.h"
+#include "pvmp3_normalize.h"
+#include "mp3_mem_funcs.h"
+#include "pvmp3_tables.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define Q30_fmt(a)(int32(double(0x40000000)*a))
+#define Q29_fmt(a)(int32(double(0x20000000)*a))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int32 pretab[22] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0};
+
+const int32 pow_2_1_fourth[4] =
+{
+    Q30_fmt(1.0),                Q30_fmt(1.18920711500272),
+    Q30_fmt(1.41421356237310),   Q30_fmt(1.68179283050743)
+};
+
+const int32 two_cubic_roots[7] =
+{
+    Q29_fmt(0),                  Q29_fmt(1.25992104989487),
+    Q29_fmt(1.58740105196820),   Q29_fmt(2.00000000000000),
+    Q29_fmt(2.51984209978975),   Q29_fmt(3.17480210393640),
+    Q29_fmt(3.99999999999999)
+};
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+
+int32 power_1_third(int32 xx)
+{
+
+    if (xx <= 512)
+    {
+        return (power_one_third[xx] >> 1);
+    }
+    else
+    {
+        if (xx >> 15)
+        {
+            return 0x7FFFFFFF;  /* saturate any value over 32767 */
+        }
+        else
+        {
+            int32 x = xx;
+            int32 m = 22 - pvmp3_normalize(xx);
+
+            xx >>= m;
+            xx = (power_one_third[xx]) + (((power_one_third[xx+1] - power_one_third[xx]) >> m) * (x & ((1 << m) - 1)));
+            return (fxp_mul32_Q30(xx, two_cubic_roots[m]));
+        }
+
+    }
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+
+void pvmp3_dequantize_sample(int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                             mp3ScaleFactors *scalefac,
+                             granuleInfo *gr_info,
+                             int32  used_freq_lines,
+                             mp3Header *info)
+{
+    int32 ss;
+    int32 cb = 0;
+    int32 global_gain;
+    int32 sfreq = info->sampling_frequency + info->version_x + (info->version_x << 1);
+
+    /* apply formula per block type */
+
+    if (gr_info->window_switching_flag && (gr_info->block_type == 2))
+    {
+        int32 next_cb_boundary;
+        int32 cb_begin = 0;
+        int32 cb_width = 0;
+        int32 mixstart = 8;                                       /* added 2003/08/21  efs */
+
+        if (info->version_x != MPEG_1)
+        {
+            mixstart = 6;                                   /* different value in MPEG2 LSF */
+        }
+
+        if (gr_info->mixed_block_flag)
+        {
+            next_cb_boundary = mp3_sfBandIndex[sfreq].l[1];  /* LONG blocks: 0,1,3 */
+        }
+        else
+        {
+            next_cb_boundary = mp3_sfBandIndex[sfreq].s[1] * 3; /* pure SHORT block */
+            cb_width = 0;
+        }
+
+        global_gain =  gr_info->global_gain;
+        int32 two_raise_one_fourth = pow_2_1_fourth[global_gain&0x3];
+        global_gain = 12 + (global_gain >> 2);
+
+        for (ss = 0 ; ss < used_freq_lines ; ss++)
+        {
+            if (ss == next_cb_boundary)
+            {
+                cb++;       /*  critical band counter */
+                if (gr_info->mixed_block_flag)
+                {
+                    if (next_cb_boundary == mp3_sfBandIndex[sfreq].l[mixstart])
+                    {
+                        next_cb_boundary = mp3_sfBandIndex[sfreq].s[4] * 3;
+
+                        cb_begin = mp3_sfBandIndex[sfreq].s[3] * 3;
+                        cb_width = 3;
+                        cb = 3;
+                    }
+                    else if (ss < mp3_sfBandIndex[sfreq].l[mixstart])
+                    {
+                        next_cb_boundary = mp3_sfBandIndex[sfreq].l[cb+1];
+                    }
+                    else
+                    {
+                        next_cb_boundary = mp3_sfBandIndex[sfreq].s[cb+1] * 3;
+
+                        cb_width = cb;
+                        cb_begin = mp3_sfBandIndex[sfreq].s[cb] * 3;
+                    }
+
+                    if (ss < 2*FILTERBANK_BANDS)
+                    {   /*  1st 2 subbands of switched blocks */
+                        global_gain  = (gr_info->global_gain);
+                        global_gain -= (1 + gr_info->scalefac_scale) *
+                                       (scalefac->l[cb] + gr_info->preflag * pretab[cb]) << 1;
+
+                        two_raise_one_fourth = pow_2_1_fourth[global_gain&0x3];
+                        global_gain = 12 + (global_gain >> 2);
+                    }
+                }
+                else
+                {
+                    next_cb_boundary = mp3_sfBandIndex[sfreq].s[cb+1] * 3;
+                    cb_width = cb;
+                    cb_begin = mp3_sfBandIndex[sfreq].s[cb] * 3;
+                }
+
+            }   /*  end-if ( ss == next_cb_boundary) */
+
+            /* Do long/short dependent scaling operations. */
+            if ((gr_info->mixed_block_flag == 0) || (gr_info->mixed_block_flag && (ss >= 2*FILTERBANK_BANDS)))
+            {
+                int32 temp2 = fxp_mul32_Q32((ss - cb_begin) << 16, mp3_shortwindBandWidths[sfreq][cb_width]);
+                temp2 = (temp2 + 1) >> 15;
+
+                global_gain  = (gr_info->global_gain);
+                global_gain -=  gr_info->subblock_gain[temp2] << 3;
+                global_gain -= (1 + gr_info->scalefac_scale) * (scalefac->s[temp2][cb] << 1);
+
+                two_raise_one_fourth = pow_2_1_fourth[global_gain&0x3];
+                global_gain = 12 + (global_gain >> 2);
+
+            }
+
+
+            /*
+             *       xr[sb][ss] = 2^(global_gain/4)
+             */
+
+            /* Scale quantized value. */
+
+            /* 0 < abs(is[ss]) < 8192 */
+
+            int32 tmp = fxp_mul32_Q30((is[ss] << 16), power_1_third(pv_abs(is[ ss])));
+
+            tmp = fxp_mul32_Q30(tmp, two_raise_one_fourth);
+
+            if (global_gain < 0)
+            {
+                int32 temp = - global_gain;
+                if (temp < 32)
+                {
+                    is[ss] = (tmp >> temp);
+                }
+                else
+                {
+                    is[ss] = 0;
+                }
+            }
+            else
+            {
+                is[ss] = (tmp << global_gain);
+            }
+
+        }  /*   for (ss=0 ; ss < used_freq_lines ; ss++)   */
+
+    }
+    else
+    {
+
+        for (cb = 0 ; cb < 22 ; cb++)
+        {
+
+            /* Compute overall (global) scaling. */
+
+            global_gain  = (gr_info->global_gain);
+
+            global_gain -= (1 + gr_info->scalefac_scale) *
+                           (scalefac->l[cb] + gr_info->preflag * pretab[cb]) << 1;
+
+
+            int32 two_raise_one_fourth = pow_2_1_fourth[global_gain&0x3];
+            global_gain = 12 + (global_gain >> 2);
+
+            /*
+             *       xr[sb][ss] = 2^(global_gain/4)
+             */
+
+            /* Scale quantized value. */
+
+            if (used_freq_lines >= mp3_sfBandIndex[sfreq].l[cb+1])
+            {
+                if (global_gain <= 0)
+                {
+                    global_gain = - global_gain;
+                    if (global_gain < 32)
+                    {
+                        for (ss = mp3_sfBandIndex[sfreq].l[cb]; ss < mp3_sfBandIndex[sfreq].l[cb+1]; ss += 2)
+                        {
+                            int32 tmp =  is[ss];
+                            if (tmp)
+                            {
+                                tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                                is[ss] = fxp_mul32_Q30(tmp, two_raise_one_fourth) >> global_gain;
+                            }
+                            tmp =  is[ss+1];
+                            if (tmp)
+                            {
+                                tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                                is[ss+1] = fxp_mul32_Q30(tmp, two_raise_one_fourth) >> global_gain;
+                            }
+                        }
+                    }
+                    else
+                    {
+                        pv_memset(&is[ mp3_sfBandIndex[sfreq].l[cb]],
+                                  0,
+                                  (mp3_sfBandIndex[sfreq].l[cb+1] - mp3_sfBandIndex[sfreq].l[cb])*sizeof(*is));
+                    }
+                }
+                else
+                {
+                    for (ss = mp3_sfBandIndex[sfreq].l[cb]; ss < mp3_sfBandIndex[sfreq].l[cb+1]; ss += 2)
+                    {
+                        int32 tmp =  is[ss];
+                        if (tmp)
+                        {
+                            tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                            is[ss] = fxp_mul32_Q30(tmp, two_raise_one_fourth) << global_gain;
+                        }
+
+                        tmp =  is[ss+1];
+                        if (tmp)
+                        {
+                            tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                            is[ss+1] = fxp_mul32_Q30(tmp, two_raise_one_fourth) << global_gain;
+                        }
+                    }
+                }
+            }
+            else
+            {
+                if (global_gain <= 0)
+                {
+                    global_gain = - global_gain;
+                    if (global_gain < 32)
+                    {
+                        for (ss = mp3_sfBandIndex[sfreq].l[cb]; ss < used_freq_lines; ss += 2)
+                        {
+                            int32 tmp =  is[ss];
+                            if (tmp)
+                            {
+                                tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                                is[ss] = fxp_mul32_Q30(tmp, two_raise_one_fourth) >> global_gain;
+                            }
+                            tmp =  is[ss+1];
+                            if (tmp)
+                            {
+                                tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                                is[ss+1] = fxp_mul32_Q30(tmp, two_raise_one_fourth) >> global_gain;
+                            }
+                        }
+
+                    }
+                    else
+                    {
+                        pv_memset(&is[ mp3_sfBandIndex[sfreq].l[cb]],
+                                  0,
+                                  (mp3_sfBandIndex[sfreq].l[cb+1] - mp3_sfBandIndex[sfreq].l[cb])*sizeof(*is));
+                    }
+                }
+                else
+                {
+                    for (ss = mp3_sfBandIndex[sfreq].l[cb]; ss < used_freq_lines; ss++)
+                    {
+                        int32 tmp =  is[ss];
+
+                        if (tmp)
+                        {
+                            tmp = fxp_mul32_Q30((tmp << 16), power_1_third(pv_abs(tmp)));
+                            is[ss] = fxp_mul32_Q30(tmp, two_raise_one_fourth) << global_gain;
+                        }
+                    }
+                }
+
+                cb = 22;  // force breaking out of the loop
+
+            } /*  if ( used_freq_lines >= mp3_sfBandIndex[sfreq].l[cb+1]) */
+
+        }   /* for (cb=0 ; cb < 22 ; cb++)  */
+
+    }   /*  if (gr_info->window_switching_flag && (gr_info->block_type == 2))  */
+
+
+    pv_memset(&is[used_freq_lines],
+              0,
+              (FILTERBANK_BANDS*SUBBANDS_NUMBER - used_freq_lines)*sizeof(*is));
+
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.h
new file mode 100644
index 0000000..9393eb1
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_dequantize_sample.h
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_dequantize_sample.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_DEQUANTIZE_SAMPLE_H
+#define PVMP3_DEQUANTIZE_SAMPLE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int32 power_1_third(int32 xx);
+
+    void pvmp3_dequantize_sample(int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                                 mp3ScaleFactors *scalefac,
+                                 granuleInfo *gr_info,
+                                 int32  num_lines,
+                                 mp3Header *info);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
new file mode 100644
index 0000000..f4a4efb
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.cpp
@@ -0,0 +1,415 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_equalizer.cpp
+
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+  Input
+    int32          *inData,           pointer to the spectrum frequency-line
+    e_equalization equalizerType,     equalization mode
+    int32          *pt_work_buff
+
+  Output
+    int32          *pt_work_buff      pointer to the equalized frequency-line
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Equalizer
+    Each subband sample is scaled according to a spectrum shape setting
+    defined by "equalizerType"
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_equalizer.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LEVEL__0__dB  0.999999970f
+#define LEVEL__1_5dB  0.841395142f
+#define LEVEL__3__dB  0.707106781f
+#define LEVEL__4_5dB  0.595662143f
+#define LEVEL__6__dB  0.500000000f
+#define LEVEL__7_5dB  0.421696503f
+#define LEVEL__9__dB  0.353553393f
+#define LEVEL_12__dB  0.250000000f
+#define LEVEL_15__dB  0.176776695f
+#define LEVEL_18__dB  0.125000000f
+#define LEVEL_21__dB  0.088388347f
+#define LEVEL_30__dB  0.031250000f
+#define LEVEL_45__dB  0.005524271f
+#define LEVEL_60__dB  0.000976562f
+
+#define Qmf31( x)    (int32)(x*(float)0x7FFFFFFF)
+
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+
+const int32 equalizerTbl[8][SUBBANDS_NUMBER] =
+{
+    /*  FLAT */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB)
+    },
+    /*  BASS BOOST */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__1_5dB), Qmf31(LEVEL__3__dB),
+
+        Qmf31(LEVEL__4_5dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB)
+    },
+    /*  ROCK */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__1_5dB), Qmf31(LEVEL__3__dB),
+
+        Qmf31(LEVEL__4_5dB), Qmf31(LEVEL__6__dB),
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__1_5dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB)
+    },
+    /*  POP */
+    {
+        Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+
+        Qmf31(LEVEL__1_5dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB)
+    },
+    /*  JAZZ */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__1_5dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB)
+    },
+    /*  CLASSICAL */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+        Qmf31(LEVEL__9__dB), Qmf31(LEVEL__9__dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__1_5dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB)
+    },
+    /*  TALK */
+    {
+        Qmf31(LEVEL__9__dB),
+
+        Qmf31(LEVEL__6__dB), Qmf31(LEVEL__6__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__1_5dB),
+
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB), Qmf31(LEVEL__3__dB),
+        Qmf31(LEVEL__3__dB)
+    },
+    /*  FLAT */
+    {
+        Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB), Qmf31(LEVEL__0__dB),
+        Qmf31(LEVEL__0__dB)
+    }
+};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_equalizer(int32 *circ_buffer,
+                     e_equalization equalizerType,
+                     int32 *work_buff)
+{
+
+    if (equalizerType == flat)
+    {
+        for (int32 band = 0; band < FILTERBANK_BANDS; band += 2)
+        {
+
+            int32 *pt_work_buff = &work_buff[band];
+            int32 *inData = &circ_buffer[544 - (band<<5)];
+
+            int32 i;
+            for (i = 0; i < SUBBANDS_NUMBER*FILTERBANK_BANDS; i += FILTERBANK_BANDS << 2)
+            {
+                int32 temp1 = (pt_work_buff[ i ]);
+                int32 temp2 = (pt_work_buff[ i +   FILTERBANK_BANDS ]);
+                int32 temp3 = (pt_work_buff[ i + 2*FILTERBANK_BANDS ]);
+                int32 temp4 = (pt_work_buff[ i + 3*FILTERBANK_BANDS ]);
+                *(inData++) = temp1;
+                *(inData++) = temp2;
+                *(inData++) = temp3;
+                *(inData++) = temp4;
+            }
+
+            inData -= SUBBANDS_NUMBER << 1;
+            pt_work_buff++;
+
+            for (i = 0; i < SUBBANDS_NUMBER*FILTERBANK_BANDS; i += FILTERBANK_BANDS << 2)
+            {
+                int32 temp1 = (pt_work_buff[ i ]);
+                int32 temp2 = (pt_work_buff[ i +   FILTERBANK_BANDS ]);
+                int32 temp3 = (pt_work_buff[ i + 2*FILTERBANK_BANDS ]);
+                int32 temp4 = (pt_work_buff[ i + 3*FILTERBANK_BANDS ]);
+                *(inData++) = temp1;
+                *(inData++) = temp2;
+                *(inData++) = temp3;
+                *(inData++) = temp4;
+            }
+        }
+    }
+    else
+    {
+        const int32 *pt_equalizer = equalizerTbl[equalizerType&7];
+
+
+        for (int32 band = 0; band < FILTERBANK_BANDS; band += 3)
+        {
+            int32 *inData = &circ_buffer[544 - (band<<5)];
+
+            int32 *pt_work_buff = &work_buff[band];
+            int32 i;
+
+            for (i = 0; i < SUBBANDS_NUMBER*FILTERBANK_BANDS; i += FILTERBANK_BANDS << 2)
+            {
+                int32 temp1 = (pt_work_buff[ i ]);
+                int32 temp2 = (pt_work_buff[ i +   FILTERBANK_BANDS ]);
+                int32 temp3 = (pt_work_buff[ i + 2*FILTERBANK_BANDS ]);
+                int32 temp4 = (pt_work_buff[ i + 3*FILTERBANK_BANDS ]);
+                *(inData++) = fxp_mul32_Q32(temp1 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp2 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp3 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp4 << 1, *(pt_equalizer++));
+            }
+
+            pt_equalizer -= SUBBANDS_NUMBER;
+
+            inData -= SUBBANDS_NUMBER << 1;
+            pt_work_buff++;
+
+            for (i = 0; i < SUBBANDS_NUMBER*FILTERBANK_BANDS; i += FILTERBANK_BANDS << 2)
+            {
+                int32 temp1 = (pt_work_buff[ i ]);
+                int32 temp2 = (pt_work_buff[ i +   FILTERBANK_BANDS ]);
+                int32 temp3 = (pt_work_buff[ i + 2*FILTERBANK_BANDS ]);
+                int32 temp4 = (pt_work_buff[ i + 3*FILTERBANK_BANDS ]);
+                *(inData++) = fxp_mul32_Q32(temp1 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp2 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp3 << 1, *(pt_equalizer++));
+                *(inData++) = fxp_mul32_Q32(temp4 << 1, *(pt_equalizer++));
+            }
+            pt_equalizer -= SUBBANDS_NUMBER;
+
+        }
+    }
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.h
new file mode 100644
index 0000000..bbf134f
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_equalizer.h
@@ -0,0 +1,101 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_equalizer.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_EQUALIZER_H
+#define PVMP3_EQUALIZER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3decoder_api.h"
+
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_equalizer(int32 *inData,
+    e_equalization equalizerType,
+    int32 *pt_work_buff);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp
new file mode 100644
index 0000000..26bc25c
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.cpp
@@ -0,0 +1,834 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_framedecoder.cpp
+
+   Functions:
+    pvmp3_framedecoder
+    pvmp3_InitDecoder
+    pvmp3_resetDecoder
+
+    Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    pExt = pointer to the external interface structure. See the file
+           pvmp3decoder_api.h for a description of each field.
+           Data type of pointer to a tPVMP3DecoderExternal
+           structure.
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tmp3dec_file structure. This structure
+           contains information that needs to persist between calls to
+           this function, or is too big to be placed on the stack, even
+           though the data is only needed during execution of this function
+           Data type void pointer, internally pointer to a tmp3dec_file
+           structure.
+
+
+ Outputs:
+     status = ERROR condition.  see structure  ERROR_CODE
+
+ Pointers and Buffers Modified:
+    pMem contents are modified.
+    pExt: (more detail in the file pvmp3decoder_api.h)
+    inputBufferUsedLength - number of array elements used up by the stream.
+    samplingRate - sampling rate in samples per sec
+    bitRate - bit rate in bits per second, varies frame to frame.
+
+
+
+------------------------------------------------------------------------------
+ FUNCTIONS DESCRIPTION
+
+    pvmp3_framedecoder
+        frame decoder library driver
+    pvmp3_InitDecoder
+        Decoder Initialization
+    pvmp3_resetDecoder
+        Reset Decoder
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+
+#include "pvmp3_framedecoder.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_poly_phase_synthesis.h"
+#include "pvmp3_tables.h"
+#include "pvmp3_imdct_synth.h"
+#include "pvmp3_alias_reduction.h"
+#include "pvmp3_reorder.h"
+#include "pvmp3_dequantize_sample.h"
+#include "pvmp3_stereo_proc.h"
+#include "pvmp3_mpeg2_stereo_proc.h"
+#include "pvmp3_get_side_info.h"
+#include "pvmp3_get_scale_factors.h"
+#include "pvmp3_mpeg2_get_scale_factors.h"
+#include "pvmp3_decode_header.h"
+#include "pvmp3_get_main_data_size.h"
+#include "s_tmp3dec_file.h"
+#include "pvmp3_getbits.h"
+#include "mp3_mem_funcs.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
+----------------------------------------------------------------------------*/
+
+ERROR_CODE pvmp3_framedecoder(tPVMP3DecoderExternal *pExt,
+                              void              *pMem)
+{
+
+    ERROR_CODE        errorCode  = NO_DECODING_ERROR;
+
+    int32   crc_error_count = 0;
+    uint32  sent_crc = 0;
+    uint32  computed_crc = 0;
+
+    tmp3dec_chan   *pChVars[CHAN];
+    tmp3dec_file   *pVars = (tmp3dec_file *)pMem;
+
+    mp3Header info_data;
+    mp3Header *info = &info_data;
+
+    pVars->inputStream.pBuffer  = pExt->pInputBuffer;
+
+
+    pVars->inputStream.usedBits  = pExt->inputBufferUsedLength << 3;
+    pVars->inputStream.inputBufferCurrentLength  = pExt->inputBufferCurrentLength;
+
+
+    errorCode = pvmp3_decode_header(&pVars->inputStream,
+                                    info,
+                                    &computed_crc);
+
+    if (errorCode != NO_DECODING_ERROR)
+    {
+        pExt->outputFrameSize = 0;
+        return errorCode;
+    }
+
+    pVars->num_channels = (info->mode == MPG_MD_MONO) ? 1 : 2;
+    pExt->num_channels = pVars->num_channels;
+
+    int32 outputFrameSize = (info->version_x == MPEG_1) ?
+                            2 * SUBBANDS_NUMBER * FILTERBANK_BANDS :
+                            SUBBANDS_NUMBER * FILTERBANK_BANDS;
+
+    outputFrameSize = (info->mode == MPG_MD_MONO) ? outputFrameSize : outputFrameSize << 1;
+
+
+    /*
+     *  Check if output buffer has enough room to hold output PCM
+     */
+    if (pExt->outputFrameSize >= outputFrameSize)
+    {
+        pExt->outputFrameSize = outputFrameSize;
+    }
+    else
+    {
+        pExt->outputFrameSize = 0;
+        return OUTPUT_BUFFER_TOO_SMALL;
+    }
+
+
+    pChVars[ LEFT] = &pVars->perChan[ LEFT];
+    pChVars[RIGHT] = &pVars->perChan[RIGHT];
+
+
+
+
+    if (info->error_protection)
+    {
+        /*
+         *  Get crc content
+         */
+        sent_crc = getUpTo17bits(&pVars->inputStream, 16);
+    }
+
+
+    if (info->layer_description == 3)
+    {
+        int32 gr;
+        int32 ch;
+        uint32 main_data_end;
+        int32 bytes_to_discard;
+        int16 *ptrOutBuffer = pExt->pOutputBuffer;
+
+        /*
+         * Side Information must be extracted from the bitstream and store for use
+         * during the decoded of the associated frame
+         */
+
+        errorCode = pvmp3_get_side_info(&pVars->inputStream,
+                                        &pVars->sideInfo,
+                                        info,
+                                        &computed_crc);
+
+        if (errorCode != NO_DECODING_ERROR)
+        {
+            pExt->outputFrameSize = 0;
+            return errorCode;
+        }
+
+        /*
+         *  If CRC was sent, check that matches the one got while parsing data
+         *  disable crc if this is the desired mode
+         */
+        if (info->error_protection)
+        {
+            if ((computed_crc != sent_crc) && pExt->crcEnabled)
+            {
+                crc_error_count++;
+            }
+        }
+
+        /*
+         * main data (scalefactors, Huffman coded, etc,) are not necessarily located
+         * adjacent to the side-info. Beginning of main data is located using
+         * field "main_data_begin" of the current frame. The length does not include
+         * header and side info.
+         * "main_data_begin" points to the first bit of main data of a frame. It is a negative
+         * offset in bytes from the first byte of the sync word
+         * main_data_begin = 0  <===> main data start rigth after side info.
+         */
+
+        int32 temp = pvmp3_get_main_data_size(info, pVars);
+
+
+        /*
+         *  Check if available data holds a full frame, if not flag an error
+         */
+
+        if ((uint32)pVars->predicted_frame_size > pVars->inputStream.inputBufferCurrentLength)
+        {
+            pExt->outputFrameSize = 0;
+            return NO_ENOUGH_MAIN_DATA_ERROR;
+        }
+
+        /*
+         *  Fill in internal circular buffer
+         */
+        fillMainDataBuf(pVars, temp);
+
+
+        main_data_end = pVars->mainDataStream.usedBits >> 3; /* in bytes */
+        if ((main_data_end << 3) < pVars->mainDataStream.usedBits)
+        {
+            main_data_end++;
+            pVars->mainDataStream.usedBits = main_data_end << 3;
+        }
+
+
+        bytes_to_discard = pVars->frame_start - pVars->sideInfo.main_data_begin - main_data_end;
+
+
+        if (main_data_end > BUFSIZE)   /* check overflow on the buffer */
+        {
+            pVars->frame_start -= BUFSIZE;
+
+            pVars->mainDataStream.usedBits -= (BUFSIZE << 3);
+        }
+
+        pVars->frame_start += temp;
+
+
+        if (bytes_to_discard < 0 || crc_error_count)
+        {
+            /*
+             *  Not enough data to decode, then we should avoid reading this
+             *  data ( getting/ignoring sido info and scale data)
+             *  Main data could be located in the previous frame, so an unaccounted
+             *  frame can cause incorrect processing
+             *  Just run the polyphase filter to "clean" the history buffer
+             */
+            errorCode = NO_ENOUGH_MAIN_DATA_ERROR;
+
+            /*
+             *  Clear the input to these filters
+             */
+
+            pv_memset((void*)pChVars[RIGHT]->work_buf_int32,
+                      0,
+                      SUBBANDS_NUMBER*FILTERBANK_BANDS*sizeof(pChVars[RIGHT]->work_buf_int32[0]));
+
+            pv_memset((void*)pChVars[LEFT]->work_buf_int32,
+                      0,
+                      SUBBANDS_NUMBER*FILTERBANK_BANDS*sizeof(pChVars[LEFT]->work_buf_int32[0]));
+
+            /*  clear circular buffers, to avoid any glitch */
+            pv_memset((void*)&pChVars[ LEFT]->circ_buffer[576],
+                      0,
+                      480*sizeof(pChVars[ LEFT]->circ_buffer[0]));
+            pv_memset((void*)&pChVars[RIGHT]->circ_buffer[576],
+                      0,
+                      480*sizeof(pChVars[RIGHT]->circ_buffer[0]));
+
+            pChVars[ LEFT]->used_freq_lines = 575;
+            pChVars[RIGHT]->used_freq_lines = 575;
+
+        }
+        else
+        {
+            pVars->mainDataStream.usedBits += (bytes_to_discard << 3);
+        }
+
+        /*
+         *  if (fr_ps->header->version_x == MPEG_1), use 2 granules, otherwise just 1
+         */
+        for (gr = 0; gr < (1 + !(info->version_x)); gr++)
+        {
+            if (errorCode != NO_ENOUGH_MAIN_DATA_ERROR)
+            {
+                for (ch = 0; ch < pVars->num_channels; ch++)
+                {
+                    int32 part2_start = pVars->mainDataStream.usedBits;
+
+                    if (info->version_x == MPEG_1)
+                    {
+
+                        pvmp3_get_scale_factors(&pVars->scaleFactors[ch],
+                                                &pVars->sideInfo,
+                                                gr,
+                                                ch,
+                                                &pVars->mainDataStream);
+                    }
+                    else
+                    {
+                        int32 * tmp = pVars->Scratch_mem;
+                        pvmp3_mpeg2_get_scale_factors(&pVars->scaleFactors[ch],
+                                                      &pVars->sideInfo,
+                                                      gr,
+                                                      ch,
+                                                      info,
+                                                      (uint32 *)tmp,
+                                                      &pVars->mainDataStream);
+                    }
+
+                    pChVars[ch]->used_freq_lines = pvmp3_huffman_parsing(pChVars[ch]->work_buf_int32,
+                                                   &pVars->sideInfo.ch[ch].gran[gr],
+                                                   pVars,
+                                                   part2_start,
+                                                   info);
+
+
+                    pvmp3_dequantize_sample(pChVars[ch]->work_buf_int32,
+                                            &pVars->scaleFactors[ch],
+                                            &pVars->sideInfo.ch[ch].gran[gr],
+                                            pChVars[ch]->used_freq_lines,
+                                            info);
+
+
+
+
+                }   /* for (ch=0; ch<stereo; ch++)  */
+
+                if (pVars->num_channels == 2)
+                {
+
+                    int32 used_freq_lines = (pChVars[ LEFT]->used_freq_lines  >
+                                             pChVars[RIGHT]->used_freq_lines) ?
+                                            pChVars[ LEFT]->used_freq_lines  :
+                                            pChVars[RIGHT]->used_freq_lines;
+
+                    pChVars[ LEFT]->used_freq_lines = used_freq_lines;
+                    pChVars[RIGHT]->used_freq_lines = used_freq_lines;
+
+                    if (info->version_x == MPEG_1)
+                    {
+                        pvmp3_stereo_proc(pChVars[ LEFT]->work_buf_int32,
+                                          pChVars[RIGHT]->work_buf_int32,
+                                          &pVars->scaleFactors[RIGHT],
+                                          &pVars->sideInfo.ch[LEFT].gran[gr],
+                                          used_freq_lines,
+                                          info);
+                    }
+                    else
+                    {
+                        int32 * tmp = pVars->Scratch_mem;
+                        pvmp3_mpeg2_stereo_proc(pChVars[ LEFT]->work_buf_int32,
+                                                pChVars[RIGHT]->work_buf_int32,
+                                                &pVars->scaleFactors[RIGHT],
+                                                &pVars->sideInfo.ch[ LEFT].gran[gr],
+                                                &pVars->sideInfo.ch[RIGHT].gran[gr],
+                                                (uint32 *)tmp,
+                                                used_freq_lines,
+                                                info);
+                    }
+                }
+
+            } /* if ( errorCode != NO_ENOUGH_MAIN_DATA_ERROR) */
+
+            for (ch = 0; ch < pVars->num_channels; ch++)
+            {
+
+                pvmp3_reorder(pChVars[ch]->work_buf_int32,
+                              &pVars->sideInfo.ch[ch].gran[gr],
+                              &pChVars[ ch]->used_freq_lines,
+                              info,
+                              pVars->Scratch_mem);
+
+                pvmp3_alias_reduction(pChVars[ch]->work_buf_int32,
+                                      &pVars->sideInfo.ch[ch].gran[gr],
+                                      &pChVars[ ch]->used_freq_lines,
+                                      info);
+
+
+                /*
+                 *   IMDCT
+                 */
+                /* set mxposition
+                 * In case of mixed blocks, # of bands with long
+                 * blocks (2 or 4) else 0
+                 */
+                uint16 mixedBlocksLongBlocks = 0; /*  0 = long or short, 2=mixed, 4=mixed 2.5@8000 */
+                if (pVars->sideInfo.ch[ch].gran[gr].mixed_block_flag &&
+                        pVars->sideInfo.ch[ch].gran[gr].window_switching_flag)
+                {
+                    if ((info->version_x == MPEG_2_5) && (info->sampling_frequency == 2))
+                    {
+                        mixedBlocksLongBlocks = 4; /* mpeg2.5 @ 8 KHz */
+                    }
+                    else
+                    {
+                        mixedBlocksLongBlocks = 2;
+                    }
+                }
+
+                pvmp3_imdct_synth(pChVars[ch]->work_buf_int32,
+                                  pChVars[ch]->overlap,
+                                  pVars->sideInfo.ch[ch].gran[gr].block_type,
+                                  mixedBlocksLongBlocks,
+                                  pChVars[ ch]->used_freq_lines,
+                                  pVars->Scratch_mem);
+
+
+                /*
+                 *   Polyphase synthesis
+                 */
+
+                pvmp3_poly_phase_synthesis(pChVars[ch],
+                                           pVars->num_channels,
+                                           pExt->equalizerType,
+                                           &ptrOutBuffer[ch]);
+
+
+            }/* end ch loop */
+
+            ptrOutBuffer += pVars->num_channels * SUBBANDS_NUMBER * FILTERBANK_BANDS;
+        }  /*   for (gr=0;gr<Max_gr;gr++)  */
+
+        /* skip ancillary data */
+        if (info->bitrate_index > 0)
+        { /* if not free-format */
+
+            int32 ancillary_data_lenght = pVars->predicted_frame_size << 3;
+
+            ancillary_data_lenght  -= pVars->inputStream.usedBits;
+
+            /* skip ancillary data */
+            if (ancillary_data_lenght > 0)
+            {
+                pVars->inputStream.usedBits += ancillary_data_lenght;
+            }
+
+        }
+
+        /*
+         *  This overrides a possible NO_ENOUGH_MAIN_DATA_ERROR
+         */
+        errorCode = NO_DECODING_ERROR;
+
+    }
+    else
+    {
+        /*
+         * The info on the header leads to an unsupported layer, more data
+         * will not fix this, so this is a bad frame,
+         */
+
+        pExt->outputFrameSize = 0;
+        return UNSUPPORTED_LAYER;
+    }
+
+    pExt->inputBufferUsedLength = pVars->inputStream.usedBits >> 3;
+    pExt->totalNumberOfBitsUsed += pVars->inputStream.usedBits;
+    pExt->version = info->version_x;
+    pExt->samplingRate = mp3_s_freq[info->version_x][info->sampling_frequency];
+    pExt->bitRate = mp3_bitrate[pExt->version][info->bitrate_index];
+
+
+    /*
+     *  Always verify buffer overrun condition
+     */
+
+    if (pExt->inputBufferUsedLength > pExt->inputBufferCurrentLength)
+    {
+        pExt->outputFrameSize = 0;
+        errorCode = NO_ENOUGH_MAIN_DATA_ERROR;
+    }
+
+    return errorCode;
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+__inline void fillDataBuf(tmp3Bits *pMainData,
+                          uint32 val)       /* val to write into the buffer */
+{
+    pMainData->pBuffer[module(pMainData->offset++, BUFSIZE)] = (uint8)val;
+}
+
+
+void fillMainDataBuf(void  *pMem, int32 temp)
+{
+    tmp3dec_file   *pVars = (tmp3dec_file *)pMem;
+
+
+    int32 offset = (pVars->inputStream.usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+    /*
+     *  Check if input circular buffer boundaries need to be enforced
+     */
+    if ((offset + temp) < BUFSIZE)
+    {
+        uint8 * ptr = pVars->inputStream.pBuffer + offset;
+
+        offset = pVars->mainDataStream.offset;
+
+        /*
+         *  Check if main data circular buffer boundaries need to be enforced
+         */
+        if ((offset + temp) < BUFSIZE)
+        {
+            pv_memcpy((pVars->mainDataStream.pBuffer + offset), ptr, temp*sizeof(uint8));
+            pVars->mainDataStream.offset += temp;
+        }
+        else
+        {
+            int32 tmp1 = *(ptr++);
+            for (int32 nBytes = temp >> 1; nBytes != 0; nBytes--)  /* read main data. */
+            {
+                int32 tmp2 = *(ptr++);
+                fillDataBuf(&pVars->mainDataStream, tmp1);
+                fillDataBuf(&pVars->mainDataStream, tmp2);
+                tmp1 = *(ptr++);
+            }
+
+            if (temp&1)
+            {
+                fillDataBuf(&pVars->mainDataStream, tmp1);
+            }
+
+            /* adjust circular buffer counter */
+            pVars->mainDataStream.offset = module(pVars->mainDataStream.offset, BUFSIZE);
+        }
+    }
+    else
+    {
+        for (int32 nBytes = temp >> 1; nBytes != 0; nBytes--)  /* read main data. */
+        {
+            fillDataBuf(&pVars->mainDataStream, *(pVars->inputStream.pBuffer + module(offset++  , BUFSIZE)));
+            fillDataBuf(&pVars->mainDataStream, *(pVars->inputStream.pBuffer + module(offset++  , BUFSIZE)));
+        }
+        if (temp&1)
+        {
+            fillDataBuf(&pVars->mainDataStream, *(pVars->inputStream.pBuffer + module(offset  , BUFSIZE)));
+        }
+    }
+
+
+    pVars->inputStream.usedBits += (temp) << INBUF_ARRAY_INDEX_SHIFT;
+}
+
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+uint32 pvmp3_decoderMemRequirements(void)
+{
+    uint32 size;
+
+    size = (uint32) sizeof(tmp3dec_file);
+    return (size);
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_decode_huff_cw.h"
+
+void pvmp3_InitDecoder(tPVMP3DecoderExternal *pExt,
+                       void  *pMem)
+{
+
+    tmp3dec_file      *pVars;
+    huffcodetab       *pHuff;
+
+    pVars = (tmp3dec_file *)pMem;
+
+    pVars->num_channels = 0;
+
+    pExt->totalNumberOfBitsUsed = 0;
+    pExt->inputBufferCurrentLength = 0;
+    pExt->inputBufferUsedLength    = 0;
+
+    pVars->mainDataStream.offset = 0;
+
+    pv_memset((void*)pVars->mainDataBuffer,
+              0,
+              BUFSIZE*sizeof(*pVars->mainDataBuffer));
+
+
+    pVars->inputStream.pBuffer = pExt->pInputBuffer;
+
+    /*
+     *  Initialize huffman decoding table
+     */
+
+    pHuff = pVars->ht;
+    pHuff[0].linbits = 0;
+    pHuff[0].pdec_huff_tab = pvmp3_decode_huff_cw_tab0;
+    pHuff[1].linbits = 0;
+    pHuff[1].pdec_huff_tab = pvmp3_decode_huff_cw_tab1;
+    pHuff[2].linbits = 0;
+    pHuff[2].pdec_huff_tab = pvmp3_decode_huff_cw_tab2;
+    pHuff[3].linbits = 0;
+    pHuff[3].pdec_huff_tab = pvmp3_decode_huff_cw_tab3;
+    pHuff[4].linbits = 0;
+    pHuff[4].pdec_huff_tab = pvmp3_decode_huff_cw_tab0; /* tbl 4 is not used */
+    pHuff[5].linbits = 4;
+    pHuff[5].pdec_huff_tab = pvmp3_decode_huff_cw_tab5;
+    pHuff[6].linbits = 0;
+    pHuff[6].pdec_huff_tab = pvmp3_decode_huff_cw_tab6;
+    pHuff[7].linbits = 0;
+    pHuff[7].pdec_huff_tab = pvmp3_decode_huff_cw_tab7;
+    pHuff[8].linbits = 0;
+    pHuff[8].pdec_huff_tab = pvmp3_decode_huff_cw_tab8;
+    pHuff[9].linbits = 0;
+    pHuff[9].pdec_huff_tab = pvmp3_decode_huff_cw_tab9;
+    pHuff[10].linbits = 0;
+    pHuff[10].pdec_huff_tab = pvmp3_decode_huff_cw_tab10;
+    pHuff[11].linbits = 0;
+    pHuff[11].pdec_huff_tab = pvmp3_decode_huff_cw_tab11;
+    pHuff[12].linbits = 0;
+    pHuff[12].pdec_huff_tab = pvmp3_decode_huff_cw_tab12;
+    pHuff[13].linbits = 0;
+    pHuff[13].pdec_huff_tab = pvmp3_decode_huff_cw_tab13;
+    pHuff[14].linbits = 0;
+    pHuff[14].pdec_huff_tab = pvmp3_decode_huff_cw_tab0; /* tbl 14 is not used */
+    pHuff[15].linbits = 0;
+    pHuff[15].pdec_huff_tab = pvmp3_decode_huff_cw_tab15;
+    pHuff[16].linbits = 1;
+    pHuff[16].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[17].linbits = 2;
+    pHuff[17].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[18].linbits = 3;
+    pHuff[18].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[19].linbits = 4;
+    pHuff[19].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[20].linbits = 6;
+    pHuff[20].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[21].linbits = 8;
+    pHuff[21].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[22].linbits = 10;
+    pHuff[22].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[23].linbits = 13;
+    pHuff[23].pdec_huff_tab = pvmp3_decode_huff_cw_tab16;
+    pHuff[24].linbits = 4;
+    pHuff[24].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[25].linbits = 5;
+    pHuff[25].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[26].linbits = 6;
+    pHuff[26].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[27].linbits = 7;
+    pHuff[27].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[28].linbits = 8;
+    pHuff[28].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[29].linbits = 9;
+    pHuff[29].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[30].linbits = 11;
+    pHuff[30].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[31].linbits = 13;
+    pHuff[31].pdec_huff_tab = pvmp3_decode_huff_cw_tab24;
+    pHuff[32].linbits = 0;
+    pHuff[32].pdec_huff_tab = pvmp3_decode_huff_cw_tab32;
+    pHuff[33].linbits = 0;
+    pHuff[33].pdec_huff_tab = pvmp3_decode_huff_cw_tab33;
+
+    /*
+     *  Initialize polysynthesis circular buffer mechanism
+     */
+    /* clear buffers */
+
+    pvmp3_resetDecoder(pMem);
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+void pvmp3_resetDecoder(void  *pMem)
+{
+
+    tmp3dec_file      *pVars;
+    tmp3dec_chan      *pChVars[CHAN];
+
+    pVars = (tmp3dec_file *)pMem;
+    pChVars[ LEFT] = &pVars->perChan[ LEFT];
+    pChVars[RIGHT] = &pVars->perChan[RIGHT];
+
+    pVars->frame_start = 0;
+
+    pVars->mainDataStream.offset = 0;
+
+    pVars->mainDataStream.pBuffer =  pVars->mainDataBuffer;
+    pVars->mainDataStream.usedBits = 0;
+
+
+    pVars->inputStream.usedBits = 0; // in bits
+
+
+    pChVars[ LEFT]->used_freq_lines = 575;
+    pChVars[RIGHT]->used_freq_lines = 575;
+
+
+    /*
+     *  Initialize polysynthesis circular buffer mechanism
+     */
+
+    pv_memset((void*)&pChVars[ LEFT]->circ_buffer[576],
+              0,
+              480*sizeof(pChVars[ LEFT]->circ_buffer[0]));
+    pv_memset((void*)&pChVars[RIGHT]->circ_buffer[576],
+              0,
+              480*sizeof(pChVars[RIGHT]->circ_buffer[0]));
+
+
+    pv_memset((void*)pChVars[ LEFT]->overlap,
+              0,
+              SUBBANDS_NUMBER*FILTERBANK_BANDS*sizeof(pChVars[ LEFT]->overlap[0]));
+
+
+    pv_memset((void*)pChVars[ RIGHT]->overlap,
+              0,
+              SUBBANDS_NUMBER*FILTERBANK_BANDS*sizeof(pChVars[ RIGHT]->overlap[0]));
+
+
+
+
+
+    /*
+     *  Clear all the structures
+     */
+
+
+    pv_memset((void*)&pVars->scaleFactors[RIGHT],
+              0,
+              sizeof(mp3ScaleFactors));
+
+    pv_memset((void*)&pVars->scaleFactors[LEFT],
+              0,
+              sizeof(mp3ScaleFactors));
+
+    pv_memset((void*)&pVars->sideInfo,
+              0,
+              sizeof(mp3SideInfo));
+
+    pv_memset((void*)&pVars->sideInfo,
+              0,
+              sizeof(mp3SideInfo));
+
+}
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.h
new file mode 100644
index 0000000..f6d4a35
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_framedecoder.h
@@ -0,0 +1,115 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_framedecoder.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_FRAMEDECODER_H
+#define PVMP3_FRAMEDECODER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3decoder_api.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    ERROR_CODE pvmp3_framedecoder(tPVMP3DecoderExternal *pExt,
+    void                  *pMem);
+
+
+
+    uint32 pvmp3_decoderMemRequirements(void);
+
+    void pvmp3_InitDecoder(tPVMP3DecoderExternal *pExt,
+                           void  *pMem);
+
+
+    void pvmp3_resetDecoder(void                  *pMem);
+
+
+    void fillMainDataBuf(void  *pMem, int32 temp);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp
new file mode 100644
index 0000000..423a7b1
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.cpp
@@ -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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_main_data_size.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Input
+    mp3Header *info,         pointer to mp3 header info structure
+    tmp3dec_file  *pVars
+                             contains information that needs to persist
+                             between calls to this function, or is too big to
+                             be placed on the stack, even though the data is
+                             only needed during execution of this function
+
+  Returns
+
+    main data frame size
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    get main data frame size
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_tables.h"
+#include "pvmp3_get_main_data_size.h"
+#include "pv_mp3dec_fxd_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
+----------------------------------------------------------------------------*/
+
+int32 pvmp3_get_main_data_size(mp3Header *info,
+                               tmp3dec_file  *pVars)
+{
+
+
+    int32 numBytes = fxp_mul32_Q28(mp3_bitrate[info->version_x][info->bitrate_index] << 20,
+                                   inv_sfreq[info->sampling_frequency]);
+
+
+    numBytes >>= (20 - info->version_x);
+
+    /*
+     *  Remove the size of the side information from the main data total
+     */
+    if (info->version_x == MPEG_1)
+    {
+        pVars->predicted_frame_size = numBytes;
+        if (info->mode == MPG_MD_MONO)
+        {
+            numBytes -= 17;
+        }
+        else
+        {
+            numBytes -= 32;
+        }
+    }
+    else
+    {
+        numBytes >>= 1;
+        pVars->predicted_frame_size = numBytes;
+
+        if (info->mode == MPG_MD_MONO)
+        {
+            numBytes -= 9;
+        }
+        else
+        {
+            numBytes -= 17;
+        }
+    }
+
+    if (info->padding)
+    {
+        numBytes++;
+        pVars->predicted_frame_size++;
+    }
+
+    if (info->error_protection)
+    {
+        numBytes -= 6;
+    }
+    else
+    {
+        numBytes -= 4;
+    }
+
+
+    if (numBytes < 0)
+    {
+        numBytes = 0;
+    }
+
+    return(numBytes);
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.h
new file mode 100644
index 0000000..8e9eaa8
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_main_data_size.h
@@ -0,0 +1,101 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_main_data_size.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_GET_MAIN_DATA_SIZE_H
+#define PVMP3_GET_MAIN_DATA_SIZE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "s_tmp3dec_file.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int32 pvmp3_get_main_data_size(mp3Header *info,
+    tmp3dec_file  *pVars);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
new file mode 100644
index 0000000..f1a3ff8
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.cpp
@@ -0,0 +1,226 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_scale_factors.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Input
+    mp3ScaleFactors *scalefac,
+    mp3SideInfo *si,               side info
+    int32 gr,                      granule
+    int32 ch,                      channel
+    tbits *pMainData               bit stream
+
+  Returns
+
+    mp3ScaleFactors *scalefac,   scale factors
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    get scale factors
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_get_scale_factors.h"
+#include "pvmp3_getbits.h"
+#include "mp3_mem_funcs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define Qfmt_28(a)(int32(double(0x10000000)*a))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int32 slen[2][16] =
+{
+    {0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4},
+    {0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3}
+};
+
+const struct
+{
+    int32 l[5];
+    int32 s[3];
+} sfbtable =
+{
+    {0, 6, 11, 16, 21},
+    {0, 6, 12}
+};
+
+const int32 long_sfbtable[4] = { 6, 5, 5, 5};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_get_scale_factors(mp3ScaleFactors *scalefac,
+                             mp3SideInfo    *si,
+                             int32          gr,
+                             int32          ch,
+                             tmp3Bits       *pMainData)
+{
+    int32 sfb;
+    int32 i;
+    int32 window;
+    granuleInfo *gr_info = &(si->ch[ch].gran[gr]);
+
+    if (gr_info->window_switching_flag && (gr_info->block_type == 2))
+    {
+        if (gr_info->mixed_block_flag)
+        { /* MIXED */
+            for (sfb = 0; sfb < 8; sfb++)
+            {
+                scalefac->l[sfb] = getNbits(pMainData, slen[0][gr_info->scalefac_compress]);
+            }
+
+            for (sfb = 3; sfb < 6; sfb++)
+            {
+                for (window = 0; window < 3; window++)
+                {
+                    scalefac->s[window][sfb] = getNbits(pMainData, slen[0][gr_info->scalefac_compress]);
+                }
+            }
+            for (sfb = 6; sfb < 12; sfb++)
+            {
+                for (window = 0; window < 3; window++)
+                {
+                    scalefac->s[window][sfb] = getNbits(pMainData, slen[1][gr_info->scalefac_compress]);
+                }
+            }
+        }
+        else
+        {  /* SHORT*/
+            for (i = 0; i < 2; i++)
+            {
+                for (sfb = sfbtable.s[i]; sfb < sfbtable.s[i+1]; sfb++)
+                {
+                    for (window = 0; window < 3; window++)
+                    {
+                        scalefac->s[window][sfb] = getNbits(pMainData, slen[i][gr_info->scalefac_compress]);
+                    }
+                }
+            }
+        }
+
+        scalefac->s[0][12] = 0;    /* sfb = 12 win= 0 */
+        scalefac->s[1][12] = 0;    /* sfb = 12 win= 1 */
+        scalefac->s[2][12] = 0;    /* sfb = 12 win= 2 */
+    }
+    else
+    {   /* LONG types 0,1,3 */
+
+        int32 *ptr = &scalefac->l[0];
+
+        for (i = 0; i < 4; i++)
+        {
+            int32 tmp4 = long_sfbtable[i];
+
+            if ((si->ch[ch].scfsi[i] == 0) || (gr == 0))
+            {
+                int32 tmp1 = slen[(i>>1)][gr_info->scalefac_compress];
+
+                if (tmp1)
+                {
+                    int32 tmp2 = tmp1 * tmp4;
+                    uint32 tmp3 = getNbits(pMainData, tmp2);
+                    tmp4 = 32 - tmp1;
+                    for (; tmp2 > 0; tmp2 -= tmp1)
+                    {
+                        *(ptr++) = (tmp3 << (32 - tmp2)) >> tmp4;
+                    }
+                }
+                else
+                {
+                    for (sfb = tmp4; sfb != 0; sfb--)
+                    {
+                        *(ptr++) = 0;
+                    }
+
+                }
+            }
+            else
+            {
+                ptr += tmp4;
+            }
+        }
+        scalefac->l[21] = 0;
+        scalefac->l[22] = 0;
+    }
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.h
new file mode 100644
index 0000000..d4f262bf
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_scale_factors.h
@@ -0,0 +1,104 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_scale_factors.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_GET_SCALE_FACTORS_H
+#define PVMP3_GET_SCALE_FACTORS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_get_scale_factors(mp3ScaleFactors *scalefac,
+    mp3SideInfo *si,
+    int32 gr,
+    int32 ch,
+    tmp3Bits *pMainData);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp
new file mode 100644
index 0000000..7eaa860
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.cpp
@@ -0,0 +1,285 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_side_info.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    mp3SideInfo     *si,
+    mp3Header       *info,             mp3 header information
+    uint32          *crc               initialized crc value (if enabled)
+
+
+ Returns
+
+    mp3SideInfo     *si,               side information
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    acquires side information
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_get_side_info.h"
+#include "pvmp3_crc.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
+----------------------------------------------------------------------------*/
+
+ERROR_CODE pvmp3_get_side_info(tmp3Bits    *inputStream,
+                               mp3SideInfo *si,
+                               mp3Header   *info,
+                               uint32      *crc)
+{
+    int32 ch, gr;
+    uint32 tmp;
+
+    int stereo  = (info->mode == MPG_MD_MONO) ? 1 : 2;
+
+    if (info->version_x == MPEG_1)
+    {
+        if (stereo == 1)
+        {
+            tmp = getbits_crc(inputStream, 14, crc, info->error_protection);
+            si->main_data_begin = (tmp << 18) >> 23;    /* 9 */
+            si->private_bits    = (tmp << 23) >> 27;    /* 5 */
+        }
+        else
+        {
+            tmp = getbits_crc(inputStream, 12, crc, info->error_protection);
+            si->main_data_begin = (tmp << 20) >> 23;    /* 9 */
+            si->private_bits    = (tmp << 23) >> 29;    /* 3 */
+
+        }
+
+        for (ch = 0; ch < stereo; ch++)
+        {
+            tmp = getbits_crc(inputStream, 4, crc, info->error_protection);
+            si->ch[ch].scfsi[0] = (tmp << 28) >> 31;    /* 1 */
+            si->ch[ch].scfsi[1] = (tmp << 29) >> 31;    /* 1 */
+            si->ch[ch].scfsi[2] = (tmp << 30) >> 31;    /* 1 */
+            si->ch[ch].scfsi[3] =  tmp & 1;         /* 1 */
+        }
+
+        for (gr = 0; gr < 2 ; gr++)
+        {
+            for (ch = 0; ch < stereo; ch++)
+            {
+                si->ch[ch].gran[gr].part2_3_length    = getbits_crc(inputStream, 12, crc, info->error_protection);
+                tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
+
+                si->ch[ch].gran[gr].big_values            = (tmp << 10) >> 23;   /* 9 */
+                si->ch[ch].gran[gr].global_gain           = ((tmp << 19) >> 24) - 210;   /* 8 */
+                si->ch[ch].gran[gr].scalefac_compress     = (tmp << 27) >> 28;   /* 4 */
+                si->ch[ch].gran[gr].window_switching_flag = tmp & 1;         /* 1 */
+
+                if (si->ch[ch].gran[gr].window_switching_flag)
+                {
+                    tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
+
+                    si->ch[ch].gran[gr].block_type       = (tmp << 10) >> 30;   /* 2 */;
+                    si->ch[ch].gran[gr].mixed_block_flag = (tmp << 12) >> 31;   /* 1 */;
+
+                    si->ch[ch].gran[gr].table_select[0]  = (tmp << 13) >> 27;   /* 5 */;
+                    si->ch[ch].gran[gr].table_select[1]  = (tmp << 18) >> 27;   /* 5 */;
+
+                    si->ch[ch].gran[gr].subblock_gain[0] = (tmp << 23) >> 29;   /* 3 */;
+                    si->ch[ch].gran[gr].subblock_gain[1] = (tmp << 26) >> 29;   /* 3 */;
+                    si->ch[ch].gran[gr].subblock_gain[2] = (tmp << 29) >> 29;   /* 3 */;
+
+                    /* Set region_count parameters since they are implicit in this case. */
+
+                    if (si->ch[ch].gran[gr].block_type == 0)
+                    {
+                        return(SIDE_INFO_ERROR);
+                    }
+                    else if ((si->ch[ch].gran[gr].block_type       == 2)
+                             && (si->ch[ch].gran[gr].mixed_block_flag == 0))
+                    {
+                        si->ch[ch].gran[gr].region0_count = 8; /* MI 9; */
+                        si->ch[ch].gran[gr].region1_count = 12;
+                    }
+                    else
+                    {
+                        si->ch[ch].gran[gr].region0_count = 7; /* MI 8; */
+                        si->ch[ch].gran[gr].region1_count = 13;
+                    }
+                }
+                else
+                {
+                    tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
+
+                    si->ch[ch].gran[gr].table_select[0] = (tmp << 10) >> 27;   /* 5 */;
+                    si->ch[ch].gran[gr].table_select[1] = (tmp << 15) >> 27;   /* 5 */;
+                    si->ch[ch].gran[gr].table_select[2] = (tmp << 20) >> 27;   /* 5 */;
+
+                    si->ch[ch].gran[gr].region0_count   = (tmp << 25) >> 28;   /* 4 */;
+                    si->ch[ch].gran[gr].region1_count   = (tmp << 29) >> 29;   /* 3 */;
+
+                    si->ch[ch].gran[gr].block_type      = 0;
+                }
+
+                tmp = getbits_crc(inputStream, 3, crc, info->error_protection);
+                si->ch[ch].gran[gr].preflag            = (tmp << 29) >> 31;    /* 1 */
+                si->ch[ch].gran[gr].scalefac_scale     = (tmp << 30) >> 31;    /* 1 */
+                si->ch[ch].gran[gr].count1table_select =  tmp & 1;         /* 1 */
+            }
+        }
+    }
+    else /* Layer 3 LSF */
+    {
+        si->main_data_begin = getbits_crc(inputStream,      8, crc, info->error_protection);
+        si->private_bits    = getbits_crc(inputStream, stereo, crc, info->error_protection);
+
+        for (ch = 0; ch < stereo; ch++)
+        {
+            tmp = getbits_crc(inputStream, 21, crc, info->error_protection);
+            si->ch[ch].gran[0].part2_3_length    = (tmp << 11) >> 20;  /* 12 */
+            si->ch[ch].gran[0].big_values        = (tmp << 23) >> 23;  /*  9 */
+
+            tmp = getbits_crc(inputStream, 18, crc, info->error_protection);
+            si->ch[ch].gran[0].global_gain           = ((tmp << 14) >> 24) - 210;   /* 8 */
+            si->ch[ch].gran[0].scalefac_compress     = (tmp << 22) >> 23;   /* 9 */
+            si->ch[ch].gran[0].window_switching_flag = tmp & 1;         /* 1 */
+
+            if (si->ch[ch].gran[0].window_switching_flag)
+            {
+
+                tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
+
+                si->ch[ch].gran[0].block_type       = (tmp << 10) >> 30;   /* 2 */;
+                si->ch[ch].gran[0].mixed_block_flag = (tmp << 12) >> 31;   /* 1 */;
+
+                si->ch[ch].gran[0].table_select[0]  = (tmp << 13) >> 27;   /* 5 */;
+                si->ch[ch].gran[0].table_select[1]  = (tmp << 18) >> 27;   /* 5 */;
+
+                si->ch[ch].gran[0].subblock_gain[0] = (tmp << 23) >> 29;   /* 3 */;
+                si->ch[ch].gran[0].subblock_gain[1] = (tmp << 26) >> 29;   /* 3 */;
+                si->ch[ch].gran[0].subblock_gain[2] = (tmp << 29) >> 29;   /* 3 */;
+
+                /* Set region_count parameters since they are implicit in this case. */
+
+                if (si->ch[ch].gran[0].block_type == 0)
+                {
+                    return(SIDE_INFO_ERROR);
+                }
+                else if ((si->ch[ch].gran[0].block_type       == 2)
+                         && (si->ch[ch].gran[0].mixed_block_flag == 0))
+                {
+                    si->ch[ch].gran[0].region0_count = 8; /* MI 9; */
+                    si->ch[ch].gran[0].region1_count = 12;
+                }
+                else
+                {
+                    si->ch[ch].gran[0].region0_count = 7; /* MI 8; */
+                    si->ch[ch].gran[0].region1_count = 13;
+                }
+            }
+            else
+            {
+                tmp = getbits_crc(inputStream, 22, crc, info->error_protection);
+
+                si->ch[ch].gran[0].table_select[0] = (tmp << 10) >> 27;   /* 5 */;
+                si->ch[ch].gran[0].table_select[1] = (tmp << 15) >> 27;   /* 5 */;
+                si->ch[ch].gran[0].table_select[2] = (tmp << 20) >> 27;   /* 5 */;
+
+                si->ch[ch].gran[0].region0_count   = (tmp << 25) >> 28;   /* 4 */;
+                si->ch[ch].gran[0].region1_count   = (tmp << 29) >> 29;   /* 3 */;
+
+                si->ch[ch].gran[0].block_type      = 0;
+            }
+
+            tmp = getbits_crc(inputStream, 2, crc, info->error_protection);
+            si->ch[ch].gran[0].scalefac_scale     =  tmp >> 1;  /* 1 */
+            si->ch[ch].gran[0].count1table_select =  tmp & 1;  /* 1 */
+
+        }
+    }
+    return (NO_DECODING_ERROR);
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.h
new file mode 100644
index 0000000..2d6ccd8
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_get_side_info.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_get_side_info.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_GET_SIDE_INFO_H
+#define PVMP3_GET_SIDE_INFO_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    ERROR_CODE pvmp3_get_side_info(tmp3Bits  *inputStream,
+    mp3SideInfo *si,
+    mp3Header *info,
+    uint32 *crc);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp
new file mode 100644
index 0000000..8ff7953
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.cpp
@@ -0,0 +1,257 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_getbits.cpp
+
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    tmp3Bits *inputStream,     structure holding the input stream parameters
+    int32     neededBits       number of bits to read from the bit stream
+
+ Outputs:
+
+    word parsed from teh bitstream, with size neededBits-bits,
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_getbits.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
+----------------------------------------------------------------------------*/
+
+uint32 getNbits(tmp3Bits *ptBitStream,
+                int32 neededBits) /* number of bits to read from the bitstream (up to 25) */
+{
+
+    uint32    offset;
+    uint32    bitIndex;
+    uint8     Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8     Elem1;
+    uint8     Elem2;
+    uint8     Elem3;
+    uint32   returnValue = 0;
+
+    if (!neededBits)
+    {
+        return (returnValue);
+    }
+
+    offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
+    Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
+    Elem3 = *(ptBitStream->pBuffer + module(offset + 3, BUFSIZE));
+
+
+    returnValue = (((uint32)(Elem)) << 24) |
+                  (((uint32)(Elem1)) << 16) |
+                  (((uint32)(Elem2)) << 8) |
+                  ((uint32)(Elem3));
+
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
+    /* This line is faster than to mask off the high bits. */
+    returnValue <<= bitIndex;
+
+    /* Move the field down. */
+    returnValue >>= (32 - neededBits);
+
+    ptBitStream->usedBits += neededBits;
+
+    return (returnValue);
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+uint16 getUpTo9bits(tmp3Bits *ptBitStream,
+                    int32 neededBits) /* number of bits to read from the bit stream 2 to 9 */
+{
+
+    uint32    offset;
+    uint32    bitIndex;
+    uint8    Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8    Elem1;
+    uint16   returnValue;
+
+    offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
+
+
+    returnValue = (((uint16)(Elem)) << 8) |
+                  ((uint16)(Elem1));
+
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
+    ptBitStream->usedBits += neededBits;
+    /* This line is faster than to mask off the high bits. */
+    returnValue = (returnValue << (bitIndex));
+
+    /* Move the field down. */
+
+    return (uint16)(returnValue >> (16 - neededBits));
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+uint32 getUpTo17bits(tmp3Bits *ptBitStream,
+                     int32 neededBits) /* number of bits to read from the bit stream 2 to 8 */
+{
+
+    uint32    offset;
+    uint32    bitIndex;
+    uint8     Elem;         /* Needs to be same type as pInput->pBuffer */
+    uint8     Elem1;
+    uint8     Elem2;
+    uint32   returnValue;
+
+    offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+    Elem  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+    Elem1 = *(ptBitStream->pBuffer + module(offset + 1, BUFSIZE));
+    Elem2 = *(ptBitStream->pBuffer + module(offset + 2, BUFSIZE));
+
+
+    returnValue = (((uint32)(Elem)) << 16) |
+                  (((uint32)(Elem1)) << 8) |
+                  ((uint32)(Elem2));
+
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+
+    ptBitStream->usedBits += neededBits;
+    /* This line is faster than to mask off the high bits. */
+    returnValue = 0xFFFFFF & (returnValue << (bitIndex));
+
+    /* Move the field down. */
+
+    return (uint32)(returnValue >> (24 - neededBits));
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+uint8 get1bit(tmp3Bits *ptBitStream)  /* number of bits to read from the bit stream */
+{
+
+    uint32    offset;
+    uint32    bitIndex;
+    uint8   returnValue;
+
+    offset = (ptBitStream->usedBits) >> INBUF_ARRAY_INDEX_SHIFT;
+
+    returnValue  = *(ptBitStream->pBuffer + module(offset  , BUFSIZE));
+
+    /* Remove extra high bits by shifting up */
+    bitIndex = module(ptBitStream->usedBits, INBUF_BIT_WIDTH);
+    ptBitStream->usedBits++;
+
+    /* This line is faster than to mask off the high bits. */
+    returnValue = (returnValue << (bitIndex));
+
+    return (uint8)(returnValue >> 7);
+
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.h
new file mode 100644
index 0000000..b058b00
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_getbits.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_getbits.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_GETBITS_H
+#define PVMP3_GETBITS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_dec_defs.h"
+#include "s_mp3bits.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define INBUF_ARRAY_INDEX_SHIFT  (3)
+#define INBUF_BIT_WIDTH         (1<<(INBUF_ARRAY_INDEX_SHIFT))
+#define INBUF_BIT_MODULO_MASK   ((INBUF_BIT_WIDTH)-1)
+
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    uint32 getNbits(tmp3Bits *pMainData,
+    int32 neededBits);
+
+    uint16 getUpTo9bits(tmp3Bits *pMainData,
+                        int32 neededBits);
+
+    uint32 getUpTo17bits(tmp3Bits *pMainData,
+                         int32 neededBits);
+
+    uint8 get1bit(tmp3Bits *pMainData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp
new file mode 100644
index 0000000..5d58cd2
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_decoding.cpp
@@ -0,0 +1,304 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_huffman_decoding.cpp
+
+ Funtions:
+    pvmp3_huffman_quad_decoding
+    pvmp3_huffman_pair_decoding
+    pvmp3_huffman_pair_decoding_linbits
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    struct huffcodetab *h,   pointer to huffman code record
+    int32 *x,    returns decoded x value
+    int32 *y,    returns decoded y value
+    int32 *v,    returns decoded v value   (only in quad function)
+    int32 *w,    returns decoded w value   (only in quad function)
+    tbits *pMainData     bit stream
+
+ Outputs:
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   These functions are used to decode huffman codewords from the input
+   bitstream using combined binary search and look-up table approach.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_dec_defs.h"
+#include "pv_mp3_huffman.h"
+#include "pvmp3_getbits.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 pvmp3_huffman_quad_decoding(struct huffcodetab *h,
+                                 int32 *is,
+                                 tmp3Bits *pMainData)
+{
+
+    int32 x;
+    int32 y;
+    int32 v;
+    int32 w;
+
+    y = (*h->pdec_huff_tab)(pMainData);
+
+
+    if (y)
+    {
+        v = (y >> 3);
+
+        if (v)
+        {
+            if (get1bit(pMainData))
+            {
+                v = -v;
+            }
+        }
+        w = (y >> 2) & 1;
+        if (w)
+        {
+            if (get1bit(pMainData))
+            {
+                w = -w;
+            }
+        }
+        x = (y >> 1) & 1;
+        if (x)
+        {
+            if (get1bit(pMainData))
+            {
+                x = -x;
+            }
+        }
+        y =  y & 1;
+        if (y)
+        {
+            if (get1bit(pMainData))
+            {
+                y = -y;
+            }
+        }
+
+    }
+    else
+    {
+        v = 0;
+        w = 0;
+        x = 0;
+
+    }
+
+    *is     = v;
+    *(is + 1) = w;
+    *(is + 2) = x;
+    *(is + 3) = y;
+
+}
+
+
+
+void pvmp3_huffman_pair_decoding(struct huffcodetab *h,     /* pointer to huffman code record   */
+                                 int32 *is,
+                                 tmp3Bits *pMainData)
+{
+    /* Lookup in Huffman table. */
+    int32 x;
+    int32 y;
+
+    uint16 cw = (*h->pdec_huff_tab)(pMainData);
+
+    /* Process sign and escape encodings for dual tables. */
+
+
+    if (cw)
+    {
+        x = cw >> 4;
+
+        if (x)
+        {
+            if (get1bit(pMainData))
+            {
+                x = -x;
+            }
+            y = cw & 0xf;
+            if (y && get1bit(pMainData))
+            {
+                y = -y;
+            }
+
+        }
+        else
+        {
+            y = cw & 0xf;
+            if (get1bit(pMainData))
+            {
+                y = -y;
+            }
+        }
+
+        *is     = x;
+        *(is + 1) = y;
+    }
+    else
+    {
+        *is     = 0;
+        *(is + 1) = 0;
+    }
+
+
+
+}
+
+
+
+
+void pvmp3_huffman_pair_decoding_linbits(struct huffcodetab *h,     /* pointer to huffman code record   */
+        int32 *is,
+        tmp3Bits *pMainData)
+{
+    int32 x;
+    int32 y;
+
+    uint16 cw;
+    /* Lookup in Huffman table. */
+
+
+    cw = (*h->pdec_huff_tab)(pMainData);
+    x = cw >> 4;
+
+    /* Process sign and escape encodings for dual tables. */
+
+
+    if (15 == (uint32)x)
+    {
+        int32 tmp = getUpTo17bits(pMainData, (h->linbits + 1));
+        x += tmp >> 1;
+        if (tmp&1)
+        {
+            x = -x;
+        }
+    }
+    else if (x)
+    {
+        if (get1bit(pMainData))
+        {
+            x = -x;
+        }
+    }
+
+    y = cw & 0xf;
+    if (15 == (uint32)y)
+    {
+        int32 tmp = getUpTo17bits(pMainData, (h->linbits + 1));
+        y += tmp >> 1;
+        if (tmp&1)
+        {
+            y = -y;
+        }
+    }
+    else if (y)
+    {
+        if (get1bit(pMainData))
+        {
+            y = -y;
+        }
+    }
+
+    *is     = x;
+    *(is + 1) = y;
+
+}
+
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp
new file mode 100644
index 0000000..ff815dc
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_huffman_parsing.cpp
@@ -0,0 +1,328 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_huffman_decoding.cpp
+
+ Funtions:
+    pvmp3_huffman_quad_decoding
+    pvmp3_huffman_pair_decoding
+    pvmp3_huffman_pair_decoding_linbits
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+    int32 is[],
+    granuleInfo  *grInfo,    information for the given channel and granule
+    tmp3dec_file   *pVars,   decoder state structure
+    int32 part2_start,       index to beginning of part 2 data
+    mp3Header *info          mp3 header info
+
+ Outputs:
+    int32 is[],              uncompressed data
+
+  Return:
+     non zero frequency lines
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+   These functions are used to decode huffman codewords from the input
+   bitstream using combined binary search and look-up table approach.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_mp3_huffman.h"
+#include "s_mp3bits.h"
+#include "mp3_mem_funcs.h"
+#include "pvmp3_tables.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
+----------------------------------------------------------------------------*/
+
+int32 pvmp3_huffman_parsing(int32 is[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                            granuleInfo *grInfo,
+                            tmp3dec_file   *pVars,
+                            int32 part2_start,
+                            mp3Header *info)
+
+
+{
+    int32 i;
+    int32 region1Start;
+    int32 region2Start;
+    int32 sfreq;
+    uint32 grBits;
+    void(*pt_huff)(struct huffcodetab *, int32 *, tmp3Bits *);
+    struct huffcodetab *h;
+
+    tmp3Bits *pMainData = &pVars->mainDataStream;
+
+
+    /*int32 bt = (*si).ch[ch].gr[gr].window_switching_flag && ((*si).ch[ch].gr[gr].block_type == 2);*/
+
+    sfreq = info->sampling_frequency + info->version_x + (info->version_x << 1);
+
+    /* Find region boundary for short block case. */
+
+
+    if ((grInfo->window_switching_flag) && (grInfo->block_type == 2))
+    {
+        if (info->version_x == MPEG_1)
+        {
+            /* Region2. */
+            region1Start = 12;
+        }
+        else
+        {
+            /* Region2. */
+            i = grInfo->region0_count + 1;
+            region1Start = mp3_sfBandIndex[sfreq].s[i/3];
+        }
+
+        region1Start += region1Start << 1;
+        region2Start = 576; /* No Region2 for short block case. */
+    }
+    else
+    {          /* Find region boundary for long block case. */
+        i = grInfo->region0_count + 1;
+        region1Start = mp3_sfBandIndex[sfreq].l[i];
+        region2Start = mp3_sfBandIndex[sfreq].l[i + grInfo->region1_count + 1];
+    }
+
+    /* Read bigvalues area. */
+
+
+    if (grInfo->big_values > (FILTERBANK_BANDS*SUBBANDS_NUMBER >> 1))
+    {
+        grInfo->big_values = (FILTERBANK_BANDS * SUBBANDS_NUMBER >> 1);
+    }
+
+    if ((grInfo->big_values << 1) > (uint32)region2Start)
+    {
+        h = &(pVars->ht[grInfo->table_select[0]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+
+        for (i = 0; i < region1Start; i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+
+        h = &(pVars->ht[grInfo->table_select[1]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+
+        for (; i < region2Start; i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+
+        h = &(pVars->ht[grInfo->table_select[2]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+
+        for (; (uint32)i < (grInfo->big_values << 1); i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+    }
+    else if ((grInfo->big_values << 1) > (uint32)region1Start)
+    {
+        h = &(pVars->ht[grInfo->table_select[0]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+        for (i = 0; i < region1Start; i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+
+        h = &(pVars->ht[grInfo->table_select[1]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+        for (; (uint32)i < (grInfo->big_values << 1); i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+    }
+    else
+    {
+        h = &(pVars->ht[grInfo->table_select[0]]);
+        if (h->linbits)
+        {
+            pt_huff = pvmp3_huffman_pair_decoding_linbits;
+        }
+        else
+        {
+            pt_huff = pvmp3_huffman_pair_decoding;
+        }
+
+        for (i = 0; (uint32)i < (grInfo->big_values << 1); i += 2)
+        {
+            (*pt_huff)(h, &is[i], pMainData);
+        }
+    }
+
+
+
+    /* Read count1 area. */
+    h = &(pVars->ht[grInfo->count1table_select+32]);
+
+    grBits     = part2_start + grInfo->part2_3_length;
+
+    while ((pMainData->usedBits < grBits) &&
+            (i < FILTERBANK_BANDS*SUBBANDS_NUMBER - 4))
+    {
+        pvmp3_huffman_quad_decoding(h, &is[i], pMainData);
+        i += 4;
+    }
+
+    if ((pMainData->usedBits < grBits) &&
+            (i < FILTERBANK_BANDS*SUBBANDS_NUMBER))
+    {
+        pvmp3_huffman_quad_decoding(h, &is[i], pMainData);
+        i += 4;
+
+        if ((i - 2) >= FILTERBANK_BANDS*SUBBANDS_NUMBER)
+        {
+            i -= 2;
+            is[i] = 0;
+            is[(i+1)] = 0;
+        }
+    }
+
+    if (pMainData->usedBits > grBits)
+    {
+        i -= 4;
+
+        if (i < 0 || i > FILTERBANK_BANDS*SUBBANDS_NUMBER - 4)
+        {
+            /* illegal parameters may cause invalid access, set i to 0 */
+            i = 0;
+        }
+
+        is[i] = 0;
+        is[(i+1)] = 0;
+        is[(i+2)] = 0;
+        is[(i+3)] = 0;
+
+    }
+
+    pMainData->usedBits = grBits;
+
+    return (i);
+
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.cpp
new file mode 100644
index 0000000..11961d1
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.cpp
@@ -0,0 +1,376 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_imdct_synth.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Input
+    int32 in[],         Pointer to spec values of current channel
+    int32 overlap[],    Pointer to overlap values of current channel
+    uint32 blk_type,    Block type
+    int16 mx_band,      In case of mixed blocks, # of bands with long
+                        blocks (2 or 4) else 0
+    int32 *Scratch_mem
+  Returns
+
+    int32 in[],
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    The frequency lines are preprocessed by the "alias reduction" scheme
+    and fed into the IMDCT matrix, each 18 into one transform block.
+    The first half of the output values are added to the stored overlap
+    values from the last block. These values are new output values and
+    are input values for the polyphase filterbank. The second half of the
+    output values is stored for overlap with the next data granule.
+    The number of windowed samples is 12 for short blocks, and 36 for long
+    blocks
+
+Windowing
+
+    Depending on window_switching_flag[gr][ch], block_type[gr][ch] and
+    mixed_block_flag[gr][ch] different shapes of windows are used.
+        normal window
+        start window
+        stop window
+        short windows
+            Each of the three short blocks is windowed separately.
+            The windowed short blocks must be overlapped and concatenated.
+
+Overlapping and adding with previous block
+
+    The first half (18 values) of the current block (36 values) has to be
+    overlapped with the second half of the previous block. The second half
+    of the current block has to be stored for overlapping with the next block
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_imdct_synth.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_mdct_18.h"
+#include "pvmp3_mdct_6.h"
+#include "mp3_mem_funcs.h"
+
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define LONG        0
+#define START       1
+#define SHORT       2
+#define STOP        3
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/*
+ *   sin(pi/36*(k+0.5)),k=0..35
+ */
+
+const int32 normal_win[36] =
+{
+    Qfmt_31(0.08723877473068f),   Qfmt_31(0.26105238444010f),   Qfmt_31(0.43287922787620f),
+    Qfmt_31(0.60141159900854f),   Qfmt_31(0.76536686473018f),   Qfmt_31(0.92349722647006f),
+    Qfmt_31(0.53729960834682f),   Qfmt_31(0.60876142900872f),   Qfmt_31(0.67559020761566f),
+    Qfmt_31(-0.73727733681012f),   Qfmt_31(-0.79335334029124f),   Qfmt_31(0.84339144581289f),
+    Qfmt_31(0.88701083317822f),   Qfmt_31(0.92387953251129f),   Qfmt_31(-0.95371695074823f),
+    Qfmt_31(-0.97629600711993f),   Qfmt_31(-0.99144486137381f),   Qfmt_31(-0.99904822158186f),
+    Qfmt_31(0.99904822158186f),   Qfmt_31(0.99144486137381f),   Qfmt_31(0.97629600711993f),
+    Qfmt_31(0.95371695074823f),   Qfmt_31(0.92387953251129f),   Qfmt_31(0.88701083317822f),
+    Qfmt_31(0.84339144581289f),   Qfmt_31(0.79335334029124f),   Qfmt_31(0.73727733681012f),
+    Qfmt_31(0.67559020761566f),   Qfmt_31(0.60876142900872f),   Qfmt_31(0.53729960834682f),
+    Qfmt_31(0.46174861323503f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.30070579950427f),
+    Qfmt_31(0.21643961393810f),   Qfmt_31(0.13052619222005f),   Qfmt_31(0.04361938736534f)
+};
+
+
+const int32 start_win[36] =
+{
+    /*   k=0..17  sin(pi/36*(k+0.5)),  */
+    Qfmt_31(0.08723877473068f),   Qfmt_31(0.26105238444010f),   Qfmt_31(0.43287922787620f),
+    Qfmt_31(0.60141159900854f),   Qfmt_31(0.76536686473018f),   Qfmt_31(0.92349722647006f),
+    Qfmt_31(0.53729960834682f),   Qfmt_31(0.60876142900872f),   Qfmt_31(0.67559020761566f),
+    Qfmt_31(-0.73727733681012f),   Qfmt_31(-0.79335334029124f),   Qfmt_31(0.84339144581289f),
+    Qfmt_31(0.88701083317822f),   Qfmt_31(0.92387953251129f),   Qfmt_31(-0.95371695074823f),
+    Qfmt_31(-0.97629600711993f),   Qfmt_31(-0.99144486137381f),   Qfmt_31(-0.99904822158186f),
+
+    Qfmt_31(0.99999990000000f),   Qfmt_31(0.99999990000000f),   Qfmt_31(0.99999990000000f),
+    Qfmt_31(0.99999990000000f),   Qfmt_31(0.99999990000000f),   Qfmt_31(0.99999990000000f),
+    /*    k=24..29; sin(pi/12*(k-18+0.5)) */
+    Qfmt_31(0.99144486137381f),   Qfmt_31(0.92387953251129f),   Qfmt_31(0.79335334029124f),
+    Qfmt_31(0.60876142900872f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.13052619222005f),
+
+    Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),
+    Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f)
+};
+
+
+const int32 stop_win[36] =
+{
+    Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),
+    Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),   Qfmt_31(0.00000000000000f),
+    /*    k=6..11; sin(pi/12*(k-6+0.5)) */
+    Qfmt_31(0.13052619222005f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.60876142900872f),
+    Qfmt_31(-0.79335334029124f),   Qfmt_31(-0.92387953251129f),   Qfmt_31(0.99144486137381f),
+
+    Qfmt_31(0.99999990000000f),   Qfmt_31(0.99999990000000f),   Qfmt_31(-0.99999990000000f),
+    Qfmt_31(-0.99999990000000f),   Qfmt_31(-0.99999990000000f),   Qfmt_31(-0.99999990000000f),
+    /*   k=18..35  sin(pi/36*(k+0.5)),  */
+    Qfmt_31(0.99904822158186f),   Qfmt_31(0.99144486137381f),   Qfmt_31(0.97629600711993f),
+    Qfmt_31(0.95371695074823f),   Qfmt_31(0.92387953251129f),   Qfmt_31(0.88701083317822f),
+    Qfmt_31(0.84339144581289f),   Qfmt_31(0.79335334029124f),   Qfmt_31(0.73727733681012f),
+    Qfmt_31(0.67559020761566f),   Qfmt_31(0.60876142900872f),   Qfmt_31(0.53729960834682f),
+    Qfmt_31(0.46174861323503f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.30070579950427f),
+    Qfmt_31(0.21643961393810f),   Qfmt_31(0.13052619222005f),   Qfmt_31(0.04361938736534f)
+};
+
+
+const int32 short_win[12] =
+{
+    /*    k=0..11; sin(pi/12*(k+0.5)) */
+    Qfmt_31(0.13052619222005f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.60876142900872f),
+    Qfmt_31(0.79335334029124f),   Qfmt_31(0.92387953251129f),   Qfmt_31(0.99144486137381f),
+    Qfmt_31(0.99144486137381f),   Qfmt_31(0.92387953251129f),   Qfmt_31(0.79335334029124f),
+    Qfmt_31(0.60876142900872f),   Qfmt_31(0.38268343236509f),   Qfmt_31(0.13052619222005f),
+};
+/*----------------------------------------------------------------------------
+; 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 pvmp3_imdct_synth(int32  in[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       int32  overlap[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       uint32 blk_type,
+                       int16  mx_band,
+                       int32  used_freq_lines,
+                       int32  *Scratch_mem)
+{
+
+    int32 band;
+    int32 bands2process = used_freq_lines + 2;
+
+    if (bands2process > SUBBANDS_NUMBER)
+    {
+        bands2process = SUBBANDS_NUMBER;  /* default */
+    }
+
+
+    /*
+     *  in case of mx_poly_band> 0, do
+     *  long transforms
+     */
+
+
+    for (band = 0; band < bands2process; band++)
+    {
+        uint32 current_blk_type = (band < mx_band) ? LONG : blk_type;
+
+        int32 * out     = in      + (band * FILTERBANK_BANDS);
+        int32 * history = overlap + (band * FILTERBANK_BANDS);
+
+        switch (current_blk_type)
+        {
+            case LONG:
+
+                pvmp3_mdct_18(out, history, normal_win);
+
+                break;
+
+            case START:
+
+                pvmp3_mdct_18(out, history, start_win);
+
+                break;
+
+            case STOP:
+
+                pvmp3_mdct_18(out, history, stop_win);
+
+                break;
+
+            case SHORT:
+            {
+                int32 *tmp_prev_ovr = &Scratch_mem[FILTERBANK_BANDS];
+                int32 i;
+
+                for (i = 0; i < 6; i++)
+                {
+                    Scratch_mem[i    ] = out[(i*3)];
+                    Scratch_mem[6  +i] = out[(i*3) + 1];
+                    Scratch_mem[12 +i] = out[(i*3) + 2];
+                }
+
+                pvmp3_mdct_6(&Scratch_mem[ 0], &tmp_prev_ovr[ 0]);
+                pvmp3_mdct_6(&Scratch_mem[ 6], &tmp_prev_ovr[ 6]);
+                pvmp3_mdct_6(&Scratch_mem[12], &tmp_prev_ovr[12]);
+
+                for (i = 0; i < 6; i++)
+                {
+                    int32 temp  =  history[i];
+                    /* next iteration overlap */
+                    history[i]  =  fxp_mul32_Q32(tmp_prev_ovr[ 6+i] << 1, short_win[6+i]);
+                    history[i] +=  fxp_mul32_Q32(Scratch_mem[12+i] << 1, short_win[  i]);
+                    out[i]  =  temp;
+                }
+
+                for (i = 0; i < 6; i++)
+                {
+                    out[i+6]   =  fxp_mul32_Q32(Scratch_mem[i] << 1, short_win[i]);
+                    out[i+6]  +=  history[i+6];
+                    /* next iteration overlap */
+                    history[i+6]  =  fxp_mul32_Q32(tmp_prev_ovr[12+i] << 1, short_win[6+i]);
+
+                }
+                for (i = 0; i < 6; i++)
+                {
+                    out[i+12]  =  fxp_mul32_Q32(tmp_prev_ovr[  i] << 1, short_win[6+i]);
+                    out[i+12] +=  fxp_mul32_Q32(Scratch_mem[6+i] << 1, short_win[  i]);
+                    out[i+12] +=  history[i+12];
+                    history[12+i]  =  0;
+                }
+            }
+
+            break;
+        }
+
+        /*
+         *     Compensation for frequency inversion of polyphase filterbank
+         *     every odd time sample of every odd odd subband is mulitplied by -1  before
+         *     processing by the polyphase filter
+         */
+
+        if (band & 1)
+        {
+            for (int32 slot = 1; slot < FILTERBANK_BANDS; slot += 6)
+            {
+                int32 temp1 = out[slot  ];
+                int32 temp2 = out[slot+2];
+                int32 temp3 = out[slot+4];
+                out[slot  ] = -temp1;
+                out[slot+2] = -temp2;
+                out[slot+4] = -temp3;
+            }
+        }
+    }
+
+
+    for (band = bands2process; band < SUBBANDS_NUMBER; band++)
+    {
+        int32 * out     = in      + (band * FILTERBANK_BANDS);
+        int32 * history = overlap + (band * FILTERBANK_BANDS);
+        int32 slot;
+
+        if (band & 1)
+        {
+            for (slot = 0; slot < FILTERBANK_BANDS; slot += 6)
+            {
+                int32 temp1 =  history[slot  ];
+                int32 temp2 =  history[slot+1];
+                int32 temp3 =  history[slot+2];
+                out[slot  ] =  temp1;
+                out[slot+1] = -temp2;
+                out[slot+2] =  temp3;
+
+                temp1 =  history[slot+3];
+                temp2 =  history[slot+4];
+                temp3 =  history[slot+5];
+                out[slot+3] = -temp1;
+                out[slot+4] =  temp2;
+                out[slot+5] = -temp3;
+            }
+        }
+        else
+        {
+            for (slot = 0; slot < FILTERBANK_BANDS; slot += 3)
+            {
+                int32 temp1 =  history[slot  ];
+                int32 temp2 =  history[slot+1];
+                int32 temp3 =  history[slot+2];
+                out[slot  ] =  temp1;
+                out[slot+1] =  temp2;
+                out[slot+2] =  temp3;
+            }
+        }
+
+        pv_memset(history, 0, FILTERBANK_BANDS*sizeof(*overlap));
+    }
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.h
new file mode 100644
index 0000000..ea42e49
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_imdct_synth.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_imdct_synth.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+*/
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+
+#ifndef PVMP3_IMDCT_SYNTH_H
+#define PVMP3_IMDCT_SYNTH_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_imdct_synth(int32 in[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    int32 overlap[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    uint32 blk_type,
+    int16 mx_band,
+    int32 used_freq_lines,
+    int32 *Scratch_mem);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.cpp
new file mode 100644
index 0000000..09a735b
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.cpp
@@ -0,0 +1,289 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: mdct_18.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    int32 vec[],        input vector of length 18
+    int32 *history      input for overlap and add, vector updated with
+                        next overlap and add values
+    const int32 *window sine window used in the mdct, three types are allowed
+                        noraml, start and stop
+Returns
+    none                mdct computation in-place
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns the mdct of length 18 of the input vector, as well as the overlap
+    vector for next iteration ( on history[])
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#if ( !defined(PV_ARM_GCC_V5) && !defined(PV_ARM_GCC_V4) && !defined(PV_ARM_V5) && !defined(PV_ARM_V4) )
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_mdct_18.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
+----------------------------------------------------------------------------*/
+const int32 cosTerms_dct18[9] =
+{
+    Qfmt(0.50190991877167f),   Qfmt(0.51763809020504f),   Qfmt(0.55168895948125f),
+    Qfmt(0.61038729438073f),   Qfmt(0.70710678118655f),   Qfmt(0.87172339781055f),
+    Qfmt(1.18310079157625f),   Qfmt(1.93185165257814f),   Qfmt(5.73685662283493f)
+};
+
+
+const int32 cosTerms_1_ov_cos_phi[18] =
+{
+
+    Qfmt1(0.50047634258166f),  Qfmt1(0.50431448029008f),  Qfmt1(0.51213975715725f),
+    Qfmt1(0.52426456257041f),  Qfmt1(0.54119610014620f),  Qfmt1(0.56369097343317f),
+    Qfmt1(0.59284452371708f),  Qfmt1(0.63023620700513f),  Qfmt1(0.67817085245463f),
+
+    Qfmt2(0.74009361646113f),  Qfmt2(0.82133981585229f),  Qfmt2(0.93057949835179f),
+    Qfmt2(1.08284028510010f),  Qfmt2(1.30656296487638f),  Qfmt2(1.66275476171152f),
+    Qfmt2(2.31011315767265f),  Qfmt2(3.83064878777019f),  Qfmt2(11.46279281302667f)
+};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_mdct_18(int32 vec[], int32 *history, const int32 *window)
+{
+    int32 i;
+    int32 tmp;
+    int32 tmp1;
+    int32 tmp2;
+    int32 tmp3;
+    int32 tmp4;
+
+
+
+    const int32 *pt_cos_split = cosTerms_dct18;
+    const int32 *pt_cos       = cosTerms_1_ov_cos_phi;
+    const int32 *pt_cos_x     = &cosTerms_1_ov_cos_phi[17];
+    int32 *pt_vec   =  vec;
+    int32 *pt_vec_o = &vec[17];
+
+
+    for (i = 9; i != 0; i--)
+    {
+        tmp  = *(pt_vec);
+        tmp1 = *(pt_vec_o);
+        tmp  = fxp_mul32_Q32(tmp << 1,  *(pt_cos++));
+        tmp1 = fxp_mul32_Q27(tmp1, *(pt_cos_x--));
+        *(pt_vec++)   =   tmp + tmp1 ;
+        *(pt_vec_o--) = fxp_mul32_Q28((tmp - tmp1), *(pt_cos_split++));
+    }
+
+
+    pvmp3_dct_9(vec);         // Even terms
+    pvmp3_dct_9(&vec[9]);     // Odd  terms
+
+
+    tmp3     = vec[16];  //
+    vec[16]  = vec[ 8];
+    tmp4     = vec[14];  //
+    vec[14]  = vec[ 7];
+    tmp      = vec[12];
+    vec[12]  = vec[ 6];
+    tmp2     = vec[10];  // vec[10]
+    vec[10]  = vec[ 5];
+    vec[ 8]  = vec[ 4];
+    vec[ 6]  = vec[ 3];
+    vec[ 4]  = vec[ 2];
+    vec[ 2]  = vec[ 1];
+    vec[ 1]  = vec[ 9] - tmp2; //  vec[9] +  vec[10]
+    vec[ 3]  = vec[11] - tmp2;
+    vec[ 5]  = vec[11] - tmp;
+    vec[ 7]  = vec[13] - tmp;
+    vec[ 9]  = vec[13] - tmp4;
+    vec[11]  = vec[15] - tmp4;
+    vec[13]  = vec[15] - tmp3;
+    vec[15]  = vec[17] - tmp3;
+
+
+    /* overlap and add */
+
+    tmp2 = vec[0];
+    tmp3 = vec[9];
+
+    for (i = 0; i < 6; i++)
+    {
+        tmp  = history[ i];
+        tmp4 = vec[i+10];
+        vec[i+10] = tmp3 + tmp4;
+        tmp1 = vec[i+1];
+        vec[ i] =  fxp_mac32_Q32(tmp, (vec[i+10]), window[ i]);
+        tmp3 = tmp4;
+        history[i  ] = -(tmp2 + tmp1);
+        tmp2 = tmp1;
+    }
+
+    tmp  = history[ 6];
+    tmp4 = vec[16];
+    vec[16] = tmp3 + tmp4;
+    tmp1 = vec[7];
+    vec[ 6] =  fxp_mac32_Q32(tmp, vec[16] << 1, window[ i]);
+    tmp  = history[ 7];
+    history[6] = -(tmp2 + tmp1);
+    history[7] = -(tmp1 + vec[8]);
+
+    tmp1  = history[ 8];
+    tmp4    = vec[17] + tmp4;
+    vec[ 7] =  fxp_mac32_Q32(tmp, tmp4 << 1, window[ 7]);
+    history[8] = -(vec[8] + vec[9]);
+    vec[ 8] =  fxp_mac32_Q32(tmp1, vec[17] << 1, window[ 8]);
+
+    tmp  = history[9];
+    tmp1 = history[17];
+    tmp2 = history[16];
+    vec[ 9] =  fxp_mac32_Q32(tmp,  vec[17] << 1, window[ 9]);
+
+    vec[17] =  fxp_mac32_Q32(tmp1, vec[10] << 1, window[17]);
+    vec[10] = -vec[ 16];
+    vec[16] =  fxp_mac32_Q32(tmp2, vec[11] << 1, window[16]);
+    tmp1 = history[15];
+    tmp2 = history[14];
+    vec[11] = -vec[ 15];
+    vec[15] =  fxp_mac32_Q32(tmp1, vec[12] << 1, window[15]);
+    vec[12] = -vec[ 14];
+    vec[14] =  fxp_mac32_Q32(tmp2, vec[13] << 1, window[14]);
+
+    tmp  = history[13];
+    tmp1 = history[12];
+    tmp2 = history[11];
+    tmp3 = history[10];
+    vec[13] =  fxp_mac32_Q32(tmp,  vec[12] << 1, window[13]);
+    vec[12] =  fxp_mac32_Q32(tmp1, vec[11] << 1, window[12]);
+    vec[11] =  fxp_mac32_Q32(tmp2, vec[10] << 1, window[11]);
+    vec[10] =  fxp_mac32_Q32(tmp3,    tmp4 << 1, window[10]);
+
+
+    /* next iteration overlap */
+
+    tmp1 = history[ 8];
+    tmp3 = history[ 7];
+    tmp2 = history[ 1];
+    tmp  = history[ 0];
+    tmp1 <<= 1;
+    tmp3 <<= 1;
+
+    history[ 0] = fxp_mul32_Q32(tmp1, window[18]);
+    history[17] = fxp_mul32_Q32(tmp1, window[35]);
+    history[ 1] = fxp_mul32_Q32(tmp3, window[19]);
+    history[16] = fxp_mul32_Q32(tmp3, window[34]);
+
+    tmp2 <<= 1;
+    tmp  <<= 1;
+    history[ 7] = fxp_mul32_Q32(tmp2, window[25]);
+    history[10] = fxp_mul32_Q32(tmp2, window[28]);
+    history[ 8] = fxp_mul32_Q32(tmp,  window[26]);
+    history[ 9] = fxp_mul32_Q32(tmp,  window[27]);
+
+    tmp1 = history[ 6];
+    tmp3 = history[ 5];
+    tmp4 = history[ 4];
+    tmp2 = history[ 3];
+    tmp  = history[ 2];
+
+    tmp1 <<= 1;
+    tmp3 <<= 1;
+    tmp4 <<= 1;
+
+    history[ 2] = fxp_mul32_Q32(tmp1, window[20]);
+    history[15] = fxp_mul32_Q32(tmp1, window[33]);
+    history[ 3] = fxp_mul32_Q32(tmp3, window[21]);
+    history[14] = fxp_mul32_Q32(tmp3, window[32]);
+    history[ 4] = fxp_mul32_Q32(tmp4, window[22]);
+    history[13] = fxp_mul32_Q32(tmp4, window[31]);
+    tmp2 <<= 1;
+    tmp  <<= 1;
+    history[ 5] = fxp_mul32_Q32(tmp2, window[23]);
+    history[12] = fxp_mul32_Q32(tmp2, window[30]);
+    history[ 6] = fxp_mul32_Q32(tmp,  window[24]);
+    history[11] = fxp_mul32_Q32(tmp,  window[29]);
+}
+
+#endif // If not assembly
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
new file mode 100644
index 0000000..e497aee
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_18.h
@@ -0,0 +1,109 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./include/pvmp3_mdct_18.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines function mdct_18, dct9, mdct_6 and dct_6
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef  MDCT_18_H
+#define  MDCT_18_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define Qfmt(a)    (Int32)(a*((Int32)1<<28) )
+#define Qfmt1(a)   (Int32)(a*((Int32)0x7FFFFFFF))
+#define Qfmt2(a)   (Int32)(a*((Int32)1<<27))
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_mdct_18(int32 vec[], int32 *history, const int32 *window);
+
+    void pvmp3_dct_9(int32 vec[]);
+
+    void pvmp3_mdct_6(int32 vec[], int32 *overlap);
+
+    void pvmp3_dct_6(int32 vec[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
new file mode 100644
index 0000000..6a72aad
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.cpp
@@ -0,0 +1,165 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+   Filename: mdct_18.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    int32 vec[],        input vector of length 6
+    int32 *history      input for overlap and add, vector updated with
+                        next overlap and add values
+Returns
+    none                mdct computation in-place
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns the mdct of length 6 of the input vector, as well as the overlap
+    vector for next iteration ( on history[])
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_mdct_6.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define QFORMAT    29
+#define Qfmt29(a)   (int32)(a*((int32)1<<QFORMAT) + (a>=0?0.5F:-0.5F))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/*
+ *  (1./(2*cos((pi/(2*N))*(2*i+1)))),  N = 12, i = [0:N/2-1]
+ */
+
+const int32 cosTerms_1_ov_cos_phi_N6[6] =
+{
+
+    Qfmt29(0.50431448029008f),   Qfmt29(0.54119610014620f),
+    Qfmt29(0.63023620700513f),   Qfmt29(0.82133981585229f),
+    Qfmt29(1.30656296487638f),   Qfmt29(3.83064878777019f)
+};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_mdct_6(int32 vec[], int32 *history)
+{
+    int32 i;
+    int32 tmp;
+    int32 tmp1;
+    int32 tmp2;
+
+    int32 *pt_vec   = vec;
+    int32 *pt_vec_o = vec;
+    const int32 *pt_cos = cosTerms_1_ov_cos_phi_N6;
+
+    for (i = 2; i != 0; i--)
+    {
+        tmp  = *(pt_vec++);
+        tmp1 = *(pt_vec++);
+        tmp2 = *(pt_vec++);
+        *(pt_vec_o++)   = fxp_mul32_Q29(tmp, *(pt_cos++));
+        *(pt_vec_o++)   = fxp_mul32_Q29(tmp1, *(pt_cos++));
+        *(pt_vec_o++)   = fxp_mul32_Q29(tmp2, *(pt_cos++));
+    }
+
+
+    pvmp3_dct_6(vec);    // Even terms
+
+
+    tmp = -(vec[0] + vec[1]);
+    history[3] = tmp;
+    history[2] = tmp;
+    tmp = -(vec[1] + vec[2]);
+    vec[0] =  vec[3] + vec[4];
+    vec[1] =  vec[4] + vec[5];
+    history[4] = tmp;
+    history[1] = tmp;
+    tmp = -(vec[2] + vec[3]);
+    vec[4] = -vec[1];
+    history[5] = tmp;
+    history[0] = tmp;
+
+    vec[2] =  vec[5];
+    vec[3] = -vec[5];
+    vec[5] = -vec[0];
+
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
new file mode 100644
index 0000000..6ba53d7
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mdct_6.h
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Pathname: ./include/pvmp3_mdct_6.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines function mdct_18, dct9, mdct_6 and dct_6
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef  PVMP3_MDCT_6_H
+#define  PVMP3_MDCT_6_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define Qfmt(a)    (Int32)(a*((Int32)1<<28) )
+#define Qfmt1(a)   (Int32)(a*((Int32)0x7FFFFFFF))
+#define Qfmt2(a)   (Int32)(a*((Int32)1<<27))
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void pvmp3_mdct_6(int32 vec[], int32 *overlap);
+
+    void pvmp3_dct_6(int32 vec[]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
new file mode 100644
index 0000000..ee42dc5
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.cpp
@@ -0,0 +1,247 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_get_scale_data.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    mp3SideInfo     *si,                    side information
+    int32           gr,                     granule
+    int32           ch,                     channel
+    mp3Header       *info,                  mp3 header information
+    uint32          *scalefac_buffer,
+    uint32          *scalefac_IIP_buffer,
+    tbits           *pMainData               bit stream Data
+
+ Returns
+
+    uint32          *scalefac_buffer,       acquired scale band data
+    uint32          *scalefac_IIP_buffer,   auxiliary scale data
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    get scale data for mpeg2 layer III LSF extension
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_mpeg2_get_scale_data.h"
+#include "pvmp3_getbits.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
+----------------------------------------------------------------------------*/
+
+const uint32 nr_of_sfb_block[6][3][4] =
+{   {{ 6,  5, 5, 5}, {  9,  9,  9, 9}, { 6,  9,  9, 9}},
+    {{ 6,  5, 7, 3}, {  9,  9, 12, 6}, { 6,  9, 12, 6}},
+    {{11, 10, 0, 0}, { 18, 18,  0, 0}, {15, 18,  0, 0}},
+    {{ 7,  7, 7, 0}, { 12, 12, 12, 0}, { 6, 15, 12, 0}},
+    {{ 6,  6, 6, 3}, { 12,  9,  9, 6}, { 6, 12,  9, 6}},
+    {{ 8,  8, 5, 0}, { 15, 12,  9, 0}, { 6, 18,  9, 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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void pvmp3_mpeg2_get_scale_data(mp3SideInfo *si,
+                                int32        gr,
+                                int32        ch,
+                                mp3Header   *info,
+                                uint32      *scalefac_buffer,
+                                uint32      *scalefac_IIP_buffer,
+                                tmp3Bits    *pMainData)
+{
+    int16 i;
+    int16 j;
+    int16 k;
+    int16 blocktypenumber = 0;
+    int16 blocknumber = 0;
+
+    granuleInfo *gr_info = &(si->ch[ch].gran[gr]);
+    uint32 scalefac_comp, int_scalefac_comp, new_slen[4];
+
+    scalefac_comp =  gr_info->scalefac_compress;
+
+
+
+    if ((((info->mode_ext &1)) && (ch == 1)))
+    {
+        /*   intensity_scale = scalefac_comp %2; */
+        int_scalefac_comp = scalefac_comp >> 1;
+
+        if (int_scalefac_comp  < 180)
+        {
+            new_slen[0] = int_scalefac_comp  / 36;
+            new_slen[1] = (int_scalefac_comp % 36) / 6;
+            new_slen[2] = int_scalefac_comp % 6;
+            blocknumber = 3;
+        }
+        else if (int_scalefac_comp  < 244)
+        {
+            int_scalefac_comp -= 180;
+            new_slen[0] = (int_scalefac_comp & 63) >> 4;
+            new_slen[1] = (int_scalefac_comp & 15) >> 2;
+            new_slen[2] =  int_scalefac_comp &  3;
+            blocknumber = 4;
+        }
+        else if (int_scalefac_comp  <= 255)
+        {
+            int_scalefac_comp -= 244;
+            new_slen[0] = (int_scalefac_comp) / 3;
+            new_slen[1] = (int_scalefac_comp) % 3;
+            new_slen[2] = 0;
+            blocknumber = 5;
+        }
+        new_slen[3] = 0;
+        si->ch[ch].gran[gr].preflag = 0;
+    }
+    else
+    {
+        if (scalefac_comp < 400)
+        {
+            new_slen[0] = (scalefac_comp >> 4) / 5;
+            new_slen[1] = (scalefac_comp >> 4) % 5;
+            new_slen[2] = (scalefac_comp & 15) >> 2 ;
+            new_slen[3] = (scalefac_comp & 3);
+            si->ch[ch].gran[gr].preflag = 0;
+
+            blocknumber = 0;
+        }
+        else if (scalefac_comp  < 500)
+        {
+            scalefac_comp -= 400;
+            new_slen[0] = (scalefac_comp >> 2) / 5;
+            new_slen[1] = (scalefac_comp >> 2) % 5;
+            new_slen[2] = scalefac_comp  & 3;
+            new_slen[3] = 0;
+            si->ch[ch].gran[gr].preflag = 0;
+            blocknumber = 1;
+        }
+        else if (scalefac_comp  < 512)
+        {
+            scalefac_comp -= 500;
+            new_slen[0] = scalefac_comp / 3;
+            new_slen[1] = scalefac_comp % 3;
+            new_slen[2] = 0 ;
+            new_slen[3] = 0;
+            si->ch[ch].gran[gr].preflag = 1;
+            blocknumber = 2;
+        }
+    }
+
+    if (gr_info->block_type == 2)
+    {
+        if (gr_info->mixed_block_flag)
+        {
+            blocktypenumber = 2;
+        }
+        else
+        {
+            blocktypenumber = 1;
+        }
+    }
+
+    k = 0;
+    for (i = 0; i < 4; i++)
+    {
+        if (new_slen[i])
+        {
+            for (j = 0; j < (int16)nr_of_sfb_block[blocknumber][blocktypenumber][i]; j++)
+            {
+                scalefac_buffer[k] =  getNbits(pMainData, new_slen[i]);
+                scalefac_IIP_buffer[k] = (1L << new_slen[i]) - 1;
+                k++;
+            }
+        }
+        else
+        {
+            for (j = 0; j < (int16)nr_of_sfb_block[blocknumber][blocktypenumber][i]; j++)
+            {
+                scalefac_buffer[k]     = 0;
+                scalefac_IIP_buffer[k] = 0;
+                k++;
+            }
+        }
+    }
+}
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h
new file mode 100644
index 0000000..630ed61
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_data.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_get_scale_data.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_MPEG2_GET_SCALE_DATA_H
+#define PVMP3_MPEG2_GET_SCALE_DATA_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_mpeg2_get_scale_data(mp3SideInfo  *si,
+    int32         gr,
+    int32         ch,
+    mp3Header    *info,
+    uint32       *scalefac_buffer,
+    uint32       *scalefac_IIP_buffer,
+    tmp3Bits     *pMainData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp
new file mode 100644
index 0000000..e4d29d6
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.cpp
@@ -0,0 +1,202 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_get_scale_factors.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+    mp3ScaleFactors *scalefac,
+    mp3SideInfo     *si,                    side information
+    int32           gr,                     granule
+    int32           ch,                     channel
+    mp3Header       *info,                  mp3 header information
+    uint32          *scalefac_IIP_buffer,   auxiliary scale data
+    tbits           *pMainData               bit stream Data
+
+ Returns
+
+    III_scalefac_t  *scalefac,              scale factor
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    get scale factor for mpe2 layer III LSF extension
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_mpeg2_get_scale_factors.h"
+#include "pvmp3_mpeg2_get_scale_data.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 pvmp3_mpeg2_get_scale_factors(mp3ScaleFactors *scalefac,
+                                   mp3SideInfo     *si,
+                                   int32           gr,
+                                   int32           ch,
+                                   mp3Header       *info,
+                                   uint32          *scalefac_IIP_buffer,
+                                   tmp3Bits        *pMainData)
+{
+
+    int32 sfb;
+    int32 k = 0;
+    int32 window;
+    uint32 *scalefac_buffer     = &scalefac_IIP_buffer[56];
+
+    granuleInfo *gr_info = &(si->ch[ch].gran[gr]);
+
+    pvmp3_mpeg2_get_scale_data(si,
+                               gr,
+                               ch,
+                               info,
+                               (uint32 *)scalefac_buffer,
+                               (uint32 *)scalefac_IIP_buffer,
+                               pMainData);
+
+
+    if (gr_info->window_switching_flag && (gr_info->block_type == 2))
+    {
+        if (gr_info->mixed_block_flag)
+        {
+            for (sfb = 0; sfb < 6; sfb++)
+            {
+                scalefac->l[sfb] = scalefac_buffer[sfb];
+            }
+
+
+            k = 6;
+            for (sfb = 3; sfb < 12; sfb++)
+            {
+                for (window = 0; window < 3; window++)
+                {
+                    scalefac->s[window][sfb] = scalefac_buffer[k];
+                    k++;
+                }
+            }
+
+
+            /* adjust position of "illegal position" information in scalefac_IIP_buffer[] */
+            /* in mixed blocks mode for short sfb, move them 3 places up. efs 3002-07-04  */
+            for (sfb = 11; sfb >= 3; sfb--)
+            {
+                scalefac_IIP_buffer[3*sfb + 2] = scalefac_IIP_buffer[3*sfb - 1];
+                scalefac_IIP_buffer[3*sfb + 1] = scalefac_IIP_buffer[3*sfb - 2];
+                scalefac_IIP_buffer[3*sfb    ] = scalefac_IIP_buffer[3*sfb - 3];
+
+            }
+        }
+        else
+        {  /* SHORT*/
+            for (sfb = 0; sfb < 12; sfb++)
+            {
+                for (window = 0; window < 3; window++)
+                {
+                    scalefac->s[window][sfb] = scalefac_buffer[k];
+                    k++;
+                }
+            }
+        }
+
+        scalefac->s[0][12] = 0;
+        scalefac->s[1][12] = 0;
+        scalefac->s[2][12] = 0;
+
+    }
+    else
+    {   /* LONG types 0,1,3 */
+        for (sfb = 0; sfb < 21; sfb++)
+        {
+            scalefac->l[sfb] = scalefac_buffer[sfb];
+        }
+        scalefac->l[21] = 0;
+        scalefac->l[22] = 0;
+
+    }
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h
new file mode 100644
index 0000000..46d16b3
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_get_scale_factors.h
@@ -0,0 +1,105 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_get_scale_factors.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_MPEG2_GET_SCALE_FACTORS_H
+#define PVMP3_MPEG2_GET_SCALE_FACTORS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+#include "s_mp3bits.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_mpeg2_get_scale_factors(mp3ScaleFactors *scalefac,
+    mp3SideInfo     *si,
+    int32           gr,
+    int32           ch,
+    mp3Header       *info,
+    uint32          *scalefac_IIP_buffer,
+    tmp3Bits        *pMainData);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
new file mode 100644
index 0000000..c79062c
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.cpp
@@ -0,0 +1,700 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_stereo_proc.cpp
+
+   Functions:
+
+     pvmp3_st_intensity_ver2
+     pvmp3_mpeg2_stereo_proc
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+
+------------------------------------------------------------------------------
+
+pvmp3_st_intensity_ver2
+
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+   int32 xr[],      input channel
+   int32 xl[],
+   int32 m,         selecting index: io = 2(1/4) (m=0), io = 2(1/8) (m=1)
+   int32 is_pos,    index on table  is_pos_pow_eitgh_root_of_2
+   int32 Start,     Location of first element where stereo intensity is applied
+   int32 Number     number of elements affected
+
+ Returns
+
+   int32 xl[],      generated stereo channel
+
+
+
+
+------------------------------------------------------------------------------
+
+pvmp3_mpeg2_stereo_proc
+
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+   int32 xr[],                     input channel
+   int32 xl[],
+   mp3ScaleFactors *scalefac,      scale factors structure for Right channel
+   granuleInfo *gr_info_l,         granule structure for the left channel
+   granuleInfo *gr_info_r,         granule structure for the rigth channel
+   uint32 *scalefac_IIP_buffer,    auxiliary scale factor vector
+   mp3Header *info                 mp3 header info
+ Returns
+
+   int32 xl[],      generated stereo channel
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    stereo processing for mpeg2 layer III LSF extension
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_mpeg2_stereo_proc.h"
+#include "pvmp3_stereo_proc.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_tables.h"
+#include "mp3_mem_funcs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+const int32 is_pos_pow_eitgh_root_of_2[8] =
+{
+    /*   --- 2^(1/8) ----- */
+    Q31_fmt(1.00000000000000),   Q31_fmt(0.91700404320467),   Q31_fmt(0.84089641525371),
+    Q31_fmt(0.77110541270397),   Q31_fmt(0.70710678118655),   Q31_fmt(0.64841977732550),
+    Q31_fmt(0.59460355750136),   Q31_fmt(0.54525386633263)
+};
+
+/*----------------------------------------------------------------------------
+; 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 pvmp3_st_intensity_ver2(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                             int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                             int32 m,
+                             int32 is_pos,
+                             int32 Start,
+                             int32 Number)
+{
+    int32 k[2];
+
+    /* pow(io, ((is_pos + 1)>>1)); io = 2(1/4) (m=0), io = 2(1/8) (m=1) */
+    k[0] = is_pos_pow_eitgh_root_of_2[((is_pos+1)&(3+(m<<2)))<<(1-m)] >> ((is_pos + 1) >> (2 + m));
+    /* pow(io, (is_pos>>1)); io = 2(1/4) (m=0), io = 2(1/8) (m=1)  */
+    k[1] = is_pos_pow_eitgh_root_of_2[(is_pos&(3+(m<<2)))<<(1-m)] >> (is_pos >> (2 + m));
+
+
+    int32 *pt_xr  = &xr[Start];
+    int32 *pt_xl  = &xl[Start];
+
+    if (is_pos == 0)    /* 0 < is_pos < 31 */
+    {
+        pv_memcpy(pt_xl, pt_xr, Number*sizeof(*pt_xr));
+    }
+    else if (is_pos & 1)
+    {
+        for (int32 i = Number >> 1; i != 0; i--)
+        {
+            *(pt_xl++) = (*pt_xr);
+            *(pt_xr) = fxp_mul32_Q32((*pt_xr) << 1, k[0]);
+            pt_xr++;
+            *(pt_xl++) = (*pt_xr);
+            *(pt_xr) = fxp_mul32_Q32((*pt_xr) << 1, k[0]);
+            pt_xr++;
+        }
+        if (Number&1)
+        {
+            *(pt_xl) = (*pt_xr);
+            *(pt_xr) = fxp_mul32_Q32((*pt_xr) << 1, k[0]);
+        }
+    }
+    else
+    {
+        for (int32 i = Number >> 1; i != 0; i--)
+        {
+            *(pt_xl++) = fxp_mul32_Q32((*(pt_xr++)) << 1, k[1]);
+            *(pt_xl++) = fxp_mul32_Q32((*(pt_xr++)) << 1, k[1]);
+        }
+        if (Number&1)
+        {
+            *(pt_xl) = fxp_mul32_Q32((*pt_xr) << 1, k[1]);
+        }
+    }
+
+}
+
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void pvmp3_mpeg2_stereo_proc(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                             int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                             mp3ScaleFactors *scalefac_R,
+                             granuleInfo *gr_info_l,
+                             granuleInfo *gr_info_r,
+                             uint32 *scalefac_IIP_buffer,
+                             int32 used_freq_lines,
+                             mp3Header *info)
+{
+
+    int32 sfreq;
+    int32 sb;
+    int32 ss;
+    int32 sfbNo;
+    int32 sfbStart;
+    int32 sfb;
+    int32 sfbTemp;
+    int32 i;
+    int32 j;
+    int32 io;
+
+
+    int32 i_stereo  = (info->mode == MPG_MD_JOINT_STEREO) &&
+                      (info->mode_ext & 0x1);
+
+    int32 ms_stereo = (info->mode == MPG_MD_JOINT_STEREO) &&
+                      (info->mode_ext & 0x2);
+
+
+    if (i_stereo)
+    {
+        if (gr_info_r->scalefac_compress & 1)
+        {
+            io = 0;  /* 2^(-1/4) */
+        }
+        else
+        {
+            io = 1;  /* 2^(-1/8) */
+        }
+
+        sfreq =  info->version_x + (info->version_x << 1);
+        sfreq += info->sampling_frequency;
+
+        if (gr_info_l->window_switching_flag && (gr_info_l->block_type == 2))
+        {
+            if (gr_info_l->mixed_block_flag)
+            {
+                /*
+                 * mixed blocks processing
+                 */
+                i = 31;
+                ss = 17;
+                sb = -1;
+
+                while (i >= 0)
+                {
+                    if (xl[(i*FILTERBANK_BANDS) + ss])
+                    {
+                        sb = (i << 4) + (i << 1) + ss;
+                        i = -1;
+                    }
+                    else
+                    {
+                        ss--;
+                        if (ss < 0)
+                        {
+                            i--;
+                            ss = 17;
+                        }
+                    }
+                }   /* now sb is the number of highest line with value != 0      */
+                /* can be between -1 (all lines zero) and 575 (no line zero) */
+
+                if (sb < 36)    /*  was (sb <= 36)  */
+                {
+                    /*
+                     *  mixed blocks processing: intensity bound inside long blocks
+                     */
+                    /* 1. long blocks up to intensity border: Stereo or M/S */
+                    if (mp3_sfBandIndex[sfreq].l[4] <= sb)
+                    {
+                        i = 4;
+                    }
+                    else
+                    {
+                        i = 0;
+                    }
+
+                    while (mp3_sfBandIndex[sfreq].l[i] <= sb)
+                    {
+                        i++;
+                    }
+                    sfbTemp = i;  /* from that (long) sfb on we have intensity stereo */
+
+                    sfbNo = mp3_sfBandIndex[sfreq].l[sfbTemp]; /* number of lines to process */
+
+                    /* from sfbStart up sfbNo lines do ms_stereo or normal stereo */
+                    if (ms_stereo)
+                    {
+                        pvmp3_st_mid_side(xr, xl, 0, sfbNo);
+                    }
+
+                    /* 2. long blocks from intensity border up to sfb band 6: intensity */
+                    /* calc. MPEG_1_2_Factor[0], MPEG_1_2_Factor[1] */
+
+                    for (sfb = sfbTemp; sfb < 6; sfb++)
+                    {
+                        sfbStart = mp3_sfBandIndex[sfreq].l[sfb];  /* = Start in 0 ... 575 */
+                        sfbNo = mp3_sfBandIndex[sfreq].l[sfb+1] - mp3_sfBandIndex[sfreq].l[sfb]; /* No of lines to process */
+
+                        if ((uint32)(scalefac_R->l[sfb]) != scalefac_IIP_buffer[sfb])
+                        {
+                            pvmp3_st_intensity_ver2(xr, xl, io, scalefac_R->l[sfb], sfbStart, sfbNo);
+                        }
+                        else if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+                    }
+
+                    /* 3. now process all sfb with short blocks (3...12), all in intensity mode */
+
+                    for (j = 0; j < 3; j++)
+                    {
+                        /*   first calculate directional factors for intensity stereo,
+                         *   for all sfb in intensity mode, but only
+                         *   if they do not have "illegal" position:
+                         */
+                        /* to do this for all sfb we have to get information for last scale factor band:
+                         * here we clearly have more than one sfb in intensity mode,
+                         *  so copy factors and legal/illegal information from sfb11 to sfb12
+                         */
+                        (scalefac_R->s[j][12]) = (scalefac_R->s[j][11]);
+                        scalefac_IIP_buffer[36 + j] = scalefac_IIP_buffer[33 + j];  /* legal/illegal in sfb 12 same as in sfb 11 */
+
+                        for (sfb = 3; sfb < 13; sfb++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb]; /* No of lines to process */
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfb] + j * sfbNo;
+
+                            if ((uint32)(scalefac_R->s[j][sfb]) != scalefac_IIP_buffer[3*sfb + j])
+                            {
+                                pvmp3_st_intensity_ver2(xr, xl, io, scalefac_R->s[j][sfb], sfbStart, sfbNo);
+                            }
+                            else if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+                        }
+                    } /* for (j = 0; j < 3; j++) */
+                }
+                else  /*  else then (sb >= 36)  */
+                {
+                    /*
+                     *   mixed blocks processing: intensity bound outside long blocks
+                     */
+
+                    /* 2. short blocks, do for all 3  */
+                    /* ------------------------------ */
+                    for (j = 0; j < 3; j++)
+                    {
+                        int32 sfbcnt = -1;
+
+                        for (sfb = 12; sfb >= 3; sfb--)
+                        {
+                            int32 lines = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+
+                            i = 3 * mp3_sfBandIndex[sfreq].s[sfb] + (j + 1) * lines - 1;
+
+                            while (lines > 0)
+                            {
+                                if (xl[i])
+                                {
+                                    sfbcnt = sfb;
+                                    sfb = -10;
+                                    lines = -10;
+                                }
+                                lines--;
+                                i--;
+                            }
+                        }
+
+                        sfbcnt += 1;
+                        if (sfbcnt < 3)
+                        {
+                            sfbcnt = 3;   /* should not be necessary */
+                        }
+
+                        sfbTemp = sfbcnt; /* from this (short) sfb on we have intensity mode        */
+                        /* can have values between 3 (all short sfb in intensity) */
+                        /* and 13 (no short sfb in intensity mode)                */
+
+                        /* 3. from sfbTemp to last sfb calculate is_ratio values:    */
+                        /* first calculate directional factors for intensity stereo, */
+                        /* for all sfb in intensity mode, but only                   */
+                        /* if they do not have "illegal" position:                   */
+
+                        /* to do this for all sfb we have to get information for last scale factor band: */
+                        /*  get factors for last scale factor band: */
+                        /* more than one sfb in intensity mode,
+                        copy factors and legal/illegal information from sfb11 to sfb12 */
+                        if (sfbTemp < 12)
+                        {
+                            (scalefac_R->s[j][12]) = (scalefac_R->s[j][11]);
+                            scalefac_IIP_buffer[36 + j] = scalefac_IIP_buffer[33 + j];   /* legal/illegal in sfb 12 same as in sfb 11 */
+                        }
+                        else if (sfbTemp == sfb)
+                            /* only sfb 12 in intensity mode, use factors corresponding to is_pos[12] == 0 */
+                        {
+                            (scalefac_R->s[j][12]) = 0;
+                            scalefac_IIP_buffer[36 + j] = 1;    /* the scf value 0 in sfb12 is "legal" */
+                        }
+                        /* if sfbTemp > sfb (no sfb in intensity mode): do nothing */
+
+
+                        /* 4. do normal stereo or MS stereo from sfb 3 to < sfbTemp: */
+                        for (sfb = 3; sfb < sfbTemp; sfb++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfb] + j * sfbNo;
+
+                            if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+                        }
+
+                        /* 5. now intensity stereo processing of the remaining sfb's: */
+
+                        for (sfb = sfbTemp; sfb < 13; sfb++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb]; /* No of lines to process */
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfb] + j * sfbNo;
+                            if ((uint32)(scalefac_R->s[j][sfb]) != scalefac_IIP_buffer[3*sfb + j])
+                            {
+                                pvmp3_st_intensity_ver2(xr, xl, io, scalefac_R->s[j][sfb], sfbStart, sfbNo);
+                            }
+                            else if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+                        }
+                        /*  end of correction by efs 2003-07-04 */
+                    } /* for (j = 0; j < 3; j++) */
+
+
+                    /* long blocks 0 up to sfb band 6: no intensity */
+
+                    sfbNo = mp3_sfBandIndex[sfreq].l[6];        /* number of lines to process */
+                    if (ms_stereo)
+                    {
+                        pvmp3_st_mid_side(xr, xl, 0, sfbNo);
+                    }
+
+                }  /* if intensity bound inside or outside long blocks */
+            }  /* if (gr_info->mixed_block_flag) */
+            else
+            {
+                /*
+                 *  short block processing
+                 */
+                for (j = 0; j < 3; j++)
+                {
+                    int32 sfbcnt = -1;
+
+                    for (sfb = 12; sfb >= 0; sfb--)
+                    {
+                        int32 lines = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+                        i = 3 * mp3_sfBandIndex[sfreq].s[sfb] + (j + 1) * lines - 1;
+
+                        while (lines > 0)
+                        {
+                            if (xl[i])
+                            {
+                                sfbcnt = sfb;
+                                sfb = -10;
+                                lines = -10;
+                            }
+                            lines--;
+                            i--;
+                        }
+                    }
+
+                    sfbcnt += 1;
+
+                    /*  start of corrected version by efs 2003-07-04  */
+                    sfbTemp = sfbcnt; /* from this (short) sfb on we have intensity mode        */
+                    /* can have values between 3 (all short sfb in intensity) */
+                    /* and 13 (no short sfb in intensity mode)                */
+
+                    /* first calculate directional factors for intensity stereo,
+                    for all sfb in intensity mode, but only
+                    if they do not have "illegal" position: */
+
+                    /* to do this for all sfb we have to get information for last scale factor band: */
+                    /* get factors for last scale factor band: */
+                    /* more than one sfb in intensity mode,
+                    copy factors and legal/illegal information from sfb11 to sfb12 */
+                    if (sfbTemp < 12)
+                    {
+                        (scalefac_R->s[j][12]) = (scalefac_R->s[j][11]);
+                        scalefac_IIP_buffer[36 + j] = scalefac_IIP_buffer[33 + j];  /* legal/illegal in sfb 12 same as in sfb 11 */
+                    }
+                    else if (sfbTemp == 12)
+                        /* only sfb 12 in intensity mode, use factors corresponding to is_pos[12] == 0 */
+                    {
+                        (scalefac_R->s[j][12]) = 0;
+                        scalefac_IIP_buffer[36 + j] = 1;    /* the scf value 0 in sfb12 is "legal" */
+                    }
+                    /* if sfbTemp > sfb (no sfb in intensity mode): do nothing */
+
+
+                    /* Now process audio samples */
+                    /* first process lower sfb's not in intensity mode */
+                    for (sfb = 0; sfb < sfbTemp; sfb++)
+                    {
+                        sfbNo = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+                        sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfb] + j * sfbNo;
+
+                        if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+                    }
+
+                    /* now intensity stereo processing of the remaining sfb's: */
+                    for (sfb = sfbTemp; sfb < 13; sfb++)
+                    {
+                        sfbNo = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb]; /* No of lines to process */
+                        sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfb] + j * sfbNo;
+
+                        if ((uint32)(scalefac_R->s[j][sfb]) != scalefac_IIP_buffer[3*sfb + j])
+                        {
+                            pvmp3_st_intensity_ver2(xr, xl, io, scalefac_R->s[j][sfb], sfbStart, sfbNo);
+                        }
+                        else if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+                    }
+
+                } /* for (j = 0; j < 3; j++) */
+
+            } /* end of else ( gr_info->mixed_block_flag) */
+
+        }  /* if (gr_info->window_switching_flag && (gr_info->block_type == 2)) */
+        else
+        {
+            /*
+             *  long block processing
+             */
+            i = 31;
+            ss = 17;
+            sb = 0;
+
+            while (i >= 0)
+            {
+                if (xl[(i*FILTERBANK_BANDS) + ss])
+                {
+                    sb = (i << 4) + (i << 1) + ss;
+                    /*  i = -1     patched RF    24-09-2002   */
+                    i = -2;
+                }
+                else
+                {
+                    ss--;
+                    if (ss < 0)
+                    {
+                        i--;
+                        ss = 17;
+                    }
+                }
+            }
+
+            /*  patched RF    24-09-2002   */
+            if (sb)
+            {
+                if (mp3_sfBandIndex[sfreq].l[14] <= sb)
+                {
+                    i = 14;
+                }
+                else if (mp3_sfBandIndex[sfreq].l[7] <= sb)
+                {
+                    i = 7;
+                }
+                else
+                {
+                    i = 0;
+                }
+
+                while (mp3_sfBandIndex[sfreq].l[i] <= sb)
+                {
+                    i++;
+                }
+            }
+
+            else
+            {
+                if (i == -1)
+                {
+                    /*  all xr[1][][] are 0: set IS bound sfb to 0  */
+                    i = 0;
+                }
+                else
+                {
+                    /*  xr[1][0][0] is unequal 0 and all others are 0: set IS bound sfb to 1 */
+                    i = 1;
+                }
+            }
+            /*  corrected version by efs 2003-07-04  */
+            sfbTemp = i;  /* from this (long) sfb on we have intensity mode        */
+            /* can have values between 0 (all long sfb in intensity) */
+            /* and 22 (no long sfb in intensity mode)                */
+
+            /* first calculate directional factors for intensity stereo,
+            for all sfb in intensity mode, but only if they
+            do not have "illegal" position: */
+
+            /* to do this for all sfb we have to get information for last scale factor band: */
+            if (sfbTemp < 21)
+                /* more than one sfb in intensity mode, */
+                /* copy factors and legal/illegal information from sfb20 to sfb21 */
+            {
+                (scalefac_R->l[21]) = (scalefac_R->l[20]);
+                scalefac_IIP_buffer[21] = scalefac_IIP_buffer[20];  /* legal/illegal in sfb 21 same as in sfb 20 */
+            }
+            else if (sfbTemp == 21)
+                /* only sfb 21 in intensity mode, is_pos[21] = 0 */
+            {
+                (scalefac_R->l[21]) = 0;
+                scalefac_IIP_buffer[21] = 1;    /* the scf value 0 in sfb21 is "legal" */
+            }
+            /* if sfbTemp > 21 (no sfb in intensity mode): do nothing */
+
+
+            /* Now process audio samples */
+            /* first process lower sfb's not in intensity mode */
+
+            sfbNo = mp3_sfBandIndex[sfreq].l[sfbTemp] - mp3_sfBandIndex[sfreq].l[0];
+            sfbStart = mp3_sfBandIndex[sfreq].l[0];
+
+            if (ms_stereo)
+            {
+                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+            }
+
+            /* now intensity stereo processing of the remaining sfb's: */
+            for (sfb = sfbTemp; sfb < 22; sfb++)
+            {
+                sfbNo = mp3_sfBandIndex[sfreq].l[sfb+1] - mp3_sfBandIndex[sfreq].l[sfb]; /* number of lines to process */
+                sfbStart = mp3_sfBandIndex[sfreq].l[sfb];                          /* start of sfb */
+
+                if ((uint32)(scalefac_R->l[sfb]) != scalefac_IIP_buffer[sfb]) /* "legal" position ? */
+                {
+                    pvmp3_st_intensity_ver2(xr, xl, io, scalefac_R->l[sfb], sfbStart, sfbNo);
+                }
+                else if (ms_stereo)
+                {
+                    pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                }
+
+            }  /* for (sfb = sfbTemp; sfb < 22; sfb++) */
+
+        }  /* if (gr_info->window_switching_flag && (gr_info->block_type == 2)) */
+
+    }  /* if (i_stereo) */
+    else
+    {
+        /*
+         *  normal or ms stereo processing
+         */
+        if (ms_stereo)
+        {
+            pvmp3_st_mid_side(xr, xl, 0, used_freq_lines);
+        }
+
+    } /* if (i_stereo) */
+
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.h
new file mode 100644
index 0000000..7db0c53
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_mpeg2_stereo_proc.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_mpeg2_stereo_proc.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_MPEG2_STEREO_PROC_H
+#define PVMP3_MPEG2_STEREO_PROC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_mpeg2_stereo_proc(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    mp3ScaleFactors *scalefac,
+    granuleInfo *gr_info_l,
+    granuleInfo *gr_info_r,
+    uint32 *scalefac_IIP_buffer,
+    int32 used_freq_lines,
+    mp3Header *info);
+
+
+    void pvmp3_st_intensity_ver2(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                                 int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                                 int32 m,
+                                 int32 is_pos,
+                                 int32 Start,
+                                 int32 Number);
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.cpp
new file mode 100644
index 0000000..e579bbd
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.cpp
@@ -0,0 +1,173 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_normalize.cpp
+
+     Date: 10/02/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+    Int32 x             32-bit integer non-zero input
+Returns
+    Int32 i             number of leading zeros on x
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    Returns number of leading zeros on the non-zero input
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3_normalize.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
+----------------------------------------------------------------------------*/
+
+#if (defined(PV_ARM_V5)||defined(PV_ARM_V4))
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+
+/* function is inlined in header file */
+
+
+#else
+
+int32 pvmp3_normalize(int32 x)
+{
+    /*----------------------------------------------------------------------------
+    ; Define all local variables
+    ----------------------------------------------------------------------------*/
+    int32 i;
+
+
+    if (x > 0x0FFFFFFF)
+    {
+        i = 0;  /* most likely case */
+    }
+    else if (x > 0x00FFFFFF)
+    {
+        i = 3;  /* second most likely case */
+    }
+    else if (x > 0x0000FFFF)
+    {
+        i  = x > 0x000FFFFF ?  7 :  11;
+    }
+    else
+    {
+        if (x > 0x000000FF)
+        {
+            i  = x > 0x00000FFF ?  15 :  19;
+        }
+        else
+        {
+            i  = x > 0x0000000F ?  23 :  27;
+        }
+    }
+
+
+    x <<= i;
+
+    switch (x & 0x78000000)
+    {
+        case 0x08000000:
+            i += 3;
+            break;
+
+        case 0x18000000:
+        case 0x10000000:
+            i += 2;
+            break;
+        case 0x28000000:
+        case 0x20000000:
+        case 0x38000000:
+        case 0x30000000:
+            i++;
+
+        default:
+            ;
+    }
+
+    return i;
+
+}
+
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.h
new file mode 100644
index 0000000..5471771
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_normalize.h
@@ -0,0 +1,108 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_normalize.h
+
+   Date: 10/02/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVMP3_NORMALIZE_H
+#define PVMP3_NORMALIZE_H
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+#if (defined(PV_ARM_V5)||defined(PV_ARM_V4))
+
+__inline int32 pvmp3_normalize(int32 x)
+{
+    int32 y;
+    __asm
+    {
+        clz y, x;
+        sub y, y, #1
+    }
+    return (y);
+}
+
+
+#elif (defined(PV_ARM_GCC_V5)||defined(PV_ARM_GCC_V4))
+
+__inline int32 pvmp3_normalize(int32 x)
+{
+    register int32 y;
+    register int32 ra = x;
+
+
+    asm volatile(
+        "clz %0, %1\n\t"
+        "sub %0, %0, #1"
+    : "=&r*i"(y)
+                : "r"(ra));
+    return (y);
+
+}
+
+#else
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    int32 pvmp3_normalize(int32 x);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
+
+#endif  /* PV_NORMALIZE_H */
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp
new file mode 100644
index 0000000..33c8e61
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.cpp
@@ -0,0 +1,187 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_poly_phase_synthesis.cpp
+
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+  Input
+    tmp3dec_chan   *pChVars,          decoder state structure per channel
+    int32          numChannels,       number of channels
+    e_equalization equalizerType,     equalization mode
+    int16          *outPcm            pointer to the PCM output data
+
+  Output
+    int16          *outPcm            pointer to the PCM output data
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    polyphase synthesis
+    Each time the subband samples for all 32 polyphase subbands of one
+    channel have been calculated, they can be applied to the synthesis
+    subband filter and 32 consecutive audio samples can be calculated
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_poly_phase_synthesis.h"
+#include "pvmp3_polyphase_filter_window.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_dct_16.h"
+#include "pvmp3_equalizer.h"
+#include "mp3_mem_funcs.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 pvmp3_poly_phase_synthesis(tmp3dec_chan   *pChVars,
+                                int32          numChannels,
+                                e_equalization equalizerType,
+                                int16          *outPcm)
+{
+    /*
+     *  Equalizer
+     */
+    pvmp3_equalizer(pChVars->circ_buffer,
+                    equalizerType,
+                    pChVars->work_buf_int32);
+
+
+    int16 * ptr_out = outPcm;
+
+
+    for (int32  band = 0; band < FILTERBANK_BANDS; band += 2)
+    {
+        int32 *inData  = &pChVars->circ_buffer[544 - (band<<5)];
+
+        /*
+         *   DCT 32
+         */
+
+        pvmp3_split(&inData[16]);
+
+        pvmp3_dct_16(&inData[16], 0);
+        pvmp3_dct_16(inData, 1);     // Even terms
+
+        pvmp3_merge_in_place_N32(inData);
+
+        pvmp3_polyphase_filter_window(inData,
+                                      ptr_out,
+                                      numChannels);
+
+        inData  -= SUBBANDS_NUMBER;
+
+        /*
+         *   DCT 32
+         */
+
+        pvmp3_split(&inData[16]);
+
+        pvmp3_dct_16(&inData[16], 0);
+        pvmp3_dct_16(inData, 1);     // Even terms
+
+        pvmp3_merge_in_place_N32(inData);
+
+        pvmp3_polyphase_filter_window(inData,
+                                      ptr_out + (numChannels << 5),
+                                      numChannels);
+
+        ptr_out += (numChannels << 6);
+
+        inData  -= SUBBANDS_NUMBER;
+
+    }/* end band loop */
+
+    pv_memmove(&pChVars->circ_buffer[576],
+               pChVars->circ_buffer,
+               480*sizeof(*pChVars->circ_buffer));
+
+}
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h
new file mode 100644
index 0000000..166cffd
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_poly_phase_synthesis.h
@@ -0,0 +1,102 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_poly_phase_synthesis.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_POLY_PHASE_SYNTHESIS_H
+#define PVMP3_POLY_PHASE_SYNTHESIS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "s_tmp3dec_chan.h"
+#include "pvmp3decoder_api.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_poly_phase_synthesis(tmp3dec_chan   *pChVars,
+    int32          numChannels,
+    e_equalization equalizerType,
+    int16          *outPcm);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp
new file mode 100644
index 0000000..8380437
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.cpp
@@ -0,0 +1,239 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_polyphase_filter_window.cpp
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+
+Input
+    int32 *synth_buffer,    synthesis input buffer
+    int16 *outPcm,          generated output ( 32 values)
+    int32 numChannels       number of channels
+ Returns
+
+    int16 *outPcm
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    apply polyphase filter window
+    Input 32 subband samples
+    Calculate 64 values
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+#if ( !defined(PV_ARM_GCC_V5) && !defined(PV_ARM_GCC_V4) && !defined(PV_ARM_V5) && !defined(PV_ARM_V4) )
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_polyphase_filter_window.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_tables.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module1 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 module1
+----------------------------------------------------------------------------*/
+/*----------------------------------------------------------------------------
+; EXTERNAL FUNCTION REFERENCES
+; Declare functions defined elsewhere and referenced in this module_x
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
+; Declare variables used in this module_x but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void pvmp3_polyphase_filter_window(int32 *synth_buffer,
+                                   int16 *outPcm,
+                                   int32 numChannels)
+{
+    int32 sum1;
+    int32 sum2;
+    const int32 *winPtr = pqmfSynthWin;
+    int32 i;
+
+
+    for (int16 j = 1; j < SUBBANDS_NUMBER / 2; j++)
+    {
+        sum1 = 0x00000020;
+        sum2 = 0x00000020;
+
+
+        for (i = (SUBBANDS_NUMBER >> 1);
+                i < HAN_SIZE + (SUBBANDS_NUMBER >> 1);
+                i += SUBBANDS_NUMBER << 4)
+        {
+            int32 *pt_1 = &synth_buffer[ i+j];
+            int32 *pt_2 = &synth_buffer[ i-j];
+            int32 temp1 = pt_1[ 0];
+            int32 temp3 = pt_2[ SUBBANDS_NUMBER*15 ];
+            int32 temp2 = pt_2[ SUBBANDS_NUMBER* 1 ];
+            int32 temp4 = pt_1[ SUBBANDS_NUMBER*14 ];
+
+            sum1  = fxp_mac32_Q32(sum1, temp1,  winPtr[ 0]);
+            sum2  = fxp_mac32_Q32(sum2, temp3,  winPtr[ 0]);
+            sum2  = fxp_mac32_Q32(sum2, temp1,  winPtr[ 1]);
+            sum1  = fxp_msb32_Q32(sum1, temp3,  winPtr[ 1]);
+            sum1  = fxp_mac32_Q32(sum1, temp2,  winPtr[ 2]);
+            sum2  = fxp_msb32_Q32(sum2, temp4,  winPtr[ 2]);
+            sum2  = fxp_mac32_Q32(sum2, temp2,  winPtr[ 3]);
+            sum1  = fxp_mac32_Q32(sum1, temp4,  winPtr[ 3]);
+
+            temp1 = pt_1[ SUBBANDS_NUMBER* 2];
+            temp3 = pt_2[ SUBBANDS_NUMBER*13];
+            temp2 = pt_2[ SUBBANDS_NUMBER* 3];
+            temp4 = pt_1[ SUBBANDS_NUMBER*12];
+
+            sum1  = fxp_mac32_Q32(sum1, temp1,  winPtr[ 4]);
+            sum2  = fxp_mac32_Q32(sum2, temp3,  winPtr[ 4]);
+            sum2  = fxp_mac32_Q32(sum2, temp1,  winPtr[ 5]);
+            sum1  = fxp_msb32_Q32(sum1, temp3,  winPtr[ 5]);
+            sum1  = fxp_mac32_Q32(sum1, temp2,  winPtr[ 6]);
+            sum2  = fxp_msb32_Q32(sum2, temp4,  winPtr[ 6]);
+            sum2  = fxp_mac32_Q32(sum2, temp2,  winPtr[ 7]);
+            sum1  = fxp_mac32_Q32(sum1, temp4,  winPtr[ 7]);
+
+            temp1 = pt_1[ SUBBANDS_NUMBER* 4 ];
+            temp3 = pt_2[ SUBBANDS_NUMBER*11 ];
+            temp2 = pt_2[ SUBBANDS_NUMBER* 5 ];
+            temp4 = pt_1[ SUBBANDS_NUMBER*10 ];
+
+            sum1  = fxp_mac32_Q32(sum1, temp1,  winPtr[ 8]);
+            sum2  = fxp_mac32_Q32(sum2, temp3,  winPtr[ 8]);
+            sum2  = fxp_mac32_Q32(sum2, temp1,  winPtr[ 9]);
+            sum1  = fxp_msb32_Q32(sum1, temp3,  winPtr[ 9]);
+            sum1  = fxp_mac32_Q32(sum1, temp2,  winPtr[10]);
+            sum2  = fxp_msb32_Q32(sum2, temp4,  winPtr[10]);
+            sum2  = fxp_mac32_Q32(sum2, temp2,  winPtr[11]);
+            sum1  = fxp_mac32_Q32(sum1, temp4,  winPtr[11]);
+
+            temp1 = pt_1[ SUBBANDS_NUMBER*6 ];
+            temp3 = pt_2[ SUBBANDS_NUMBER*9 ];
+            temp2 = pt_2[ SUBBANDS_NUMBER*7 ];
+            temp4 = pt_1[ SUBBANDS_NUMBER*8 ];
+
+            sum1  = fxp_mac32_Q32(sum1, temp1,  winPtr[12]);
+            sum2  = fxp_mac32_Q32(sum2, temp3,  winPtr[12]);
+            sum2  = fxp_mac32_Q32(sum2, temp1,  winPtr[13]);
+            sum1  = fxp_msb32_Q32(sum1, temp3,  winPtr[13]);
+            sum1  = fxp_mac32_Q32(sum1, temp2,  winPtr[14]);
+            sum2  = fxp_msb32_Q32(sum2, temp4,  winPtr[14]);
+            sum2  = fxp_mac32_Q32(sum2, temp2,  winPtr[15]);
+            sum1  = fxp_mac32_Q32(sum1, temp4,  winPtr[15]);
+
+            winPtr += 16;
+        }
+
+
+
+        int32 k = j << (numChannels - 1);
+        outPcm[k] = saturate16(sum1 >> 6);
+        outPcm[(numChannels<<5) - k] = saturate16(sum2 >> 6);
+    }
+
+
+
+    sum1 = 0x00000020;
+    sum2 = 0x00000020;
+
+
+    for (i = 16; i < HAN_SIZE + 16; i += (SUBBANDS_NUMBER << 2))
+    {
+        int32 *pt_synth = &synth_buffer[i];
+        int32 temp1 = pt_synth[ 0                ];
+        int32 temp2 = pt_synth[ SUBBANDS_NUMBER  ];
+        int32 temp3 = pt_synth[ SUBBANDS_NUMBER/2];
+
+        sum1 = fxp_mac32_Q32(sum1, temp1, winPtr[0]) ;
+        sum1 = fxp_mac32_Q32(sum1, temp2, winPtr[1]) ;
+        sum2 = fxp_mac32_Q32(sum2, temp3, winPtr[2]) ;
+
+        temp1 = pt_synth[ SUBBANDS_NUMBER<<1 ];
+        temp2 = pt_synth[ 3*SUBBANDS_NUMBER  ];
+        temp3 = pt_synth[ SUBBANDS_NUMBER*5/2];
+
+        sum1 = fxp_mac32_Q32(sum1, temp1, winPtr[3]) ;
+        sum1 = fxp_mac32_Q32(sum1, temp2, winPtr[4]) ;
+        sum2 = fxp_mac32_Q32(sum2, temp3, winPtr[5]) ;
+
+        winPtr += 6;
+    }
+
+
+    outPcm[0] = saturate16(sum1 >> 6);
+    outPcm[(SUBBANDS_NUMBER/2)<<(numChannels-1)] = saturate16(sum2 >> 6);
+
+
+}
+
+#endif // If not assembly
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h
new file mode 100644
index 0000000..b9eccad
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_polyphase_filter_window.h
@@ -0,0 +1,138 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_decode_header.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_POLYPHASE_FILTER_WINDOW_H
+#define PVMP3_POLYPHASE_FILTER_WINDOW_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_audio_type_defs.h"
+#include "s_tmp3dec_chan.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define MAX_16BITS_INT  0x7FFF
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#if (defined(PV_ARM_V5)||defined(PV_ARM_V4))
+
+
+    __inline int16 saturate16(int32 sample)
+    {
+        int32 a;
+        int32 b = 31;
+        __asm
+        {
+            mov   a, sample, asr#15
+            teq a, sample, asr b
+            eorne sample, MAX_16BITS_INT, sample, asr#31
+        }
+        return sample ;
+    }
+
+#else
+
+    inline int16 saturate16(int32 sample)
+    {
+
+        if ((sample >> 15) ^(sample >> 31))
+        {
+            sample = MAX_16BITS_INT ^(sample >> 31);
+        }
+        return sample;
+
+    }
+#endif
+
+
+    void pvmp3_polyphase_filter_window(int32 *synth_buffer,
+                                       int16 *outPcm,
+                                       int32 numChannels);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.cpp
new file mode 100644
index 0000000..35b6475
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.cpp
@@ -0,0 +1,197 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_reorder.cpp
+
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+ Inputs:
+
+    int32 xr[ ],                rescaled data
+    struct gr_info_s *gr_info,  granule structure
+    mp3Header *info,            mp3 header info
+    int32  Scratch_mem[168]     for temporary usage
+
+ Outputs:
+
+    int32 xr[ ],                reordered data
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+ If short blocks are used (block_type[gr][ch]=='10'), the rescaled data
+ xr[scf_band][window][freq_line] shall be reordered in polyphase subband
+ order, xr[subband][window][freq_line], prior to the IMDCT operation.
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_reorder.h"
+#include "pvmp3_tables.h"
+#include "mp3_mem_funcs.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 pvmp3_reorder(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                   granuleInfo *gr_info,
+                   int32  *used_freq_lines,
+                   mp3Header *info,
+                   int32  Scratch_mem[168])
+{
+    int32 sfreq =  info->version_x + (info->version_x << 1);
+    sfreq += info->sampling_frequency;
+
+    if (gr_info->window_switching_flag && (gr_info->block_type == 2))
+    {
+        int32   sfb_lines;
+        int32   freq;
+        int32   src_line;
+        int32   sfb;
+        if (gr_info->mixed_block_flag)
+        {
+            /* REORDERING FOR REST SWITCHED SHORT */
+            sfb = 3;  /* no reorder for low 2 subbands */
+            src_line = 36;
+        }
+        else
+        {  /* pure short */
+            sfb = 0;
+            src_line = 0;
+        }
+        int16 ct = src_line;
+
+        for (; sfb < 13; sfb++)
+        {
+            if (*used_freq_lines > 3*mp3_sfBandIndex[sfreq].s[sfb+1])
+            {
+                sfb_lines = mp3_sfBandIndex[sfreq].s[sfb+1]  - mp3_sfBandIndex[sfreq].s[sfb];
+
+                for (freq = 0; freq < 3*sfb_lines; freq += 3)
+                {
+                    int32 tmp1 = xr[src_line];
+                    int32 tmp2 = xr[src_line+(sfb_lines)];
+                    int32 tmp3 = xr[src_line+(sfb_lines<<1)];
+                    src_line++;
+                    Scratch_mem[freq  ] = tmp1;
+                    Scratch_mem[freq+1] = tmp2;
+                    Scratch_mem[freq+2] = tmp3;
+                }
+                src_line += (sfb_lines << 1);
+
+                pv_memcpy(&xr[ct], Scratch_mem, sfb_lines*3*sizeof(int32));
+                ct += sfb_lines + (sfb_lines << 1);
+
+            }
+            else
+            {
+
+                sfb_lines = mp3_sfBandIndex[sfreq].s[sfb+1]  - mp3_sfBandIndex[sfreq].s[sfb];
+
+                for (freq = 0; freq < 3*sfb_lines; freq += 3)
+                {
+                    int32 tmp1 = xr[src_line];
+                    int32 tmp2 = xr[src_line+(sfb_lines)];
+                    int32 tmp3 = xr[src_line+(sfb_lines<<1)];
+                    src_line++;
+                    Scratch_mem[freq  ] = tmp1;
+                    Scratch_mem[freq+1] = tmp2;
+                    Scratch_mem[freq+2] = tmp3;
+                }
+
+                pv_memcpy(&xr[ct], Scratch_mem, sfb_lines*3*sizeof(int32));
+
+                *used_freq_lines = mp3_sfBandIndex[sfreq].s[sfb+1] * 3;
+
+                sfb = 13;   /* force out of the for-loop */
+            }
+        }
+    }
+}
+
+
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.h
new file mode 100644
index 0000000..ba6ec16
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_reorder.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_reorder.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_REORDER_H
+#define PVMP3_REORDER_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    void pvmp3_reorder(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    granuleInfo *gr_info,
+    int32 *used_freq_lines,
+    mp3Header *info,
+    int32  Scratch_mem[168]);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.cpp
new file mode 100644
index 0000000..82faafd
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.cpp
@@ -0,0 +1,308 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_seek_synch.cpp
+
+   Functions:
+        pvmp3_seek_synch
+        pvmp3_header_sync
+
+
+     Date: 9/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+pvmp3_frame_synch
+
+Input
+    pExt = pointer to the external interface structure. See the file
+           pvmp3decoder_api.h for a description of each field.
+           Data type of pointer to a tPVMP3DecoderExternal
+           structure.
+
+    pMem = void pointer to hide the internal implementation of the library
+           It is cast back to a tmp3dec_file structure. This structure
+           contains information that needs to persist between calls to
+           this function, or is too big to be placed on the stack, even
+           though the data is only needed during execution of this function
+           Data type void pointer, internally pointer to a tmp3dec_file
+           structure.
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    search mp3 sync word, when found, it verifies, based on header parameters,
+    the locations of the very next sync word,
+    - if fails, then indicates a false sync,
+    - otherwise, it confirm synchronization of at least 2 consecutives frames
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_seek_synch.h"
+#include "pvmp3_getbits.h"
+#include "s_tmp3dec_file.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_tables.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
+----------------------------------------------------------------------------*/
+
+
+
+ERROR_CODE pvmp3_frame_synch(tPVMP3DecoderExternal *pExt,
+                             void                  *pMem) /* bit stream structure */
+{
+    uint16 val;
+    ERROR_CODE err;
+
+    tmp3dec_file      *pVars;
+
+    pVars = (tmp3dec_file *)pMem;
+
+    pVars->inputStream.pBuffer = pExt->pInputBuffer;
+    pVars->inputStream.usedBits = (pExt->inputBufferUsedLength << 3); // in bits
+
+
+    pVars->inputStream.inputBufferCurrentLength = (pExt->inputBufferCurrentLength); // in bits
+
+    err = pvmp3_header_sync(&pVars->inputStream);
+
+    if (err == NO_DECODING_ERROR)
+    {
+        /* validate synchronization by checking two consecutive sync words */
+
+        // to avoid multiple bitstream accesses
+        uint32 temp = getNbits(&pVars->inputStream, 21);
+        // put back whole header
+        pVars->inputStream.usedBits -= 21 + SYNC_WORD_LNGTH;
+
+        int32  version;
+
+        switch (temp >> 19)  /* 2 */
+        {
+            case 0:
+                version = MPEG_2_5;
+                break;
+            case 2:
+                version = MPEG_2;
+                break;
+            case 3:
+                version = MPEG_1;
+                break;
+            default:
+                version = INVALID_VERSION;
+                break;
+        }
+
+        int32 freq_index = (temp << 20) >> 30;
+
+        if (version != INVALID_VERSION && (freq_index != 3))
+        {
+            int32 numBytes = fxp_mul32_Q28(mp3_bitrate[version][(temp<<16)>>28] << 20,
+                                           inv_sfreq[freq_index]);
+
+            numBytes >>= (20 - version);
+
+            if (version != MPEG_1)
+            {
+                numBytes >>= 1;
+            }
+            if ((temp << 22) >> 31)
+            {
+                numBytes++;
+            }
+
+            if (numBytes > (int32)pVars->inputStream.inputBufferCurrentLength)
+            {
+                /* frame should account for padding and 2 bytes to check sync */
+                pExt->CurrentFrameLength = numBytes + 3;
+                return (SYNCH_LOST_ERROR);
+            }
+            else if (numBytes == (int32)pVars->inputStream.inputBufferCurrentLength)
+            {
+                /* No enough data to validate, but current frame appears to be correct ( EOF case) */
+                pExt->inputBufferUsedLength = pVars->inputStream.usedBits >> 3;
+                return (NO_DECODING_ERROR);
+            }
+            else
+            {
+
+                int32 offset = pVars->inputStream.usedBits + ((numBytes) << 3);
+
+                offset >>= INBUF_ARRAY_INDEX_SHIFT;
+                uint8    *pElem  = pVars->inputStream.pBuffer + offset;
+                uint16 tmp1 = *(pElem++);
+                uint16 tmp2 = *(pElem);
+
+                val = (tmp1 << 3);
+                val |= (tmp2 >> 5);
+            }
+        }
+        else
+        {
+            val = 0; // force mismatch
+        }
+
+        if (val == SYNC_WORD)
+        {
+            pExt->inputBufferUsedLength = pVars->inputStream.usedBits >> 3; ///  !!!!!
+            err = NO_DECODING_ERROR;
+        }
+        else
+        {
+            pExt->inputBufferCurrentLength = 0;
+            err = SYNCH_LOST_ERROR;
+        }
+    }
+    else
+    {
+        pExt->inputBufferCurrentLength = 0;
+    }
+
+    return(err);
+
+}
+
+/*
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+------------------------------------------------------------------------------
+ INPUT AND OUTPUT DEFINITIONS
+
+pvmp3_header_sync
+
+Input
+    tmp3Bits *inputStream,     structure holding the input stream parameters
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    search mp3 sync word
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+
+ERROR_CODE pvmp3_header_sync(tmp3Bits  *inputStream)
+{
+    uint16 val;
+    uint32 availableBits = (inputStream->inputBufferCurrentLength << 3); // in bits
+
+    // byte aligment
+    inputStream->usedBits = (inputStream->usedBits + 7) & 8;
+
+    val = (uint16)getUpTo17bits(inputStream, SYNC_WORD_LNGTH);
+
+    while (((val&SYNC_WORD) != SYNC_WORD) && (inputStream->usedBits < availableBits))
+    {
+        val <<= 8;
+        val |= getUpTo9bits(inputStream, 8);
+    }
+
+    if ((val&SYNC_WORD) == SYNC_WORD && (inputStream->usedBits < availableBits))
+    {
+        return(NO_DECODING_ERROR);
+    }
+    else
+    {
+        return(SYNCH_LOST_ERROR);
+    }
+
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.h
new file mode 100644
index 0000000..8097cee
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_seek_synch.h
@@ -0,0 +1,106 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_seek_synch.h
+
+   Date: 09/21/2007
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_SEEK_SYNCH_H
+#define PVMP3_SEEK_SYNCH_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3decoder_api.h"
+#include "s_tmp3dec_file.h"
+#include "pvmp3_dec_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    ERROR_CODE pvmp3_frame_synch(tPVMP3DecoderExternal *pExt,
+    void                  *pMem);
+
+    ERROR_CODE pvmp3_header_sync(tmp3Bits  *inputStream);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif  /* DECODE_READ_INPUT_H */
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.cpp
new file mode 100644
index 0000000..d69a46d
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_stereo_proc.cpp
+
+   Functions:
+
+    pvmp3_st_mid_side
+    pvmp3_st_intensity
+    pvmp3_stereo_proc
+
+------------------------------------------------------------------------------
+
+pvmp3_st_mid_side
+
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+   int32 xr[],      input channel
+   int32 xl[],
+   int32 Start,     Location of first element where stereo intensity is applied
+   int32 Number     number of elements affected
+
+ Returns
+
+   int32 xl[],      generated stereo channel
+
+
+------------------------------------------------------------------------------
+
+pvmp3_st_intensity
+
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+   int32 xr[],      input channel
+   int32 xl[],
+   int32 is_pos,    index to table is_ratio_factor[]
+   int32 Start,     Location of first element where stereo intensity is applied
+   int32 Number     number of elements affected
+
+ Returns
+
+   int32 xl[],      generated stereo channel
+
+
+------------------------------------------------------------------------------
+
+pvmp3_stereo_proc
+
+ INPUT AND OUTPUT DEFINITIONS
+
+Input
+
+   int32 xr[],                    input channel
+   int32 xl[],
+   mp3ScaleFactors  *scalefac,    scale factors structure
+   struct gr_info_s *gr_info,     granule structure
+   mp3Header *info                mp3 header info
+ Returns
+
+   int32 xl[],      generated stereo channel
+
+
+------------------------------------------------------------------------------
+ FUNCTION DESCRIPTION
+
+    stereo processing for mpeg1 layer III
+    After requantization, the reconstructed values are processed for ms_stereo
+    or intensity_stereo modes or both, before passing them to the synthesis
+    filterbank
+
+    In ms_stereo mode the values of the normalized middle/side channels
+    M[l] and S[l] are transmitted instead of the left/right channel values
+    L[l] and R[l]. From here, L[l] and R[l] are reconstructed
+
+    Intensity_stereo is done by specifying the magnitude (via the
+    scalefactors of the left channel) and a stereo position is_pos[sfb],
+    which is transmitted instead of scalefactors of the right channel.
+    The stereo position is used to derive the left and right channel signals
+
+------------------------------------------------------------------------------
+ REQUIREMENTS
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+ PSEUDO-CODE
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_stereo_proc.h"
+#include "pv_mp3dec_fxd_op.h"
+#include "pvmp3_tables.h"
+
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here. Include conditional
+; compile variables also.
+----------------------------------------------------------------------------*/
+#define N31 31
+
+#define Q31_fmt(a)    (int32(double(0x7FFFFFFF)*a))
+
+/*----------------------------------------------------------------------------
+; LOCAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; LOCAL STORE/BUFFER/POINTER DEFINITIONS
+; Variable declaration - defined here and used outside this module
+----------------------------------------------------------------------------*/
+/*
+ *  TmpFac= tan(is_pos * (PI /12));
+ *
+ *  TmpFac /= (1 + TmpFac);
+ *
+ */
+
+const int32  is_ratio_factor[8] = {0,
+                                   Q31_fmt(0.21132486540519),   Q31_fmt(0.36602540378444),   Q31_fmt(0.50000000000000),
+                                   Q31_fmt(0.63397459621556),   Q31_fmt(0.78867513459481),   Q31_fmt(1.00000000000000),
+                                   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
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void pvmp3_st_mid_side(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       int32 Start,
+                       int32 Number)
+{
+
+    int32 *pt_xr  = &xr[Start];
+    int32 *pt_xl  = &xl[Start];
+
+    for (int32 i = Number >> 1; i != 0; i--)
+    {
+        int32 xxr = *(pt_xr) << 1;
+        int32 xxl = *(pt_xl) << 1;
+        *(pt_xr++)  = fxp_mul32_Q32((xxr + xxl), Q31_fmt(0.70710678118655));   /* Sum */
+        *(pt_xl++)  = fxp_mul32_Q32((xxr - xxl), Q31_fmt(0.70710678118655));   /* Diff */
+        xxr = *(pt_xr) << 1;
+        xxl = *(pt_xl) << 1;
+        *(pt_xr++)  = fxp_mul32_Q32((xxr + xxl), Q31_fmt(0.70710678118655));   /* Sum */
+        *(pt_xl++)  = fxp_mul32_Q32((xxr - xxl), Q31_fmt(0.70710678118655));   /* Diff */
+    }
+
+
+    if (Number&1)
+    {
+        int32 xxr = *(pt_xr) << 1;
+        int32 xxl = *(pt_xl) << 1;
+        *(pt_xr)  = fxp_mul32_Q32((xxr + xxl), Q31_fmt(0.70710678118655));   /* Sum */
+        *(pt_xl)  = fxp_mul32_Q32((xxr - xxl), Q31_fmt(0.70710678118655));   /* Diff */
+    }
+
+}
+
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+
+void pvmp3_st_intensity(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                        int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                        int32 is_pos,
+                        int32 Start,
+                        int32 Number)
+{
+
+    int32 TmpFac = is_ratio_factor[ is_pos & 7];
+
+    int32 *pt_xr  = &xr[Start];
+    int32 *pt_xl  = &xl[Start];
+
+    for (int32 i = Number >> 1; i != 0; i--)
+    {
+        int32 tmp = fxp_mul32_Q32((*pt_xr) << 1, TmpFac);
+        *(pt_xl++) = (*pt_xr) - tmp;
+        *(pt_xr++) = tmp;
+        tmp = fxp_mul32_Q32((*pt_xr) << 1, TmpFac);
+        *(pt_xl++) = (*pt_xr) - tmp;
+        *(pt_xr++) = tmp;
+    }
+
+    if (Number&1)
+    {
+        int32 tmp = fxp_mul32_Q32((*pt_xr) << 1, TmpFac);
+        *(pt_xl) = (*pt_xr) - tmp;
+        *(pt_xr) = tmp;
+    }
+
+}
+
+/*----------------------------------------------------------------------------
+; FUNCTION CODE
+----------------------------------------------------------------------------*/
+void pvmp3_stereo_proc(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                       mp3ScaleFactors *scalefac,
+                       granuleInfo *gr_info,
+                       int32 used_freq_lines,
+                       mp3Header *info)
+{
+
+
+    int32 sb;
+    int32 ss;
+    int32 sfbNo;
+    int32 sfbStart;
+
+    int32 sfb;
+    int32 sfbTemp;
+    int32 i;
+    int32 j;
+
+
+    int32 i_stereo  = (info->mode == MPG_MD_JOINT_STEREO) &&
+                      (info->mode_ext & 0x1);
+
+    int32 ms_stereo = (info->mode == MPG_MD_JOINT_STEREO) &&
+                      (info->mode_ext & 0x2);
+
+    int32 sfreq  = info->version_x + (info->version_x << 1);
+    sfreq += info->sampling_frequency;
+
+
+
+
+    if (i_stereo)
+    {
+        if (gr_info->window_switching_flag && (gr_info->block_type == 2))
+        {
+            if (gr_info->mixed_block_flag)
+            {
+                /*
+                 * mixed blocks processing
+                 */
+                i = 31;
+                ss = 17;
+                sb = 0;
+                while (i >= 0)
+                {
+                    if (xl[(i*FILTERBANK_BANDS) + ss])
+                    {
+                        sb = (i << 4) + (i << 1) + ss;
+                        i = -1;
+                    }
+                    else
+                    {
+                        ss--;
+                        if (ss < 0)
+                        {
+                            i--;
+                            ss = 17;
+                        }
+                    }
+                }
+
+                if (sb < 36)
+                {
+                    /*
+                     * mixed blocks processing: intensity bound inside long blocks
+                     */
+                    /* 1. long blocks up to intensity border: not intensity */
+
+                    if (mp3_sfBandIndex[sfreq].l[4] <= sb)
+                    {
+                        sfb = 4;
+                    }
+                    else
+                    {
+                        sfb = 0;
+                    }
+
+                    while (mp3_sfBandIndex[sfreq].l[sfb] < sb)
+                    {
+                        sfb++;
+                    }
+
+                    /* from that sfb on intensity stereo */
+                    sfbTemp = sfb;  /* save for later use */
+
+                    sfbStart = mp3_sfBandIndex[sfreq].l[sfb];
+
+                    /* from 0 up to sfbStart do ms_stereo or normal stereo */
+
+                    if (ms_stereo)
+                    {
+                        pvmp3_st_mid_side(xr, xl, 0, sfbStart);
+                    }
+
+                    /* 2. long blocks from intensity border up to sfb band 8: intensity */
+                    /* calc. is_ratio */
+
+
+                    /* Start of intensity stereo of remaining sfc bands: */
+                    for (; sfbTemp < 8; sfbTemp++)
+                    {
+                        sfbStart = mp3_sfBandIndex[sfreq].l[sfbTemp];  /* = Start in 0 ... 575 */
+                        sfbNo = mp3_sfBandIndex[sfreq].l[sfbTemp+1] - mp3_sfBandIndex[sfreq].l[sfbTemp]; /* No of lines to process */
+
+                        if (scalefac->l[sfbTemp] != 7)
+                        {
+                            pvmp3_st_intensity(xr, xl, scalefac->l[sfbTemp], sfbStart, sfbNo);
+                        }
+                        else if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+
+                    }  /* for (; sfbTemp < 8; sfbTemp++) */
+
+                    for (j = 0; j < 3; j++)
+                    {
+                        /* 3. short blocks from sfbcnt to last sfb do intensity stereo */
+                        for (sfbTemp = 3; sfbTemp < 13; sfbTemp++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sfbTemp+1] - mp3_sfBandIndex[sfreq].s[sfbTemp]; /* No of lines to process */
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfbTemp] + j * sfbNo;
+
+                            if (scalefac->s[j][sfbTemp] != 7)
+                            {
+                                pvmp3_st_intensity(xr, xl, scalefac->s[j][sfbTemp], sfbStart, sfbNo);
+                            }
+                            else if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+
+                        }  /* for (; sfbTemp < 22; sfbTemp++) */
+                    } /* for (j = 0; j < 3; j++) */
+                }
+                else   /* else for (sb >= 36) */
+                {
+                    /*
+                     * mixed blocks processing: intensity bound outside long blocks
+                     */
+
+
+                    /*
+                     * 2. short blocks from sfb band 3 up to intensity border: normal stereo, ms stereo and intensity
+                     */
+                    for (j = 0; j < 3; j++)
+                    {
+                        int32 sfbcnt;
+                        sfbcnt = -1;
+
+                        for (sfb = 12; sfb >= 3; sfb--)
+                        {
+                            int32 lines;
+                            lines = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+                            i = 3 * mp3_sfBandIndex[sfreq].s[sfb] + (j + 1) * lines - 1;
+
+                            while (lines > 0)
+                            {
+                                if (xl[i])
+                                {
+                                    sfbcnt = sfb;
+                                    sfb = -10;
+                                    lines = -10;
+                                }
+                                lines--;
+                                i--;
+                            }
+                        }
+
+                        sfbcnt += 1;
+                        if (sfbcnt < 3)
+                        {
+                            sfbcnt = 3;
+                        }
+
+                        sfbTemp = sfbcnt;        /* for later use */
+
+
+                        /*
+                         *   do normal stereo or MS stereo from sfb 3 to < sfbcnt:
+                         */
+                        for (sb = 3; sb < sfbcnt; sb++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sb+1] - mp3_sfBandIndex[sfreq].s[sb];
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sb] + j * sfbNo;
+
+                            if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+
+                        }
+
+                        /* from sfbcnt to last sfb do intensity stereo */
+                        for (; sfbTemp < 13; sfbTemp++)
+                        {
+                            sfbNo = mp3_sfBandIndex[sfreq].s[sfbTemp+1] - mp3_sfBandIndex[sfreq].s[sfbTemp]; /* No of lines to process */
+                            sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfbTemp] + j * sfbNo;
+
+                            if (scalefac->s[j][sfbTemp] != 7)
+                            {
+                                pvmp3_st_intensity(xr, xl, scalefac->s[j][sfbTemp], sfbStart, sfbNo);
+                            }
+                            else if (ms_stereo)
+                            {
+                                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                            }
+
+                        }  /* for (; sfbTemp < 22; sfbTemp++) */
+
+                    } /* for (j = 0; j < 3; j++) */
+
+                    /* 1. long blocks up to sfb band 8: not intensity */
+                    /* from 0 to sfb 8 ms_stereo or normal stereo */
+
+                    sfbStart = mp3_sfBandIndex[sfreq].l[8];
+
+                    if (ms_stereo)
+                    {
+                        pvmp3_st_mid_side(xr, xl, 0, sfbStart);
+                    }
+
+                }
+            }  /* if (gr_info->mixed_block_flag) */
+            else
+            {
+                /*
+                 * short block processing
+                 */
+                for (j = 0; j < 3; j++)
+                {
+                    int32 sfbcnt = -1;
+
+                    for (sfb = 12; sfb >= 0; sfb--)
+                    {
+                        int32 lines = mp3_sfBandIndex[sfreq].s[sfb+1] - mp3_sfBandIndex[sfreq].s[sfb];
+                        i = 3 * mp3_sfBandIndex[sfreq].s[sfb] + (j + 1) * lines - 1;
+
+                        while (lines > 0)
+                        {
+                            if (xl[i])
+                            {
+                                sfbcnt = sfb;
+                                sfb = -10;
+                                lines = -10;
+                            }
+                            lines--;
+                            i--;
+                        }
+                    }
+
+                    sfbcnt += 1;
+                    sfbTemp = sfbcnt;        /* for later use */
+
+                    /* do normal stereo or MS stereo from 0 to sfbcnt */
+                    for (sb = 0; sb < sfbcnt; sb++)
+                    {
+                        sfbNo = mp3_sfBandIndex[sfreq].s[sb+1] - mp3_sfBandIndex[sfreq].s[sb];
+                        sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sb] + j * sfbNo;
+
+                        if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+                    }
+
+
+                    /* from sfbcnt to last sfb do intensity stereo */
+                    for (; sfbTemp < 13; sfbTemp++)
+                    {
+                        sfbNo = mp3_sfBandIndex[sfreq].s[sfbTemp+1] - mp3_sfBandIndex[sfreq].s[sfbTemp]; /* No of lines to process */
+                        sfbStart = 3 * mp3_sfBandIndex[sfreq].s[sfbTemp] + j * sfbNo;
+
+                        if (scalefac->s[j][sfbTemp] != 7)
+                        {
+                            pvmp3_st_intensity(xr, xl, scalefac->s[j][sfbTemp], sfbStart, sfbNo);
+                        }
+                        else if (ms_stereo)
+                        {
+                            pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                        }
+
+                    }  /* for (; sfbTemp < 22; sfbTemp++) */
+
+                } /* for (j = 0; j < 3; j++) */
+
+            } /* if( gr_info->mixed_block_flag) */
+
+
+
+        }  /* if (gr_info->window_switching_flag && (gr_info->block_type == 2)) */
+        else
+        {
+            /*
+             *   long block processing
+             */
+            i = 31;
+            ss = 17;
+            sb = 0;
+
+            while (i >= 0)
+            {
+                if (xl[(i*FILTERBANK_BANDS) + ss] != 0)
+                {
+                    sb = (i << 4) + (i << 1) + ss;
+                    i = -2;
+                }
+                else
+                {
+                    ss--;
+                    if (ss < 0)
+                    {
+                        i--;
+                        ss = 17;
+                    }
+                }
+            }
+
+            if (sb)
+            {
+                if (mp3_sfBandIndex[sfreq].l[14] <= sb)
+                {
+                    sfb = 14;
+                }
+                else if (mp3_sfBandIndex[sfreq].l[7] <= sb)
+                {
+                    sfb = 7;
+                }
+                else
+                {
+                    sfb = 0;
+                }
+
+
+                while (mp3_sfBandIndex[sfreq].l[sfb] <= sb)
+                {
+                    sfb++;
+                }
+            }
+            else
+            {
+                if (i == -1)
+                {
+                    /*  all xr[1][][] are 0: set IS bound sfb to 0  */
+                    sfb = 0;
+                }
+                else
+                {
+                    /*  xr[1][0][0] is unequal 0 and all others are 0: set IS bound sfb to 1 */
+                    sfb = 1;
+                }
+            }
+
+            sfbTemp = sfb;  /* save for later use */
+
+
+            sfbStart = mp3_sfBandIndex[sfreq].l[sfb];
+
+            /* from 0 to sfbStart ms_stereo or normal stereo */
+            if (ms_stereo)
+            {
+                pvmp3_st_mid_side(xr, xl, 0, sfbStart);
+            }
+
+            /* now intensity stereo of the remaining sfb's: */
+            for (; sfb < 21; sfb++)
+            {
+                sfbStart = mp3_sfBandIndex[sfreq].l[sfb];
+                sfbNo = mp3_sfBandIndex[sfreq].l[sfb+1] - mp3_sfBandIndex[sfreq].l[sfb]; /* No of lines to process */
+
+                if (scalefac->l[sfb] != 7)
+                {
+                    pvmp3_st_intensity(xr, xl, scalefac->l[sfb], sfbStart, sfbNo);
+                }
+                else if (ms_stereo)
+                {
+                    pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+                }
+
+            }  /* for (; sfbTemp < 22; sfbTemp++) */
+
+
+
+            sfbStart = mp3_sfBandIndex[sfreq].l[21];
+            sfbNo = mp3_sfBandIndex[sfreq].l[22] - mp3_sfBandIndex[sfreq].l[21]; /* No of lines to process */
+
+            if (scalefac->l[21] != 7)
+            {
+                if (sfbTemp < 21)
+                {
+                    sfbTemp = scalefac->l[20];
+                }
+                else
+                {
+                    sfbTemp = 0;  /* if scalefac[20] is not an intensity position, is_pos = 0 */
+                }
+
+                pvmp3_st_intensity(xr, xl, sfbTemp, sfbStart, sfbNo);
+            }
+            else if (ms_stereo)
+            {
+                pvmp3_st_mid_side(xr, xl, sfbStart, sfbNo);
+            }
+
+        }  /* if (gr_info->window_switching_flag && (gr_info->block_type == 2)) */
+
+
+    }  /* if (i_stereo)  */
+    else
+    {
+        /*
+         * normal or ms stereo processing
+         */
+        if (ms_stereo)
+        {
+
+            pvmp3_st_mid_side(xr, xl, 0, used_freq_lines);
+
+        }
+
+    } /* if (i_stereo) */
+
+}
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_proc.h
new file mode 100644
index 0000000..bfaf1a1
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_stereo_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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_stereo_proc.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef PVMP3_STEREO_PROC_H
+#define PVMP3_STEREO_PROC_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+    void pvmp3_stereo_proc(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+    mp3ScaleFactors *scalefac,
+    granuleInfo *gr_info,
+    int32 used_freq_lines,
+    mp3Header *info);
+
+    void pvmp3_st_intensity(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                            int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                            int32 is_pos,
+                            int32 Start,
+                            int32 Number);
+
+    void pvmp3_st_mid_side(int32 xr[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                           int32 xl[SUBBANDS_NUMBER*FILTERBANK_BANDS],
+                           int32 Start,
+                           int32 Number);
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
new file mode 100644
index 0000000..90e524a
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.cpp
@@ -0,0 +1,2934 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: pvmp3_tables.cpp
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+
+ Description:
+
+
+------------------------------------------------------------------------------
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+------------------------------------------------------------------------------
+*/
+
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_tables.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
+----------------------------------------------------------------------------*/
+
+const int32  mp3_s_freq[4][4] =
+{
+    {44100, 48000, 32000, 0},
+    {22050, 24000, 16000, 0},
+    {11025, 12000,  8000, 0}
+}; // MPEG-2.5
+
+
+/*
+ *  144000./s_freq
+ */
+const int32 inv_sfreq[4] =
+{
+    Qfmt_28(3.26530612244898),
+    Qfmt_28(3.0),
+    Qfmt_28(4.5),
+    0
+};
+
+
+/* 1: MPEG-1, 0: MPEG-2 LSF, 1995-07-11 shn */
+
+
+const int16  mp3_bitrate[3][15] =
+{
+    {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320},
+    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160},
+    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}
+};
+
+
+const mp3_scaleFactorBandIndex mp3_sfBandIndex[9] =
+{
+
+    /* MPEG 1 */
+
+    {{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576},
+    {0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192}},
+    {{0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576},
+    {0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192}},
+    {{0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576},
+        {0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192}},
+
+    /* MPEG 2 - LSF */
+
+    {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576},
+    {0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192}},
+    {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576},
+    {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192}},
+    {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576},
+        {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}},
+
+    /* MPEG 2.5  extension */
+
+    {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576},
+    {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}},
+    {{0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576},
+    {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}},
+    {{0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576},
+        {0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192}}
+
+};
+
+#define INV_Q31( x)   (int32)(0x7FFFFFFF/(float)x - 1.0f)
+
+const int32 mp3_shortwindBandWidths[9][13] =
+{
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(10),
+        INV_Q31(12), INV_Q31(14), INV_Q31(18), INV_Q31(22), INV_Q31(30), INV_Q31(56)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(6), INV_Q31(10),
+      INV_Q31(12), INV_Q31(14), INV_Q31(16), INV_Q31(20), INV_Q31(26), INV_Q31(66)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(12),
+      INV_Q31(16), INV_Q31(20), INV_Q31(26), INV_Q31(34), INV_Q31(42), INV_Q31(12)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(6), INV_Q31(8), INV_Q31(10),
+      INV_Q31(14), INV_Q31(18), INV_Q31(26), INV_Q31(32), INV_Q31(42), INV_Q31(18)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(10), INV_Q31(12),
+      INV_Q31(14), INV_Q31(18), INV_Q31(24), INV_Q31(32), INV_Q31(44), INV_Q31(12)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(10), INV_Q31(12),
+      INV_Q31(14), INV_Q31(18), INV_Q31(24), INV_Q31(30), INV_Q31(40), INV_Q31(18)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(10), INV_Q31(12),
+      INV_Q31(14), INV_Q31(18), INV_Q31(24), INV_Q31(30), INV_Q31(40), INV_Q31(18)},
+    { INV_Q31(4), INV_Q31(4), INV_Q31(4), INV_Q31(6), INV_Q31(8), INV_Q31(10), INV_Q31(12),
+      INV_Q31(14), INV_Q31(18), INV_Q31(24), INV_Q31(30), INV_Q31(40), INV_Q31(18)},
+    { INV_Q31(8), INV_Q31(8), INV_Q31(8), INV_Q31(12), INV_Q31(16), INV_Q31(20), INV_Q31(24),
+      INV_Q31(28), INV_Q31(36), INV_Q31(2), INV_Q31(2), INV_Q31(2), INV_Q31(26)}
+};
+
+
+#define Q30_fmt(a)    (int32((0x40000000)*a))
+
+const int32 pqmfSynthWin[(HAN_SIZE/2) + 8] =
+{
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000396729F), Q30_fmt(0.000473022F), Q30_fmt(0.003173828F),
+    Q30_fmt(0.003326416F), Q30_fmt(0.006118770F), Q30_fmt(0.007919310F), Q30_fmt(0.031478880F),
+    Q30_fmt(0.030517578F), Q30_fmt(0.073059080F), Q30_fmt(0.084182740F), Q30_fmt(0.108856200F),
+    Q30_fmt(0.090927124F), Q30_fmt(0.543823240F), Q30_fmt(0.600219727F), Q30_fmt(1.144287109F),
+
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000366211F), Q30_fmt(0.000534058F), Q30_fmt(0.003082275F),
+    Q30_fmt(0.003387451F), Q30_fmt(0.005294800F), Q30_fmt(0.008865360F), Q30_fmt(0.031738280F),
+    Q30_fmt(0.029785160F), Q30_fmt(0.067520140F), Q30_fmt(0.089706420F), Q30_fmt(0.116577150F),
+    Q30_fmt(0.080688480F), Q30_fmt(0.515609740F), Q30_fmt(0.628295900F), Q30_fmt(1.142211914F),
+
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000320435F), Q30_fmt(0.000579834F), Q30_fmt(0.002990723F),
+    Q30_fmt(0.003433228F), Q30_fmt(0.004486080F), Q30_fmt(0.009841920F), Q30_fmt(0.031845090F),
+    Q30_fmt(0.028884890F), Q30_fmt(0.061996460F), Q30_fmt(0.095169070F), Q30_fmt(0.123474120F),
+    Q30_fmt(0.069595340F), Q30_fmt(0.487472530F), Q30_fmt(0.656219480F), Q30_fmt(1.138763428F),
+
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000289917F), Q30_fmt(0.000625610F), Q30_fmt(0.002899170F),
+    Q30_fmt(0.003463745F), Q30_fmt(0.003723140F), Q30_fmt(0.010849000F), Q30_fmt(0.031814580F),
+    Q30_fmt(0.027801510F), Q30_fmt(0.056533810F), Q30_fmt(0.100540160F), Q30_fmt(0.129577640F),
+    Q30_fmt(0.057617190F), Q30_fmt(0.459472660F), Q30_fmt(0.683914180F), Q30_fmt(1.133926392F),
+
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000259399F), Q30_fmt(0.000686646F), Q30_fmt(0.002792358F),
+    Q30_fmt(0.003479004F), Q30_fmt(0.003005981F), Q30_fmt(0.011886600F), Q30_fmt(0.031661990F),
+    Q30_fmt(0.026535030F), Q30_fmt(0.051132200F), Q30_fmt(0.105819700F), Q30_fmt(0.134887700F),
+    Q30_fmt(0.044784550F), Q30_fmt(0.431655880F), Q30_fmt(0.711318970F), Q30_fmt(1.127746582F),
+
+    Q30_fmt(-0.000015259F), Q30_fmt(0.000244141F), Q30_fmt(0.000747681F), Q30_fmt(0.002685547F),
+    Q30_fmt(0.003479004F), Q30_fmt(0.002334595F), Q30_fmt(0.012939450F), Q30_fmt(0.031387330F),
+    Q30_fmt(0.025085450F), Q30_fmt(0.045837400F), Q30_fmt(0.110946660F), Q30_fmt(0.139450070F),
+    Q30_fmt(0.031082153F), Q30_fmt(0.404083250F), Q30_fmt(0.738372800F), Q30_fmt(1.120223999F),
+
+    Q30_fmt(-0.000030518F), Q30_fmt(0.000213623F), Q30_fmt(0.000808716F), Q30_fmt(0.002578735F),
+    Q30_fmt(0.003463745F), Q30_fmt(0.001693726F), Q30_fmt(0.014022830F), Q30_fmt(0.031005860F),
+    Q30_fmt(0.023422240F), Q30_fmt(0.040634160F), Q30_fmt(0.115921020F), Q30_fmt(0.143264770F),
+    Q30_fmt(0.016510010F), Q30_fmt(0.376800540F), Q30_fmt(0.765029907F), Q30_fmt(1.111373901F),
+
+    Q30_fmt(-0.000030518F), Q30_fmt(0.000198364F), Q30_fmt(0.000885010F), Q30_fmt(0.002456665F),
+    Q30_fmt(0.003417969F), Q30_fmt(0.001098633F), Q30_fmt(0.015121460F), Q30_fmt(0.030532840F),
+    Q30_fmt(0.021575930F), Q30_fmt(0.035552980F), Q30_fmt(0.120697020F), Q30_fmt(0.146362300F),
+    Q30_fmt(0.001068120F), Q30_fmt(0.349868770F), Q30_fmt(0.791213990F), Q30_fmt(1.101211548F),
+
+    Q30_fmt(-0.000030518F), Q30_fmt(0.000167847F), Q30_fmt(0.000961304F), Q30_fmt(0.002349854F),
+    Q30_fmt(0.003372192F), Q30_fmt(0.000549316F), Q30_fmt(0.016235350F), Q30_fmt(0.029937740F),
+    Q30_fmt(0.019531250F), Q30_fmt(0.030609130F), Q30_fmt(0.125259400F), Q30_fmt(0.148773190F),
+    Q30_fmt(-0.015228270F), Q30_fmt(0.323318480F), Q30_fmt(0.816864010F), Q30_fmt(1.089782715F),
+
+    Q30_fmt(-0.000030518F), Q30_fmt(0.000152588F), Q30_fmt(0.001037598F), Q30_fmt(0.002243042F),
+    Q30_fmt(0.003280640F), Q30_fmt(0.000030518F), Q30_fmt(0.017349240F), Q30_fmt(0.029281620F),
+    Q30_fmt(0.017257690F), Q30_fmt(0.025817870F), Q30_fmt(0.129562380F), Q30_fmt(0.150497440F),
+    Q30_fmt(-0.032379150F), Q30_fmt(0.297210693F), Q30_fmt(0.841949463F), Q30_fmt(1.077117920F),
+
+    Q30_fmt(-0.000045776F), Q30_fmt(0.000137329F), Q30_fmt(0.001113892F), Q30_fmt(0.002120972F),
+    Q30_fmt(0.003173828F), Q30_fmt(-0.000442505F), Q30_fmt(0.018463130F), Q30_fmt(0.028533940F),
+    Q30_fmt(0.014801030F), Q30_fmt(0.021179200F), Q30_fmt(0.133590700F), Q30_fmt(0.151596070F),
+    Q30_fmt(-0.050354000F), Q30_fmt(0.271591190F), Q30_fmt(0.866363530F), Q30_fmt(1.063217163F),
+
+    Q30_fmt(-0.000045776F), Q30_fmt(0.000122070F), Q30_fmt(0.001205444F), Q30_fmt(0.002014160F),
+    Q30_fmt(0.003051758F), Q30_fmt(-0.000869751F), Q30_fmt(0.019577030F), Q30_fmt(0.027725220F),
+    Q30_fmt(0.012115480F), Q30_fmt(0.016708370F), Q30_fmt(0.137298580F), Q30_fmt(0.152069090F),
+    Q30_fmt(-0.069168090F), Q30_fmt(0.246505740F), Q30_fmt(0.890090940F), Q30_fmt(1.048156738F),
+
+    Q30_fmt(-0.000061035F), Q30_fmt(0.000106812F), Q30_fmt(0.001296997F), Q30_fmt(0.001907349F),
+    Q30_fmt(0.002883911F), Q30_fmt(-0.001266479F), Q30_fmt(0.020690920F), Q30_fmt(0.026840210F),
+    Q30_fmt(0.009231570F), Q30_fmt(0.012420650F), Q30_fmt(0.140670780F), Q30_fmt(0.151962280F),
+    Q30_fmt(-0.088775630F), Q30_fmt(0.221984860F), Q30_fmt(0.913055420F), Q30_fmt(1.031936646F),
+
+    Q30_fmt(-0.000061035F), Q30_fmt(0.000106812F), Q30_fmt(0.001388550F), Q30_fmt(0.001785278F),
+    Q30_fmt(0.002700806F), Q30_fmt(-0.001617432F), Q30_fmt(0.021789550F), Q30_fmt(0.025909420F),
+    Q30_fmt(0.006134030F), Q30_fmt(0.008316040F), Q30_fmt(0.143676760F), Q30_fmt(0.151306150F),
+    Q30_fmt(-0.109161380F), Q30_fmt(0.198059080F), Q30_fmt(0.935195920F), Q30_fmt(1.014617920F),
+
+    Q30_fmt(-0.000076294F), Q30_fmt(0.000091553F), Q30_fmt(0.001480103F), Q30_fmt(0.001693726F),
+    Q30_fmt(0.002487183F), Q30_fmt(-0.001937866F), Q30_fmt(0.022857670F), Q30_fmt(0.024932860F),
+    Q30_fmt(0.002822880F), Q30_fmt(0.004394530F), Q30_fmt(0.146255490F), Q30_fmt(0.150115970F),
+    Q30_fmt(-0.130310060F), Q30_fmt(0.174789430F), Q30_fmt(0.956481930F), Q30_fmt(0.996246338F),
+
+    Q30_fmt(0.000000000F), Q30_fmt(0.000442505F), Q30_fmt(0.001586910F), Q30_fmt(0.003250122F),
+    Q30_fmt(0.007003780F), Q30_fmt(0.023910525F), Q30_fmt(0.031082153F), Q30_fmt(0.078628545F),
+    Q30_fmt(0.148422240F), Q30_fmt(0.100311279F), Q30_fmt(0.572036740F), Q30_fmt(0.976852417F),
+    Q30_fmt(1.144989014F), Q30_fmt(-0.572036745F), Q30_fmt(-0.152206421F), Q30_fmt(0.100311279F),
+
+    Q30_fmt(-0.078628540F), Q30_fmt(-0.000686646F), Q30_fmt(0.031082153F), Q30_fmt(-0.007003785F),
+    Q30_fmt(0.002227783F), Q30_fmt(0.003250122F), Q30_fmt(-0.000442500F), Q30_fmt(-0.000076294F),
+};
+
+
+
+
+
+const uint16  huffTable_1[8] =
+{
+    0x1103,    0x0103,    0x1002,    0x1002,
+    0x0001,    0x0001,    0x0001,    0x0001
+};
+
+const uint16  huffTable_2[15] =
+{
+    0x1103,    0x0103,    0x1003,    0x0001,
+    0x0001,    0x0001,    0x0001,    0x2206,
+    0x0206,    0x1205,    0x1205,    0x2105,
+    0x2105,    0x2005,    0x2005
+};
+
+const uint16 huffTable_3[15] =
+{
+
+    0x1003,    0x1102,    0x1102,    0x0102,
+    0x0102,    0x0002,    0x0002,    0x2206,
+    0x0206,    0x1205,    0x1205,    0x2105,
+    0x2105,    0x2005,    0x2005
+};
+
+const uint16 huffTable_5[25] =
+{
+
+    0x1103,    0x0103,    0x1003,    0x0001,
+    0x0001,    0x0001,    0x0001,    0x3106,
+    0x3106,    0x1307,    0x0307,    0x3007,
+    0x2207,    0x1206,    0x1206,    0x2106,
+    0x2106,    0x0206,    0x0206,    0x2006,
+    0x2006,    0x3308,    0x2308,    0x3207,
+    0x3207
+};
+
+
+const uint16 huffTable_6[26] =
+{
+
+    0x1204,    0x2104,    0x2004,    0x0103,
+    0x0103,    0x1102,    0x1102,    0x1102,
+    0x1102,    0x1003,    0x1003,    0x0003,
+    0x0003,    0x2306,    0x3206,    0x3006,
+    0x1305,    0x1305,    0x3105,    0x3105,
+    0x2205,    0x2205,    0x0205,    0x0205,
+    0x3307,    0x0307
+};
+
+
+
+const uint16 huffTable_7[73] =
+{
+    0x0103,
+    0x1003,
+    0x0001,
+    0x0001,
+    0x0001,
+    0x0001,
+    0x1206,
+    0x2105,
+    0x2105,
+    0x0206,
+    0x2006,
+    0x1104,
+    0x1104,
+    0x1104,
+    0x1104,
+    0x3509,
+    0x4409,
+    0x2509,
+    0x5209,
+    0x1508,
+    0x1508,
+    0x5108,
+    0x5108,
+    0x0509,
+    0x3409,
+    0x5008,
+    0x5008,
+    0x4309,
+    0x3309,
+    0x2408,
+    0x2408,
+    0x4208,
+    0x4208,
+    0x1407,
+    0x1407,
+    0x1407,
+    0x1407,
+    0x4107,
+    0x4107,
+    0x4107,
+    0x4107,
+    0x4007,
+    0x4007,
+    0x4007,
+    0x4007,
+    0x0408,
+    0x0408,
+    0x2308,
+    0x2308,
+    0x3208,
+    0x3208,
+    0x0308,
+    0x0308,
+    0x1307,
+    0x1307,
+    0x1307,
+    0x1307,
+    0x3107,
+    0x3107,
+    0x3107,
+    0x3107,
+    0x3007,
+    0x3007,
+    0x3007,
+    0x3007,
+    0x2207,
+    0x2207,
+    0x2207,
+    0x2207,
+    0x550a,
+    0x450a,
+    0x540a,
+    0x530a
+};
+
+const uint16 huffTable_8[66] =
+{
+    0x1204,
+    0x2104,
+    0x1102,
+    0x1102,
+    0x1102,
+    0x1102,
+    0x0103,
+    0x0103,
+    0x1003,
+    0x1003,
+    0x0002,
+    0x0002,
+    0x0002,
+    0x0002,
+    0x2206,
+    0x0206,
+    0x2006,
+    0x2509,
+    0x5209,
+    0x0509,
+    0x1508,
+    0x1508,
+    0x5108,
+    0x5108,
+    0x3409,
+    0x4309,
+    0x5009,
+    0x3309,
+    0x2408,
+    0x2408,
+    0x4208,
+    0x4208,
+    0x1408,
+    0x1408,
+    0x4107,
+    0x4107,
+    0x4107,
+    0x4107,
+    0x0408,
+    0x0408,
+    0x4008,
+    0x4008,
+    0x2308,
+    0x2308,
+    0x3208,
+    0x3208,
+    0x1308,
+    0x1308,
+    0x3108,
+    0x3108,
+    0x0308,
+    0x0308,
+    0x3008,
+    0x3008,
+    0x550b,
+    0x540b,
+    0x450a,
+    0x450a,
+    0x5309,
+    0x5309,
+    0x5309,
+    0x5309,
+    0x350a,
+    0x350a,
+    0x440a,
+    0x440a
+
+};
+
+
+const uint16 huffTable_9[53] =
+{
+    0x1204,
+    0x2104,
+    0x2004,
+    0x1103,
+    0x1103,
+    0x0103,
+    0x0103,
+    0x1003,
+    0x1003,
+    0x0003,
+    0x0003,
+    0x1406,
+    0x4106,
+    0x2306,
+    0x3206,
+    0x1305,
+    0x1305,
+    0x3105,
+    0x3105,
+    0x0306,
+    0x3006,
+    0x2205,
+    0x2205,
+    0x0205,
+    0x0205,
+    0x4408,
+    0x2508,
+    0x5208,
+    0x1508,
+    0x5107,
+    0x5107,
+    0x3407,
+    0x3407,
+    0x4307,
+    0x4307,
+    0x5008,
+    0x0408,
+    0x2407,
+    0x2407,
+    0x4207,
+    0x4207,
+    0x3307,
+    0x3307,
+    0x4007,
+    0x4007,
+    0x5509,
+    0x4509,
+    0x3508,
+    0x3508,
+    0x5308,
+    0x5308,
+    0x5409,
+    0x0509
+
+};
+
+
+const uint16 huffTable_10[96] =
+{
+    0x0001,
+    0x1104,
+    0x0103,
+    0x0103,
+    0x1003,
+    0x1003,
+    0x1206,
+    0x2106,
+    0x0206,
+    0x2006,
+    0x1408,
+    0x4108,
+    0x4008,
+    0x2308,
+    0x3208,
+    0x0308,
+    0x1307,
+    0x1307,
+    0x3107,
+    0x3107,
+    0x3007,
+    0x3007,
+    0x2207,
+    0x2207,
+    0x1608,
+    0x1608,
+    0x6108,
+    0x6108,
+    0x6008,
+    0x6008,
+    0x0509,
+    0x5009,
+    0x2409,
+    0x4209,
+    0x3309,
+    0x0409,
+    0x2709,
+    0x2709,
+    0x7209,
+    0x7209,
+    0x640a,
+    0x070a,
+    0x7009,
+    0x7009,
+    0x6209,
+    0x6209,
+    0x450a,
+    0x350a,
+    0x0609,
+    0x0609,
+    0x530a,
+    0x440a,
+    0x1708,
+    0x1708,
+    0x1708,
+    0x1708,
+    0x7108,
+    0x7108,
+    0x7108,
+    0x7108,
+    0x3609,
+    0x3609,
+    0x2609,
+    0x2609,
+    0x250a,
+    0x520a,
+    0x1509,
+    0x1509,
+    0x5109,
+    0x5109,
+    0x340a,
+    0x430a,
+    0x770b,
+    0x670b,
+    0x760b,
+    0x570b,
+    0x750b,
+    0x660b,
+    0x470a,
+    0x470a,
+    0x740a,
+    0x740a,
+    0x560a,
+    0x560a,
+    0x650a,
+    0x650a,
+    0x370a,
+    0x370a,
+    0x730a,
+    0x730a,
+    0x460a,
+    0x460a,
+    0x550b,
+    0x540b,
+    0x630a,
+    0x630a
+};
+
+
+const uint16 huffTable_11[116] =
+{
+    0x1103,
+    0x0103,
+    0x1003,
+    0x0002,
+    0x0002,
+    0x2105,
+    0x1204,     /*  0100         */
+    0x1204,     /*  010         */
+    0x0205,     /*  01010        */
+    0x2005,     /*  01011        */
+    0x1408,     /*      10 */
+    0x4108,     /*   00      */
+    0x0408,     /*   0 0     */
+    0x4008,     /*   0 1     */
+    0x2307,     /*    0      */
+    0x2307,     /*          */
+    0x3207,     /*    1      */
+    0x3207,     /*          */
+    0x1306,     /*   010       */
+    0x1306,     /*   01       */
+    0x1306,     /*   01       */
+    0x1306,     /*   01       */
+    0x3106,     /*   011       */
+    0x3106,     /*   01      */
+    0x3106,     /*   01      */
+    0x3106,     /*   01      */
+    0x0307,     /*   1000      */
+    0x0307,     /*   100      */
+    0x3007,     /*   1       */
+    0x3007,     /*   100      */
+    0x2206,     /*   101       */
+    0x2206,     /*   10      */
+    0x2206,     /*   10      */
+    0x2206,     /*   10      */
+    0x2708,
+    0x2708,     /*  000 0     */
+    0x7208,     /*  000 10     */
+    0x7208,     /*  000 1     */
+    0x6409,     /*  000 110    */
+    0x0709,
+    0x7107,
+    0x7107,
+    0x7107,     /*  00 0      */
+    0x7107,     /*  00 0      */
+    0x1708,
+    0x1708,     /*  00 01     */
+    0x7008,
+    0x7008,
+    0x3608,
+    0x3608,     /*  00 10     */
+    0x6308,     /*  00 101     */
+    0x6308,     /*  00 10     */
+    0x6008,
+    0x6008,     /*  00 11     */
+    0x4409,
+    0x2509,
+    0x5209,     /*  0      */
+    0x0509,     /*  0 00     */
+    0x1508,     /*  0 0      */
+    0x1508,     /*  0 000     */
+    0x6207,     /*  0        */
+    0x6207,     /*  0 00     */
+    0x6207,     /*  0 00     */
+    0x6207,     /*  0 00     */
+    0x2608,
+    0x2608,     /*  0 010     */
+    0x0608,
+    0x0608,
+    0x1607,
+    0x1607,
+    0x1607,
+    0x1607,
+    0x6107,
+    0x6107,
+    0x6107,
+    0x6107,
+    0x5108,
+    0x5108,
+    0x3408,
+    0x3408,
+    0x5008,
+    0x5008,
+    0x4309,
+    0x3309,
+    0x2408,
+    0x2408,     /*  0 111     */
+    0x4208,     /*  0 1111     */
+    0x4208,     /*  0 111     */
+    0x560a,
+    0x650a,
+    0x3709,
+    0x3709,
+    0x7309,
+    0x7309,
+    0x4609,
+    0x4609,
+    0x450a,
+    0x540a,     /*  000 0    */
+    0x350a,     /*  000  0   */
+    0x530a,     /*  000  1   */
+    0x770a,
+    0x770a,
+    0x670a,
+    0x670a,
+    0x760a,     /*    0   */
+    0x760a,     /*       */
+    0x750a,     /*    1   */
+    0x750a,     /*       */
+    0x660a,     /*    00   */
+    0x660a,     /*    0   */
+    0x470a,     /*    01   */
+    0x470a,     /*    0   */
+    0x740a,     /*    10   */
+    0x740a,     /*    1   */
+    0x570b,     /*    110  */
+    0x550b  /*    111  */
+
+};
+
+const uint16 huffTable_12[134] =
+{
+
+    0x1103,     /*  101          */
+    0x0103,     /*  110          */
+    0x1003,     /*  111          */
+    0x1204,
+    0x1204,     /*  011         */
+    0x2104,     /*  0111         */
+    0x2104,     /*  011         */
+    0x0205,     /*  10000        */
+    0x2005,     /*  10         */
+    0x0004,     /*  1          */
+    0x0004,     /*  100         */
+    0x3006,
+    0x1305,     /*  01         */
+    0x1305,     /*  0100        */
+    0x3105,
+    0x3105,
+    0x2205,
+    0x2205,     /*  0101        */
+    0x1507,
+    0x1507,     /*   000      */
+    0x5107,     /*   0       */
+    0x5107,     /*   000      */
+    0x3407,     /*    0      */
+    0x3407,     /*          */
+    0x4307,     /*    1      */
+    0x4307,     /*          */
+    0x5008,
+    0x0408,
+    0x2407,
+    0x2407,     /*   010      */
+    0x4207,
+    0x4207,
+    0x1407,     /*   0111      */
+    0x1407,     /*   011      */
+    0x3306,
+    0x3306,
+    0x3306,
+    0x3306,
+    0x4106,
+    0x4106,
+    0x4106,
+    0x4106,
+    0x2306,
+    0x2306,
+    0x2306,
+    0x2306,
+    0x3206,
+    0x3206,
+    0x3206,
+    0x3206,
+    0x4007,
+    0x4007,
+    0x0307,
+    0x0307,     /*  010000      */
+    0x7208,
+    0x7208,     /*  00 00     */
+    0x4608,     /*  00       */
+    0x4608,     /*  00 00     */
+    0x6408,
+    0x6408,     /*  00 01     */
+    0x1708,     /*  00 011     */
+    0x1708,
+    0x7108,     /*  00 100     */
+    0x7108,
+    0x0709,
+    0x7009,
+    0x3608,
+    0x3608,     /*  00 11     */
+    0x6308,
+    0x6308,
+    0x4508,
+    0x4508,
+    0x5408,     /*  0 0      */
+    0x5408,     /*  0 000     */
+    0x4408,     /*  0  0     */
+    0x4408,     /*  0       */
+    0x0609,     /*  0  10    */
+    0x0509,     /*  0  11    */
+    0x2607,
+    0x2607,
+    0x2607,
+    0x2607,
+    0x6207,
+    0x6207,
+    0x6207,
+    0x6207,
+    0x6107,
+    0x6107,
+    0x6107,
+    0x6107,
+    0x1608,     /*  0 1010     */
+    0x1608,     /*  0 101     */
+    0x6008,     /*  0 1011     */
+    0x6008,     /*  0 101     */
+    0x3508,
+    0x3508,     /*  0 110     */
+    0x5308,     /*  0 1101     */
+    0x5308,     /*  0 110     */
+    0x2508,
+    0x2508,     /*  0 111     */
+    0x5208,     /*  0 1111     */
+    0x5208,     /*  0 111     */
+    0x770a,
+    0x670a,
+    0x7609,     /*        */
+    0x7609,
+    0x5709,     /*    0    */
+    0x5709,     /*        */
+    0x7509,     /*    1    */
+    0x7509,     /*        */
+    0x6609,
+    0x6609,
+    0x4709,     /*  0000 01    */
+    0x4709,     /*  0000 0    */
+    0x7409,
+    0x7409,     /*  0000 1    */
+    0x6509,
+    0x6509,     /*  0000 1    */
+    0x5608,
+    0x5608,
+    0x5608,
+    0x5608,
+    0x3708,
+    0x3708,
+    0x3708,
+    0x3708,
+    0x7309,     /*  000 100    */
+    0x7309,     /*  000 10    */
+    0x5509,
+    0x5509,     /*  000 10    */
+    0x2708,
+    0x2708,
+    0x2708,
+    0x2708,
+};
+
+
+
+const uint16 huffTable_13[491] =
+{
+    0x0001,
+    0x1104,
+    0x0104,
+    0x1003,
+    0x1003,
+    0x4107,
+    0x4107,
+    0x0408,
+    0x4008,
+    0x2308,
+    0x3208,
+    0x1307,
+    0x1307,
+    0x3107,
+    0x3107,
+    0x0307,
+    0x0307,
+    0x3007,
+    0x3007,
+    0x2207,
+    0x2207,
+    0x1206,
+    0x1206,
+    0x1206,
+    0x1206,
+    0x2106,
+    0x2106,
+    0x2106,
+    0x2106,
+    0x0206,
+    0x0206,
+    0x0206,
+    0x0206,
+    0x2006,
+    0x2006,
+    0x2006,
+    0x2006,
+    0x370a,
+    0x270a,     /*  0 000           */
+    0x1709,     /*  0 00            */
+    0x1709,
+    0x7109,
+    0x7109,     /*  0 0            */
+    0x550a,
+    0x070a,     /*  0 0 11          */
+    0x700a,
+    0x360a,     /*  0             */
+    0x630a,
+    0x450a,     /*  0  011          */
+    0x540a,
+    0x260a,     /*  0  101          */
+    0x620a,
+    0x350a,     /*  0  111          */
+    0x8108,
+    0x8108,     /*  0 010            */
+    0x8108,
+    0x8108,     /*  0 010            */
+    0x0809,
+    0x0809,     /*  0 0101           */
+    0x8009,
+    0x8009,     /*  0 0101           */
+    0x1609,
+    0x1609,     /*  0 0110           */
+    0x6109,
+    0x6109,     /*  0 0110           */
+    0x0609,
+    0x0609,     /*  0 0111           */
+    0x6009,
+    0x6009,     /*  0 0111           */
+    0x530a,
+    0x440a,     /*  0 100           */
+    0x2509,
+    0x2509,     /*  0 1000           */
+    0x5209,
+    0x5209,     /*  0 1            */
+    0x0509,
+    0x0509,     /*  0 1            */
+    0x1508,
+    0x1508,     /*  0 101            */
+    0x1508,
+    0x1508,     /*  0 101            */
+    0x5108,
+    0x5108,     /*  0 101           */
+    0x5108,
+    0x5108,     /*  0 101           */
+    0x3409,
+    0x3409,     /*  0 1100           */
+    0x4309,
+    0x4309,     /*  0 1100           */
+    0x5009,
+    0x5009,     /*  0 1101           */
+    0x2409,
+    0x2409,     /*  0 1101           */
+    0x4209,
+    0x4209,     /*  0 1110           */
+    0x3309,
+    0x3309,     /*  0 1110           */
+    0x1408,
+    0x1408,     /*  0 111           */
+    0x1408,
+    0x1408,     /*  0 111           */
+    0x1a0a,
+    0x1a0a,
+    0xa10a,     /*  00 00           */
+    0xa10a,
+    0x0a0b,
+    0x680b,
+    0xa00a,
+    0xa00a,
+    0x860b,
+    0x490b,
+    0x930a,
+    0x930a,
+    0x390b,
+    0x580b,
+    0x850b,
+    0x670b,
+    0x290a,
+    0x290a,
+    0x920a,
+    0x920a,
+    0x570b,
+    0x750b,
+    0x380a,
+    0x380a,
+    0x830a,
+    0x830a,
+    0x660b,
+    0x470b,
+    0x740b,
+    0x560b,
+    0x650b,
+    0x730b,
+    0x1909,
+    0x1909,
+    0x1909,
+    0x1909,
+    0x9109,
+    0x9109,
+    0x9109,
+    0x9109,
+    0x090a,     /*  00 10100          */
+    0x090a,
+    0x900a,     /*  00 10101          */
+    0x900a,
+    0x480a,     /*  00 10110          */
+    0x480a,
+    0x840a,     /*  00 10111          */
+    0x840a,
+    0x720a,     /*  00 11000          */
+    0x720a,
+    0x460b,     /*  00 11 0         */
+    0x640b,
+    0x2809,
+    0x2809,
+    0x2809,
+    0x2809,
+    0x8209,
+    0x8209,
+    0x8209,
+    0x8209,
+    0x1809,
+    0x1809,
+    0x1809,
+    0x1809,
+    0xc10b,
+    0xc10b,     /*  000 0000         */
+    0x980c,
+    0x0c0c,     /*  000 00 1        */
+    0xc00b,
+    0xc00b,     /*  000 0          */
+    0xb40c,
+    0x6a0c,     /*  000 0 11        */
+    0xa60c,
+    0x790c,     /*  000           */
+    0x3b0b,
+    0x3b0b,     /*  000  0         */
+    0xb30b,
+    0xb30b,     /*  000  1         */
+    0x880c,
+    0x5a0c,     /*  000  111        */
+    0x2b0b,
+    0x2b0b,     /*  000 0100         */
+    0xa50c,
+    0x690c,     /*  000 01 1        */
+    0xa40b,
+    0xa40b,     /*  000 0101         */
+    0x780c,
+    0x870c,
+    0x940b,
+    0x940b,     /*  000 0110         */
+    0x770c,
+    0x760c,     /*  000 011011        */
+    0xb20a,
+    0xb20a,     /*  000 011         */
+    0xb20a,
+    0xb20a,     /*  000 011         */
+    0x1b0a,
+    0x1b0a,     /*  000 100          */
+    0x1b0a,
+    0x1b0a,     /*  000 100          */
+    0xb10a,
+    0xb10a,
+    0xb10a,     /*  000 100         */
+    0xb10a,     /*  000 100         */
+    0x0b0b,     /*  000 10100         */
+    0x0b0b,     /*  000 1010         */
+    0xb00b,
+    0xb00b,     /*  000 1010         */
+    0x960b,     /*  000 10110         */
+    0x960b,     /*  000 1011         */
+    0x4a0b,
+    0x4a0b,     /*  000 1011         */
+    0x3a0b,     /*  000 11000         */
+    0x3a0b,     /*  000 1100         */
+    0xa30b,     /*  000 11          */
+    0xa30b,     /*  000 1100         */
+    0x590b,
+    0x590b,     /*  000 1101         */
+    0x950b,     /*  000 11011         */
+    0x950b,     /*  000 1101         */
+    0x2a0a,
+    0x2a0a,
+    0x2a0a,
+    0x2a0a,
+    0xa20a,
+    0xa20a,
+    0xa20a,
+    0xa20a,
+    0xf00c,
+    0xf00c,     /*    000        */
+    0xba0d,
+    0xe50d,     /*    0 1       */
+    0xe40d,
+    0x8c0d,     /*     01       */
+    0x6d0d,
+    0xe30d,     /*     11       */
+    0xe20c,     /*    0100        */
+    0xe20c,
+    0x2e0d,     /*    01010       */
+    0x0e0d,
+    0x1e0c,     /*    0110        */
+    0x1e0c,
+    0xe10c,     /*    0111        */
+    0xe10c,
+    0xe00d,     /*    10000       */
+    0x5d0d,
+    0xd50d,     /*    1 0       */
+    0x7c0d,
+    0xc70d,
+    0x4d0d,
+    0x8b0d,
+    0xb80d,
+    0xd40d,
+    0x9a0d,
+    0xa90d,
+    0x6c0d,
+    0xc60c,
+    0xc60c,
+    0x3d0c,
+    0x3d0c,     /*    111        */
+    0xd30d,     /*  0000         */
+    0x7b0d,
+    0x2d0c,
+    0x2d0c,
+    0xd20c,
+    0xd20c,
+    0x1d0c,
+    0x1d0c,
+    0xb70c,
+    0xb70c,     /*  0000  0        */
+    0x5c0d,
+    0xc50d,     /*  0000  011       */
+    0x990d,
+    0x7a0d,
+    0xc30c,
+    0xc30c,     /*  0000  1        */
+    0xa70d,
+    0x970d,
+    0x4b0c,
+    0x4b0c,
+    0xd10b,
+    0xd10b,
+    0xd10b,     /*  0000 010        */
+    0xd10b,
+    0x0d0c,
+    0x0d0c,
+    0xd00c,
+    0xd00c,
+    0x8a0c,
+    0x8a0c,
+    0xa80c,
+    0xa80c,
+    0x4c0c,
+    0x4c0c,
+    0xc40c,
+    0xc40c,
+    0x6b0c,
+    0x6b0c,     /*  0000 1         */
+    0xb60c,     /*  0000 1 1        */
+    0xb60c,     /*  0000 1         */
+    0x3c0b,
+    0x3c0b,
+    0x3c0b,
+    0x3c0b,
+    0x2c0b,     /*  0000 1011         */
+    0x2c0b,     /*  0000 101        */
+    0x2c0b,     /*  0000 101        */
+    0x2c0b,     /*  0000 101        */
+    0xc20b,
+    0xc20b,
+    0xc20b,
+    0xc20b,
+    0x5b0b,     /*  0000 1101         */
+    0x5b0b,
+    0x5b0b,     /*  0000 110        */
+    0x5b0b,     /*  0000 110        */
+    0xb50c,
+    0xb50c,
+    0x890c,
+    0x890c,     /*  0000 1110        */
+    0x1c0b,
+    0x1c0b,
+    0x1c0b,
+    0x1c0b,
+    0x2f0d,
+    0x2f0d,     /*    000       */
+    0xf20d,     /*    0        */
+    0xf20d,     /*    000       */
+    0x6e0e,     /*     00      */
+    0x9c0e,     /*     01      */
+    0x0f0d,     /*     1       */
+    0x0f0d,     /*            */
+    0xc90e,
+    0x5e0e,     /*    01       */
+    0xab0d,     /*    0101       */
+    0xab0d,
+    0x7d0e,     /*    01100      */
+    0xd70e,
+    0x4e0d,     /*    0111       */
+    0x4e0d,
+    0xc80e,
+    0xd60e,     /*    10       */
+    0x3e0d,
+    0x3e0d,     /*    100       */
+    0xb90d,
+    0xb90d,     /*    101       */
+    0x9b0e,
+    0xaa0e,     /*    10111      */
+    0x1f0c,
+    0x1f0c,     /*    11        */
+    0x1f0c,     /*    11        */
+    0x1f0c,
+    0xf10c,     /*    111        */
+    0xf10c,     /*    11       */
+    0xf10c,     /*    11       */
+    0xf10c,     /*    11       */
+    0xe80e,
+    0xe80e,
+    0x5f0e,
+    0x5f0e,
+    0x9d0e,
+    0x9d0e,
+    0xd90e,
+    0xd90e,     /*  0000000        */
+    0xf50e,
+    0xf50e,
+    0xe70e,
+    0xe70e,
+    0xac0e,
+    0xac0e,
+    0xbb0e,
+    0xbb0e,
+    0x4f0e,
+    0x4f0e,
+    0xf40e,     /*  0000000 1       */
+    0xf40e,
+    0xca0f,
+    0xe60f,
+    0xf30e,
+    0xf30e,     /*  0000000 101      */
+    0x3f0d,
+    0x3f0d,     /*  0000000 11       */
+    0x3f0d,
+    0x3f0d,     /*  0000000 11       */
+    0x8d0e,
+    0x8d0e,
+    0xd80e,     /*  0000000 1111      */
+    0xd80e,
+    0x8f0f,
+    0x8f0f,     /*  00000000 000     */
+    0xf80f,     /*  00000000 0      */
+    0xf80f,
+    0xcc0f,     /*  00000000  0     */
+    0xcc0f,
+    0xae10,
+    0x9e10,     /*  00000000  11    */
+    0x8e0f,
+    0x8e0f,
+    0x7f10,
+    0x7e10,
+    0xf70e,     /*  00000000 011      */
+    0xf70e,
+    0xf70e,
+    0xf70e,     /*  00000000 01     */
+    0xda0e,
+    0xda0e,     /*  00000000 10      */
+    0xda0e,
+    0xda0e,     /*  00000000 10      */
+    0xad0f,
+    0xad0f,     /*  00000000 101     */
+    0xbc0f,
+    0xbc0f,     /*  00000000 101     */
+    0xcb0f,
+    0xcb0f,     /*  00000000 110     */
+    0xf60f,
+    0xf60f,     /*  00000000 110     */
+    0x6f0e,
+    0x6f0e,     /*  00000000 11     */
+    0x6f0e,     /*  00000000 11     */
+    0x6f0e,     /*  00000000 11     */
+    0xff10,
+    0xff10,
+    0xef10,
+    0xef10,     /*  000000000000     */
+    0xdf10,     /*  000000000000 1    */
+    0xdf10,     /*  000000000000     */
+    0xee10,     /*  00000000000 00    */
+    0xee10,     /*  00000000000 0    */
+    0xcf10,     /*  00000000000 01    */
+    0xcf10,
+    0xde10,     /*  00000000000 10    */
+    0xde10,
+    0xbf10,     /*  00000000000 11    */
+    0xbf10,     /*  00000000000 1    */
+    0xfb10,
+    0xfb10,
+    0xce10,
+    0xce10,     /*  0000000000 00    */
+    0xdc10,     /*  0000000000 010    */
+    0xdc10,
+    0xaf11,
+    0xe911,
+    0xec0f,     /*  0000000000 10     */
+    0xec0f,     /*  0000000000 1     */
+    0xec0f,     /*  0000000000 1     */
+    0xec0f,     /*  0000000000 1     */
+    0xdd0f,     /*  0000000000 11     */
+    0xdd0f,     /*  0000000000 1    */
+    0xdd0f,     /*  0000000000 1    */
+    0xdd0f,     /*  0000000000 1    */
+    0xfa10,     /*  000000000 0000    */
+    0xfa10,     /*  000000000 000    */
+    0xcd10,     /*  000000000 0     */
+    0xcd10,     /*  000000000 000    */
+    0xbe0f,     /*  000000000       */
+    0xbe0f,
+    0xbe0f,
+    0xbe0f,
+    0xeb0f,
+    0xeb0f,
+    0xeb0f,
+    0xeb0f,     /*  000000000 01     */
+    0x9f0f,     /*  000000000 011     */
+    0x9f0f,     /*  000000000 01    */
+    0x9f0f,
+    0x9f0f,
+    0xf90f,     /*  000000000 100     */
+    0xf90f,     /*  000000000 10     */
+    0xf90f,     /*  000000000 10     */
+    0xf90f,     /*  000000000 10     */
+    0xea0f,     /*  000000000 101     */
+    0xea0f,     /*  000000000 10    */
+    0xea0f,     /*  000000000 10    */
+    0xea0f,     /*  000000000 10    */
+    0xbd0f,     /*  000000000 110     */
+    0xbd0f,     /*  000000000 11     */
+    0xbd0f,     /*  000000000 11     */
+    0xbd0f,     /*  000000000 11     */
+    0xdb0f,     /*  000000000 111     */
+    0xdb0f,     /*  000000000 11    */
+    0xdb0f,     /*  000000000 11    */
+    0xdb0f,     /*  000000000 11    */
+    0xfe13,
+    0xfc13,
+    0xfd12,
+    0xfd12,
+    0xed11,
+    0xed11,
+    0xed11,
+    0xed11
+
+};
+
+
+
+const uint16 huffTable_15[421] =
+{
+    0x1103,
+    0x1103,
+    0x0104,
+    0x1004,
+    0x0003,     /*  111                 */
+    0x0003, /*  11                 */
+    0x3407,
+    0x4307,
+    0x2407,     /*  0101              */
+    0x4207,     /*  0101010             */
+    0x3307,
+    0x4106,     /*  010110              */
+    0x4106,
+    0x1407,     /*  0101110             */
+    0x0407,
+    0x2306,     /*  011000              */
+    0x2306,
+    0x3206,     /*  011               */
+    0x3206,
+    0x4007,
+    0x0307,
+    0x1306,     /*  011011              */
+    0x1306,     /*  01101              */
+    0x3106,     /*  011100              */
+    0x3106,     /*  01110              */
+    0x3006,     /*  011101              */
+    0x3006,     /*  01110              */
+    0x2205,     /*  01111               */
+    0x2205,     /*  0111              */
+    0x2205,     /*  0111              */
+    0x2205,     /*  0111              */
+    0x1205,     /*  10000               */
+    0x1205,     /*  1000               */
+    0x1205,     /*  1000               */
+    0x1205,     /*  1000               */
+    0x2105,     /*  10                */
+    0x2105,     /*  1000              */
+    0x2105,     /*  1000              */
+    0x2105,     /*  1000              */
+    0x0205,
+    0x0205,     /*  1                */
+    0x0205,     /*  1                */
+    0x0205,     /*  1                */
+    0x2005,     /*  1 1               */
+    0x2005,     /*  1               */
+    0x2005,     /*  1               */
+    0x2005,     /*  1               */
+    0x5809,
+    0x8509,
+    0x2909,     /*               */
+    0x6709,     /*   000            */
+    0x7609,     /*   00 0           */
+    0x9209,     /*   00 1           */
+    0x9108,     /*   0 0            */
+    0x9108,     /*   0             */
+    0x1909,     /*   0 10           */
+    0x9009,     /*   0 11           */
+    0x4809,     /*    000           */
+    0x8409,     /*                */
+    0x5709,     /*    010           */
+    0x7509,     /*    011           */
+    0x3809,     /*    100           */
+    0x8309,     /*    101           */
+    0x6609,     /*    110           */
+    0x4709,     /*    111           */
+    0x2808,
+    0x2808,     /*   0100            */
+    0x8208,     /*   01             */
+    0x8208,     /*   0100            */
+    0x1808,     /*   01010            */
+    0x1808,     /*   0101            */
+    0x8108,     /*   01011            */
+    0x8108,     /*   0101            */
+    0x7409,
+    0x0809,     /*   011            */
+    0x8009,     /*   011010           */
+    0x5609,
+    0x6509,     /*   011100           */
+    0x3709,
+    0x7309,     /*   011110           */
+    0x4609,
+    0x2708,     /*   10000            */
+    0x2708,     /*   1000            */
+    0x7208,     /*   10             */
+    0x7208,     /*   1000            */
+    0x6408,     /*   1 0            */
+    0x6408,     /*   1             */
+    0x1708,     /*   1 1            */
+    0x1708,     /*   1             */
+    0x5508,     /*   10100            */
+    0x5508,
+    0x7108,     /*   10101            */
+    0x7108,
+    0x0709,     /*   101100           */
+    0x7009,     /*   101101           */
+    0x3608,     /*   10111            */
+    0x3608,     /*   1011            */
+    0x6308,     /*   11000            */
+    0x6308,     /*   1100            */
+    0x4508,     /*   11             */
+    0x4508,     /*   1100            */
+    0x5408,     /*   11010            */
+    0x5408,     /*   1101            */
+    0x2608,     /*   11011            */
+    0x2608,     /*   1101            */
+    0x6208,     /*   11100            */
+    0x6208,     /*   1110            */
+    0x1608,     /*   11101            */
+    0x1608,     /*   1110            */
+    0x0609,     /*   111100           */
+    0x6009,     /*   111101           */
+    0x3508,     /*   11111            */
+    0x3508,     /*   1111            */
+    0x6107,
+    0x6107,
+    0x6107,
+    0x6107,
+    0x5308,     /*  0100 0            */
+    0x5308,     /*  0100             */
+    0x4408,     /*  0100 1            */
+    0x4408,     /*  0100             */
+    0x2507,     /*  010 0             */
+    0x2507,     /*  010              */
+    0x2507,     /*  010              */
+    0x2507,     /*  010              */
+    0x5207,     /*  010 1             */
+    0x5207,     /*  010             */
+    0x5207,     /*  010             */
+    0x5207,     /*  010             */
+    0x1507,     /*  01 00             */
+    0x1507,     /*  01 0             */
+    0x1507,     /*  01 0             */
+    0x1507,     /*  01 0             */
+    0x5107,     /*  01 01             */
+    0x5107,     /*  01 0            */
+    0x5107,     /*  01 0            */
+    0x5107,     /*  01 0            */
+    0x0508,     /*  01 100            */
+    0x0508,     /*  01 10            */
+    0x5008,     /*  01 101            */
+    0x5008,     /*  01 10            */
+    0xc209,
+    0xc209,
+    0x2c0a,     /*  00 11110          */
+    0x5b0a,
+    0xb50a,     /*  0            */
+    0x1c0a,     /*  0 000           */
+    0x890a,     /*  0 00 0          */
+    0x980a,
+    0xc10a,     /*  0 0 00          */
+    0x4b0a,     /*  0 0 01          */
+    0xb40a,     /*  0 0 10          */
+    0x6a0a,     /*  0 0 11          */
+    0x3b0a,     /*  0  000          */
+    0x790a,     /*  0             */
+    0xb309,     /*  0  01           */
+    0xb309,     /*  0  0           */
+    0x970a,     /*  0  100          */
+    0x880a,     /*  0  101          */
+    0x2b0a,     /*  0  110          */
+    0x5a0a,     /*  0  111          */
+    0xb209,     /*  0 01000           */
+    0xb209,     /*  0 0100           */
+    0xa50a,     /*  0 01 0          */
+    0x1b0a,     /*  0 01 1          */
+    0xb109,     /*  0 01010           */
+    0xb109,     /*  0 0101           */
+    0xb00a,     /*  0 010110          */
+    0x690a,     /*  0 010111          */
+    0x960a,     /*  0 011000          */
+    0x4a0a,     /*  0 011           */
+    0xa40a,     /*  0 011010          */
+    0x780a,     /*  0 011011          */
+    0x870a,     /*  0 011100          */
+    0x3a0a,     /*  0 011101          */
+    0xa309,     /*  0 01111           */
+    0xa309,     /*  0 0111           */
+    0x5909,     /*  0 10000           */
+    0x5909,     /*  0 1000           */
+    0x9509,     /*  0 10            */
+    0x9509,     /*  0 1000           */
+    0x2a09,     /*  0 1 0           */
+    0x2a09,     /*  0 1            */
+    0xa209,     /*  0 1 1           */
+    0xa209,     /*  0 1            */
+    0x1a09,     /*  0 10100           */
+    0x1a09,     /*  0 1010           */
+    0xa109,     /*  0 10101           */
+    0xa109,     /*  0 1010           */
+    0x0a0a,     /*  0 101100          */
+    0xa00a,     /*  0 101101          */
+    0x6809,     /*  0 10111           */
+    0x6809,     /*  0 1011           */
+    0x8609,     /*  0 11000           */
+    0x8609,     /*  0 1100           */
+    0x4909,     /*  0 11            */
+    0x4909,     /*  0 1100           */
+    0x9409,     /*  0 11010           */
+    0x9409,     /*  0 1101           */
+    0x3909,     /*  0 11011           */
+    0x3909,     /*  0 1101           */
+    0x9309,     /*  0 11100           */
+    0x9309,     /*  0 1110           */
+    0x770a,     /*  0 111010          */
+    0x090a,     /*  0 111011          */
+    0x7c0b,
+    0xc70b,     /*  00 000          */
+    0x4d0b,     /*  00 00 0         */
+    0x8b0b,     /*  00 00 1         */
+    0xd40a,     /*  00 0 0          */
+    0xd40a,     /*  00 0           */
+    0xb80b,     /*  00 0 10         */
+    0x9a0b,     /*  00 0 11         */
+    0xa90b,     /*  00  000         */
+    0x6c0b,     /*  00            */
+    0xc60b,     /*  00  010         */
+    0x3d0b,     /*  00  011         */
+    0xd30a,     /*  00  10          */
+    0xd30a,     /*  00  1          */
+    0xd20a,     /*  00  11          */
+    0xd20a,     /*  00  1          */
+    0x2d0b,     /*  00 010000         */
+    0x0d0b,     /*  00 010          */
+    0x1d0a,     /*  00 01           */
+    0x1d0a,     /*  00 0100          */
+    0x7b0a,     /*  00 01010          */
+    0x7b0a,     /*  00 0101          */
+    0xb70a,     /*  00 01011          */
+    0xb70a,     /*  00 0101          */
+    0xd10a,     /*  00 01100          */
+    0xd10a,     /*  00 0110          */
+    0x5c0b,     /*  00 011010         */
+    0xd00b,     /*  00 011011         */
+    0xc50a,     /*  00 01110          */
+    0xc50a,     /*  00 0111          */
+    0x8a0a,     /*  00 01111          */
+    0x8a0a,     /*  00 0111          */
+    0xa80a,     /*  00 10000          */
+    0xa80a,     /*  00 1000          */
+    0x4c0a,     /*  00 10           */
+    0x4c0a,     /*  00 1000          */
+    0xc40a,     /*  00 1 0          */
+    0xc40a,     /*  00 1           */
+    0x6b0a,     /*  00 1 1          */
+    0x6b0a,     /*  00 1           */
+    0xb60a,     /*  00 10100          */
+    0xb60a,     /*  00 1010          */
+    0x990b,     /*  00 101010         */
+    0x0c0b,     /*  00 101011         */
+    0x3c0a,     /*  00 10110          */
+    0x3c0a,     /*  00 1011          */
+    0xc30a,     /*  00 10111          */
+    0xc30a,     /*  00 1011          */
+    0x7a0a,     /*  00 11000          */
+    0x7a0a,     /*  00 1100          */
+    0xa70a,     /*  00 11           */
+    0xa70a,     /*  00 1100          */
+    0xa60a,     /*  00 11010          */
+    0xa60a,     /*  00 1101          */
+    0xc00b,     /*  00 110110         */
+    0x0b0b,     /*  00 110111         */
+    0xcb0b,
+    0xcb0b,     /*  0000 000         */
+    0xf60b,     /*  0000 0          */
+    0xf60b,     /*  0000 000         */
+    0x8e0c,     /*  0000  00        */
+    0xe80c,     /*  0000  01        */
+    0x5f0c,     /*  0000  10        */
+    0x9d0c,     /*  0000  11        */
+    0xf50b,     /*  0000 0100         */
+    0xf50b,     /*  0000 010         */
+    0x7e0b,     /*  0000 0101         */
+    0x7e0b,     /*  0000 010         */
+    0xe70b,     /*  0000 0110         */
+    0xe70b,     /*  0000 011         */
+    0xac0b,     /*  0000 0111         */
+    0xac0b,     /*  0000 011         */
+    0xca0b,     /*  0000 1000         */
+    0xca0b,     /*  0000 100         */
+    0xbb0b,     /*  0000 1          */
+    0xbb0b,     /*  0000 100         */
+    0xd90c,     /*  0000 10100        */
+    0x8d0c,     /*  0000 10101        */
+    0x4f0b,     /*  0000 1011         */
+    0x4f0b,     /*  0000 101         */
+    0xf40b,     /*  0000 1100         */
+    0xf40b,     /*  0000 110         */
+    0x3f0b,     /*  0000 1101         */
+    0x3f0b,     /*  0000 110         */
+    0xf30b,     /*  0000 1110         */
+    0xf30b,     /*  0000 111         */
+    0xd80b,     /*  0000 1111         */
+    0xd80b,     /*  0000 111         */
+    0xe60b,     /*  000           */
+    0xe60b,     /*  000 0000         */
+    0x2f0b,     /*  000 00          */
+    0x2f0b,     /*  000 0000         */
+    0xf20b,     /*  000 0 0         */
+    0xf20b,     /*  000 0          */
+    0x6e0c,     /*  000 0 10        */
+    0xf00c,     /*  000 0 11        */
+    0x1f0b,     /*  000  00         */
+    0x1f0b,     /*  000  0         */
+    0xf10b,     /*  000  01         */
+    0xf10b,     /*  000  0         */
+    0x9c0b,     /*  000  10         */
+    0x9c0b,     /*  000  1         */
+    0xc90b,     /*  000  11         */
+    0xc90b,     /*  000  1         */
+    0x5e0b,     /*  000 01000         */
+    0x5e0b,     /*  000 0100         */
+    0xab0b,     /*  000 01          */
+    0xab0b,     /*  000 0100         */
+    0xba0b,     /*  000 01010         */
+    0xba0b,     /*  000 0101         */
+    0xe50b,     /*  000 01011         */
+    0xe50b,     /*  000 0101         */
+    0x7d0b,     /*  000 01100         */
+    0x7d0b,     /*  000 0110         */
+    0xd70b,     /*  000 01101         */
+    0xd70b,
+    0x4e0b,     /*  000 01110         */
+    0x4e0b,
+    0xe40b,     /*  000 01111         */
+    0xe40b,     /*  000 0111         */
+    0x8c0b,
+    0x8c0b,     /*  000 1000         */
+    0xc80b,     /*  000 10          */
+    0xc80b,
+    0x3e0b,     /*  000 1 0         */
+    0x3e0b,     /*  000 1          */
+    0x6d0b,
+    0x6d0b,     /*  000 1          */
+    0xd60b,     /*  000 10100         */
+    0xd60b,     /*  000 1010         */
+    0xe30b,
+    0xe30b,     /*  000 1010         */
+    0x9b0b,     /*  000 10110         */
+    0x9b0b,     /*  000 1011         */
+    0xb90b,
+    0xb90b,     /*  000 1011         */
+    0x2e0b,     /*  000 11000         */
+    0x2e0b,     /*  000 1100         */
+    0xaa0b,
+    0xaa0b,     /*  000 1100         */
+    0xe20b,
+    0xe20b,     /*  000 1101         */
+    0x1e0b,
+    0x1e0b,     /*  000 1101         */
+    0xe10b,
+    0xe10b,     /*  000 1110         */
+    0x0e0c,
+    0xe00c,     /*  000 111011        */
+    0x5d0b,
+    0x5d0b,     /*  000 1111         */
+    0xd50b,
+    0xd50b,     /*  000 1111         */
+    0xff0d,
+    0xef0d,
+    0xfe0d,
+    0xdf0d,
+    0xee0c,
+    0xee0c,
+    0xfd0d,
+    0xcf0d,
+    0xfc0d,
+    0xde0d,
+    0xed0d,
+    0xbf0d,
+    0xfb0c,
+    0xfb0c,
+    0xce0d,
+    0xec0d,
+    0xdd0c,     /*    000        */
+    0xdd0c,     /*    00        */
+    0xaf0c,     /*             */
+    0xaf0c,     /*    00        */
+    0xfa0c,     /*    010        */
+    0xfa0c,     /*    01        */
+    0xbe0c,     /*    011        */
+    0xbe0c,     /*    01        */
+    0xeb0c,     /*    100        */
+    0xeb0c,     /*    10        */
+    0xcd0c,     /*    101        */
+    0xcd0c,     /*    10        */
+    0xdc0c,     /*    110        */
+    0xdc0c,     /*    11        */
+    0x9f0c,     /*    111        */
+    0x9f0c,     /*    11        */
+    0xf90c,     /*    0000        */
+    0xf90c,     /*    000        */
+    0xea0c,     /*    0         */
+    0xea0c,     /*    000        */
+    0xbd0c,     /*     0        */
+    0xbd0c,     /*             */
+    0xdb0c,     /*     1        */
+    0xdb0c,     /*             */
+    0x8f0c,     /*    0100        */
+    0x8f0c,     /*    010        */
+    0xf80c,     /*    0101        */
+    0xf80c,     /*    010        */
+    0xcc0c,
+    0xcc0c,     /*    011        */
+    0x9e0c,     /*    0111        */
+    0x9e0c,     /*    011        */
+    0xe90c,     /*    1000        */
+    0xe90c,     /*    100        */
+    0x7f0c,     /*    1         */
+    0x7f0c,
+    0xf70c,     /*    1010        */
+    0xf70c,     /*    101        */
+    0xad0c,     /*    1011        */
+    0xad0c,     /*    101        */
+    0xda0c,     /*    1100        */
+    0xda0c,     /*    110        */
+    0xbc0c,
+    0xbc0c,     /*    110        */
+    0x6f0c,     /*    1110        */
+    0x6f0c,     /*    111        */
+    0xae0d,     /*    11110       */
+    0x0f0d
+};
+
+const uint16 huffTable_16[465] =
+{
+    0x0001,
+    0x1104,
+    0x0104,
+    0x1003,
+    0x1003,
+    0x2308,
+    0x3208,     /*    11            */
+    0x1307,     /*   0100             */
+    0x1307,     /*   010             */
+    0x3107,
+    0x3107,
+    0x0308,
+    0x3008,
+    0x2207,     /*   0111             */
+    0x2207,     /*   011             */
+    0x1206,     /*   100              */
+    0x1206,     /*   10              */
+    0x1206,     /*   10              */
+    0x1206,     /*   10              */
+    0x2106,     /*   101              */
+    0x2106,     /*   10             */
+    0x2106,     /*   10             */
+    0x2106,     /*   10             */
+    0x0206,
+    0x0206,
+    0x0206,
+    0x0206,
+    0x2006,
+    0x2006,
+    0x2006,
+    0x2006,
+    0x1709,
+    0x1709,     /*  0 0111           */
+    0x7109,     /*  0 10000           */
+    0x7109,     /*  0 1000           */
+    0x700a,     /*  0 10 0          */
+    0x360a,     /*  0 10 1          */
+    0x630a,     /*  0 1 00          */
+    0x450a,     /*  0 1 01          */
+    0x540a,     /*  0 1 10          */
+    0x260a,     /*  0 1 11          */
+    0x6209,     /*  0 10100           */
+    0x6209,     /*  0 1010           */
+    0x1609,
+    0x1609,
+    0x6109,     /*  0 10110           */
+    0x6109,     /*  0 1011           */
+    0x060a,     /*  0 101110          */
+    0x600a,
+    0x5309,
+    0x5309,     /*  0 1100           */
+    0x350a,     /*  0 11 0          */
+    0x440a,     /*  0 11 1          */
+    0x2509,     /*  0 11010           */
+    0x2509,     /*  0 1101           */
+    0x5209,     /*  0 11011           */
+    0x5209,     /*  0 1101           */
+    0x5108,
+    0x5108,
+    0x5108,
+    0x5108,
+    0x1509,
+    0x1509,     /*  0 1111           */
+    0x0509,     /*  0 11111           */
+    0x0509,     /*  0 1111           */
+    0x3409,     /*               */
+    0x3409,     /*               */
+    0x4309,     /*   000            */
+    0x4309,     /*               */
+    0x5009,     /*   00 0           */
+    0x5009,     /*   00            */
+    0x2409,     /*   00 1           */
+    0x2409,     /*   00            */
+    0x4209,     /*   0 00           */
+    0x4209,     /*   0 0           */
+    0x3309,     /*   0 01           */
+    0x3309,     /*   0 0           */
+    0x1408,     /*   0 1            */
+    0x1408,     /*   0            */
+    0x1408,     /*   0            */
+    0x1408,     /*   0            */
+    0x4108,     /*    00            */
+    0x4108,     /*    0            */
+    0x4108,     /*    0            */
+    0x4108,     /*    0            */
+    0x0409,     /*    010           */
+    0x0409,     /*    01           */
+    0x4009,     /*    011           */
+    0x4009,     /*    01           */
+    0x1d0b,
+    0x1d0b,     /*  00 10101         */
+    0xc40c,     /*  00 1011000        */
+    0x6b0c,     /*  00 1011         */
+    0xc30c,     /*  00 1011010        */
+    0xa70c,     /*  00 1011011        */
+    0x2c0b,     /*  00 101110         */
+    0x2c0b,     /*  00 10111         */
+    0xc20c,     /*  00 1011110        */
+    0xb50c,     /*  00 1011111        */
+    0xc10c,     /*  00 1100000        */
+    0x0c0c,     /*  00 1100         */
+    0x4b0c,     /*  00 110 0        */
+    0xb40c,     /*  00 110 1        */
+    0x6a0c,     /*  00 11 00        */
+    0xa60c,     /*  00 11 01        */
+    0xb30b,     /*  00 11 1         */
+    0xb30b,     /*  00 11          */
+    0x5a0c,     /*  00 1101000        */
+    0xa50c,     /*  00 1101         */
+    0x2b0b,     /*  00 110101         */
+    0x2b0b,     /*  00 11010         */
+    0xb20b,     /*  00 110110         */
+    0xb20b,     /*  00 11011         */
+    0x1b0b,     /*  00 110111         */
+    0x1b0b,     /*  00 11011         */
+    0xb10b,     /*  00 111000         */
+    0xb10b,     /*  00 11100         */
+    0x0b0c,     /*  00 111 0        */
+    0xb00c,     /*  00 111 1        */
+    0x690c,     /*  00 1110100        */
+    0x960c,     /*  00 1110101        */
+    0x4a0c,     /*  00 1110110        */
+    0xa40c,     /*  00 1110111        */
+    0x780c,     /*  00 1111000        */
+    0x870c,     /*  00 1111         */
+    0xa30b,     /*  00 111101         */
+    0xa30b,     /*  00 11110         */
+    0x3a0c,     /*  00 1111100        */
+    0x590c,     /*  00 1111101        */
+    0x2a0b,     /*  00 111111         */
+    0x2a0b,     /*  00 11111         */
+    0x950c,     /*  0 00000000        */
+    0x680c,     /*  0           */
+    0xa10b,     /*  0 0000          */
+    0xa10b,     /*  0           */
+    0x860c,     /*  0 000 00        */
+    0x770c,     /*  0 000 01        */
+    0x940b,     /*  0 000 1         */
+    0x940b,     /*  0 000          */
+    0x490c,     /*  0 00 000        */
+    0x570c,     /*  0 00          */
+    0x670b,     /*  0 00 01         */
+    0x670b,     /*  0 00 0         */
+    0xa20a,     /*  0 00 1          */
+    0xa20a,     /*  0 00          */
+    0xa20a,     /*  0 00          */
+    0xa20a,     /*  0 00          */
+    0x1a0a,     /*  0 0 00          */
+    0x1a0a,     /*  0 0 0          */
+    0x1a0a,     /*  0 0 0          */
+    0x1a0a,     /*  0 0 0          */
+    0x0a0b,     /*  0 0 010         */
+    0x0a0b,     /*  0 0 01         */
+    0xa00b,     /*  0 0 011         */
+    0xa00b,     /*  0 0 01         */
+    0x390b,     /*  0 0 100         */
+    0x390b,     /*  0 0 10         */
+    0x930b,     /*  0 0 101         */
+    0x930b,     /*  0 0 10         */
+    0x580b,     /*  0 0 110         */
+    0x580b,     /*  0 0 11         */
+    0x850b,     /*  0 0 111         */
+    0x850b,     /*  0 0 11         */
+    0x290a,     /*  0  000          */
+    0x290a,     /*  0  00          */
+    0x290a,     /*  0  00          */
+    0x290a,     /*  0  00          */
+    0x920a,     /*  0             */
+    0x920a,     /*  0  00         */
+    0x920a,     /*  0  00         */
+    0x920a,     /*  0  00         */
+    0x760b,     /*  0  0100         */
+    0x760b,     /*  0  010         */
+    0x090b,     /*  0  0101         */
+    0x090b,     /*  0  010         */
+    0x190a,     /*  0  011          */
+    0x190a,     /*  0  01         */
+    0x190a,     /*  0  01         */
+    0x190a,     /*  0  01         */
+    0x910a,     /*  0  100          */
+    0x910a,     /*  0  10          */
+    0x910a,     /*  0  10          */
+    0x910a,     /*  0  10          */
+    0x900b,     /*  0  1010         */
+    0x900b,     /*  0  101         */
+    0x480b,     /*  0  1011         */
+    0x480b,     /*  0  101         */
+    0x840b,     /*  0  1100         */
+    0x840b,     /*  0  110         */
+    0x750b,     /*  0  1101         */
+    0x750b,     /*  0  110         */
+    0x380b,     /*  0  1110         */
+    0x380b,     /*  0  111         */
+    0x830b,     /*  0  1111         */
+    0x830b,     /*  0  111         */
+    0x660b,     /*  0 0100000         */
+    0x660b,     /*  0 010000         */
+    0x280b,     /*  0 0100          */
+    0x280b,     /*  0 010000         */
+    0x820a,     /*  0 010           */
+    0x820a,     /*  0 01000         */
+    0x820a,     /*  0 01000         */
+    0x820a,     /*  0 01000         */
+    0x470b,     /*  0 01 00         */
+    0x470b,     /*  0 01 0         */
+    0x740b,     /*  0 01 01         */
+    0x740b,     /*  0 01 0         */
+    0x180a,     /*  0 01 1          */
+    0x180a,     /*  0 01          */
+    0x180a,     /*  0 01          */
+    0x180a,     /*  0 01          */
+    0x810a,     /*  0 010100          */
+    0x810a,     /*  0 01010          */
+    0x810a,     /*  0 01010          */
+    0x810a,     /*  0 01010          */
+    0x800a,     /*  0 010101          */
+    0x800a,     /*  0 01010         */
+    0x800a,     /*  0 01010         */
+    0x800a,     /*  0 01010         */
+    0x080b,     /*  0 0101100         */
+    0x080b,     /*  0 010110         */
+    0x560b,     /*  0 0101101         */
+    0x560b,     /*  0 010110         */
+    0x370a,     /*  0 010111          */
+    0x370a,     /*  0 01011         */
+    0x370a,     /*  0 01011         */
+    0x370a,     /*  0 01011         */
+    0x730a,     /*  0 011000          */
+    0x730a,     /*  0 01100          */
+    0x730a,     /*  0 01100          */
+    0x730a,     /*  0 01100          */
+    0x650b,     /*  0 011 0         */
+    0x650b,     /*  0 011          */
+    0x460b,     /*  0 011 1         */
+    0x460b,     /*  0 011          */
+    0x270a,     /*  0 011010          */
+    0x270a,     /*  0 01101          */
+    0x270a,     /*  0 01101          */
+    0x270a,     /*  0 01101          */
+    0x720a,     /*  0 011011          */
+    0x720a,     /*  0 01101         */
+    0x720a,     /*  0 01101         */
+    0x720a,     /*  0 01101         */
+    0x640b,     /*  0 0111000         */
+    0x640b,     /*  0 011100         */
+    0x550b,     /*  0 0111          */
+    0x550b,     /*  0 011100         */
+    0x070a,     /*  0 011101          */
+    0x070a,     /*  0 01110         */
+    0x070a,     /*  0 01110         */
+    0x070a,     /*  0 01110         */
+    0x9e0d,
+    0x9e0d,     /*  00 0110000       */
+    0xbc0e,     /*  00 01100 0      */
+    0xcb0e,     /*  00 01100 1      */
+    0x8e0e,     /*  00 0110 00      */
+    0xe80e,     /*  00 0110 01      */
+    0x9d0e,     /*  00 0110 10      */
+    0xe70e,     /*  00 0110 11      */
+    0xbb0e,     /*  00 011 000      */
+    0x8d0e,     /*  00 011        */
+    0xd80e,     /*  00 011 010      */
+    0x6e0e,     /*  00 011 011      */
+    0xe60d,     /*  00 011 10       */
+    0xe60d,     /*  00 011 1       */
+    0x9c0d,     /*  00 011 11       */
+    0x9c0d,     /*  00 011 1       */
+    0xab0e,     /*  00 011010000      */
+    0xba0e,     /*  00 011010       */
+    0xe50e,     /*  00 01101 0      */
+    0xd70e,     /*  00 01101 1      */
+    0x4e0d,     /*  00 01101010       */
+    0x4e0d,     /*  00 0110101       */
+    0xe40e,     /*  00 011010110      */
+    0x8c0e,     /*  00 011010111      */
+    0xc80d,     /*  00 01101100       */
+    0xc80d,     /*  00 0110110       */
+    0x3e0d,     /*  00 01101101       */
+    0x3e0d,     /*  00 0110110       */
+    0x6d0d,     /*  00 01101110       */
+    0x6d0d,     /*  00 0110111       */
+    0xd60e,     /*  00 011011110      */
+    0x9b0e,     /*  00 011011111      */
+    0xb90e,     /*  00 011100000      */
+    0xaa0e,     /*  00 011100       */
+    0xe10d,     /*  00 01110        */
+    0xe10d,     /*  00 0111000       */
+    0xd40d,     /*  00 0111 0       */
+    0xd40d,     /*  00 0111        */
+    0xb80e,     /*  00 0111 10      */
+    0xa90e,     /*  00 0111 11      */
+    0x7b0d,     /*  00 01110100       */
+    0x7b0d,     /*  00 0111010       */
+    0xb70e,     /*  00 011101010      */
+    0xd00e,     /*  00 011101011      */
+    0xe30c,     /*  00 0111011        */
+    0xe30c,     /*  00 011101       */
+    0xe30c,     /*  00 011101       */
+    0xe30c,     /*  00 011101       */
+    0x0e0d,     /*  00 01111000       */
+    0x0e0d,     /*  00 0111100       */
+    0xe00d,     /*  00 01111        */
+    0xe00d,     /*  00 0111100       */
+    0x5d0d,     /*  00 01111010       */
+    0x5d0d,     /*  00 0111101       */
+    0xd50d,     /*  00 01111011       */
+    0xd50d,     /*  00 0111101       */
+    0x7c0d,     /*  00 01111100       */
+    0x7c0d,     /*  00 0111110       */
+    0xc70d,     /*  00 01111101       */
+    0xc70d,     /*  00 0111110       */
+    0x4d0d,     /*  00 01111110       */
+    0x4d0d,     /*  00 0111111       */
+    0x8b0d,     /*  00 01111111       */
+    0x8b0d,     /*  00 0111111       */
+    0x9a0d,
+    0x6c0d,     /*  00 10000        */
+    0xc60d,     /*  00 1000 0       */
+    0x3d0d,     /*  00 1000 1       */
+    0x5c0d,     /*  00 100 00       */
+    0xc50d,     /*  00 100 01       */
+    0x0d0c,     /*  00 100 1        */
+    0x0d0c,     /*  00 100         */
+    0x8a0d,     /*  00 10 000       */
+    0xa80d,     /*  00 10         */
+    0x990d,     /*  00 10 010       */
+    0x4c0d,     /*  00 10 011       */
+    0xb60d,     /*  00 10 100       */
+    0x7a0d,     /*  00 10 101       */
+    0x3c0c,     /*  00 10 11        */
+    0x3c0c,     /*  00 10 1        */
+    0x5b0d,     /*  00 1 0000       */
+    0x890d,     /*  00 1 0        */
+    0x1c0c,     /*  00 1          */
+    0x1c0c,     /*  00 1 00        */
+    0xc00c,     /*  00 1 010        */
+    0xc00c,     /*  00 1 01        */
+    0x980d,     /*  00 1 0110       */
+    0x790d,     /*  00 1 0111       */
+    0xe20b,     /*  00 1 10         */
+    0xe20b,     /*  00 1 1         */
+    0xe20b,     /*  00 1 1         */
+    0xe20b,     /*  00 1 1         */
+    0x2e0c,     /*  00 1 110        */
+    0x2e0c,     /*  00 1 11        */
+    0x1e0c,     /*  00 1 111        */
+    0x1e0c,     /*  00 1 11        */
+    0xd30c,     /*  00 1010000        */
+    0xd30c,     /*  00 101000        */
+    0x2d0c,     /*  00 1010         */
+    0x2d0c,     /*  00 101000        */
+    0xd20c,     /*  00 101 0        */
+    0xd20c,     /*  00 101         */
+    0xd10c,     /*  00 101 1        */
+    0xd10c,     /*  00 101         */
+    0x3b0c,     /*  00 1010100        */
+    0x3b0c,     /*  00 101010        */
+    0x970d,     /*  00 10101010       */
+    0x880d,     /*  00 10101011       */
+    0xf208,
+    0xf208,     /*  000 1            */
+    0x2f09,     /*  00 0000           */
+    0x0f09,     /*  00 0            */
+    0x1f08,     /*  00              */
+    0x1f08,     /*  00 00            */
+    0xf108,     /*  00 010            */
+    0xf108,     /*  00 01            */
+    0xce10,
+    0xce10,     /*  000 101100000    */
+    0xec11,     /*  000 1011000 0   */
+    0xdd11,     /*  000 1011000 1   */
+    0xde0f,     /*  000 101100      */
+    0xde0f,     /*  000 10110000    */
+    0xde0f,     /*  000 10110000    */
+    0xde0f,     /*  000 10110000    */
+    0xe90f,     /*  000 10110 0     */
+    0xe90f,     /*  000 10110      */
+    0xe90f,     /*  000 10110      */
+    0xe90f,     /*  000 10110      */
+    0xea10,     /*  000 10110 10    */
+    0xea10,     /*  000 10110 1    */
+    0xd910,     /*  000 10110 11    */
+    0xd910,     /*  000 10110 1    */
+    0xee0e,
+    0xee0e,     /*  000 1011       */
+    0xed0f,     /*  000 1011 10     */
+    0xeb0f,     /*  000 1011 11     */
+    0xbe0e,     /*  000 10110100      */
+    0xbe0e,     /*  000 1011010      */
+    0xcd0e,     /*  000 10110101      */
+    0xcd0e,     /*  000 1011010      */
+    0xdc0f,     /*  000 101101100     */
+    0xdb0f,     /*  000 101101101     */
+    0xae0e,     /*  000 10110111      */
+    0xae0e,     /*  000 1011011      */
+    0xcc0e,     /*  000 10111000      */
+    0xcc0e,     /*  000 1011100      */
+    0xad0f,     /*  000 10111 0     */
+    0xda0f,     /*  000 10111 1     */
+    0x7e0f,     /*  000 101110100     */
+    0xac0f,     /*  000 101110101     */
+    0xca0e,     /*  000 10111011      */
+    0xca0e,     /*  000 1011101      */
+    0xc90f,     /*  000 101111000     */
+    0x7d0f,     /*  000 101111      */
+    0x5e0e,     /*  000 10111101      */
+    0x5e0e,     /*  000 1011110      */
+    0xbd0d,     /*  000 1011111       */
+    0xbd0d,     /*  000 101111      */
+    0xbd0d,     /*  000 101111      */
+    0xbd0d,     /*  000 101111      */
+    0xef0b,
+    0xfe0b,     /*  00000000          */
+    0xdf0b,     /*  0000000 0         */
+    0xfd0b,     /*  0000000 1         */
+    0xcf0b,     /*    00         */
+    0xfc0b,     /*    01         */
+    0xbf0b,     /*    10         */
+    0xfb0b,     /*    11         */
+    0xaf0a,     /*    00          */
+    0xaf0a,     /*    0          */
+    0xfa0b,     /*    010         */
+    0x9f0b,     /*    011         */
+    0xf90b,     /*    100         */
+    0xf80b,     /*    101         */
+    0x8f0a,     /*    11          */
+    0x8f0a,     /*    1          */
+    0x7f0a,     /*  0000 000          */
+    0x7f0a,     /*  0000 00          */
+    0xf70a,     /*  0000            */
+    0xf70a,     /*  0000 00          */
+    0x6f0a,     /*  0000 010          */
+    0x6f0a,     /*  0000 01          */
+    0xf60a,     /*  0000 011          */
+    0xf60a,     /*  0000 01          */
+    0xff08,     /*  0000 1            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0xff08,     /*  0000            */
+    0x5f0a,     /*  000 0000          */
+    0x5f0a,     /*  000 000          */
+    0xf50a,     /*  000 0           */
+    0xf50a,     /*  000 000          */
+    0x4f09,     /*  000             */
+    0x4f09,     /*  000 00          */
+    0x4f09,     /*  000 00          */
+    0x4f09,     /*  000 00          */
+    0xf409,     /*  000 010           */
+    0xf409,     /*  000 01           */
+    0xf409,     /*  000 01           */
+    0xf409,     /*  000 01           */
+    0xf309,     /*  000 011           */
+    0xf309,     /*  000 01          */
+    0xf309,     /*  000 01          */
+    0xf309,     /*  000 01          */
+    0xf009,     /*  000 100           */
+    0xf009,     /*  000 10           */
+    0xf009,     /*  000 10           */
+    0xf009,     /*  000 10           */
+    0x3f0a,
+    0x3f0a
+};
+
+
+
+const uint16 huffTable_24[478] =
+{
+
+    0x2206,     /*  101               */
+    0x1205,     /*  10101               */
+    0x1205,     /*  1010               */
+    0x2105,     /*  10110               */
+    0x2105,     /*  1011               */
+    0x0206,     /*  101110              */
+    0x2006,     /*  101111              */
+    0x1104,
+    0x1104,
+    0x1104,
+    0x1104,
+    0x0104,
+    0x0104,
+    0x0104,
+    0x0104,
+    0x1004,
+    0x1004,
+    0x1004,
+    0x1004,
+    0x0004,
+    0x0004,
+    0x0004,
+    0x0004,
+    0x7308,
+    0x7308,
+    0x3709,
+    0x2709,
+    0x7208,
+    0x7208,
+    0x4608,     /*  01110000            */
+    0x4608,     /*  0111000            */
+    0x6408,     /*  01110             */
+    0x6408,     /*  0111000            */
+    0x5508,     /*  0111 0            */
+    0x5508,     /*  0111             */
+    0x7108,     /*  0111 1            */
+    0x7108,     /*  0111             */
+    0x3608,     /*  01110100            */
+    0x3608,     /*  0111010            */
+    0x6308,     /*  01110101            */
+    0x6308,     /*  0111010            */
+    0x4508,     /*  01110110            */
+    0x4508,     /*  0111011            */
+    0x5408,     /*  01110111            */
+    0x5408,     /*  0111011            */
+    0x2608,     /*  01111000            */
+    0x2608,     /*  0111100            */
+    0x6208,     /*  01111             */
+    0x6208,     /*  0111100            */
+    0x1608,     /*  01111010            */
+    0x1608,     /*  0111101            */
+    0x6108,     /*  01111011            */
+    0x6108,     /*  0111101            */
+    0x0609,     /*  011111000           */
+    0x6009,     /*  011111            */
+    0x3508,     /*  01111101            */
+    0x3508,     /*  0111110            */
+    0x5308,     /*  01111110            */
+    0x5308,     /*  0111111            */
+    0x4408,     /*  01111111            */
+    0x4408,     /*  0111111            */
+    0x2508,     /*  10000000            */
+    0x2508,     /*  1000000            */
+    0x5208,     /*  10000             */
+    0x5208,     /*  1000000            */
+    0x1508,     /*  1000 0            */
+    0x1508,     /*  1000             */
+    0x0509,     /*  1000 10           */
+    0x5009,     /*  1000 11           */
+    0x5107,     /*  100 0             */
+    0x5107,     /*  100              */
+    0x5107,     /*  100              */
+    0x5107,     /*  100              */
+    0x3408,     /*  100 10            */
+    0x3408,     /*  100 1            */
+    0x4308,     /*  100 11            */
+    0x4308,     /*  100 1            */
+    0x2407,     /*  10 00             */
+    0x2407,     /*  10 0             */
+    0x2407,     /*  10 0             */
+    0x2407,     /*  10 0             */
+    0x4207,     /*  10 01             */
+    0x4207,     /*  10 0            */
+    0x4207,     /*  10 0            */
+    0x4207,     /*  10 0            */
+    0x3307,     /*  10 10             */
+    0x3307,     /*  10 1             */
+    0x3307,     /*  10 1             */
+    0x3307,     /*  10 1             */
+    0x1407,     /*  10 11             */
+    0x1407,     /*  10 1            */
+    0x1407,     /*  10 1            */
+    0x1407,     /*  10 1            */
+    0x4107,     /*  1 000             */
+    0x4107,     /*  1 00             */
+    0x4107,     /*  1 00             */
+    0x4107,     /*  1 00             */
+    0x0408,     /*  1  0            */
+    0x0408,     /*  1              */
+    0x4008,     /*  1  1            */
+    0x4008,     /*  1              */
+    0x2307,     /*  1 010             */
+    0x2307,     /*  1 01             */
+    0x2307,     /*  1 01             */
+    0x2307,     /*  1 01             */
+    0x3207,     /*  1 011             */
+    0x3207,     /*  1 01            */
+    0x3207,     /*  1 01            */
+    0x3207,     /*  1 01            */
+    0x1306,     /*  1 10              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x1306,     /*  1 1              */
+    0x3106,     /*  1 11              */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x3106,     /*  1 1             */
+    0x0307,     /*  1010000             */
+    0x0307,     /*  101000             */
+    0x0307,     /*  101000             */
+    0x0307,     /*  101000             */
+    0x3007,     /*  1010              */
+    0x3007,     /*  101000            */
+    0x3007,     /*  101000            */
+    0x3007,     /*  101000            */
+    0xb309,
+    0xb309,
+    0x8809,     /*  010101            */
+    0x8809,     /*  01010100           */
+    0x2b0a,     /*  0101010100          */
+    0x5a0a,     /*  0101010101          */
+    0xb209,     /*  010101011           */
+    0xb209,     /*  01010101           */
+    0xa50a,     /*  0101011000          */
+    0x1b0a,     /*  0101011           */
+    0xb10a,     /*  0101011010          */
+    0x690a,     /*  0101011011          */
+    0x9609,     /*  010101110           */
+    0x9609,     /*  01010111           */
+    0xa409,     /*  010101111           */
+    0xa409,     /*  01010111           */
+    0x4a0a,     /*  0101100000          */
+    0x780a,     /*  0101100           */
+    0x8709,     /*  010110            */
+    0x8709,     /*  01011000           */
+    0x3a09,     /*  01011 0           */
+    0x3a09,     /*  01011            */
+    0xa309,     /*  01011 1           */
+    0xa309,     /*  01011            */
+    0x5909,     /*  010110100           */
+    0x5909,     /*  01011010           */
+    0x9509,     /*  010110101           */
+    0x9509,     /*  01011010           */
+    0x2a09,     /*  010110110           */
+    0x2a09,     /*  01011011           */
+    0xa209,     /*  010110111           */
+    0xa209,     /*  01011011           */
+    0xa109,     /*  010111000           */
+    0xa109,     /*  01011100           */
+    0x6809,     /*  010111            */
+    0x6809,     /*  01011100           */
+    0x8609,     /*  010111010           */
+    0x8609,     /*  01011101           */
+    0x7709,     /*  010111011           */
+    0x7709,     /*  01011101           */
+    0x4909,     /*  010111100           */
+    0x4909,     /*  01011110           */
+    0x9409,     /*  010111101           */
+    0x9409,     /*  01011110           */
+    0x3909,     /*  010111110           */
+    0x3909,     /*  01011111           */
+    0x9309,     /*  010111111           */
+    0x9309,     /*  01011111           */
+    0x5809,     /*  011000000           */
+    0x5809,     /*  01100000           */
+    0x8509,     /*  011000            */
+    0x8509,     /*  01100000           */
+    0x2909,     /*  01100 0           */
+    0x2909,     /*  01100            */
+    0x6709,     /*  01100 1           */
+    0x6709,     /*  01100            */
+    0x7609,     /*  0110 00           */
+    0x7609,     /*  0110 0           */
+    0x9209,     /*  0110 01           */
+    0x9209,     /*  0110 0           */
+    0x1909,     /*  0110 10           */
+    0x1909,     /*  0110 1           */
+    0x9109,     /*  0110 11           */
+    0x9109,     /*  0110 1           */
+    0x4809,     /*  011 000           */
+    0x4809,     /*  011 00           */
+    0x8409,     /*  011             */
+    0x8409,     /*  011 00           */
+    0x5709,     /*  011 010           */
+    0x5709,     /*  011 01           */
+    0x7509,     /*  011 011           */
+    0x7509,     /*  011 01           */
+    0x3809,     /*  011 100           */
+    0x3809,     /*  011 10           */
+    0x8309,     /*  011 101           */
+    0x8309,     /*  011 10           */
+    0x6609,     /*  011 110           */
+    0x6609,     /*  011 11           */
+    0x2809,     /*  011 111           */
+    0x2809,     /*  011 11           */
+    0x8209,     /*  011010000           */
+    0x8209,     /*  01101000           */
+    0x1809,     /*  011010            */
+    0x1809,     /*  01101000           */
+    0x4709,     /*  01101 0           */
+    0x4709,     /*  01101            */
+    0x7409,     /*  01101 1           */
+    0x7409,     /*  01101            */
+    0x8109,     /*  011010100           */
+    0x8109,     /*  01101010           */
+    0x080a,     /*  0110101010          */
+    0x800a,     /*  0110101011          */
+    0x5609,     /*  011010110           */
+    0x5609,     /*  01101011           */
+    0x6509,     /*  011010111           */
+    0x6509,     /*  01101011           */
+    0x1709,     /*  011011000           */
+    0x1709,     /*  01101100           */
+    0x070a,     /*  011011 0          */
+    0x700a,     /*  011011 1          */
+    0x6e0b,
+    0x9c0b,
+    0xc90a,     /*  01000 01          */
+    0xc90a,     /*  01000 0          */
+    0x5e0a,     /*  01000 10          */
+    0x5e0a,     /*  01000 1          */
+    0xba0a,     /*  01000 11          */
+    0xba0a,     /*  01000 1          */
+    0xe50a,     /*  0100 000          */
+    0xe50a,     /*  0100 00          */
+    0xab0b,     /*  0100  0         */
+    0x7d0b,     /*  0100  1         */
+    0xd70a,     /*  0100 010          */
+    0xd70a,     /*  0100 01          */
+    0xe40a,     /*  0100 011          */
+    0xe40a,     /*  0100 01          */
+    0x8c0a,     /*  0100 100          */
+    0x8c0a,
+    0xc80a,
+    0xc80a,
+    0x4e0b,     /*  0100 1100         */
+    0x2e0b,     /*  0100 1101         */
+    0x3e0a,     /*  0100 111          */
+    0x3e0a,     /*  0100 11          */
+    0x6d0a,     /*  010 0000          */
+    0x6d0a,     /*  010 000          */
+    0xd60a,     /*  010 0           */
+    0xd60a,     /*  010 000          */
+    0xe30a,     /*  010  0          */
+    0xe30a,     /*  010            */
+    0x9b0a,     /*  010  1          */
+    0x9b0a,     /*  010            */
+    0xb90a,     /*  010 0100          */
+    0xb90a,     /*  010 010          */
+    0xaa0a,     /*  010 0101          */
+    0xaa0a,
+    0xe20a,
+    0xe20a,
+    0x1e0a,
+    0x1e0a,
+    0xe10a,
+    0xe10a,
+    0x5d0a,
+    0x5d0a,
+    0xd50a,
+    0xd50a,
+    0x7c0a,
+    0x7c0a,
+    0xc70a,
+    0xc70a,
+    0x4d0a,
+    0x4d0a,
+    0x8b0a,
+    0x8b0a,
+    0xb80a,
+    0xb80a,
+    0xd40a,
+    0xd40a,
+    0x9a0a,
+    0x9a0a,
+    0xa90a,     /*  01 0 0          */
+    0xa90a,     /*  01 0           */
+    0x6c0a,     /*  01 0 1          */
+    0x6c0a,     /*  01 0           */
+    0xc60a,     /*  01  00          */
+    0xc60a,     /*  01  0          */
+    0x3d0a,     /*  01  01          */
+    0x3d0a,     /*  01  0          */
+    0xd30a,     /*  01  10          */
+    0xd30a,     /*  01  1          */
+    0x2d0a,     /*  01  11          */
+    0x2d0a,     /*  01  1          */
+    0xd20a,
+    0xd20a,
+    0x1d0a,     /*  01 01           */
+    0x1d0a,     /*  01 0100          */
+    0x7b0a,     /*  01 01010          */
+    0x7b0a,     /*  01 0101          */
+    0xb70a,     /*  01 01011          */
+    0xb70a,
+    0xd10a,
+    0xd10a,     /*  01 0110          */
+    0x5c0a,     /*  01 01101          */
+    0x5c0a,     /*  01 0110          */
+    0xc50a,     /*  01 01110          */
+    0xc50a,     /*  01 0111          */
+    0x8a0a,     /*  01 01111          */
+    0x8a0a,     /*  01 0111          */
+    0xa80a,     /*  01 10000          */
+    0xa80a,     /*  01 1000          */
+    0x990a,     /*  01 10           */
+    0x990a,     /*  01 1000          */
+    0x4c0a,     /*  01 1 0          */
+    0x4c0a,     /*  01 1           */
+    0xc40a,     /*  01 1 1          */
+    0xc40a,     /*  01 1           */
+    0x6b0a,     /*  01 10100          */
+    0x6b0a,     /*  01 1010          */
+    0xb60a,     /*  01 10101          */
+    0xb60a,     /*  01 1010          */
+    0xd00b,     /*  01 101100         */
+    0x0c0b,     /*  01 101101         */
+    0x3c0a,     /*  01 10111          */
+    0x3c0a,     /*  01 1011          */
+    0xc30a,     /*  01 11000          */
+    0xc30a,     /*  01 1100          */
+    0x7a0a,     /*  01 11           */
+    0x7a0a,     /*  01 1100          */
+    0xa70a,     /*  01 11010          */
+    0xa70a,     /*  01 1101          */
+    0x2c0a,     /*  01 11011          */
+    0x2c0a,     /*  01 1101          */
+    0xc20a,     /*  01 11100          */
+    0xc20a,     /*  01 1110          */
+    0x5b0a,     /*  01 11101          */
+    0x5b0a,     /*  01 1110          */
+    0xb50a,     /*  01 11110          */
+    0xb50a,     /*  01 1111          */
+    0x1c0a,
+    0x1c0a,
+    0x890a,
+    0x890a,
+    0x980a,
+    0x980a,
+    0xc10a,     /*  010100 0          */
+    0xc10a,     /*  010100           */
+    0x4b0a,     /*  010100 1          */
+    0x4b0a,     /*  010100           */
+    0xc00b,     /*  01010 000         */
+    0x0b0b,     /*  01010           */
+    0x3b0a,     /*  01010 01          */
+    0x3b0a,     /*  01010 0          */
+    0xb00b,     /*  01010 100         */
+    0x0a0b,     /*  01010 101         */
+    0x1a0a,     /*  01010 11          */
+    0x1a0a,     /*  01010 1          */
+    0xb409,     /*  0101 00           */
+    0xb409,     /*  0101 0           */
+    0xb409,     /*  0101 0           */
+    0xb409,     /*  0101 0           */
+    0x6a0a,     /*  0101 010          */
+    0x6a0a,     /*  0101 01          */
+    0xa60a,     /*  0101 011          */
+    0xa60a,     /*  0101 01          */
+    0x790a,     /*  0101 100          */
+    0x790a,     /*  0101 10          */
+    0x970a,     /*  0101 101          */
+    0x970a,     /*  0101 10          */
+    0xa00b,     /*  0101 1100         */
+    0x090b,     /*  0101 1101         */
+    0x900a,     /*  0101 111          */
+    0x900a,     /*  0101 11          */
+    0xca0b,
+    0xca0b,
+    0xbb0b,
+    0xbb0b,
+    0x8d0b,
+    0x8d0b,     /*  0100000          */
+    0xd80b,     /*  0100000 1         */
+    0xd80b,     /*  0100000          */
+    0x0e0c,     /*  010000 000        */
+    0xe00c,     /*  010000          */
+    0x0d0b,     /*  010000 01         */
+    0x0d0b,     /*  010000 0         */
+    0xe60a,     /*  010000 1          */
+    0xe60a,     /*  010000          */
+    0xe60a,     /*  010000          */
+    0xe60a,     /*  010000          */
+    0x0f09,     /*   011000      401  */
+    0x0f09,     /*   01100           */
+    0x0f09,     /*   01100           */
+    0x0f09,     /*   01100           */
+    0xee0b,     /*   011 00         */
+    0xde0b,     /*   011 01         */
+    0xed0b,     /*   011 10         */
+    0xce0b,     /*   011 11         */
+    0xec0b,     /*   01101000         */
+    0xdd0b,     /*   01101          */
+    0xbe0b,     /*   01101010         */
+    0xeb0b,     /*   01101011         */
+    0xcd0b,     /*   01101100         */
+    0xdc0b,     /*   01101101         */
+    0xae0b,     /*   01101110         */
+    0xea0b,     /*   01101111         */
+    0xbd0b,     /*   01110000         */
+    0xdb0b,     /*   01110          */
+    0xcc0b,     /*   0111 0         */
+    0x9e0b,     /*   0111 1         */
+    0xe90b,     /*   01110100         */
+    0xad0b,     /*   01110101         */
+    0xda0b,     /*   01110110         */
+    0xbc0b,     /*   01110111         */
+    0xcb0b,     /*   01111000         */
+    0x8e0b,
+    0xe80b,
+    0x9d0b,
+    0xd90b,
+    0x7e0b,
+    0xe70b,
+    0xac0b,
+    0xff04,
+    0xef08,
+    0xfe08,
+    0xdf08,     /*  0000 0            */
+    0xfd08,     /*  0000 1            */
+    0xcf08,     /*  000 00            */
+    0xfc08,     /*  000 01            */
+    0xbf08,     /*  000 10            */
+    0xfb08,     /*  000 11            */
+    0xfa07,     /*  00 00             */
+    0xfa07,     /*  00 0             */
+    0xaf08,     /*  00 010            */
+    0x9f08,     /*  00 011            */
+    0xf907,     /*  00 10             */
+    0xf907,     /*  00 1             */
+    0xf807,     /*  00 11             */
+    0xf807,     /*  00 1             */
+    0x8f08,
+    0x7f08,     /*  0 0             */
+    0xf707,     /*  0               */
+    0xf707,     /*  0 00             */
+    0x6f07,     /*  0 010             */
+    0x6f07,     /*  0 01             */
+    0xf607,     /*  0 011             */
+    0xf607,     /*  0 01             */
+    0x5f07,
+    0x5f07,     /*  0 10             */
+    0xf507,     /*  0 101             */
+    0xf507,     /*  0 10             */
+    0x4f07,     /*  0 110             */
+    0x4f07,     /*  0 11             */
+    0xf407,     /*  0 111             */
+    0xf407,     /*  0 11             */
+    0x3f07,
+    0x3f07,
+    0xf307,     /*   0              */
+    0xf307,
+    0x2f07,     /*    0             */
+    0x2f07,     /*                 */
+    0xf207,     /*    1             */
+    0xf207,     /*                 */
+    0xf107,
+    0xf107,
+    0x1f08,
+    0xf008
+
+};
+
+
+const uint16 huffTable_32[33] =
+{
+
+    0x0b06,
+    0x0f06,
+    0x0d06,
+    0x0e06,
+    0x0706,
+    0x0506,
+    0x0905,
+    0x0905,
+    0x0605,
+    0x0605,
+    0x0305,
+    0x0305,
+    0x0a05,
+    0x0a05,
+    0x0c05,
+    0x0c05,
+    0x0204,
+    0x0204,
+    0x0204,
+    0x0204,
+    0x0104,
+    0x0104,
+    0x0104,
+    0x0104,
+    0x0404,
+    0x0404,
+    0x0404,
+    0x0404,
+    0x0804,
+    0x0804,
+    0x0804,
+    0x0804,
+    0x0001
+
+};
+
+
+/*
+ *  MM = 512; z = [0:(MM)]; a = z.^(1/3);
+ *  Table is in Q27
+ */
+const int32  power_one_third[513] =
+{
+
+    0x00000000,  0x08000000,  0x0A14517D,  0x0B89BA25,
+    0x0CB2FF53,  0x0DAE07DE,  0x0E897685,  0x0F4DAEDD,
+    0x10000000,  0x10A402FD,  0x113C4841,  0x11CAB613,
+    0x1250BFE2,  0x12CF8890,  0x1347F8AB,  0x13BACD65,
+    0x1428A2FA,  0x1491FC15,  0x14F74744,  0x1558E2F7,
+    0x15B72095,  0x161246D7,  0x166A9399,  0x16C03D55,
+    0x17137449,  0x17646369,  0x17B33124,  0x18000000,
+    0x184AEF29,  0x18941AD8,  0x18DB9CB7,  0x19218C2E,
+    0x1965FEA5,  0x19A907C2,  0x19EAB998,  0x1A2B24D0,
+    0x1A6A58D5,  0x1AA863EE,  0x1AE5535D,  0x1B213377,
+    0x1B5C0FBD,  0x1B95F2EC,  0x1BCEE70F,  0x1C06F590,
+    0x1C3E2745,  0x1C74847A,  0x1CAA1501,  0x1CDEE035,
+    0x1D12ED0B,  0x1D464212,  0x1D78E582,  0x1DAADD3A,
+    0x1DDC2ECF,  0x1E0CDF8C,  0x1E3CF476,  0x1E6C7257,
+    0x1E9B5DBA,  0x1EC9BAF6,  0x1EF78E2C,  0x1F24DB4E,
+    0x1F51A620,  0x1F7DF23C,  0x1FA9C314,  0x1FD51BF2,
+    0x20000000,  0x202A7244,  0x205475A6,  0x207E0CEE,
+    0x20A73ACA,  0x20D001CC,  0x20F8646D,  0x2120650E,
+    0x214805FA,  0x216F4963,  0x2196316C,  0x21BCC020,
+    0x21E2F77A,  0x2208D961,  0x222E67AD,  0x2253A425,
+    0x22789082,  0x229D2E6E,  0x22C17F82,  0x22E5854F,
+    0x23094155,  0x232CB509,  0x234FE1D5,  0x2372C918,
+    0x23956C26,  0x23B7CC47,  0x23D9EABB,  0x23FBC8B9,
+    0x241D676E,  0x243EC7FF,  0x245FEB86,  0x2480D319,
+    0x24A17FC3,  0x24C1F28B,  0x24E22C6C,  0x25022E5F,
+    0x2521F954,  0x25418E33,  0x2560EDE2,  0x2580193E,
+    0x259F111F,  0x25BDD657,  0x25DC69B4,  0x25FACBFE,
+    0x2618FDF8,  0x26370060,  0x2654D3EF,  0x2672795C,
+    0x268FF156,  0x26AD3C8A,  0x26CA5BA2,  0x26E74F41,
+    0x27041808,  0x2720B695,  0x273D2B81,  0x27597762,
+    0x27759ACB,  0x2791964B,  0x27AD6A6F,  0x27C917C0,
+    0x27E49EC5,  0x28000000,  0x281B3BF3,  0x2836531B,
+    0x285145F3,  0x286C14F5,  0x2886C096,  0x28A1494B,
+    0x28BBAF85,  0x28D5F3B3,  0x28F01641,  0x290A179B,
+    0x2923F82A,  0x293DB854,  0x2957587E,  0x2970D90A,
+    0x298A3A59,  0x29A37CCA,  0x29BCA0BB,  0x29D5A687,
+    0x29EE8E87,  0x2A075914,  0x2A200684,  0x2A38972C,
+    0x2A510B5F,  0x2A696370,  0x2A819FAE,  0x2A99C069,
+    0x2AB1C5ED,  0x2AC9B088,  0x2AE18085,  0x2AF9362C,
+    0x2B10D1C6,  0x2B28539B,  0x2B3FBBEF,  0x2B570B09,
+    0x2B6E412B,  0x2B855E97,  0x2B9C6390,  0x2BB35056,
+    0x2BCA2527,  0x2BE0E242,  0x2BF787E4,  0x2C0E1649,
+    0x2C248DAD,  0x2C3AEE4A,  0x2C513859,  0x2C676C13,
+    0x2C7D89AF,  0x2C939164,  0x2CA98368,  0x2CBF5FF1,
+    0x2CD52731,  0x2CEAD95E,  0x2D0076A9,  0x2D15FF45,
+    0x2D2B7363,  0x2D40D332,  0x2D561EE4,  0x2D6B56A7,
+    0x2D807AAA,  0x2D958B19,  0x2DAA8823,  0x2DBF71F4,
+    0x2DD448B7,  0x2DE90C98,  0x2DFDBDC0,  0x2E125C5C,
+    0x2E26E892,  0x2E3B628D,  0x2E4FCA75,  0x2E642070,
+    0x2E7864A8,  0x2E8C9741,  0x2EA0B862,  0x2EB4C831,
+    0x2EC8C6D3,  0x2EDCB46C,  0x2EF09121,  0x2F045D14,
+    0x2F18186A,  0x2F2BC345,  0x2F3F5DC7,  0x2F52E812,
+    0x2F666247,  0x2F79CC88,  0x2F8D26F4,  0x2FA071AC,
+    0x2FB3ACD0,  0x2FC6D87F,  0x2FD9F4D7,  0x2FED01F8,
+    0x30000000,  0x3012EF0C,  0x3025CF39,  0x3038A0A6,
+    0x304B636D,  0x305E17AD,  0x3070BD81,  0x30835504,
+    0x3095DE51,  0x30A85985,  0x30BAC6B9,  0x30CD2609,
+    0x30DF778D,  0x30F1BB60,  0x3103F19C,  0x31161A59,
+    0x312835B0,  0x313A43BA,  0x314C4490,  0x315E3849,
+    0x31701EFD,  0x3181F8C4,  0x3193C5B4,  0x31A585E6,
+    0x31B7396F,  0x31C8E066,  0x31DA7AE1,  0x31EC08F6,
+    0x31FD8ABC,  0x320F0047,  0x322069AC,  0x3231C702,
+    0x3243185C,  0x32545DCF,  0x32659770,  0x3276C552,
+    0x3287E78A,  0x3298FE2C,  0x32AA094A,  0x32BB08F9,
+    0x32CBFD4A,  0x32DCE652,  0x32EDC423,  0x32FE96D0,
+    0x330F5E6A,  0x33201B04,  0x3330CCB0,  0x33417380,
+    0x33520F85,  0x3362A0D0,  0x33732774,  0x3383A380,
+    0x33941506,  0x33A47C17,  0x33B4D8C4,  0x33C52B1B,
+    0x33D5732F,  0x33E5B10F,  0x33F5E4CA,  0x34060E71,
+    0x34162E14,  0x342643C1,  0x34364F88,  0x34465178,
+    0x345649A1,  0x34663810,  0x34761CD6,  0x3485F800,
+    0x3495C99D,  0x34A591BB,  0x34B55069,  0x34C505B4,
+    0x34D4B1AB,  0x34E4545B,  0x34F3EDD2,  0x35037E1D,
+    0x3513054B,  0x35228367,  0x3531F881,  0x354164A3,
+    0x3550C7DC,  0x35602239,  0x356F73C5,  0x357EBC8E,
+    0x358DFCA0,  0x359D3408,  0x35AC62D1,  0x35BB8908,
+    0x35CAA6B9,  0x35D9BBF0,  0x35E8C8B9,  0x35F7CD20,
+    0x3606C92F,  0x3615BCF3,  0x3624A878,  0x36338BC8,
+    0x364266EE,  0x365139F6,  0x366004EC,  0x366EC7D9,
+    0x367D82C9,  0x368C35C6,  0x369AE0DC,  0x36A98414,
+    0x36B81F7A,  0x36C6B317,  0x36D53EF7,  0x36E3C323,
+    0x36F23FA5,  0x3700B488,  0x370F21D5,  0x371D8797,
+    0x372BE5D7,  0x373A3CA0,  0x37488BF9,  0x3756D3EF,
+    0x37651489,  0x37734DD1,  0x37817FD1,  0x378FAA92,
+    0x379DCE1D,  0x37ABEA7C,  0x37B9FFB7,  0x37C80DD7,
+    0x37D614E6,  0x37E414EC,  0x37F20DF1,  0x38000000,
+    0x380DEB20,  0x381BCF5A,  0x3829ACB6,  0x3837833D,
+    0x384552F8,  0x38531BEE,  0x3860DE28,  0x386E99AF,
+    0x387C4E89,  0x3889FCC0,  0x3897A45B,  0x38A54563,
+    0x38B2DFDF,  0x38C073D7,  0x38CE0152,  0x38DB885A,
+    0x38E908F4,  0x38F68329,  0x3903F701,  0x39116483,
+    0x391ECBB6,  0x392C2CA1,  0x3939874D,  0x3946DBC0,
+    0x39542A01,  0x39617218,  0x396EB40C,  0x397BEFE4,
+    0x398925A7,  0x3996555C,  0x39A37F09,  0x39B0A2B7,
+    0x39BDC06A,  0x39CAD82B,  0x39D7EA01,  0x39E4F5F0,
+    0x39F1FC01,  0x39FEFC3A,  0x3A0BF6A2,  0x3A18EB3E,
+    0x3A25DA16,  0x3A32C32F,  0x3A3FA691,  0x3A4C8441,
+    0x3A595C46,  0x3A662EA6,  0x3A72FB67,  0x3A7FC28F,
+    0x3A8C8425,  0x3A99402E,  0x3AA5F6B1,  0x3AB2A7B3,
+    0x3ABF533A,  0x3ACBF94D,  0x3AD899F1,  0x3AE5352C,
+    0x3AF1CB03,  0x3AFE5B7D,  0x3B0AE6A0,  0x3B176C70,
+    0x3B23ECF3,  0x3B306830,  0x3B3CDE2C,  0x3B494EEB,
+    0x3B55BA74,  0x3B6220CC,  0x3B6E81F9,  0x3B7ADE00,
+    0x3B8734E5,  0x3B9386B0,  0x3B9FD364,  0x3BAC1B07,
+    0x3BB85D9E,  0x3BC49B2F,  0x3BD0D3BE,  0x3BDD0751,
+    0x3BE935ED,  0x3BF55F97,  0x3C018453,  0x3C0DA427,
+    0x3C19BF17,  0x3C25D52A,  0x3C31E662,  0x3C3DF2C6,
+    0x3C49FA5B,  0x3C55FD24,  0x3C61FB27,  0x3C6DF468,
+    0x3C79E8ED,  0x3C85D8B9,  0x3C91C3D2,  0x3C9DAA3C,
+    0x3CA98BFC,  0x3CB56915,  0x3CC1418E,  0x3CCD156A,
+    0x3CD8E4AE,  0x3CE4AF5E,  0x3CF0757F,  0x3CFC3714,
+    0x3D07F423,  0x3D13ACB0,  0x3D1F60BF,  0x3D2B1055,
+    0x3D36BB75,  0x3D426224,  0x3D4E0466,  0x3D59A23F,
+    0x3D653BB4,  0x3D70D0C8,  0x3D7C6180,  0x3D87EDE0,
+    0x3D9375EC,  0x3D9EF9A8,  0x3DAA7918,  0x3DB5F43F,
+    0x3DC16B23,  0x3DCCDDC7,  0x3DD84C2E,  0x3DE3B65D,
+    0x3DEF1C58,  0x3DFA7E22,  0x3E05DBC0,  0x3E113535,
+    0x3E1C8A85,  0x3E27DBB3,  0x3E3328C4,  0x3E3E71BB,
+    0x3E49B69C,  0x3E54F76B,  0x3E60342B,  0x3E6B6CE0,
+    0x3E76A18D,  0x3E81D237,  0x3E8CFEE0,  0x3E98278D,
+    0x3EA34C40,  0x3EAE6CFE,  0x3EB989CA,  0x3EC4A2A8,
+    0x3ECFB79A,  0x3EDAC8A5,  0x3EE5D5CB,  0x3EF0DF10,
+    0x3EFBE478,  0x3F06E606,  0x3F11E3BE,  0x3F1CDDA2,
+    0x3F27D3B6,  0x3F32C5FD,  0x3F3DB47B,  0x3F489F32,
+    0x3F538627,  0x3F5E695C,  0x3F6948D5,  0x3F742494,
+    0x3F7EFC9D,  0x3F89D0F3,  0x3F94A19A,  0x3F9F6E94,
+    0x3FAA37E4,  0x3FB4FD8E,  0x3FBFBF94,  0x3FCA7DFB,
+    0x3FD538C4,  0x3FDFEFF3,  0x3FEAA38A,  0x3FF5538E,
+    0x40000000
+};
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.h
new file mode 100644
index 0000000..b54c5bf
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/pvmp3_tables.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.
+ * -------------------------------------------------------------------
+ */
+/*
+   Filename: pvmp3_tables.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+------------------------------------------------------------------------------
+*/
+
+#ifndef PVMP3_TABLES_H
+#define PVMP3_TABLES_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+
+#include "pvmp3_dec_defs.h"
+#include "pv_mp3_huffman.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES AND SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+#define Qfmt_28(a) (int32(double(0x10000000)*a))
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+typedef struct
+{
+    int16 l[23];
+    int16 s[14];
+} mp3_scaleFactorBandIndex;
+
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    extern const int32    mp3_s_freq[4][4];
+    extern const int32    inv_sfreq[4];
+    extern const int16    mp3_bitrate[3][15];
+    extern const int32    power_one_third[513];
+
+    extern const  mp3_scaleFactorBandIndex mp3_sfBandIndex[9];
+    extern const int32 mp3_shortwindBandWidths[9][13];
+    extern const int32 pqmfSynthWin[(HAN_SIZE/2) + 8];
+
+
+    extern const uint16 huffTable_1[];
+    extern const uint16 huffTable_2[];
+    extern const uint16 huffTable_3[];
+    extern const uint16 huffTable_5[];
+    extern const uint16 huffTable_6[];
+    extern const uint16 huffTable_7[];
+    extern const uint16 huffTable_8[];
+    extern const uint16 huffTable_9[];
+    extern const uint16 huffTable_10[];
+    extern const uint16 huffTable_11[];
+    extern const uint16 huffTable_12[];
+    extern const uint16 huffTable_13[];
+    extern const uint16 huffTable_15[];
+    extern const uint16 huffTable_16[];
+    extern const uint16 huffTable_24[];
+    extern const uint16 huffTable_32[];
+    extern const uint16 huffTable_33[];
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
diff --git a/media/libstagefright/codecs/mp3dec/src/s_huffcodetab.h b/media/libstagefright/codecs/mp3dec/src/s_huffcodetab.h
new file mode 100644
index 0000000..874943d
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/s_huffcodetab.h
@@ -0,0 +1,98 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: s_huffcodetab.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+
+------------------------------------------------------------------------------
+ REFERENCES
+
+ [1] ISO MPEG Audio Subgroup Software Simulation Group (1996)
+     ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
+
+----------------------------------------------------------------------------*/
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef  S_HUFFCODETAB_H
+#define  S_HUFFCODETAB_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; MACROS
+; Define module specific macros here
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; DEFINES
+; Include all pre-processor statements here.
+----------------------------------------------------------------------------*/
+#define HUFF_TBL    34
+
+/*----------------------------------------------------------------------------
+; EXTERNAL VARIABLES REFERENCES
+; Declare variables used in this module but defined elsewhere
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; SIMPLE TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; ENUMERATED TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; STRUCTURES TYPEDEF'S
+----------------------------------------------------------------------------*/
+
+struct huffcodetab
+{
+    uint32 linbits;                  /*number of linbits  */
+    uint16(*pdec_huff_tab)(tmp3Bits *);
+};
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/s_mp3bits.h b/media/libstagefright/codecs/mp3dec/src/s_mp3bits.h
new file mode 100644
index 0000000..b905b9a
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/s_mp3bits.h
@@ -0,0 +1,107 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: s_mp3bits.h
+
+   Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, BITS
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef  S_MP3BITS_H
+#define  S_MP3BITS_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+/*
+ * Name: BITS
+ * Description: Holds information for processing the input data buffer
+ *    as a "stream". The data is in packed format.
+ * Fields:
+ *    pBuffer - pointer to the beginning of the buffer. If the data type of
+ *        this changes, make sure to update the constants in ibstream.h
+ *    usedBits - number of bits read thus far from the buffer. Bit 0 is
+ *        the LSB of pBuffer[0].
+ */
+
+
+typedef struct
+{
+    uint8       *pBuffer;
+    uint32      usedBits;
+    uint32      inputBufferCurrentLength;
+    uint32      offset;
+} tmp3Bits;
+
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+#endif
+
diff --git a/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_chan.h b/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_chan.h
new file mode 100644
index 0000000..6eb8835
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_chan.h
@@ -0,0 +1,110 @@
+/* ------------------------------------------------------------------
+ * 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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: s_tmp3dec_chan.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, tmp3dec_chan.
+ This structure contains information per channel that needs to persist
+ between calls
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TMP3DEC_CHAN_H
+#define S_TMP3DEC_CHAN_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "pvmp3_audio_type_defs.h"
+#include "pvmp3_dec_defs.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    typedef struct
+    {
+        int32  used_freq_lines;
+        int32  overlap[SUBBANDS_NUMBER*FILTERBANK_BANDS];
+        int32  work_buf_int32[SUBBANDS_NUMBER*FILTERBANK_BANDS]; /* working buffer */
+        int32  circ_buffer[480 + 576];
+
+    } tmp3dec_chan;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
diff --git a/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_file.h b/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_file.h
new file mode 100644
index 0000000..805cedb
--- /dev/null
+++ b/media/libstagefright/codecs/mp3dec/src/s_tmp3dec_file.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.
+ * -------------------------------------------------------------------
+ */
+/*
+------------------------------------------------------------------------------
+   PacketVideo Corp.
+   MP3 Decoder Library
+
+   Filename: s_tmp3dec_file.h
+
+     Date: 09/21/2007
+
+------------------------------------------------------------------------------
+ REVISION HISTORY
+
+ Description:
+
+------------------------------------------------------------------------------
+ INCLUDE DESCRIPTION
+
+ This include file defines the structure, tmp3dec_file.
+ This structure contains information that needs to persist between calls
+
+------------------------------------------------------------------------------
+*/
+
+/*----------------------------------------------------------------------------
+; CONTINUE ONLY IF NOT ALREADY DEFINED
+----------------------------------------------------------------------------*/
+#ifndef S_TMP3DEC_FILE_H
+#define S_TMP3DEC_FILE_H
+
+/*----------------------------------------------------------------------------
+; INCLUDES
+----------------------------------------------------------------------------*/
+#include "s_tmp3dec_chan.h"
+#include "s_mp3bits.h"
+#include "s_huffcodetab.h"
+
+/*----------------------------------------------------------------------------
+; 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
+----------------------------------------------------------------------------*/
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+    typedef struct
+    {
+        int32           num_channels;
+        int32           predicted_frame_size;
+        int32           frame_start;
+        int32           Scratch_mem[168];
+        tmp3dec_chan    perChan[CHAN];
+        mp3ScaleFactors scaleFactors[CHAN];
+        mp3SideInfo     sideInfo;
+        tmp3Bits        mainDataStream;
+        uint8           mainDataBuffer[BUFSIZE];
+        tmp3Bits        inputStream;
+        huffcodetab     ht[HUFF_TBL];
+    } tmp3dec_file;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+/*----------------------------------------------------------------------------
+; GLOBAL FUNCTION DEFINITIONS
+; Function Prototype declaration
+----------------------------------------------------------------------------*/
+
+/*----------------------------------------------------------------------------
+; END
+----------------------------------------------------------------------------*/
+
+#endif
+
+
+
+
diff --git a/media/libstagefright/colorconversion/Android.mk b/media/libstagefright/colorconversion/Android.mk
new file mode 100644
index 0000000..c08ce3a
--- /dev/null
+++ b/media/libstagefright/colorconversion/Android.mk
@@ -0,0 +1,22 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=                     \
+        ColorConverter.cpp            \
+        SoftwareRenderer.cpp
+
+LOCAL_C_INCLUDES := \
+        $(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
+
+LOCAL_SHARED_LIBRARIES :=       \
+        libbinder               \
+        libmedia                \
+        libutils                \
+        libui                   \
+        libcutils
+
+LOCAL_PRELINK_MODULE:= false
+
+LOCAL_MODULE:= libstagefright_color_conversion
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libstagefright/colorconversion/ColorConverter.cpp b/media/libstagefright/colorconversion/ColorConverter.cpp
new file mode 100644
index 0000000..e74782f
--- /dev/null
+++ b/media/libstagefright/colorconversion/ColorConverter.cpp
@@ -0,0 +1,297 @@
+/*
+ * 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 <media/stagefright/ColorConverter.h>
+#include <media/stagefright/MediaDebug.h>
+
+namespace android {
+
+static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
+
+ColorConverter::ColorConverter(
+        OMX_COLOR_FORMATTYPE from, OMX_COLOR_FORMATTYPE to)
+    : mSrcFormat(from),
+      mDstFormat(to),
+      mClip(NULL) {
+}
+
+ColorConverter::~ColorConverter() {
+    delete[] mClip;
+    mClip = NULL;
+}
+
+bool ColorConverter::isValid() const {
+    if (mDstFormat != OMX_COLOR_Format16bitRGB565) {
+        return false;
+    }
+
+    switch (mSrcFormat) {
+        case OMX_COLOR_FormatYUV420Planar:
+        case OMX_COLOR_FormatCbYCrY:
+        case OMX_QCOM_COLOR_FormatYVU420SemiPlanar:
+            return true;
+
+        default:
+            return false;
+    }
+}
+
+void ColorConverter::convert(
+        size_t width, size_t height,
+        const void *srcBits, size_t srcSkip,
+        void *dstBits, size_t dstSkip) {
+    CHECK_EQ(mDstFormat, OMX_COLOR_Format16bitRGB565);
+
+    switch (mSrcFormat) {
+        case OMX_COLOR_FormatYUV420Planar:
+            convertYUV420Planar(
+                    width, height, srcBits, srcSkip, dstBits, dstSkip);
+            break;
+
+        case OMX_COLOR_FormatCbYCrY:
+            convertCbYCrY(
+                    width, height, srcBits, srcSkip, dstBits, dstSkip);
+            break;
+
+        case OMX_QCOM_COLOR_FormatYVU420SemiPlanar:
+            convertQCOMYUV420SemiPlanar(
+                    width, height, srcBits, srcSkip, dstBits, dstSkip);
+            break;
+
+        default:
+        {
+            CHECK(!"Should not be here. Unknown color conversion.");
+            break;
+        }
+    }
+}
+
+void ColorConverter::convertCbYCrY(
+        size_t width, size_t height,
+        const void *srcBits, size_t srcSkip,
+        void *dstBits, size_t dstSkip) {
+    CHECK_EQ(srcSkip, 0);  // Doesn't really make sense for YUV formats.
+    CHECK(dstSkip >= width * 2);
+    CHECK((dstSkip & 3) == 0);
+
+    uint8_t *kAdjustedClip = initClip();
+
+    uint32_t *dst_ptr = (uint32_t *)dstBits;
+
+    const uint8_t *src = (const uint8_t *)srcBits;
+
+    for (size_t y = 0; y < height; ++y) {
+        for (size_t x = 0; x < width; x += 2) {
+            signed y1 = (signed)src[2 * x + 1] - 16;
+            signed y2 = (signed)src[2 * x + 3] - 16;
+            signed u = (signed)src[2 * x] - 128;
+            signed v = (signed)src[2 * x + 2] - 128;
+
+            signed u_b = u * 517;
+            signed u_g = -u * 100;
+            signed v_g = -v * 208;
+            signed v_r = v * 409;
+
+            signed tmp1 = y1 * 298;
+            signed b1 = (tmp1 + u_b) / 256;
+            signed g1 = (tmp1 + v_g + u_g) / 256;
+            signed r1 = (tmp1 + v_r) / 256;
+
+            signed tmp2 = y2 * 298;
+            signed b2 = (tmp2 + u_b) / 256;
+            signed g2 = (tmp2 + v_g + u_g) / 256;
+            signed r2 = (tmp2 + v_r) / 256;
+
+            uint32_t rgb1 =
+                ((kAdjustedClip[r1] >> 3) << 11)
+                | ((kAdjustedClip[g1] >> 2) << 5)
+                | (kAdjustedClip[b1] >> 3);
+
+            uint32_t rgb2 =
+                ((kAdjustedClip[r2] >> 3) << 11)
+                | ((kAdjustedClip[g2] >> 2) << 5)
+                | (kAdjustedClip[b2] >> 3);
+
+            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
+        }
+
+        src += width * 2;
+        dst_ptr += dstSkip / 4;
+    }
+}
+
+void ColorConverter::convertYUV420Planar(
+        size_t width, size_t height,
+        const void *srcBits, size_t srcSkip,
+        void *dstBits, size_t dstSkip) {
+    CHECK_EQ(srcSkip, 0);  // Doesn't really make sense for YUV formats.
+    CHECK(dstSkip >= width * 2);
+    CHECK((dstSkip & 3) == 0);
+
+    uint8_t *kAdjustedClip = initClip();
+
+    uint32_t *dst_ptr = (uint32_t *)dstBits;
+    const uint8_t *src_y = (const uint8_t *)srcBits;
+
+    const uint8_t *src_u =
+        (const uint8_t *)src_y + width * height;
+
+    const uint8_t *src_v =
+        (const uint8_t *)src_u + (width / 2) * (height / 2);
+
+    for (size_t y = 0; y < height; ++y) {
+        for (size_t x = 0; x < width; x += 2) {
+            // B = 1.164 * (Y - 16) + 2.018 * (U - 128)
+            // G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128)
+            // R = 1.164 * (Y - 16) + 1.596 * (V - 128)
+
+            // B = 298/256 * (Y - 16) + 517/256 * (U - 128)
+            // G = .................. - 208/256 * (V - 128) - 100/256 * (U - 128)
+            // R = .................. + 409/256 * (V - 128)
+
+            // min_B = (298 * (- 16) + 517 * (- 128)) / 256 = -277
+            // min_G = (298 * (- 16) - 208 * (255 - 128) - 100 * (255 - 128)) / 256 = -172
+            // min_R = (298 * (- 16) + 409 * (- 128)) / 256 = -223
+
+            // max_B = (298 * (255 - 16) + 517 * (255 - 128)) / 256 = 534
+            // max_G = (298 * (255 - 16) - 208 * (- 128) - 100 * (- 128)) / 256 = 432
+            // max_R = (298 * (255 - 16) + 409 * (255 - 128)) / 256 = 481
+
+            // clip range -278 .. 535
+
+            signed y1 = (signed)src_y[x] - 16;
+            signed y2 = (signed)src_y[x + 1] - 16;
+
+            signed u = (signed)src_u[x / 2] - 128;
+            signed v = (signed)src_v[x / 2] - 128;
+
+            signed u_b = u * 517;
+            signed u_g = -u * 100;
+            signed v_g = -v * 208;
+            signed v_r = v * 409;
+
+            signed tmp1 = y1 * 298;
+            signed b1 = (tmp1 + u_b) / 256;
+            signed g1 = (tmp1 + v_g + u_g) / 256;
+            signed r1 = (tmp1 + v_r) / 256;
+
+            signed tmp2 = y2 * 298;
+            signed b2 = (tmp2 + u_b) / 256;
+            signed g2 = (tmp2 + v_g + u_g) / 256;
+            signed r2 = (tmp2 + v_r) / 256;
+
+            uint32_t rgb1 =
+                ((kAdjustedClip[r1] >> 3) << 11)
+                | ((kAdjustedClip[g1] >> 2) << 5)
+                | (kAdjustedClip[b1] >> 3);
+
+            uint32_t rgb2 =
+                ((kAdjustedClip[r2] >> 3) << 11)
+                | ((kAdjustedClip[g2] >> 2) << 5)
+                | (kAdjustedClip[b2] >> 3);
+
+            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
+        }
+
+        src_y += width;
+
+        if (y & 1) {
+            src_u += width / 2;
+            src_v += width / 2;
+        }
+
+        dst_ptr += dstSkip / 4;
+    }
+}
+
+void ColorConverter::convertQCOMYUV420SemiPlanar(
+        size_t width, size_t height,
+        const void *srcBits, size_t srcSkip,
+        void *dstBits, size_t dstSkip) {
+    CHECK_EQ(srcSkip, 0);  // Doesn't really make sense for YUV formats.
+    CHECK(dstSkip >= width * 2);
+    CHECK((dstSkip & 3) == 0);
+
+    uint8_t *kAdjustedClip = initClip();
+
+    uint32_t *dst_ptr = (uint32_t *)dstBits;
+    const uint8_t *src_y = (const uint8_t *)srcBits;
+
+    const uint8_t *src_u =
+        (const uint8_t *)src_y + width * height;
+
+    for (size_t y = 0; y < height; ++y) {
+        for (size_t x = 0; x < width; x += 2) {
+            signed y1 = (signed)src_y[x] - 16;
+            signed y2 = (signed)src_y[x + 1] - 16;
+
+            signed u = (signed)src_u[x & ~1] - 128;
+            signed v = (signed)src_u[(x & ~1) + 1] - 128;
+
+            signed u_b = u * 517;
+            signed u_g = -u * 100;
+            signed v_g = -v * 208;
+            signed v_r = v * 409;
+
+            signed tmp1 = y1 * 298;
+            signed b1 = (tmp1 + u_b) / 256;
+            signed g1 = (tmp1 + v_g + u_g) / 256;
+            signed r1 = (tmp1 + v_r) / 256;
+
+            signed tmp2 = y2 * 298;
+            signed b2 = (tmp2 + u_b) / 256;
+            signed g2 = (tmp2 + v_g + u_g) / 256;
+            signed r2 = (tmp2 + v_r) / 256;
+
+            uint32_t rgb1 =
+                ((kAdjustedClip[b1] >> 3) << 11)
+                | ((kAdjustedClip[g1] >> 2) << 5)
+                | (kAdjustedClip[r1] >> 3);
+
+            uint32_t rgb2 =
+                ((kAdjustedClip[b2] >> 3) << 11)
+                | ((kAdjustedClip[g2] >> 2) << 5)
+                | (kAdjustedClip[r2] >> 3);
+
+            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
+        }
+
+        src_y += width;
+
+        if (y & 1) {
+            src_u += width;
+        }
+
+        dst_ptr += dstSkip / 4;
+    }
+}
+
+uint8_t *ColorConverter::initClip() {
+    static const signed kClipMin = -278;
+    static const signed kClipMax = 535;
+
+    if (mClip == NULL) {
+        mClip = new uint8_t[kClipMax - kClipMin + 1];
+
+        for (signed i = kClipMin; i <= kClipMax; ++i) {
+            mClip[i - kClipMin] = (i < 0) ? 0 : (i > 255) ? 255 : (uint8_t)i;
+        }
+    }
+
+    return &mClip[-kClipMin];
+}
+
+}  // namespace android
diff --git a/media/libstagefright/colorconversion/SoftwareRenderer.cpp b/media/libstagefright/colorconversion/SoftwareRenderer.cpp
new file mode 100644
index 0000000..ef6ede0
--- /dev/null
+++ b/media/libstagefright/colorconversion/SoftwareRenderer.cpp
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "SoftwareRenderer"
+#include <utils/Log.h>
+
+#include "../include/SoftwareRenderer.h"
+
+#include <binder/MemoryHeapBase.h>
+#include <media/stagefright/MediaDebug.h>
+#include <ui/ISurface.h>
+
+namespace android {
+
+SoftwareRenderer::SoftwareRenderer(
+        OMX_COLOR_FORMATTYPE colorFormat,
+        const sp<ISurface> &surface,
+        size_t displayWidth, size_t displayHeight,
+        size_t decodedWidth, size_t decodedHeight)
+    : mColorFormat(colorFormat),
+      mConverter(colorFormat, OMX_COLOR_Format16bitRGB565),
+      mISurface(surface),
+      mDisplayWidth(displayWidth),
+      mDisplayHeight(displayHeight),
+      mDecodedWidth(decodedWidth),
+      mDecodedHeight(decodedHeight),
+      mFrameSize(mDecodedWidth * mDecodedHeight * 2),  // RGB565
+      mMemoryHeap(new MemoryHeapBase(2 * mFrameSize)),
+      mIndex(0) {
+    CHECK(mISurface.get() != NULL);
+    CHECK(mDecodedWidth > 0);
+    CHECK(mDecodedHeight > 0);
+    CHECK(mMemoryHeap->heapID() >= 0);
+    CHECK(mConverter.isValid());
+
+    ISurface::BufferHeap bufferHeap(
+            mDisplayWidth, mDisplayHeight,
+            mDecodedWidth, mDecodedHeight,
+            PIXEL_FORMAT_RGB_565,
+            mMemoryHeap);
+
+    status_t err = mISurface->registerBuffers(bufferHeap);
+    CHECK_EQ(err, OK);
+}
+
+SoftwareRenderer::~SoftwareRenderer() {
+    mISurface->unregisterBuffers();
+}
+
+void SoftwareRenderer::render(
+        const void *data, size_t size, void *platformPrivate) {
+    size_t offset = mIndex * mFrameSize;
+    void *dst = (uint8_t *)mMemoryHeap->getBase() + offset;
+
+    mConverter.convert(
+            mDecodedWidth, mDecodedHeight,
+            data, 0, dst, 2 * mDecodedWidth);
+
+    mISurface->postBuffer(offset);
+    mIndex = 1 - mIndex;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/include/AACDecoder.h b/media/libstagefright/include/AACDecoder.h
new file mode 100644
index 0000000..f09addd
--- /dev/null
+++ b/media/libstagefright/include/AACDecoder.h
@@ -0,0 +1,62 @@
+/*
+ * 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 AAC_DECODER_H_
+
+#define AAC_DECODER_H_
+
+#include <media/stagefright/MediaSource.h>
+
+struct tPVMP4AudioDecoderExternal;
+
+namespace android {
+
+struct MediaBufferGroup;
+
+struct AACDecoder : public MediaSource {
+    AACDecoder(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 ~AACDecoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    MediaBufferGroup *mBufferGroup;
+
+    tPVMP4AudioDecoderExternal *mConfig;
+    void *mDecoderBuf;
+    int64_t mAnchorTimeUs;
+    int64_t mNumSamplesOutput;
+
+    MediaBuffer *mInputBuffer;
+
+    AACDecoder(const AACDecoder &);
+    AACDecoder &operator=(const AACDecoder &);
+};
+
+}  // namespace android
+
+#endif  // AAC_DECODER_H_
diff --git a/media/libstagefright/include/AMRExtractor.h b/media/libstagefright/include/AMRExtractor.h
new file mode 100644
index 0000000..1972a1c
--- /dev/null
+++ b/media/libstagefright/include/AMRExtractor.h
@@ -0,0 +1,54 @@
+/*
+ * 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_EXTRACTOR_H_
+
+#define AMR_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class String8;
+
+class AMRExtractor : public MediaExtractor {
+public:
+    AMRExtractor(const sp<DataSource> &source);
+
+    virtual size_t countTracks();
+    virtual sp<MediaSource> getTrack(size_t index);
+    virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
+
+protected:
+    virtual ~AMRExtractor();
+
+private:
+    sp<DataSource> mDataSource;
+    sp<MetaData> mMeta;
+    status_t mInitCheck;
+    size_t mFrameSize;
+    bool mIsWide;
+
+    AMRExtractor(const AMRExtractor &);
+    AMRExtractor &operator=(const AMRExtractor &);
+};
+
+bool SniffAMR(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // AMR_EXTRACTOR_H_
diff --git a/media/libstagefright/include/AMRNBDecoder.h b/media/libstagefright/include/AMRNBDecoder.h
new file mode 100644
index 0000000..cf24eda
--- /dev/null
+++ b/media/libstagefright/include/AMRNBDecoder.h
@@ -0,0 +1,59 @@
+/*
+ * 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_DECODER_H_
+
+#define AMR_NB_DECODER_H_
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+struct MediaBufferGroup;
+
+struct AMRNBDecoder : public MediaSource {
+    AMRNBDecoder(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 ~AMRNBDecoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    MediaBufferGroup *mBufferGroup;
+
+    void *mState;
+    int64_t mAnchorTimeUs;
+    int64_t mNumSamplesOutput;
+
+    MediaBuffer *mInputBuffer;
+
+    AMRNBDecoder(const AMRNBDecoder &);
+    AMRNBDecoder &operator=(const AMRNBDecoder &);
+};
+
+}  // namespace android
+
+#endif  // AMR_NB_DECODER_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_
diff --git a/media/libstagefright/include/AMRWBDecoder.h b/media/libstagefright/include/AMRWBDecoder.h
new file mode 100644
index 0000000..927c51c
--- /dev/null
+++ b/media/libstagefright/include/AMRWBDecoder.h
@@ -0,0 +1,62 @@
+/*
+ * 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_WB_DECODER_H_
+
+#define AMR_WB_DECODER_H_
+
+#include <media/stagefright/MediaSource.h>
+
+namespace android {
+
+struct MediaBufferGroup;
+
+struct AMRWBDecoder : public MediaSource {
+    AMRWBDecoder(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 ~AMRWBDecoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    MediaBufferGroup *mBufferGroup;
+
+    void *mState;
+    void *mDecoderBuf;
+    int16_t *mDecoderCookie;
+    int64_t mAnchorTimeUs;
+    int64_t mNumSamplesOutput;
+    int16_t mInputSampleBuffer[477];
+
+    MediaBuffer *mInputBuffer;
+
+    AMRWBDecoder(const AMRWBDecoder &);
+    AMRWBDecoder &operator=(const AMRWBDecoder &);
+};
+
+}  // namespace android
+
+#endif  // AMR_WB_DECODER_H_
diff --git a/media/libstagefright/include/AVCDecoder.h b/media/libstagefright/include/AVCDecoder.h
new file mode 100644
index 0000000..621aa9a
--- /dev/null
+++ b/media/libstagefright/include/AVCDecoder.h
@@ -0,0 +1,85 @@
+/*
+ * 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 AVC_DECODER_H_
+
+#define AVC_DECODER_H_
+
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaSource.h>
+#include <utils/Vector.h>
+
+struct tagAVCHandle;
+
+namespace android {
+
+struct AVCDecoder : public MediaSource,
+                    public MediaBufferObserver {
+    AVCDecoder(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);
+
+    virtual void signalBufferReturned(MediaBuffer *buffer);
+
+protected:
+    virtual ~AVCDecoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    sp<MetaData> mFormat;
+
+    Vector<MediaBuffer *> mCodecSpecificData;
+
+    tagAVCHandle *mHandle;
+    Vector<MediaBuffer *> mFrames;
+    MediaBuffer *mInputBuffer;
+
+    int64_t mAnchorTimeUs;
+    int64_t mNumSamplesOutput;
+    int64_t mPendingSeekTimeUs;
+
+    void addCodecSpecificData(const uint8_t *data, size_t size);
+
+    static int32_t ActivateSPSWrapper(
+            void *userData, unsigned int sizeInMbs, unsigned int numBuffers);
+
+    static int32_t BindFrameWrapper(
+            void *userData, int32_t index, uint8_t **yuv);
+
+    static void UnbindFrame(void *userData, int32_t index);
+
+    int32_t activateSPS(
+            unsigned int sizeInMbs, unsigned int numBuffers);
+
+    int32_t bindFrame(int32_t index, uint8_t **yuv);
+
+    void releaseFrames();
+
+    AVCDecoder(const AVCDecoder &);
+    AVCDecoder &operator=(const AVCDecoder &);
+};
+
+}  // namespace android
+
+#endif  // AVC_DECODER_H_
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
new file mode 100644
index 0000000..37b14eb
--- /dev/null
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -0,0 +1,143 @@
+/*
+ * 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 AWESOME_PLAYER_H_
+
+#define AWESOME_PLAYER_H_
+
+#include "TimedEventQueue.h"
+
+#include <media/MediaPlayerInterface.h>
+#include <media/stagefright/OMXClient.h>
+#include <utils/threads.h>
+
+namespace android {
+
+struct MediaBuffer;
+struct MediaExtractor;
+struct MediaSource;
+struct AudioPlayer;
+struct TimeSource;
+
+struct AwesomeRenderer : public RefBase {
+    AwesomeRenderer() {}
+
+    virtual void render(MediaBuffer *buffer) = 0;
+
+private:
+    AwesomeRenderer(const AwesomeRenderer &);
+    AwesomeRenderer &operator=(const AwesomeRenderer &);
+};
+
+struct AwesomePlayer {
+    AwesomePlayer();
+    ~AwesomePlayer();
+
+    void setListener(const sp<MediaPlayerBase> &listener);
+
+    status_t setDataSource(const char *uri);
+    status_t setDataSource(int fd, int64_t offset, int64_t length);
+
+    void reset();
+
+    status_t play();
+    status_t pause();
+
+    bool isPlaying() const;
+
+    void setISurface(const sp<ISurface> &isurface);
+    void setAudioSink(const sp<MediaPlayerBase::AudioSink> &audioSink);
+    status_t setLooping(bool shouldLoop);
+
+    status_t getDuration(int64_t *durationUs);
+    status_t getPosition(int64_t *positionUs);
+
+    status_t seekTo(int64_t timeUs);
+
+    status_t getVideoDimensions(int32_t *width, int32_t *height) const;
+
+private:
+    friend struct AwesomeEvent;
+
+    enum Flags {
+        PLAYING     = 1,
+        LOOPING     = 2,
+        FIRST_FRAME = 4,
+    };
+
+    mutable Mutex mLock;
+
+    OMXClient mClient;
+    TimedEventQueue mQueue;
+    sp<MediaPlayerBase> mListener;
+
+    sp<ISurface> mISurface;
+    sp<MediaPlayerBase::AudioSink> mAudioSink;
+
+    TimeSource *mTimeSource;
+
+    sp<MediaSource> mVideoSource;
+    sp<AwesomeRenderer> mVideoRenderer;
+
+    sp<MediaSource> mAudioSource;
+    AudioPlayer *mAudioPlayer;
+    int64_t mDurationUs;
+
+    uint32_t mFlags;
+
+    int32_t mVideoWidth, mVideoHeight;
+    int64_t mTimeSourceDeltaUs;
+    int64_t mVideoTimeUs;
+
+    bool mSeeking;
+    int64_t mSeekTimeUs;
+
+    sp<TimedEventQueue::Event> mVideoEvent;
+    bool mVideoEventPending;
+    sp<TimedEventQueue::Event> mStreamDoneEvent;
+    bool mStreamDoneEventPending;
+
+    void postVideoEvent_l(int64_t delayUs = -1);
+    void postStreamDoneEvent_l();
+
+    MediaBuffer *mLastVideoBuffer;
+    MediaBuffer *mVideoBuffer;
+
+    status_t setDataSource_l(const sp<MediaExtractor> &extractor);
+    void reset_l();
+    status_t seekTo_l(int64_t timeUs);
+    status_t pause_l();
+    void initRenderer_l();
+    void seekAudioIfNecessary_l();
+
+    void cancelPlayerEvents();
+
+    status_t setAudioSource(const sp<MediaSource> &source);
+    status_t setVideoSource(const sp<MediaSource> &source);
+
+    void onEvent(int32_t code);
+
+    static void AudioNotify(void *me, int what);
+    void onStreamDone();
+
+    AwesomePlayer(const AwesomePlayer &);
+    AwesomePlayer &operator=(const AwesomePlayer &);
+};
+
+}  // namespace android
+
+#endif  // AWESOME_PLAYER_H_
+
diff --git a/include/media/stagefright/ESDS.h b/media/libstagefright/include/ESDS.h
similarity index 100%
rename from include/media/stagefright/ESDS.h
rename to media/libstagefright/include/ESDS.h
diff --git a/media/libstagefright/include/HTTPStream.h b/media/libstagefright/include/HTTPStream.h
new file mode 100644
index 0000000..43ef614
--- /dev/null
+++ b/media/libstagefright/include/HTTPStream.h
@@ -0,0 +1,75 @@
+/*
+ * 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 HTTP_STREAM_H_
+
+#define HTTP_STREAM_H_
+
+#include "stagefright_string.h"
+
+#include <sys/types.h>
+
+#include <media/stagefright/MediaErrors.h>
+#include <utils/KeyedVector.h>
+
+namespace android {
+
+class HTTPStream {
+public:
+    HTTPStream();
+    ~HTTPStream();
+
+    status_t connect(const char *server, int port = 80);
+    status_t disconnect();
+
+    status_t send(const char *data, size_t size);
+
+    // Assumes data is a '\0' terminated string.
+    status_t send(const char *data);
+
+    // Receive up to "size" bytes of data.
+    ssize_t receive(void *data, size_t size);
+
+    status_t receive_header(int *http_status);
+
+    // The header key used to retrieve the status line.
+    static const char *kStatusKey;
+
+    bool find_header_value(
+            const string &key, string *value) const;
+
+private:
+    enum State {
+        READY,
+        CONNECTED
+    };
+
+    State mState;
+    int mSocket;
+
+    KeyedVector<string, string> mHeaders;
+
+    // Receive a line of data terminated by CRLF, line will be '\0' terminated
+    // _excluding_ the termianting CRLF.
+    status_t receive_line(char *line, size_t size);
+
+    HTTPStream(const HTTPStream &);
+    HTTPStream &operator=(const HTTPStream &);
+};
+
+}  // namespace android
+
+#endif  // HTTP_STREAM_H_
diff --git a/media/libstagefright/include/M4vH263Decoder.h b/media/libstagefright/include/M4vH263Decoder.h
new file mode 100644
index 0000000..880ec7c
--- /dev/null
+++ b/media/libstagefright/include/M4vH263Decoder.h
@@ -0,0 +1,66 @@
+/*
+ * 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 M4V_H263_DECODER_H_
+
+#define M4V_H263_DECODER_H_
+
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaSource.h>
+
+struct tagvideoDecControls;
+
+namespace android {
+
+struct M4vH263Decoder : public MediaSource,
+                        public MediaBufferObserver {
+    M4vH263Decoder(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);
+
+    virtual void signalBufferReturned(MediaBuffer *buffer);
+
+protected:
+    virtual ~M4vH263Decoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+    int32_t mWidth, mHeight;
+
+    sp<MetaData> mFormat;
+
+    tagvideoDecControls *mHandle;
+    MediaBuffer *mFrames[2];
+    MediaBuffer *mInputBuffer;
+
+    int64_t mNumSamplesOutput;
+
+    void releaseFrames();
+
+    M4vH263Decoder(const M4vH263Decoder &);
+    M4vH263Decoder &operator=(const M4vH263Decoder &);
+};
+
+}  // namespace android
+
+#endif  // M4V_H263_DECODER_H_
diff --git a/media/libstagefright/include/MP3Decoder.h b/media/libstagefright/include/MP3Decoder.h
new file mode 100644
index 0000000..88aa4c6
--- /dev/null
+++ b/media/libstagefright/include/MP3Decoder.h
@@ -0,0 +1,62 @@
+/*
+ * 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 MP3_DECODER_H_
+
+#define MP3_DECODER_H_
+
+#include <media/stagefright/MediaSource.h>
+
+struct tPVMP3DecoderExternal;
+
+namespace android {
+
+struct MediaBufferGroup;
+
+struct MP3Decoder : public MediaSource {
+    MP3Decoder(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 ~MP3Decoder();
+
+private:
+    sp<MediaSource> mSource;
+    bool mStarted;
+
+    MediaBufferGroup *mBufferGroup;
+
+    tPVMP3DecoderExternal *mConfig;
+    void *mDecoderBuf;
+    int64_t mAnchorTimeUs;
+    int64_t mNumSamplesOutput;
+
+    MediaBuffer *mInputBuffer;
+
+    MP3Decoder(const MP3Decoder &);
+    MP3Decoder &operator=(const MP3Decoder &);
+};
+
+}  // namespace android
+
+#endif  // MP3_DECODER_H_
diff --git a/media/libstagefright/include/MP3Extractor.h b/media/libstagefright/include/MP3Extractor.h
new file mode 100644
index 0000000..b5a6b3c
--- /dev/null
+++ b/media/libstagefright/include/MP3Extractor.h
@@ -0,0 +1,57 @@
+/*
+ * 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 MP3_EXTRACTOR_H_
+
+#define MP3_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class DataSource;
+class String8;
+
+class MP3Extractor : public MediaExtractor {
+public:
+    // Extractor assumes ownership of "source".
+    MP3Extractor(const sp<DataSource> &source);
+
+    virtual size_t countTracks();
+    virtual sp<MediaSource> getTrack(size_t index);
+    virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
+
+protected:
+    virtual ~MP3Extractor();
+
+private:
+    sp<DataSource> mDataSource;
+    off_t mFirstFramePos;
+    sp<MetaData> mMeta;
+    uint32_t mFixedHeader;
+    int32_t mByteNumber; // total number of bytes in this MP3
+    char mTableOfContents[99]; // TOC entries in XING header
+
+    MP3Extractor(const MP3Extractor &);
+    MP3Extractor &operator=(const MP3Extractor &);
+};
+
+bool SniffMP3(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // MP3_EXTRACTOR_H_
diff --git a/media/libstagefright/include/MPEG4Extractor.h b/media/libstagefright/include/MPEG4Extractor.h
new file mode 100644
index 0000000..ce4736d
--- /dev/null
+++ b/media/libstagefright/include/MPEG4Extractor.h
@@ -0,0 +1,69 @@
+/*
+ * 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 MPEG4_EXTRACTOR_H_
+
+#define MPEG4_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class DataSource;
+class SampleTable;
+class String8;
+
+class MPEG4Extractor : public MediaExtractor {
+public:
+    // Extractor assumes ownership of "source".
+    MPEG4Extractor(const sp<DataSource> &source);
+
+    size_t countTracks();
+    sp<MediaSource> getTrack(size_t index);
+    sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
+
+protected:
+    virtual ~MPEG4Extractor();
+
+private:
+    struct Track {
+        Track *next;
+        sp<MetaData> meta;
+        uint32_t timescale;
+        sp<SampleTable> sampleTable;
+        bool includes_expensive_metadata;
+    };
+
+    sp<DataSource> mDataSource;
+    bool mHaveMetadata;
+
+    Track *mFirstTrack, *mLastTrack;
+
+    uint32_t mHandlerType;
+
+    status_t readMetaData();
+    status_t parseChunk(off_t *offset, int depth);
+
+    MPEG4Extractor(const MPEG4Extractor &);
+    MPEG4Extractor &operator=(const MPEG4Extractor &);
+};
+
+bool SniffMPEG4(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // MPEG4_EXTRACTOR_H_
diff --git a/media/libstagefright/include/OMX.h b/media/libstagefright/include/OMX.h
index d0bd61e..ce0b0d5 100644
--- a/media/libstagefright/include/OMX.h
+++ b/media/libstagefright/include/OMX.h
@@ -23,6 +23,7 @@
 
 namespace android {
 
+struct OMXMaster;
 class OMXNodeInstance;
 
 class OMX : public BnOMX,
@@ -30,7 +31,7 @@
 public:
     OMX();
 
-    virtual status_t listNodes(List<String8> *list);
+    virtual status_t listNodes(List<ComponentInfo> *list);
 
     virtual status_t allocateNode(
             const char *name, const sp<IOMXObserver> &observer, node_id *node);
@@ -99,7 +100,7 @@
             OMX_IN OMX_U32 nData1,
             OMX_IN OMX_U32 nData2,
             OMX_IN OMX_PTR pEventData);
-
+        
     OMX_ERRORTYPE OnEmptyBufferDone(
             node_id node, OMX_IN OMX_BUFFERHEADERTYPE *pBuffer);
 
@@ -108,9 +109,14 @@
 
     void invalidateNodeID(node_id node);
 
+protected:
+    virtual ~OMX();
+
 private:
     Mutex mLock;
 
+    OMXMaster *mMaster;
+
     struct CallbackDispatcher;
     sp<CallbackDispatcher> mDispatcher;
 
diff --git a/media/libstagefright/include/OMXNodeInstance.h b/media/libstagefright/include/OMXNodeInstance.h
index 09a8816..923b801 100644
--- a/media/libstagefright/include/OMXNodeInstance.h
+++ b/media/libstagefright/include/OMXNodeInstance.h
@@ -26,6 +26,7 @@
 namespace android {
 
 class IOMXObserver;
+struct OMXMaster;
 
 struct OMXNodeInstance {
     OMXNodeInstance(
@@ -37,7 +38,7 @@
     sp<IOMXObserver> observer();
     OMX::node_id nodeID();
 
-    status_t freeNode();
+    status_t freeNode(OMXMaster *master);
 
     status_t sendCommand(OMX_COMMANDTYPE cmd, OMX_S32 param);
     status_t getParameter(OMX_INDEXTYPE index, void *params, size_t size);
@@ -72,7 +73,7 @@
             const char *parameterName, OMX_INDEXTYPE *index);
 
     void onMessage(const omx_message &msg);
-    void onObserverDied();
+    void onObserverDied(OMXMaster *master);
     void onGetHandleFailed();
 
     static OMX_CALLBACKTYPE kCallbacks;
@@ -84,6 +85,7 @@
     OMX::node_id mNodeID;
     OMX_HANDLETYPE mHandle;
     sp<IOMXObserver> mObserver;
+    bool mDying;
 
     struct ActiveBuffer {
         OMX_U32 mPortIndex;
diff --git a/media/libstagefright/include/SampleTable.h b/media/libstagefright/include/SampleTable.h
new file mode 100644
index 0000000..ead3431
--- /dev/null
+++ b/media/libstagefright/include/SampleTable.h
@@ -0,0 +1,111 @@
+/*
+ * 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 SAMPLE_TABLE_H_
+
+#define SAMPLE_TABLE_H_
+
+#include <sys/types.h>
+#include <stdint.h>
+
+#include <media/stagefright/MediaErrors.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class DataSource;
+
+class SampleTable : public RefBase {
+public:
+    SampleTable(const sp<DataSource> &source);
+
+    // type can be 'stco' or 'co64'.
+    status_t setChunkOffsetParams(
+            uint32_t type, off_t data_offset, size_t data_size);
+
+    status_t setSampleToChunkParams(off_t data_offset, size_t data_size);
+
+    // type can be 'stsz' or 'stz2'.
+    status_t setSampleSizeParams(
+            uint32_t type, off_t data_offset, size_t data_size);
+
+    status_t setTimeToSampleParams(off_t data_offset, size_t data_size);
+
+    status_t setSyncSampleParams(off_t data_offset, size_t data_size);
+
+    ////////////////////////////////////////////////////////////////////////////
+
+    uint32_t countChunkOffsets() const;
+    status_t getChunkOffset(uint32_t chunk_index, off_t *offset);
+
+    status_t getChunkForSample(
+            uint32_t sample_index, uint32_t *chunk_index,
+            uint32_t *chunk_relative_sample_index, uint32_t *desc_index);
+
+    uint32_t countSamples() const;
+    status_t getSampleSize(uint32_t sample_index, size_t *sample_size);
+
+    status_t getSampleOffsetAndSize(
+            uint32_t sample_index, off_t *offset, size_t *size);
+
+    status_t getMaxSampleSize(size_t *size);
+
+    status_t getDecodingTime(uint32_t sample_index, uint32_t *time);
+
+    enum {
+        kSyncSample_Flag = 1
+    };
+    status_t findClosestSample(
+            uint32_t req_time, uint32_t *sample_index, uint32_t flags);
+
+    status_t findClosestSyncSample(
+            uint32_t start_sample_index, uint32_t *sample_index);
+
+    status_t findThumbnailSample(uint32_t *sample_index);
+
+protected:
+    ~SampleTable();
+
+private:
+    sp<DataSource> mDataSource;
+    Mutex mLock;
+
+    off_t mChunkOffsetOffset;
+    uint32_t mChunkOffsetType;
+    uint32_t mNumChunkOffsets;
+
+    off_t mSampleToChunkOffset;
+    uint32_t mNumSampleToChunkOffsets;
+
+    off_t mSampleSizeOffset;
+    uint32_t mSampleSizeFieldSize;
+    uint32_t mDefaultSampleSize;
+    uint32_t mNumSampleSizes;
+
+    uint32_t mTimeToSampleCount;
+    uint32_t *mTimeToSample;
+
+    off_t mSyncSampleOffset;
+    uint32_t mNumSyncSamples;
+
+    SampleTable(const SampleTable &);
+    SampleTable &operator=(const SampleTable &);
+};
+
+}  // namespace android
+
+#endif  // SAMPLE_TABLE_H_
diff --git a/media/libstagefright/include/SoftwareRenderer.h b/media/libstagefright/include/SoftwareRenderer.h
new file mode 100644
index 0000000..9eed089
--- /dev/null
+++ b/media/libstagefright/include/SoftwareRenderer.h
@@ -0,0 +1,59 @@
+/*
+ * 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 SOFTWARE_RENDERER_H_
+
+#define SOFTWARE_RENDERER_H_
+
+#include <media/stagefright/ColorConverter.h>
+#include <media/stagefright/VideoRenderer.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+class ISurface;
+class MemoryHeapBase;
+
+class SoftwareRenderer : public VideoRenderer {
+public:
+    SoftwareRenderer(
+            OMX_COLOR_FORMATTYPE colorFormat,
+            const sp<ISurface> &surface,
+            size_t displayWidth, size_t displayHeight,
+            size_t decodedWidth, size_t decodedHeight);
+
+    virtual ~SoftwareRenderer();
+
+    virtual void render(
+            const void *data, size_t size, void *platformPrivate);
+
+private:
+    OMX_COLOR_FORMATTYPE mColorFormat;
+    ColorConverter mConverter;
+    sp<ISurface> mISurface;
+    size_t mDisplayWidth, mDisplayHeight;
+    size_t mDecodedWidth, mDecodedHeight;
+    size_t mFrameSize;
+    sp<MemoryHeapBase> mMemoryHeap;
+    int mIndex;
+
+    SoftwareRenderer(const SoftwareRenderer &);
+    SoftwareRenderer &operator=(const SoftwareRenderer &);
+};
+
+}  // namespace android
+
+#endif  // SOFTWARE_RENDERER_H_
diff --git a/media/libstagefright/include/TimedEventQueue.h b/media/libstagefright/include/TimedEventQueue.h
new file mode 100644
index 0000000..21eade3
--- /dev/null
+++ b/media/libstagefright/include/TimedEventQueue.h
@@ -0,0 +1,130 @@
+/*
+ * 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 TIMED_EVENT_QUEUE_H_
+
+#define TIMED_EVENT_QUEUE_H_
+
+#include <pthread.h>
+
+#include <utils/List.h>
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+struct TimedEventQueue {
+
+    typedef int32_t event_id;
+
+    struct Event : public RefBase {
+        Event()
+            : mEventID(0) {
+        }
+
+        virtual ~Event() {}
+
+        event_id eventID() {
+            return mEventID;
+        }
+
+    protected:
+        virtual void fire(TimedEventQueue *queue, int64_t now_us) = 0;
+
+    private:
+        friend class TimedEventQueue;
+
+        event_id mEventID;
+
+        void setEventID(event_id id) {
+            mEventID = id;
+        }
+
+        Event(const Event &);
+        Event &operator=(const Event &);
+    };
+
+    TimedEventQueue();
+    ~TimedEventQueue();
+
+    // Start executing the event loop.
+    void start();
+
+    // Stop executing the event loop, if flush is false, any pending
+    // events are discarded, otherwise the queue will stop (and this call
+    // return) once all pending events have been handled.
+    void stop(bool flush = false);
+
+    // Posts an event to the front of the queue (after all events that
+    // have previously been posted to the front but before timed events).
+    event_id postEvent(const sp<Event> &event);
+
+    event_id postEventToBack(const sp<Event> &event);
+
+    // It is an error to post an event with a negative delay.
+    event_id postEventWithDelay(const sp<Event> &event, int64_t delay_us);
+
+    // If the event is to be posted at a time that has already passed,
+    // it will fire as soon as possible.
+    event_id postTimedEvent(const sp<Event> &event, int64_t realtime_us);
+
+    // Returns true iff event is currently in the queue and has been
+    // successfully cancelled. In this case the event will have been
+    // removed from the queue and won't fire.
+    bool cancelEvent(event_id id);
+
+    // Cancel any pending event that satisfies the predicate.
+    // If stopAfterFirstMatch is true, only cancels the first event
+    // satisfying the predicate (if any).
+    void cancelEvents(
+            bool (*predicate)(void *cookie, const sp<Event> &event),
+            void *cookie,
+            bool stopAfterFirstMatch = false);
+
+    static int64_t getRealTimeUs();
+
+private:
+    struct QueueItem {
+        sp<Event> event;
+        int64_t realtime_us;
+    };
+
+    struct StopEvent : public TimedEventQueue::Event {
+        virtual void fire(TimedEventQueue *queue, int64_t now_us) {
+            queue->mStopped = true;
+        }
+    };
+
+    pthread_t mThread;
+    List<QueueItem> mQueue;
+    Mutex mLock;
+    Condition mQueueNotEmptyCondition;
+    Condition mQueueHeadChangedCondition;
+    event_id mNextEventID;
+
+    bool mRunning;
+    bool mStopped;
+
+    static void *ThreadWrapper(void *me);
+    void threadEntry();
+
+    TimedEventQueue(const TimedEventQueue &);
+    TimedEventQueue &operator=(const TimedEventQueue &);
+};
+
+}  // namespace android
+
+#endif  // TIMED_EVENT_QUEUE_H_
diff --git a/media/libstagefright/include/WAVExtractor.h b/media/libstagefright/include/WAVExtractor.h
new file mode 100644
index 0000000..10b9700
--- /dev/null
+++ b/media/libstagefright/include/WAVExtractor.h
@@ -0,0 +1,61 @@
+/*
+ * 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 WAV_EXTRACTOR_H_
+
+#define WAV_EXTRACTOR_H_
+
+#include <media/stagefright/MediaExtractor.h>
+
+namespace android {
+
+class DataSource;
+class String8;
+
+class WAVExtractor : public MediaExtractor {
+public:
+    // Extractor assumes ownership of "source".
+    WAVExtractor(const sp<DataSource> &source);
+
+    virtual size_t countTracks();
+    virtual sp<MediaSource> getTrack(size_t index);
+    virtual sp<MetaData> getTrackMetaData(size_t index, uint32_t flags);
+
+protected:
+    virtual ~WAVExtractor();
+
+private:
+    sp<DataSource> mDataSource;
+    status_t mInitCheck;
+    bool mValidFormat;
+    uint16_t mNumChannels;
+    uint32_t mSampleRate;
+    off_t mDataOffset;
+    size_t mDataSize;
+
+    status_t init();
+
+    WAVExtractor(const WAVExtractor &);
+    WAVExtractor &operator=(const WAVExtractor &);
+};
+
+bool SniffWAV(
+        const sp<DataSource> &source, String8 *mimeType, float *confidence);
+
+}  // namespace android
+
+#endif  // WAV_EXTRACTOR_H_
+
diff --git a/media/libstagefright/include/stagefright_string.h b/media/libstagefright/include/stagefright_string.h
new file mode 100644
index 0000000..5dc7116
--- /dev/null
+++ b/media/libstagefright/include/stagefright_string.h
@@ -0,0 +1,54 @@
+/*
+ * 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 STRING_H_
+
+#define STRING_H_
+
+#include <utils/String8.h>
+
+namespace android {
+
+class string {
+public:
+    typedef size_t size_type;
+    static size_type npos;
+
+    string();
+    string(const char *s);
+    string(const char *s, size_t length);
+    string(const string &from, size_type start, size_type length = npos);
+
+    const char *c_str() const;
+    size_type size() const;
+
+    void clear();
+    void erase(size_type from, size_type length);
+
+    size_type find(char c) const;
+
+    bool operator<(const string &other) const;
+    bool operator==(const string &other) const;
+
+    string &operator+=(char c);
+
+private:
+    String8 mString;
+};
+
+}  // namespace android
+
+#endif  // STRING_H_
diff --git a/media/libstagefright/omx/Android.mk b/media/libstagefright/omx/Android.mk
index 25da813..2473731 100644
--- a/media/libstagefright/omx/Android.mk
+++ b/media/libstagefright/omx/Android.mk
@@ -8,10 +8,18 @@
 
 LOCAL_C_INCLUDES += $(JNI_H_INCLUDE)
 
-LOCAL_SRC_FILES:=                 \
-	OMX.cpp                   \
-        OMXNodeInstance.cpp       \
-        SoftwareRenderer.cpp
+LOCAL_SRC_FILES:=                     \
+	OMX.cpp                       \
+        OMXComponentBase.cpp          \
+        OMXNodeInstance.cpp           \
+        OMXMaster.cpp
+
+ifneq ($(BUILD_WITHOUT_PV),true)
+LOCAL_SRC_FILES += \
+        OMXPVCodecsPlugin.cpp
+else
+LOCAL_CFLAGS += -DNO_OPENCORE
+endif
 
 LOCAL_SHARED_LIBRARIES :=       \
         libbinder               \
@@ -19,7 +27,12 @@
         libutils                \
         libui                   \
         libcutils               \
+        libstagefright_color_conversion
+
+ifneq ($(BUILD_WITHOUT_PV),true)
+LOCAL_SHARED_LIBRARIES += \
         libopencore_common
+endif
 
 ifeq ($(TARGET_OS)-$(TARGET_SIMULATOR),linux-true)
         LOCAL_LDLIBS += -lpthread -ldl
@@ -34,3 +47,6 @@
 LOCAL_MODULE:= libstagefright_omx
 
 include $(BUILD_SHARED_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
+
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
index 4ccd4bd..8c3f252 100644
--- a/media/libstagefright/omx/OMX.cpp
+++ b/media/libstagefright/omx/OMX.cpp
@@ -18,18 +18,20 @@
 #define LOG_TAG "OMX"
 #include <utils/Log.h>
 
+#include <dlfcn.h>
+
 #include "../include/OMX.h"
 #include "OMXRenderer.h"
 
-#include "pv_omxcore.h"
-
 #include "../include/OMXNodeInstance.h"
+#include "../include/SoftwareRenderer.h"
 
 #include <binder/IMemory.h>
 #include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/SoftwareRenderer.h>
 #include <media/stagefright/VideoRenderer.h>
 
+#include "OMXMaster.h"
+
 #include <OMX_Component.h>
 
 namespace android {
@@ -178,10 +180,16 @@
 };
 
 OMX::OMX()
-    : mDispatcher(new CallbackDispatcher(this)),
+    : mMaster(new OMXMaster),
+      mDispatcher(new CallbackDispatcher(this)),
       mNodeCounter(0) {
 }
 
+OMX::~OMX() {
+    delete mMaster;
+    mMaster = NULL;
+}
+
 void OMX::binderDied(const wp<IBinder> &the_late_who) {
     OMXNodeInstance *instance;
 
@@ -197,19 +205,30 @@
         invalidateNodeID_l(instance->nodeID());
     }
 
-    instance->onObserverDied();
+    instance->onObserverDied(mMaster);
 }
 
-status_t OMX::listNodes(List<String8> *list) {
-    OMX_MasterInit();  // XXX Put this somewhere else.
-
+status_t OMX::listNodes(List<ComponentInfo> *list) {
     list->clear();
 
     OMX_U32 index = 0;
     char componentName[256];
-    while (OMX_MasterComponentNameEnum(componentName, sizeof(componentName), index)
-               == OMX_ErrorNone) {
-        list->push_back(String8(componentName));
+    while (mMaster->enumerateComponents(
+                componentName, sizeof(componentName), index) == OMX_ErrorNone) {
+        list->push_back(ComponentInfo());
+        ComponentInfo &info = *--list->end();
+
+        info.mName = componentName;
+
+        Vector<String8> roles;
+        OMX_ERRORTYPE err =
+            mMaster->getRolesOfComponent(componentName, &roles);
+
+        if (err == OMX_ErrorNone) {
+            for (OMX_U32 i = 0; i < roles.size(); ++i) {
+                info.mRoles.push_back(roles[i]);
+            }
+        }
 
         ++index;
     }
@@ -223,17 +242,15 @@
 
     *node = 0;
 
-    OMX_MasterInit();  // XXX Put this somewhere else.
-
     OMXNodeInstance *instance = new OMXNodeInstance(this, observer);
 
-    OMX_HANDLETYPE handle;
-    OMX_ERRORTYPE err = OMX_MasterGetHandle(
-            &handle, const_cast<char *>(name), instance,
-            &OMXNodeInstance::kCallbacks);
+    OMX_COMPONENTTYPE *handle;
+    OMX_ERRORTYPE err = mMaster->makeComponentInstance(
+            name, &OMXNodeInstance::kCallbacks,
+            instance, &handle);
 
     if (err != OMX_ErrorNone) {
-        LOGE("FAILED to allocate omx component '%s'", name);
+        LOGV("FAILED to allocate omx component '%s'", name);
 
         instance->onGetHandleFailed();
 
@@ -258,7 +275,7 @@
     mLiveNodes.removeItemsAt(index);
     instance->observer()->asBinder()->unlinkToDeath(this);
 
-    return instance->freeNode();
+    return instance->freeNode(mMaster);
 }
 
 status_t OMX::sendCommand(
diff --git a/media/libstagefright/omx/OMXComponentBase.cpp b/media/libstagefright/omx/OMXComponentBase.cpp
new file mode 100644
index 0000000..35227a0
--- /dev/null
+++ b/media/libstagefright/omx/OMXComponentBase.cpp
@@ -0,0 +1,201 @@
+/*
+ * 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 "OMXComponentBase.h"
+
+#include <stdlib.h>
+
+#include <media/stagefright/MediaDebug.h>
+
+namespace android {
+
+OMXComponentBase::OMXComponentBase(
+        const OMX_CALLBACKTYPE *callbacks,
+        OMX_PTR appData)
+    : mCallbacks(callbacks),
+      mAppData(appData),
+      mComponentHandle(NULL) {
+}
+
+OMXComponentBase::~OMXComponentBase() {}
+
+void OMXComponentBase::setComponentHandle(OMX_COMPONENTTYPE *handle) {
+    CHECK_EQ(mComponentHandle, NULL);
+    mComponentHandle = handle;
+}
+
+void OMXComponentBase::postEvent(
+        OMX_EVENTTYPE event, OMX_U32 param1, OMX_U32 param2) {
+    (*mCallbacks->EventHandler)(
+            mComponentHandle, mAppData, event, param1, param2, NULL);
+}
+
+void OMXComponentBase::postFillBufferDone(OMX_BUFFERHEADERTYPE *bufHdr) {
+    (*mCallbacks->FillBufferDone)(mComponentHandle, mAppData, bufHdr);
+}
+
+void OMXComponentBase::postEmptyBufferDone(OMX_BUFFERHEADERTYPE *bufHdr) {
+    (*mCallbacks->EmptyBufferDone)(mComponentHandle, mAppData, bufHdr);
+}
+
+static OMXComponentBase *getBase(OMX_HANDLETYPE hComponent) {
+    return (OMXComponentBase *)
+        ((OMX_COMPONENTTYPE *)hComponent)->pComponentPrivate;
+}
+
+static OMX_ERRORTYPE SendCommandWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_COMMANDTYPE Cmd,
+        OMX_IN  OMX_U32 nParam1,
+        OMX_IN  OMX_PTR pCmdData) {
+    return getBase(hComponent)->sendCommand(Cmd, nParam1, pCmdData);
+}
+
+static OMX_ERRORTYPE GetParameterWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent, 
+        OMX_IN  OMX_INDEXTYPE nParamIndex,  
+        OMX_INOUT OMX_PTR pComponentParameterStructure) {
+    return getBase(hComponent)->getParameter(
+            nParamIndex, pComponentParameterStructure);
+}
+
+static OMX_ERRORTYPE SetParameterWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent, 
+        OMX_IN  OMX_INDEXTYPE nIndex,
+        OMX_IN  OMX_PTR pComponentParameterStructure) {
+    return getBase(hComponent)->getParameter(
+            nIndex, pComponentParameterStructure);
+}
+
+static OMX_ERRORTYPE GetConfigWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_INDEXTYPE nIndex, 
+        OMX_INOUT OMX_PTR pComponentConfigStructure) {
+    return getBase(hComponent)->getConfig(nIndex, pComponentConfigStructure);
+}
+
+static OMX_ERRORTYPE SetConfigWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_INDEXTYPE nIndex, 
+        OMX_IN  OMX_PTR pComponentConfigStructure) {
+    return getBase(hComponent)->setConfig(nIndex, pComponentConfigStructure);
+}
+
+static OMX_ERRORTYPE GetExtensionIndexWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_STRING cParameterName,
+        OMX_OUT OMX_INDEXTYPE* pIndexType) {
+    return getBase(hComponent)->getExtensionIndex(cParameterName, pIndexType);
+}
+
+static OMX_ERRORTYPE GetStateWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_OUT OMX_STATETYPE* pState) {
+    return getBase(hComponent)->getState(pState);
+}
+
+static OMX_ERRORTYPE UseBufferWrapper(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_INOUT OMX_BUFFERHEADERTYPE** ppBufferHdr,
+        OMX_IN OMX_U32 nPortIndex,
+        OMX_IN OMX_PTR pAppPrivate,
+        OMX_IN OMX_U32 nSizeBytes,
+        OMX_IN OMX_U8* pBuffer) {
+    return getBase(hComponent)->useBuffer(
+            ppBufferHdr, nPortIndex, pAppPrivate, nSizeBytes, pBuffer);
+}
+
+static OMX_ERRORTYPE AllocateBufferWrapper(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_INOUT OMX_BUFFERHEADERTYPE** ppBuffer,
+        OMX_IN OMX_U32 nPortIndex,
+        OMX_IN OMX_PTR pAppPrivate,
+        OMX_IN OMX_U32 nSizeBytes) {
+    return getBase(hComponent)->allocateBuffer(
+            ppBuffer, nPortIndex, pAppPrivate, nSizeBytes);
+}
+
+static OMX_ERRORTYPE FreeBufferWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_U32 nPortIndex,
+        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
+    return getBase(hComponent)->freeBuffer(nPortIndex, pBuffer);
+}
+
+static OMX_ERRORTYPE EmptyThisBufferWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
+    return getBase(hComponent)->emptyThisBuffer(pBuffer);
+}
+
+static OMX_ERRORTYPE FillThisBufferWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent,
+        OMX_IN  OMX_BUFFERHEADERTYPE* pBuffer) {
+    return getBase(hComponent)->fillThisBuffer(pBuffer);
+}
+
+static OMX_ERRORTYPE ComponentDeInitWrapper(
+        OMX_IN  OMX_HANDLETYPE hComponent) {
+    delete getBase(hComponent);
+    delete (OMX_COMPONENTTYPE *)hComponent;
+
+    return OMX_ErrorNone;
+}
+
+static OMX_ERRORTYPE ComponentRoleEnumWrapper(
+        OMX_IN OMX_HANDLETYPE hComponent,
+        OMX_OUT OMX_U8 *cRole,
+        OMX_IN OMX_U32 nIndex) {
+    return getBase(hComponent)->enumerateRoles(cRole, nIndex);
+}
+
+// static
+OMX_COMPONENTTYPE *OMXComponentBase::MakeComponent(OMXComponentBase *base) {
+    OMX_COMPONENTTYPE *result = new OMX_COMPONENTTYPE;
+
+    result->nSize = sizeof(OMX_COMPONENTTYPE);
+    result->nVersion.s.nVersionMajor = 1;
+    result->nVersion.s.nVersionMinor = 0;
+    result->nVersion.s.nRevision = 0;
+    result->nVersion.s.nStep = 0;
+    result->pComponentPrivate = base;
+    result->pApplicationPrivate = NULL;
+
+    result->GetComponentVersion = NULL;
+    result->SendCommand = SendCommandWrapper;
+    result->GetParameter = GetParameterWrapper;
+    result->SetParameter = SetParameterWrapper;
+    result->GetConfig = GetConfigWrapper;
+    result->SetConfig = SetConfigWrapper;
+    result->GetExtensionIndex = GetExtensionIndexWrapper;
+    result->GetState = GetStateWrapper;
+    result->ComponentTunnelRequest = NULL;
+    result->UseBuffer = UseBufferWrapper;
+    result->AllocateBuffer = AllocateBufferWrapper;
+    result->FreeBuffer = FreeBufferWrapper;
+    result->EmptyThisBuffer = EmptyThisBufferWrapper;
+    result->FillThisBuffer = FillThisBufferWrapper;
+    result->SetCallbacks = NULL;
+    result->ComponentDeInit = ComponentDeInitWrapper;
+    result->UseEGLImage = NULL;
+    result->ComponentRoleEnum = ComponentRoleEnumWrapper;
+
+    base->setComponentHandle(result);
+
+    return result;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/omx/OMXComponentBase.h b/media/libstagefright/omx/OMXComponentBase.h
new file mode 100644
index 0000000..fd0df0b
--- /dev/null
+++ b/media/libstagefright/omx/OMXComponentBase.h
@@ -0,0 +1,96 @@
+/*
+ * 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 OMX_COMPONENT_BASE_H_
+
+#define OMX_COMPONENT_BASE_H_
+
+#include <OMX_Component.h>
+
+namespace android {
+
+struct OMXComponentBase {
+    OMXComponentBase(
+            const OMX_CALLBACKTYPE *callbacks,
+            OMX_PTR appData);
+
+    virtual ~OMXComponentBase();
+
+    virtual OMX_ERRORTYPE sendCommand(
+            OMX_COMMANDTYPE cmd, OMX_U32 param, OMX_PTR cmdData) = 0;
+
+    virtual OMX_ERRORTYPE getParameter(
+            OMX_INDEXTYPE index, OMX_PTR params) = 0;
+
+    virtual OMX_ERRORTYPE setParameter(
+            OMX_INDEXTYPE index, const OMX_PTR params) = 0;
+
+    virtual OMX_ERRORTYPE getConfig(
+            OMX_INDEXTYPE index, OMX_PTR config) = 0;
+
+    virtual OMX_ERRORTYPE setConfig(
+            OMX_INDEXTYPE index, const OMX_PTR config) = 0;
+
+    virtual OMX_ERRORTYPE getExtensionIndex(
+            const OMX_STRING name, OMX_INDEXTYPE *index) = 0;
+
+    virtual OMX_ERRORTYPE useBuffer(
+            OMX_BUFFERHEADERTYPE **bufHdr,
+            OMX_U32 portIndex,
+            OMX_PTR appPrivate,
+            OMX_U32 size,
+            OMX_U8 *buffer) = 0;
+
+    virtual OMX_ERRORTYPE allocateBuffer(
+            OMX_BUFFERHEADERTYPE **bufHdr,
+            OMX_U32 portIndex,
+            OMX_PTR appPrivate,
+            OMX_U32 size) = 0;
+
+    virtual OMX_ERRORTYPE freeBuffer(
+            OMX_U32 portIndex,
+            OMX_BUFFERHEADERTYPE *buffer) = 0;
+
+    virtual OMX_ERRORTYPE emptyThisBuffer(OMX_BUFFERHEADERTYPE *buffer) = 0;
+    virtual OMX_ERRORTYPE fillThisBuffer(OMX_BUFFERHEADERTYPE *buffer) = 0;
+
+    virtual OMX_ERRORTYPE enumerateRoles(OMX_U8 *role, OMX_U32 index) = 0;
+
+    virtual OMX_ERRORTYPE getState(OMX_STATETYPE *state) = 0;
+
+    // Wraps a given OMXComponentBase instance into an OMX_COMPONENTTYPE
+    // as required by OpenMAX APIs.
+    static OMX_COMPONENTTYPE *MakeComponent(OMXComponentBase *base);
+
+protected:
+    void postEvent(OMX_EVENTTYPE event, OMX_U32 param1, OMX_U32 param2);
+    void postFillBufferDone(OMX_BUFFERHEADERTYPE *bufHdr);
+    void postEmptyBufferDone(OMX_BUFFERHEADERTYPE *bufHdr);
+
+private:
+    void setComponentHandle(OMX_COMPONENTTYPE *handle);
+
+    const OMX_CALLBACKTYPE *mCallbacks;
+    OMX_PTR mAppData;
+    OMX_COMPONENTTYPE *mComponentHandle;
+
+    OMXComponentBase(const OMXComponentBase &);
+    OMXComponentBase &operator=(const OMXComponentBase &);
+};
+
+}  // namespace android
+
+#endif  // OMX_COMPONENT_BASE_H_
diff --git a/media/libstagefright/omx/OMXMaster.cpp b/media/libstagefright/omx/OMXMaster.cpp
new file mode 100644
index 0000000..9a45bea
--- /dev/null
+++ b/media/libstagefright/omx/OMXMaster.cpp
@@ -0,0 +1,184 @@
+/*
+ * 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 "OMXMaster.h"
+
+#include <dlfcn.h>
+
+#include <media/stagefright/MediaDebug.h>
+
+#ifndef NO_OPENCORE
+#include "OMXPVCodecsPlugin.h"
+#endif
+
+namespace android {
+
+OMXMaster::OMXMaster()
+    : mVendorLibHandle(NULL) {
+    addVendorPlugin();
+
+#ifndef NO_OPENCORE
+    addPlugin(new OMXPVCodecsPlugin);
+#endif
+}
+
+OMXMaster::~OMXMaster() {
+    clearPlugins();
+
+    if (mVendorLibHandle != NULL) {
+        dlclose(mVendorLibHandle);
+        mVendorLibHandle = NULL;
+    }
+}
+
+void OMXMaster::addVendorPlugin() {
+    mVendorLibHandle = dlopen("libstagefrighthw.so", RTLD_NOW);
+
+    if (mVendorLibHandle == NULL) {
+        return;
+    }
+
+    typedef OMXPluginBase *(*CreateOMXPluginFunc)();
+    CreateOMXPluginFunc createOMXPlugin =
+        (CreateOMXPluginFunc)dlsym(
+                mVendorLibHandle, "_ZN7android15createOMXPluginEv");
+
+    if (createOMXPlugin) {
+        addPlugin((*createOMXPlugin)());
+    }
+}
+
+void OMXMaster::addPlugin(OMXPluginBase *plugin) {
+    Mutex::Autolock autoLock(mLock);
+
+    mPlugins.push_back(plugin);
+
+    OMX_U32 index = 0;
+
+    char name[128];
+    OMX_ERRORTYPE err;
+    while ((err = plugin->enumerateComponents(
+                    name, sizeof(name), index++)) == OMX_ErrorNone) {
+        String8 name8(name);
+
+        if (mPluginByComponentName.indexOfKey(name8) >= 0) {
+            LOGE("A component of name '%s' already exists, ignoring this one.",
+                 name8.string());
+
+            continue;
+        }
+
+        mPluginByComponentName.add(name8, plugin);
+    }
+    CHECK_EQ(err, OMX_ErrorNoMore);
+}
+
+void OMXMaster::clearPlugins() {
+    Mutex::Autolock autoLock(mLock);
+
+    mPluginByComponentName.clear();
+
+    for (List<OMXPluginBase *>::iterator it = mPlugins.begin();
+         it != mPlugins.end(); ++it) {
+        delete *it;
+        *it = NULL;
+    }
+
+    mPlugins.clear();
+}
+
+OMX_ERRORTYPE OMXMaster::makeComponentInstance(
+        const char *name,
+        const OMX_CALLBACKTYPE *callbacks,
+        OMX_PTR appData,
+        OMX_COMPONENTTYPE **component) {
+    Mutex::Autolock autoLock(mLock);
+
+    *component = NULL;
+
+    ssize_t index = mPluginByComponentName.indexOfKey(String8(name));
+
+    if (index < 0) {
+        return OMX_ErrorInvalidComponentName;
+    }
+
+    OMXPluginBase *plugin = mPluginByComponentName.valueAt(index);
+    OMX_ERRORTYPE err =
+        plugin->makeComponentInstance(name, callbacks, appData, component);
+
+    if (err != OMX_ErrorNone) {
+        return err;
+    }
+
+    mPluginByInstance.add(*component, plugin);
+
+    return err;
+}
+
+OMX_ERRORTYPE OMXMaster::destroyComponentInstance(
+        OMX_COMPONENTTYPE *component) {
+    Mutex::Autolock autoLock(mLock);
+
+    ssize_t index = mPluginByInstance.indexOfKey(component);
+
+    if (index < 0) {
+        return OMX_ErrorBadParameter;
+    }
+
+    OMXPluginBase *plugin = mPluginByInstance.valueAt(index);
+    mPluginByInstance.removeItemsAt(index);
+
+    return plugin->destroyComponentInstance(component);
+}
+
+OMX_ERRORTYPE OMXMaster::enumerateComponents(
+        OMX_STRING name,
+        size_t size,
+        OMX_U32 index) {
+    Mutex::Autolock autoLock(mLock);
+
+    size_t numComponents = mPluginByComponentName.size();
+
+    if (index >= numComponents) {
+        return OMX_ErrorNoMore;
+    }
+
+    const String8 &name8 = mPluginByComponentName.keyAt(index);
+
+    CHECK(size >= 1 + name8.size());
+    strcpy(name, name8.string());
+
+    return OMX_ErrorNone;
+}
+
+OMX_ERRORTYPE OMXMaster::getRolesOfComponent(
+        const char *name,
+        Vector<String8> *roles) {
+    Mutex::Autolock autoLock(mLock);
+
+    roles->clear();
+
+    ssize_t index = mPluginByComponentName.indexOfKey(String8(name));
+
+    if (index < 0) {
+        return OMX_ErrorInvalidComponentName;
+    }
+
+    OMXPluginBase *plugin = mPluginByComponentName.valueAt(index);
+    return plugin->getRolesOfComponent(name, roles);
+}
+
+}  // namespace android
diff --git a/media/libstagefright/omx/OMXMaster.h b/media/libstagefright/omx/OMXMaster.h
new file mode 100644
index 0000000..7ba8d18
--- /dev/null
+++ b/media/libstagefright/omx/OMXMaster.h
@@ -0,0 +1,70 @@
+/*
+ * 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 OMX_MASTER_H_
+
+#define OMX_MASTER_H_
+
+#include <media/stagefright/OMXPluginBase.h>
+
+#include <utils/threads.h>
+#include <utils/KeyedVector.h>
+#include <utils/List.h>
+#include <utils/String8.h>
+
+namespace android {
+
+struct OMXMaster : public OMXPluginBase {
+    OMXMaster();
+    virtual ~OMXMaster();
+
+    virtual OMX_ERRORTYPE makeComponentInstance(
+            const char *name,
+            const OMX_CALLBACKTYPE *callbacks,
+            OMX_PTR appData,
+            OMX_COMPONENTTYPE **component);
+
+    virtual OMX_ERRORTYPE destroyComponentInstance(
+            OMX_COMPONENTTYPE *component);
+
+    virtual OMX_ERRORTYPE enumerateComponents(
+            OMX_STRING name,
+            size_t size,
+            OMX_U32 index);
+
+    virtual OMX_ERRORTYPE getRolesOfComponent(
+            const char *name,
+            Vector<String8> *roles);
+
+private:
+    Mutex mLock;
+    List<OMXPluginBase *> mPlugins;
+    KeyedVector<String8, OMXPluginBase *> mPluginByComponentName;
+    KeyedVector<OMX_COMPONENTTYPE *, OMXPluginBase *> mPluginByInstance;
+
+    void *mVendorLibHandle;
+
+    void addVendorPlugin();
+    void addPlugin(OMXPluginBase *plugin);
+    void clearPlugins();
+
+    OMXMaster(const OMXMaster &);
+    OMXMaster &operator=(const OMXMaster &);
+};
+
+}  // namespace android
+
+#endif  // OMX_MASTER_H_
diff --git a/media/libstagefright/omx/OMXNodeInstance.cpp b/media/libstagefright/omx/OMXNodeInstance.cpp
index 8218918..4eb6417 100644
--- a/media/libstagefright/omx/OMXNodeInstance.cpp
+++ b/media/libstagefright/omx/OMXNodeInstance.cpp
@@ -19,8 +19,9 @@
 #include <utils/Log.h>
 
 #include "../include/OMXNodeInstance.h"
+#include "OMXMaster.h"
 
-#include "pv_omxcore.h"
+#include <OMX_Component.h>
 
 #include <binder/IMemory.h>
 #include <media/stagefright/MediaDebug.h>
@@ -77,7 +78,8 @@
     : mOwner(owner),
       mNodeID(NULL),
       mHandle(NULL),
-      mObserver(observer) {
+      mObserver(observer),
+      mDying(false) {
 }
 
 OMXNodeInstance::~OMXNodeInstance() {
@@ -106,13 +108,18 @@
     return (err == OMX_ErrorNone) ? OK : UNKNOWN_ERROR;
 }
 
-status_t OMXNodeInstance::freeNode() {
+status_t OMXNodeInstance::freeNode(OMXMaster *master) {
     // Transition the node from its current state all the way down
     // to "Loaded".
     // This ensures that all active buffers are properly freed even
     // for components that don't do this themselves on a call to
     // "FreeHandle".
 
+    // The code below may trigger some more events to be dispatched
+    // by the OMX component - we want to ignore them as our client
+    // does not expect them.
+    mDying = true;
+
     OMX_STATETYPE state;
     CHECK_EQ(OMX_GetState(mHandle, &state), OMX_ErrorNone);
     switch (state) {
@@ -157,7 +164,9 @@
             break;
     }
 
-    OMX_ERRORTYPE err = OMX_MasterFreeHandle(mHandle);
+    OMX_ERRORTYPE err = master->destroyComponentInstance(
+            static_cast<OMX_COMPONENTTYPE *>(mHandle));
+
     mHandle = NULL;
 
     if (err != OMX_ErrorNone) {
@@ -383,11 +392,11 @@
     mObserver->onMessage(msg);
 }
 
-void OMXNodeInstance::onObserverDied() {
+void OMXNodeInstance::onObserverDied(OMXMaster *master) {
     LOGE("!!! Observer died. Quickly, do something, ... anything...");
 
     // Try to force shutdown of the node and hope for the best.
-    freeNode();
+    freeNode(master);
 }
 
 void OMXNodeInstance::onGetHandleFailed() {
@@ -403,6 +412,9 @@
         OMX_IN OMX_U32 nData2,
         OMX_IN OMX_PTR pEventData) {
     OMXNodeInstance *instance = static_cast<OMXNodeInstance *>(pAppData);
+    if (instance->mDying) {
+        return OMX_ErrorNone;
+    }
     return instance->owner()->OnEvent(
             instance->nodeID(), eEvent, nData1, nData2, pEventData);
 }
@@ -413,6 +425,9 @@
         OMX_IN OMX_PTR pAppData,
         OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
     OMXNodeInstance *instance = static_cast<OMXNodeInstance *>(pAppData);
+    if (instance->mDying) {
+        return OMX_ErrorNone;
+    }
     return instance->owner()->OnEmptyBufferDone(instance->nodeID(), pBuffer);
 }
 
@@ -422,6 +437,9 @@
         OMX_IN OMX_PTR pAppData,
         OMX_IN OMX_BUFFERHEADERTYPE* pBuffer) {
     OMXNodeInstance *instance = static_cast<OMXNodeInstance *>(pAppData);
+    if (instance->mDying) {
+        return OMX_ErrorNone;
+    }
     return instance->owner()->OnFillBufferDone(instance->nodeID(), pBuffer);
 }
 
diff --git a/media/libstagefright/omx/OMXPVCodecsPlugin.cpp b/media/libstagefright/omx/OMXPVCodecsPlugin.cpp
new file mode 100644
index 0000000..d1f5be3
--- /dev/null
+++ b/media/libstagefright/omx/OMXPVCodecsPlugin.cpp
@@ -0,0 +1,101 @@
+/*
+ * 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 "OMXPVCodecsPlugin.h"
+
+#include "pv_omxcore.h"
+
+#include <media/stagefright/MediaDebug.h>
+
+namespace android {
+
+OMXPVCodecsPlugin::OMXPVCodecsPlugin() {
+    OMX_MasterInit();
+}
+
+OMXPVCodecsPlugin::~OMXPVCodecsPlugin() {
+    OMX_MasterDeinit();
+}
+
+OMX_ERRORTYPE OMXPVCodecsPlugin::makeComponentInstance(
+        const char *name,
+        const OMX_CALLBACKTYPE *callbacks,
+        OMX_PTR appData,
+        OMX_COMPONENTTYPE **component) {
+    return OMX_MasterGetHandle(
+            reinterpret_cast<OMX_HANDLETYPE *>(component),
+            const_cast<char *>(name),
+            appData,
+            const_cast<OMX_CALLBACKTYPE *>(callbacks));
+}
+
+OMX_ERRORTYPE OMXPVCodecsPlugin::destroyComponentInstance(
+        OMX_COMPONENTTYPE *component) {
+    return OMX_MasterFreeHandle(component);
+}
+
+OMX_ERRORTYPE OMXPVCodecsPlugin::enumerateComponents(
+        OMX_STRING name,
+        size_t size,
+        OMX_U32 index) {
+    return OMX_MasterComponentNameEnum(name, size, index);
+}
+
+OMX_ERRORTYPE OMXPVCodecsPlugin::getRolesOfComponent(
+        const char *name,
+        Vector<String8> *roles) {
+    roles->clear();
+
+    OMX_U32 numRoles;
+    OMX_ERRORTYPE err =
+        OMX_MasterGetRolesOfComponent(
+                const_cast<char *>(name),
+                &numRoles,
+                NULL);
+
+    if (err != OMX_ErrorNone) {
+        return err;
+    }
+
+    if (numRoles > 0) {
+        OMX_U8 **array = new OMX_U8 *[numRoles];
+        for (OMX_U32 i = 0; i < numRoles; ++i) {
+            array[i] = new OMX_U8[OMX_MAX_STRINGNAME_SIZE];
+        }
+
+        OMX_U32 numRoles2;
+        err = OMX_MasterGetRolesOfComponent(
+                const_cast<char *>(name), &numRoles2, array);
+
+        CHECK_EQ(err, OMX_ErrorNone);
+        CHECK_EQ(numRoles, numRoles2);
+
+        for (OMX_U32 i = 0; i < numRoles; ++i) {
+            String8 s((const char *)array[i]);
+            roles->push(s);
+
+            delete[] array[i];
+            array[i] = NULL;
+        }
+
+        delete[] array;
+        array = NULL;
+    }
+
+    return OMX_ErrorNone;
+}
+
+}  // namespace android
diff --git a/media/libstagefright/omx/OMXPVCodecsPlugin.h b/media/libstagefright/omx/OMXPVCodecsPlugin.h
new file mode 100644
index 0000000..c133232
--- /dev/null
+++ b/media/libstagefright/omx/OMXPVCodecsPlugin.h
@@ -0,0 +1,54 @@
+/*
+ * 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 OMX_PV_CODECS_PLUGIN_H_
+
+#define OMX_PV_CODECS_PLUGIN_H_
+
+#include <media/stagefright/OMXPluginBase.h>
+
+namespace android {
+
+struct OMXPVCodecsPlugin : public OMXPluginBase {
+    OMXPVCodecsPlugin();
+    virtual ~OMXPVCodecsPlugin();
+
+    virtual OMX_ERRORTYPE makeComponentInstance(
+            const char *name,
+            const OMX_CALLBACKTYPE *callbacks,
+            OMX_PTR appData,
+            OMX_COMPONENTTYPE **component);
+
+    virtual OMX_ERRORTYPE destroyComponentInstance(
+            OMX_COMPONENTTYPE *component);
+
+    virtual OMX_ERRORTYPE enumerateComponents(
+            OMX_STRING name,
+            size_t size,
+            OMX_U32 index);
+
+    virtual OMX_ERRORTYPE getRolesOfComponent(
+            const char *name,
+            Vector<String8> *roles);
+
+private:
+    OMXPVCodecsPlugin(const OMXPVCodecsPlugin &);
+    OMXPVCodecsPlugin &operator=(const OMXPVCodecsPlugin &);
+};
+
+}  // namespace android
+
+#endif  // OMX_PV_CODECS_PLUGIN_H_
diff --git a/media/libstagefright/omx/SoftwareRenderer.cpp b/media/libstagefright/omx/SoftwareRenderer.cpp
deleted file mode 100644
index 39de504..0000000
--- a/media/libstagefright/omx/SoftwareRenderer.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * 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.
- */
-
-#define LOG_TAG "SoftwareRenderer"
-#include <utils/Log.h>
-
-#include <binder/MemoryHeapBase.h>
-#include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/SoftwareRenderer.h>
-#include <ui/ISurface.h>
-
-namespace android {
-
-#define QCOM_YUV        0
-
-SoftwareRenderer::SoftwareRenderer(
-        OMX_COLOR_FORMATTYPE colorFormat,
-        const sp<ISurface> &surface,
-        size_t displayWidth, size_t displayHeight,
-        size_t decodedWidth, size_t decodedHeight)
-    : mColorFormat(colorFormat),
-      mISurface(surface),
-      mDisplayWidth(displayWidth),
-      mDisplayHeight(displayHeight),
-      mDecodedWidth(decodedWidth),
-      mDecodedHeight(decodedHeight),
-      mFrameSize(mDecodedWidth * mDecodedHeight * 2),  // RGB565
-      mMemoryHeap(new MemoryHeapBase(2 * mFrameSize)),
-      mIndex(0),
-      mClip(NULL) {
-    CHECK(mISurface.get() != NULL);
-    CHECK(mDecodedWidth > 0);
-    CHECK(mDecodedHeight > 0);
-    CHECK(mMemoryHeap->heapID() >= 0);
-
-    ISurface::BufferHeap bufferHeap(
-            mDisplayWidth, mDisplayHeight,
-            mDecodedWidth, mDecodedHeight,
-            PIXEL_FORMAT_RGB_565,
-            mMemoryHeap);
-
-    status_t err = mISurface->registerBuffers(bufferHeap);
-    CHECK_EQ(err, OK);
-}
-
-SoftwareRenderer::~SoftwareRenderer() {
-    mISurface->unregisterBuffers();
-
-    delete[] mClip;
-    mClip = NULL;
-}
-
-void SoftwareRenderer::render(
-        const void *data, size_t size, void *platformPrivate) {
-    static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
-
-    switch (mColorFormat) {
-        case OMX_COLOR_FormatYUV420Planar:
-            return renderYUV420Planar(data, size);
-
-        case OMX_COLOR_FormatCbYCrY:
-            return renderCbYCrY(data, size);
-
-        case OMX_QCOM_COLOR_FormatYVU420SemiPlanar:
-            return renderQCOMYUV420SemiPlanar(data, size);
-
-        default:
-        {
-            LOGW("Cannot render color format %d", mColorFormat);
-            break;
-        }
-    }
-}
-
-void SoftwareRenderer::renderYUV420Planar(
-        const void *data, size_t size) {
-    if (size != (mDecodedHeight * mDecodedWidth * 3) / 2) {
-        LOGE("size is %d, expected %d",
-                size, (mDecodedHeight * mDecodedWidth * 3) / 2);
-    }
-    CHECK(size >= (mDecodedWidth * mDecodedHeight * 3) / 2);
-
-    uint8_t *kAdjustedClip = initClip();
-
-    size_t offset = mIndex * mFrameSize;
-
-    void *dst = (uint8_t *)mMemoryHeap->getBase() + offset;
-
-    uint32_t *dst_ptr = (uint32_t *)dst;
-
-    const uint8_t *src_y = (const uint8_t *)data;
-
-    const uint8_t *src_u =
-        (const uint8_t *)src_y + mDecodedWidth * mDecodedHeight;
-
-#if !QCOM_YUV
-    const uint8_t *src_v =
-        (const uint8_t *)src_u + (mDecodedWidth / 2) * (mDecodedHeight / 2);
-#endif
-
-    for (size_t y = 0; y < mDecodedHeight; ++y) {
-        for (size_t x = 0; x < mDecodedWidth; x += 2) {
-            // B = 1.164 * (Y - 16) + 2.018 * (U - 128)
-            // G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128)
-            // R = 1.164 * (Y - 16) + 1.596 * (V - 128)
-
-            // B = 298/256 * (Y - 16) + 517/256 * (U - 128)
-            // G = .................. - 208/256 * (V - 128) - 100/256 * (U - 128)
-            // R = .................. + 409/256 * (V - 128)
-
-            // min_B = (298 * (- 16) + 517 * (- 128)) / 256 = -277
-            // min_G = (298 * (- 16) - 208 * (255 - 128) - 100 * (255 - 128)) / 256 = -172
-            // min_R = (298 * (- 16) + 409 * (- 128)) / 256 = -223
-
-            // max_B = (298 * (255 - 16) + 517 * (255 - 128)) / 256 = 534
-            // max_G = (298 * (255 - 16) - 208 * (- 128) - 100 * (- 128)) / 256 = 432
-            // max_R = (298 * (255 - 16) + 409 * (255 - 128)) / 256 = 481
-
-            // clip range -278 .. 535
-
-            signed y1 = (signed)src_y[x] - 16;
-            signed y2 = (signed)src_y[x + 1] - 16;
-
-#if QCOM_YUV
-            signed u = (signed)src_u[x & ~1] - 128;
-            signed v = (signed)src_u[(x & ~1) + 1] - 128;
-#else
-            signed u = (signed)src_u[x / 2] - 128;
-            signed v = (signed)src_v[x / 2] - 128;
-#endif
-
-            signed u_b = u * 517;
-            signed u_g = -u * 100;
-            signed v_g = -v * 208;
-            signed v_r = v * 409;
-
-            signed tmp1 = y1 * 298;
-            signed b1 = (tmp1 + u_b) / 256;
-            signed g1 = (tmp1 + v_g + u_g) / 256;
-            signed r1 = (tmp1 + v_r) / 256;
-
-            signed tmp2 = y2 * 298;
-            signed b2 = (tmp2 + u_b) / 256;
-            signed g2 = (tmp2 + v_g + u_g) / 256;
-            signed r2 = (tmp2 + v_r) / 256;
-
-            uint32_t rgb1 =
-                ((kAdjustedClip[r1] >> 3) << 11)
-                | ((kAdjustedClip[g1] >> 2) << 5)
-                | (kAdjustedClip[b1] >> 3);
-
-            uint32_t rgb2 =
-                ((kAdjustedClip[r2] >> 3) << 11)
-                | ((kAdjustedClip[g2] >> 2) << 5)
-                | (kAdjustedClip[b2] >> 3);
-
-            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
-        }
-
-        src_y += mDecodedWidth;
-
-        if (y & 1) {
-#if QCOM_YUV
-            src_u += mDecodedWidth;
-#else
-            src_u += mDecodedWidth / 2;
-            src_v += mDecodedWidth / 2;
-#endif
-        }
-
-        dst_ptr += mDecodedWidth / 2;
-    }
-
-    mISurface->postBuffer(offset);
-    mIndex = 1 - mIndex;
-}
-
-void SoftwareRenderer::renderCbYCrY(
-        const void *data, size_t size) {
-    if (size != (mDecodedHeight * mDecodedWidth * 2)) {
-        LOGE("size is %d, expected %d",
-                size, (mDecodedHeight * mDecodedWidth * 2));
-    }
-    CHECK(size >= (mDecodedWidth * mDecodedHeight * 2));
-
-    uint8_t *kAdjustedClip = initClip();
-
-    size_t offset = mIndex * mFrameSize;
-    void *dst = (uint8_t *)mMemoryHeap->getBase() + offset;
-    uint32_t *dst_ptr = (uint32_t *)dst;
-
-    const uint8_t *src = (const uint8_t *)data;
-
-    for (size_t y = 0; y < mDecodedHeight; ++y) {
-        for (size_t x = 0; x < mDecodedWidth; x += 2) {
-            signed y1 = (signed)src[2 * x + 1] - 16;
-            signed y2 = (signed)src[2 * x + 3] - 16;
-            signed u = (signed)src[2 * x] - 128;
-            signed v = (signed)src[2 * x + 2] - 128;
-
-            signed u_b = u * 517;
-            signed u_g = -u * 100;
-            signed v_g = -v * 208;
-            signed v_r = v * 409;
-
-            signed tmp1 = y1 * 298;
-            signed b1 = (tmp1 + u_b) / 256;
-            signed g1 = (tmp1 + v_g + u_g) / 256;
-            signed r1 = (tmp1 + v_r) / 256;
-
-            signed tmp2 = y2 * 298;
-            signed b2 = (tmp2 + u_b) / 256;
-            signed g2 = (tmp2 + v_g + u_g) / 256;
-            signed r2 = (tmp2 + v_r) / 256;
-
-            uint32_t rgb1 =
-                ((kAdjustedClip[r1] >> 3) << 11)
-                | ((kAdjustedClip[g1] >> 2) << 5)
-                | (kAdjustedClip[b1] >> 3);
-
-            uint32_t rgb2 =
-                ((kAdjustedClip[r2] >> 3) << 11)
-                | ((kAdjustedClip[g2] >> 2) << 5)
-                | (kAdjustedClip[b2] >> 3);
-
-            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
-        }
-
-        src += mDecodedWidth * 2;
-        dst_ptr += mDecodedWidth / 2;
-    }
-
-    mISurface->postBuffer(offset);
-    mIndex = 1 - mIndex;
-}
-
-void SoftwareRenderer::renderQCOMYUV420SemiPlanar(
-        const void *data, size_t size) {
-    if (size != (mDecodedHeight * mDecodedWidth * 3) / 2) {
-        LOGE("size is %d, expected %d",
-                size, (mDecodedHeight * mDecodedWidth * 3) / 2);
-    }
-    CHECK(size >= (mDecodedWidth * mDecodedHeight * 3) / 2);
-
-    uint8_t *kAdjustedClip = initClip();
-
-    size_t offset = mIndex * mFrameSize;
-
-    void *dst = (uint8_t *)mMemoryHeap->getBase() + offset;
-
-    uint32_t *dst_ptr = (uint32_t *)dst;
-
-    const uint8_t *src_y = (const uint8_t *)data;
-
-    const uint8_t *src_u =
-        (const uint8_t *)src_y + mDecodedWidth * mDecodedHeight;
-
-    for (size_t y = 0; y < mDecodedHeight; ++y) {
-        for (size_t x = 0; x < mDecodedWidth; x += 2) {
-            signed y1 = (signed)src_y[x] - 16;
-            signed y2 = (signed)src_y[x + 1] - 16;
-
-            signed u = (signed)src_u[x & ~1] - 128;
-            signed v = (signed)src_u[(x & ~1) + 1] - 128;
-
-            signed u_b = u * 517;
-            signed u_g = -u * 100;
-            signed v_g = -v * 208;
-            signed v_r = v * 409;
-
-            signed tmp1 = y1 * 298;
-            signed b1 = (tmp1 + u_b) / 256;
-            signed g1 = (tmp1 + v_g + u_g) / 256;
-            signed r1 = (tmp1 + v_r) / 256;
-
-            signed tmp2 = y2 * 298;
-            signed b2 = (tmp2 + u_b) / 256;
-            signed g2 = (tmp2 + v_g + u_g) / 256;
-            signed r2 = (tmp2 + v_r) / 256;
-
-            uint32_t rgb1 =
-                ((kAdjustedClip[b1] >> 3) << 11)
-                | ((kAdjustedClip[g1] >> 2) << 5)
-                | (kAdjustedClip[r1] >> 3);
-
-            uint32_t rgb2 =
-                ((kAdjustedClip[b2] >> 3) << 11)
-                | ((kAdjustedClip[g2] >> 2) << 5)
-                | (kAdjustedClip[r2] >> 3);
-
-            dst_ptr[x / 2] = (rgb2 << 16) | rgb1;
-        }
-
-        src_y += mDecodedWidth;
-
-        if (y & 1) {
-            src_u += mDecodedWidth;
-        }
-
-        dst_ptr += mDecodedWidth / 2;
-    }
-
-    mISurface->postBuffer(offset);
-    mIndex = 1 - mIndex;
-}
-
-uint8_t *SoftwareRenderer::initClip() {
-    static const signed kClipMin = -278;
-    static const signed kClipMax = 535;
-
-    if (mClip == NULL) {
-        mClip = new uint8_t[kClipMax - kClipMin + 1];
-
-        for (signed i = kClipMin; i <= kClipMax; ++i) {
-            mClip[i - kClipMin] = (i < 0) ? 0 : (i > 255) ? 255 : (uint8_t)i;
-        }
-    }
-
-    return &mClip[-kClipMin];
-}
-
-}  // namespace android
diff --git a/media/libstagefright/omx/tests/Android.mk b/media/libstagefright/omx/tests/Android.mk
new file mode 100644
index 0000000..ee117e5
--- /dev/null
+++ b/media/libstagefright/omx/tests/Android.mk
@@ -0,0 +1,23 @@
+ifeq ($(BUILD_WITH_FULL_STAGEFRIGHT),true)
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES =       \
+	OMXHarness.cpp  \
+
+LOCAL_SHARED_LIBRARIES := \
+	libstagefright libbinder libmedia libutils
+
+LOCAL_C_INCLUDES:= \
+	$(JNI_H_INCLUDE) \
+	frameworks/base/media/libstagefright \
+	$(TOP)/external/opencore/extern_libs_v2/khronos/openmax/include
+
+LOCAL_MODULE:= omx_tests
+
+include $(BUILD_EXECUTABLE)
+
+endif
+
+
diff --git a/media/libstagefright/omx/tests/OMXHarness.cpp b/media/libstagefright/omx/tests/OMXHarness.cpp
new file mode 100644
index 0000000..2e23899
--- /dev/null
+++ b/media/libstagefright/omx/tests/OMXHarness.cpp
@@ -0,0 +1,815 @@
+/*
+ * 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.
+ */
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "OMXHarness"
+#include <utils/Log.h>
+
+#include "OMXHarness.h"
+
+#include <sys/time.h>
+
+#include <binder/ProcessState.h>
+#include <binder/IServiceManager.h>
+#include <binder/MemoryDealer.h>
+#include <media/IMediaPlayerService.h>
+#include <media/stagefright/DataSource.h>
+#include <media/stagefright/MediaBuffer.h>
+#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaErrors.h>
+#include <media/stagefright/MediaExtractor.h>
+#include <media/stagefright/MediaSource.h>
+#include <media/stagefright/MetaData.h>
+#include <media/stagefright/OMXCodec.h>
+
+#define DEFAULT_TIMEOUT         500000
+
+namespace android {
+
+static int64_t getNowUs() {
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+
+    return (int64_t)tv.tv_usec + tv.tv_sec * 1000000;
+}
+
+Harness::Harness()
+    : mInitCheck(NO_INIT) {
+    mInitCheck = initOMX();
+}
+
+Harness::~Harness() {
+}
+
+status_t Harness::initCheck() const {
+    return mInitCheck;
+}
+
+status_t Harness::initOMX() {
+    sp<IServiceManager> sm = defaultServiceManager();
+    sp<IBinder> binder = sm->getService(String16("media.player"));
+    sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
+    mOMX = service->getOMX();
+
+    return mOMX != 0 ? OK : NO_INIT;
+}
+
+void Harness::onMessage(const omx_message &msg) {
+    Mutex::Autolock autoLock(mLock);
+    mMessageQueue.push_back(msg);
+    mMessageAddedCondition.signal();
+}
+
+status_t Harness::dequeueMessageForNode(
+        IOMX::node_id node, omx_message *msg, int64_t timeoutUs) {
+    return dequeueMessageForNodeIgnoringBuffers(
+            node, NULL, NULL, msg, timeoutUs);
+}
+
+// static
+bool Harness::handleBufferMessage(
+        const omx_message &msg,
+        Vector<Buffer> *inputBuffers,
+        Vector<Buffer> *outputBuffers) {
+    switch (msg.type) {
+        case omx_message::EMPTY_BUFFER_DONE:
+        {
+            if (inputBuffers) {
+                for (size_t i = 0; i < inputBuffers->size(); ++i) {
+                    if ((*inputBuffers)[i].mID == msg.u.buffer_data.buffer) {
+                        inputBuffers->editItemAt(i).mFlags &= ~kBufferBusy;
+                        return true;
+                    }
+                }
+                CHECK(!"should not be here");
+            }
+            break;
+        }
+
+        case omx_message::FILL_BUFFER_DONE:
+        {
+            if (outputBuffers) {
+                for (size_t i = 0; i < outputBuffers->size(); ++i) {
+                    if ((*outputBuffers)[i].mID == msg.u.buffer_data.buffer) {
+                        outputBuffers->editItemAt(i).mFlags &= ~kBufferBusy;
+                        return true;
+                    }
+                }
+                CHECK(!"should not be here");
+            }
+            break;
+        }
+
+        default:
+            break;
+    }
+
+    return false;
+}
+
+status_t Harness::dequeueMessageForNodeIgnoringBuffers(
+        IOMX::node_id node,
+        Vector<Buffer> *inputBuffers,
+        Vector<Buffer> *outputBuffers,
+        omx_message *msg, int64_t timeoutUs) {
+    int64_t finishBy = getNowUs() + timeoutUs;
+
+    for (;;) {
+        Mutex::Autolock autoLock(mLock);
+        List<omx_message>::iterator it = mMessageQueue.begin();
+        while (it != mMessageQueue.end()) {
+            if ((*it).node == node) {
+                if (handleBufferMessage(*it, inputBuffers, outputBuffers)) {
+                    it = mMessageQueue.erase(it);
+                    continue;
+                }
+
+                *msg = *it;
+                mMessageQueue.erase(it);
+
+                return OK;
+            }
+
+            ++it;
+        }
+
+        status_t err = (timeoutUs < 0)
+            ? mMessageAddedCondition.wait(mLock)
+            : mMessageAddedCondition.waitRelative(
+                    mLock, (finishBy - getNowUs()) * 1000);
+
+        if (err == TIMED_OUT) {
+            return err;
+        }
+        CHECK_EQ(err, OK);
+    }
+}
+
+status_t Harness::getPortDefinition(
+        IOMX::node_id node, OMX_U32 portIndex,
+        OMX_PARAM_PORTDEFINITIONTYPE *def) {
+    def->nSize = sizeof(*def);
+    def->nVersion.s.nVersionMajor = 1;
+    def->nVersion.s.nVersionMinor = 0;
+    def->nVersion.s.nRevision = 0;
+    def->nVersion.s.nStep = 0;
+    def->nPortIndex = portIndex;
+    return mOMX->getParameter(
+            node, OMX_IndexParamPortDefinition, def, sizeof(*def));
+}
+
+#define EXPECT(condition, info) \
+    if (!(condition)) {         \
+        LOGE(info); printf("\n  * " info "\n"); return UNKNOWN_ERROR; \
+    }
+
+#define EXPECT_SUCCESS(err, info) \
+    EXPECT((err) == OK, info " failed")
+
+status_t Harness::allocatePortBuffers(
+        const sp<MemoryDealer> &dealer,
+        IOMX::node_id node, OMX_U32 portIndex,
+        Vector<Buffer> *buffers) {
+    buffers->clear();
+
+    OMX_PARAM_PORTDEFINITIONTYPE def;
+    status_t err = getPortDefinition(node, portIndex, &def);
+    EXPECT_SUCCESS(err, "getPortDefinition");
+
+    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
+        Buffer buffer;
+        buffer.mMemory = dealer->allocate(def.nBufferSize);
+        buffer.mFlags = 0;
+        CHECK(buffer.mMemory != NULL);
+
+        err = mOMX->allocateBufferWithBackup(
+                node, portIndex, buffer.mMemory, &buffer.mID);
+        EXPECT_SUCCESS(err, "allocateBuffer");
+
+        buffers->push(buffer);
+    }
+
+    return OK;
+}
+
+status_t Harness::setRole(IOMX::node_id node, const char *role) {
+    OMX_PARAM_COMPONENTROLETYPE params;
+    params.nSize = sizeof(params);
+    params.nVersion.s.nVersionMajor = 1;
+    params.nVersion.s.nVersionMinor = 0;
+    params.nVersion.s.nRevision = 0;
+    params.nVersion.s.nStep = 0;
+    strncpy((char *)params.cRole, role, OMX_MAX_STRINGNAME_SIZE - 1);
+    params.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
+
+    return mOMX->setParameter(
+            node, OMX_IndexParamStandardComponentRole,
+            &params, sizeof(params));
+}
+
+struct NodeReaper {
+    NodeReaper(const sp<Harness> &harness, IOMX::node_id node)
+        : mHarness(harness),
+          mNode(node) {
+    }
+
+    ~NodeReaper() {
+        if (mNode != 0) {
+            mHarness->mOMX->freeNode(mNode);
+            mNode = 0;
+        }
+    }
+
+    void disarm() {
+        mNode = 0;
+    }
+
+private:
+    sp<Harness> mHarness;
+    IOMX::node_id mNode;
+
+    NodeReaper(const NodeReaper &);
+    NodeReaper &operator=(const NodeReaper &);
+};
+
+static sp<MediaSource> MakeSource(
+        const char *uri,
+        const char *mimeType) {
+    sp<MediaExtractor> extractor = MediaExtractor::CreateFromURI(uri);
+
+    if (extractor == NULL) {
+        return NULL;
+    }
+
+    for (size_t i = 0; i < extractor->countTracks(); ++i) {
+        sp<MetaData> meta = extractor->getTrackMetaData(i);
+
+        const char *trackMIME;
+        CHECK(meta->findCString(kKeyMIMEType, &trackMIME));
+
+        if (!strcasecmp(trackMIME, mimeType)) {
+            return extractor->getTrack(i);
+        }
+    }
+
+    return NULL;
+}
+
+status_t Harness::testStateTransitions(
+        const char *componentName, const char *componentRole) {
+    if (strncmp(componentName, "OMX.", 4)) {
+        // Non-OMX components, i.e. software decoders won't execute this
+        // test.
+        return OK;
+    }
+
+    sp<MemoryDealer> dealer = new MemoryDealer(8 * 1024 * 1024);
+    IOMX::node_id node;
+
+    status_t err =
+        mOMX->allocateNode(componentName, this, &node);
+    EXPECT_SUCCESS(err, "allocateNode");
+
+    NodeReaper reaper(this, node);
+
+    err = setRole(node, componentRole);
+    EXPECT_SUCCESS(err, "setRole");
+
+    // Initiate transition Loaded->Idle
+    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
+    EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");
+
+    omx_message msg;
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    // Make sure node doesn't just transition to idle before we are done
+    // allocating all input and output buffers.
+    EXPECT(err == TIMED_OUT,
+            "Component must not transition from loaded to idle before "
+            "all input and output buffers are allocated.");
+
+    // Now allocate buffers.
+    Vector<Buffer> inputBuffers;
+    err = allocatePortBuffers(dealer, node, 0, &inputBuffers);
+    EXPECT_SUCCESS(err, "allocatePortBuffers(input)");
+
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    CHECK_EQ(err, TIMED_OUT);
+
+    Vector<Buffer> outputBuffers;
+    err = allocatePortBuffers(dealer, node, 1, &outputBuffers);
+    EXPECT_SUCCESS(err, "allocatePortBuffers(output)");
+
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    EXPECT(err == OK
+            && msg.type == omx_message::EVENT
+            && msg.u.event_data.event == OMX_EventCmdComplete
+            && msg.u.event_data.data1 == OMX_CommandStateSet
+            && msg.u.event_data.data2 == OMX_StateIdle,
+           "Component did not properly transition to idle state "
+           "after all input and output buffers were allocated.");
+
+    // Initiate transition Idle->Executing
+    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateExecuting);
+    EXPECT_SUCCESS(err, "sendCommand(go-to-Executing)");
+
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    EXPECT(err == OK
+            && msg.type == omx_message::EVENT
+            && msg.u.event_data.event == OMX_EventCmdComplete
+            && msg.u.event_data.data1 == OMX_CommandStateSet
+            && msg.u.event_data.data2 == OMX_StateExecuting,
+           "Component did not properly transition from idle to "
+           "executing state.");
+
+    for (size_t i = 0; i < outputBuffers.size(); ++i) {
+        err = mOMX->fillBuffer(node, outputBuffers[i].mID);
+        EXPECT_SUCCESS(err, "fillBuffer");
+
+        outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
+    }
+
+    err = mOMX->sendCommand(node, OMX_CommandFlush, 1);
+    EXPECT_SUCCESS(err, "sendCommand(flush-output-port)");
+
+    err = dequeueMessageForNodeIgnoringBuffers(
+            node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
+    EXPECT(err == OK
+            && msg.type == omx_message::EVENT
+            && msg.u.event_data.event == OMX_EventCmdComplete
+            && msg.u.event_data.data1 == OMX_CommandFlush
+            && msg.u.event_data.data2 == 1,
+           "Component did not properly acknowledge flushing the output port.");
+
+    for (size_t i = 0; i < outputBuffers.size(); ++i) {
+        EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
+               "Not all output buffers have been returned to us by the time "
+               "we received the flush-complete notification.");
+    }
+
+    for (size_t i = 0; i < outputBuffers.size(); ++i) {
+        err = mOMX->fillBuffer(node, outputBuffers[i].mID);
+        EXPECT_SUCCESS(err, "fillBuffer");
+
+        outputBuffers.editItemAt(i).mFlags |= kBufferBusy;
+    }
+
+    // Initiate transition Executing->Idle
+    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateIdle);
+    EXPECT_SUCCESS(err, "sendCommand(go-to-Idle)");
+
+    err = dequeueMessageForNodeIgnoringBuffers(
+            node, &inputBuffers, &outputBuffers, &msg, DEFAULT_TIMEOUT);
+    EXPECT(err == OK
+            && msg.type == omx_message::EVENT
+            && msg.u.event_data.event == OMX_EventCmdComplete
+            && msg.u.event_data.data1 == OMX_CommandStateSet
+            && msg.u.event_data.data2 == OMX_StateIdle,
+           "Component did not properly transition to from executing to "
+           "idle state.");
+
+    for (size_t i = 0; i < inputBuffers.size(); ++i) {
+        EXPECT((inputBuffers[i].mFlags & kBufferBusy) == 0,
+                "Not all input buffers have been returned to us by the "
+                "time we received the transition-to-idle complete "
+                "notification.");
+    }
+
+    for (size_t i = 0; i < outputBuffers.size(); ++i) {
+        EXPECT((outputBuffers[i].mFlags & kBufferBusy) == 0,
+                "Not all output buffers have been returned to us by the "
+                "time we received the transition-to-idle complete "
+                "notification.");
+    }
+
+    // Initiate transition Idle->Loaded
+    err = mOMX->sendCommand(node, OMX_CommandStateSet, OMX_StateLoaded);
+    EXPECT_SUCCESS(err, "sendCommand(go-to-Loaded)");
+
+    // Make sure node doesn't just transition to loaded before we are done
+    // freeing all input and output buffers.
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    CHECK_EQ(err, TIMED_OUT);
+
+    for (size_t i = 0; i < inputBuffers.size(); ++i) {
+        err = mOMX->freeBuffer(node, 0, inputBuffers[i].mID);
+        EXPECT_SUCCESS(err, "freeBuffer");
+    }
+
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    CHECK_EQ(err, TIMED_OUT);
+
+    for (size_t i = 0; i < outputBuffers.size(); ++i) {
+        err = mOMX->freeBuffer(node, 1, outputBuffers[i].mID);
+        EXPECT_SUCCESS(err, "freeBuffer");
+    }
+
+    err = dequeueMessageForNode(node, &msg, DEFAULT_TIMEOUT);
+    EXPECT(err == OK
+            && msg.type == omx_message::EVENT
+            && msg.u.event_data.event == OMX_EventCmdComplete
+            && msg.u.event_data.data1 == OMX_CommandStateSet
+            && msg.u.event_data.data2 == OMX_StateLoaded,
+           "Component did not properly transition to from idle to "
+           "loaded state after freeing all input and output buffers.");
+
+    err = mOMX->freeNode(node);
+    EXPECT_SUCCESS(err, "freeNode");
+
+    reaper.disarm();
+
+    node = 0;
+
+    return OK;
+}
+
+static const char *GetMimeFromComponentRole(const char *componentRole) {
+    struct RoleToMime {
+        const char *mRole;
+        const char *mMime;
+    };
+    const RoleToMime kRoleToMime[] = {
+        { "video_decoder.avc", "video/avc" },
+        { "video_decoder.mpeg4", "video/mp4v-es" },
+        { "video_decoder.h263", "video/3gpp" },
+
+        // we appear to use this as a synonym to amrnb.
+        { "audio_decoder.amr", "audio/3gpp" },
+
+        { "audio_decoder.amrnb", "audio/3gpp" },
+        { "audio_decoder.amrwb", "audio/amr-wb" },
+        { "audio_decoder.aac", "audio/mp4a-latm" },
+        { "audio_decoder.mp3", "audio/mpeg" }
+    };
+
+    for (size_t i = 0; i < sizeof(kRoleToMime) / sizeof(kRoleToMime[0]); ++i) {
+        if (!strcmp(componentRole, kRoleToMime[i].mRole)) {
+            return kRoleToMime[i].mMime;
+        }
+    }
+
+    return NULL;
+}
+
+static const char *GetURLForMime(const char *mime) {
+    struct MimeToURL {
+        const char *mMime;
+        const char *mURL;
+    };
+    static const MimeToURL kMimeToURL[] = {
+        { "video/avc",
+          "file:///sdcard/media_api/video/H264_AAC.3gp" },
+        { "video/mp4v-es", "file:///sdcard/media_api/video/gingerkids.MP4" },
+        { "video/3gpp",
+          "file:///sdcard/media_api/video/H263_500_AMRNB_12.3gp" },
+        { "audio/3gpp",
+          "file:///sdcard/media_api/video/H263_500_AMRNB_12.3gp" },
+        { "audio/amr-wb",
+          "file:///sdcard/media_api/music_perf/AMRWB/"
+          "NIN_AMR-WB_15.85kbps_16kbps.amr" },
+        { "audio/mp4a-latm",
+          "file:///sdcard/media_api/music_perf/AAC/"
+          "WC_AAC_80kbps_32khz_Stereo_1pCBR_SSE.mp4" },
+        { "audio/mpeg",
+          "file:///sdcard/media_api/music_perf/MP3/"
+          "WC_256kbps_44.1khz_mono_CBR_DPA.mp3" }
+    };
+
+    for (size_t i = 0; i < sizeof(kMimeToURL) / sizeof(kMimeToURL[0]); ++i) {
+        if (!strcasecmp(kMimeToURL[i].mMime, mime)) {
+            return kMimeToURL[i].mURL;
+        }
+    }
+
+    return NULL;
+}
+
+static sp<MediaSource> CreateSourceForMime(const char *mime) {
+    const char *url = GetURLForMime(mime);
+    CHECK(url != NULL);
+
+    sp<MediaExtractor> extractor = MediaExtractor::CreateFromURI(url);
+
+    CHECK(extractor != NULL);
+
+    for (size_t i = 0; i < extractor->countTracks(); ++i) {
+        sp<MetaData> meta = extractor->getTrackMetaData(i);
+        CHECK(meta != NULL);
+
+        const char *trackMime;
+        CHECK(meta->findCString(kKeyMIMEType, &trackMime));
+
+        if (!strcasecmp(mime, trackMime)) {
+            return extractor->getTrack(i);
+        }
+    }
+
+    return NULL;
+}
+
+static double uniform_rand() {
+    return (double)rand() / RAND_MAX;
+}
+
+static bool CloseEnough(int64_t time1Us, int64_t time2Us) {
+#if 0
+    int64_t diff = time1Us - time2Us;
+    if (diff < 0) {
+        diff = -diff;
+    }
+
+    return diff <= 50000;
+#else
+    return time1Us == time2Us;
+#endif
+}
+
+status_t Harness::testSeek(
+        const char *componentName, const char *componentRole) {
+    bool isEncoder =
+        !strncmp(componentRole, "audio_encoder.", 14)
+        || !strncmp(componentRole, "video_encoder.", 14);
+
+    if (isEncoder) {
+        // Not testing seek behaviour for encoders.
+
+        printf("  * Not testing seek functionality for encoders.\n");
+        return OK;
+    }
+
+    const char *mime = GetMimeFromComponentRole(componentRole);
+
+    if (!mime) {
+        LOGI("Cannot perform seek test with this componentRole (%s)",
+             componentRole);
+
+        return OK;
+    }
+
+    sp<MediaSource> source = CreateSourceForMime(mime);
+
+    sp<MediaSource> seekSource = CreateSourceForMime(mime);
+    CHECK_EQ(seekSource->start(), OK);
+
+    sp<MediaSource> codec = OMXCodec::Create(
+            mOMX, source->getFormat(), false /* createEncoder */,
+            source, componentName);
+
+    CHECK(codec != NULL);
+
+    CHECK_EQ(codec->start(), OK);
+
+    int64_t durationUs;
+    CHECK(source->getFormat()->findInt64(kKeyDuration, &durationUs));
+
+    LOGI("stream duration is %lld us (%.2f secs)",
+         durationUs, durationUs / 1E6);
+
+    static const int32_t kNumIterations = 5000;
+
+    for (int32_t i = 0; i < kNumIterations; ++i) {
+        int64_t requestedSeekTimeUs;
+        int64_t actualSeekTimeUs;
+        MediaSource::ReadOptions options;
+
+        double r = uniform_rand();
+
+        if (r < 0.5) {
+            // 50% chance of just continuing to decode from last position.
+
+            requestedSeekTimeUs = -1;
+
+            LOGI("requesting linear read");
+        } else {
+            if (r < 0.55) {
+                // 5% chance of seeking beyond end of stream.
+
+                requestedSeekTimeUs = durationUs;
+
+                LOGI("requesting seek beyond EOF");
+            } else {
+                requestedSeekTimeUs =
+                    (int64_t)(uniform_rand() * durationUs);
+
+                LOGI("requesting seek to %lld us (%.2f secs)",
+                     requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
+            }
+
+            MediaBuffer *buffer;
+            options.setSeekTo(requestedSeekTimeUs);
+            if (seekSource->read(&buffer, &options) != OK) {
+                CHECK_EQ(buffer, NULL);
+                actualSeekTimeUs = -1;
+            } else {
+                CHECK(buffer != NULL);
+                CHECK(buffer->meta_data()->findInt64(kKeyTime, &actualSeekTimeUs));
+                CHECK(actualSeekTimeUs >= 0);
+
+                buffer->release();
+                buffer = NULL;
+            }
+
+            LOGI("nearest keyframe is at %lld us (%.2f secs)",
+                 actualSeekTimeUs, actualSeekTimeUs / 1E6);
+        }
+
+        status_t err;
+        MediaBuffer *buffer;
+        for (;;) {
+            err = codec->read(&buffer, &options);
+            options.clearSeekTo();
+            if (err == INFO_FORMAT_CHANGED) {
+                CHECK_EQ(buffer, NULL);
+                continue;
+            }
+            if (err == OK) {
+                CHECK(buffer != NULL);
+                if (buffer->range_length() == 0) {
+                    buffer->release();
+                    buffer = NULL;
+                    continue;
+                }
+            } else {
+                CHECK_EQ(buffer, NULL);
+            }
+
+            break;
+        }
+
+        if (requestedSeekTimeUs < 0) {
+            // Linear read.
+            if (err != OK) {
+                CHECK_EQ(buffer, NULL);
+            } else {
+                CHECK(buffer != NULL);
+                buffer->release();
+                buffer = NULL;
+            }
+        } else if (actualSeekTimeUs < 0) {
+            CHECK(err != OK);
+            CHECK_EQ(buffer, NULL);
+        } else {
+            EXPECT(err == OK,
+                   "Expected a valid buffer to be returned from "
+                   "OMXCodec::read.");
+            CHECK(buffer != NULL);
+
+            int64_t bufferTimeUs;
+            CHECK(buffer->meta_data()->findInt64(kKeyTime, &bufferTimeUs));
+            if (!CloseEnough(bufferTimeUs, actualSeekTimeUs)) {
+                printf("\n  * Attempted seeking to %lld us (%.2f secs)",
+                       requestedSeekTimeUs, requestedSeekTimeUs / 1E6);
+                printf("\n  * Nearest keyframe is at %lld us (%.2f secs)",
+                       actualSeekTimeUs, actualSeekTimeUs / 1E6);
+                printf("\n  * Returned buffer was at %lld us (%.2f secs)\n\n",
+                       bufferTimeUs, bufferTimeUs / 1E6);
+
+                buffer->release();
+                buffer = NULL;
+
+                CHECK_EQ(codec->stop(), OK);
+
+                return UNKNOWN_ERROR;
+            }
+
+            buffer->release();
+            buffer = NULL;
+        }
+    }
+
+    CHECK_EQ(codec->stop(), OK);
+
+    return OK;
+}
+
+status_t Harness::test(
+        const char *componentName, const char *componentRole) {
+    printf("testing %s [%s] ... ", componentName, componentRole);
+    LOGI("testing %s [%s].", componentName, componentRole);
+
+    status_t err1 = testStateTransitions(componentName, componentRole);
+    status_t err2 = testSeek(componentName, componentRole);
+
+    if (err1 != OK) {
+        return err1;
+    }
+
+    return err2;
+}
+
+status_t Harness::testAll() {
+    List<IOMX::ComponentInfo> componentInfos;
+    status_t err = mOMX->listNodes(&componentInfos);
+    EXPECT_SUCCESS(err, "listNodes");
+
+    for (List<IOMX::ComponentInfo>::iterator it = componentInfos.begin();
+         it != componentInfos.end(); ++it) {
+        const IOMX::ComponentInfo &info = *it;
+        const char *componentName = info.mName.string();
+
+        for (List<String8>::const_iterator role_it = info.mRoles.begin();
+             role_it != info.mRoles.end(); ++role_it) {
+            const char *componentRole = (*role_it).string();
+
+            err = test(componentName, componentRole);
+
+            if (err == OK) {
+                printf("OK\n");
+            }
+        }
+    }
+
+    return OK;
+}
+
+}  // namespace android
+
+static void usage(const char *me) {
+    fprintf(stderr, "usage: %s\n"
+                    "  -h(elp)  Show this information\n"
+                    "  -s(eed)  Set the random seed\n"
+                    "    [ component role ]\n\n"
+                    "When launched without specifying a specific component "
+                    "and role, tool will test all available OMX components "
+                    "in all their supported roles. To determine available "
+                    "component names, use \"stagefright -l\"\n"
+                    "It's also a good idea to run a separate \"adb logcat\""
+                    " for additional debug and progress information.", me);
+
+    exit(0);
+}
+
+int main(int argc, char **argv) {
+    using namespace android;
+
+    android::ProcessState::self()->startThreadPool();
+    DataSource::RegisterDefaultSniffers();
+
+    const char *me = argv[0];
+
+    unsigned long seed = 0xdeadbeef;
+
+    int res;
+    while ((res = getopt(argc, argv, "hs:")) >= 0) {
+        switch (res) {
+            case 's':
+            {
+                char *end;
+                unsigned long x = strtoul(optarg, &end, 10);
+
+                if (*end != '\0' || end == optarg) {
+                    fprintf(stderr, "Malformed seed.\n");
+                    return 1;
+                }
+
+                seed = x;
+                break;
+            }
+
+            case '?':
+                fprintf(stderr, "\n");
+                // fall through
+
+            case 'h':
+            default:
+            {
+                usage(me);
+                exit(1);
+                break;
+            }
+        }
+    }
+
+    argc -= optind;
+    argv += optind;
+
+    printf("To reproduce the conditions for this test, launch "
+           "with \"%s -s %lu\"\n", me, seed);
+
+    srand(seed);
+
+    sp<Harness> h = new Harness;
+    CHECK_EQ(h->initCheck(), OK);
+
+    if (argc == 0) {
+        h->testAll();
+    } else if (argc == 2) {
+        if (h->test(argv[0], argv[1]) == OK) {
+            printf("OK\n");
+        }
+    }
+
+    return 0;
+}
diff --git a/media/libstagefright/omx/tests/OMXHarness.h b/media/libstagefright/omx/tests/OMXHarness.h
new file mode 100644
index 0000000..bb8fd0c
--- /dev/null
+++ b/media/libstagefright/omx/tests/OMXHarness.h
@@ -0,0 +1,105 @@
+/*
+ * 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 OMX_HARNESS_H_
+
+#define OMX_HARNESS_H_
+
+#include <media/IOMX.h>
+#include <utils/List.h>
+#include <utils/Vector.h>
+#include <utils/threads.h>
+
+#include <OMX_Component.h>
+
+namespace android {
+
+class MemoryDealer;
+
+struct Harness : public BnOMXObserver {
+    enum BufferFlags {
+        kBufferBusy = 1
+    };
+    struct Buffer {
+        IOMX::buffer_id mID;
+        sp<IMemory> mMemory;
+        uint32_t mFlags;
+    };
+
+    Harness();
+
+    status_t initCheck() const;
+
+    status_t dequeueMessageForNode(
+            IOMX::node_id node, omx_message *msg, int64_t timeoutUs = -1);
+
+    status_t dequeueMessageForNodeIgnoringBuffers(
+            IOMX::node_id node,
+            Vector<Buffer> *inputBuffers,
+            Vector<Buffer> *outputBuffers,
+            omx_message *msg, int64_t timeoutUs = -1);
+
+    status_t getPortDefinition(
+            IOMX::node_id node, OMX_U32 portIndex,
+            OMX_PARAM_PORTDEFINITIONTYPE *def);
+
+    status_t allocatePortBuffers(
+            const sp<MemoryDealer> &dealer,
+            IOMX::node_id node, OMX_U32 portIndex,
+            Vector<Buffer> *buffers);
+
+    status_t setRole(IOMX::node_id node, const char *role);
+
+    status_t testStateTransitions(
+            const char *componentName, const char *componentRole);
+
+    status_t testSeek(
+            const char *componentName, const char *componentRole);
+
+    status_t test(
+            const char *componentName, const char *componentRole);
+
+    status_t testAll();
+
+    virtual void onMessage(const omx_message &msg);
+
+protected:
+    virtual ~Harness();
+
+private:
+    friend struct NodeReaper;
+
+    Mutex mLock;
+
+    status_t mInitCheck;
+    sp<IOMX> mOMX;
+    List<omx_message> mMessageQueue;
+    Condition mMessageAddedCondition;
+
+    status_t initOMX();
+
+    bool handleBufferMessage(
+            const omx_message &msg,
+            Vector<Buffer> *inputBuffers,
+            Vector<Buffer> *outputBuffers);
+
+    Harness(const Harness &);
+    Harness &operator=(const Harness &);
+};
+
+}  // namespace android
+
+#endif  // OMX_HARNESS_H_
diff --git a/media/libstagefright/stagefright_string.cpp b/media/libstagefright/stagefright_string.cpp
deleted file mode 100644
index 2aedb80..0000000
--- a/media/libstagefright/stagefright_string.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 <media/stagefright/stagefright_string.h>
-
-namespace android {
-
-// static
-string::size_type string::npos = (string::size_type)-1;
-
-string::string() {
-}
-
-string::string(const char *s, size_t length)
-    : mString(s, length) {
-}
-
-string::string(const string &from, size_type start, size_type length)
-    : mString(from.c_str() + start, length) {
-}
-
-string::string(const char *s)
-    : mString(s) {
-}
-
-const char *string::c_str() const {
-    return mString.string();
-}
-
-string::size_type string::size() const {
-    return mString.length();
-}
-
-void string::clear() {
-    mString = String8();
-}
-
-string::size_type string::find(char c) const {
-    char s[2];
-    s[0] = c;
-    s[1] = '\0';
-
-    ssize_t index = mString.find(s);
-
-    return index < 0 ? npos : (size_type)index;
-}
-
-bool string::operator<(const string &other) const {
-    return mString < other.mString;
-}
-
-bool string::operator==(const string &other) const {
-    return mString == other.mString;
-}
-
-string &string::operator+=(char c) {
-    mString.append(&c, 1);
-
-    return *this;
-}
-
-void string::erase(size_t from, size_t length) {
-    String8 s(mString.string(), from);
-    s.append(mString.string() + from + length);
-    
-    mString = s;
-}
-
-}  // namespace android
-
diff --git a/media/libstagefright/string.cpp b/media/libstagefright/string.cpp
new file mode 100644
index 0000000..bd6204b
--- /dev/null
+++ b/media/libstagefright/string.cpp
@@ -0,0 +1,83 @@
+/*
+ * 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 "include/stagefright_string.h"
+
+namespace android {
+
+// static
+string::size_type string::npos = (string::size_type)-1;
+
+string::string() {
+}
+
+string::string(const char *s, size_t length)
+    : mString(s, length) {
+}
+
+string::string(const string &from, size_type start, size_type length)
+    : mString(from.c_str() + start, length) {
+}
+
+string::string(const char *s)
+    : mString(s) {
+}
+
+const char *string::c_str() const {
+    return mString.string();
+}
+
+string::size_type string::size() const {
+    return mString.length();
+}
+
+void string::clear() {
+    mString = String8();
+}
+
+string::size_type string::find(char c) const {
+    char s[2];
+    s[0] = c;
+    s[1] = '\0';
+
+    ssize_t index = mString.find(s);
+
+    return index < 0 ? npos : (size_type)index;
+}
+
+bool string::operator<(const string &other) const {
+    return mString < other.mString;
+}
+
+bool string::operator==(const string &other) const {
+    return mString == other.mString;
+}
+
+string &string::operator+=(char c) {
+    mString.append(&c, 1);
+
+    return *this;
+}
+
+void string::erase(size_t from, size_t length) {
+    String8 s(mString.string(), from);
+    s.append(mString.string() + from + length);
+    
+    mString = s;
+}
+
+}  // namespace android
+